From e820dd9a5452864a0339ba96d1e97889d6a12ed0 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Tue, 11 Jul 2017 09:27:12 +0200 Subject: [PATCH 1/9] [dev] config.xml - update version --- src/app/code/local/MailUp/MailUpSync/etc/config.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/code/local/MailUp/MailUpSync/etc/config.xml b/src/app/code/local/MailUp/MailUpSync/etc/config.xml index d251ce3..e2ff3c9 100644 --- a/src/app/code/local/MailUp/MailUpSync/etc/config.xml +++ b/src/app/code/local/MailUp/MailUpSync/etc/config.xml @@ -2,7 +2,7 @@ - 2.7.2 + 2.7.5 From 91876e5553189175f1e6b7b867195c80a2296f43 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Tue, 11 Jul 2017 12:24:58 +0200 Subject: [PATCH 2/9] [dev] add files - license - privacy policy - update readme --- LICENSE.txt | 47 +++++++++++++++++++++++++++++++++++++++++++++++ README.md | 8 +++++++- privacy_policy.md | 3 +++ 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 LICENSE.txt create mode 100644 privacy_policy.md diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..c515fe3 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,47 @@ +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + +1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + +a) to reproduce the Original Work in copies, either alone or as part of a collective work; + +b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + +c) to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + +d) to perform the Original Work publicly; and + +e) to display the Original Work publicly. + +2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + +3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + +4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + +5) External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + +6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + +7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + +8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + +9) Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + +10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + +11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + +12) Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + +13) Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + +14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + +16) Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/README.md b/README.md index c5b16b4..4ff8d3c 100644 --- a/README.md +++ b/README.md @@ -25,4 +25,10 @@ mailup/magento Any contribution to the development is welcome. The best possibility to provide any code is to open a [pull request on GitHub](https://help.github.com/articles/using-pull-requests).
-You can also open an issue to advice any kind of error. \ No newline at end of file +You can also open an issue to advice any kind of error. + +--- + +### Privacy Policy + +Please look at *privacy_policy.md* \ No newline at end of file diff --git a/privacy_policy.md b/privacy_policy.md new file mode 100644 index 0000000..7fc5dea --- /dev/null +++ b/privacy_policy.md @@ -0,0 +1,3 @@ +## Mailup_MailupSync Privacy Policy + +The Magento Newsletter Subscription Service requires the collection and processing of your end user’s IP address which is used only for preventing Bots and malicious signups. \ No newline at end of file From 9b0069ccfd4b4952db117f4533433bbfb1e52bcf Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Fri, 4 Aug 2017 14:40:12 +0200 Subject: [PATCH 3/9] [dev] system config - refactoring field controller --- .../System/Config}/Consoleurlvalidator.php | 5 ++++- .../System/Config/Webservicepwdvalidator.php | 14 ++++++++++++++ .../System/Config}/Webserviceusernamevalidator.php | 5 ++++- .../code/local/MailUp/MailUpSync/etc/system.xml | 5 +++-- 4 files changed, 25 insertions(+), 4 deletions(-) rename src/app/code/local/MailUp/MailUpSync/Model/{ => Adminhtml/System/Config}/Consoleurlvalidator.php (69%) create mode 100644 src/app/code/local/MailUp/MailUpSync/Model/Adminhtml/System/Config/Webservicepwdvalidator.php rename src/app/code/local/MailUp/MailUpSync/Model/{ => Adminhtml/System/Config}/Webserviceusernamevalidator.php (66%) diff --git a/src/app/code/local/MailUp/MailUpSync/Model/Consoleurlvalidator.php b/src/app/code/local/MailUp/MailUpSync/Model/Adminhtml/System/Config/Consoleurlvalidator.php similarity index 69% rename from src/app/code/local/MailUp/MailUpSync/Model/Consoleurlvalidator.php rename to src/app/code/local/MailUp/MailUpSync/Model/Adminhtml/System/Config/Consoleurlvalidator.php index ccf4caf..7454c7f 100644 --- a/src/app/code/local/MailUp/MailUpSync/Model/Consoleurlvalidator.php +++ b/src/app/code/local/MailUp/MailUpSync/Model/Adminhtml/System/Config/Consoleurlvalidator.php @@ -1,6 +1,9 @@ getValue(); + if (strlen($value) == 0) { + Mage::throwException(Mage::helper("mailup")->__("Please fill the web service password")); + } + + return parent::save(); + } +} \ No newline at end of file diff --git a/src/app/code/local/MailUp/MailUpSync/Model/Webserviceusernamevalidator.php b/src/app/code/local/MailUp/MailUpSync/Model/Adminhtml/System/Config/Webserviceusernamevalidator.php similarity index 66% rename from src/app/code/local/MailUp/MailUpSync/Model/Webserviceusernamevalidator.php rename to src/app/code/local/MailUp/MailUpSync/Model/Adminhtml/System/Config/Webserviceusernamevalidator.php index 1b3e75b..4f0d913 100644 --- a/src/app/code/local/MailUp/MailUpSync/Model/Webserviceusernamevalidator.php +++ b/src/app/code/local/MailUp/MailUpSync/Model/Adminhtml/System/Config/Webserviceusernamevalidator.php @@ -1,6 +1,9 @@ 1 1 It's the domain portion of the URL to your MailUp Admin console (e.g. g4a0.s03.it) - mailup/consoleurlvalidator + mailup/adminhtml_system_config_consoleurlvalidator @@ -49,7 +49,7 @@ 1 1 1 - mailup/webserviceusernamevalidator + mailup/adminhtml_system_config_webserviceusernamevalidator @@ -58,6 +58,7 @@ 1 1 1 + mailup/adminhtml_system_config_webservicepwdvalidator For assistance visit http://help.mailup.com/x/PgAy From b7d036e90200c5aec05afe78d1f7f185b62bb414 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Fri, 4 Aug 2017 14:40:40 +0200 Subject: [PATCH 4/9] [dev] system save config observer - close save config to single section - remove unused check --- .../MailUp/MailUpSync/Model/Observer.php | 109 +++++++++--------- 1 file changed, 57 insertions(+), 52 deletions(-) diff --git a/src/app/code/local/MailUp/MailUpSync/Model/Observer.php b/src/app/code/local/MailUp/MailUpSync/Model/Observer.php index 4c94e13..5820de6 100644 --- a/src/app/code/local/MailUp/MailUpSync/Model/Observer.php +++ b/src/app/code/local/MailUp/MailUpSync/Model/Observer.php @@ -22,55 +22,59 @@ class MailUp_MailUpSync_Model_Observer */ public function saveSystemConfig($observer) { - Mage::getSingleton('adminhtml/session')->setMessages(Mage::getModel('core/message_collection')); + $controller = $observer->getControllerAction(); + $params = $controller->getRequest()->getParams(); - Mage::getModel('core/config_data') - ->load(self::CRON_STRING_PATH, 'path') - ->setValue($this->_getSchedule()) - ->setPath(self::CRON_STRING_PATH) - ->save(); - - Mage::app()->cleanCache(); - - $this->configCheck(); + if($params['section'] == 'mailup_newsletter') { + Mage::getSingleton('adminhtml/session')->setMessages(Mage::getModel('core/message_collection')); + + Mage::getModel('core/config_data') + ->load(self::CRON_STRING_PATH, 'path') + ->setValue($this->_getSchedule()) + ->setPath(self::CRON_STRING_PATH) + ->save(); + + Mage::app()->cleanCache(); + + $this->configCheck(); - // If there are errors in config, do not progress further as it may be testing old data - $currentMessages = Mage::getSingleton('adminhtml/session')->getMessages(); - foreach ($currentMessages->getItems() as $msg) { - if ($msg->getType() != 'success') { - return; + // If there are errors in config, do not progress further as it may be testing old data + $currentMessages = Mage::getSingleton('adminhtml/session')->getMessages(); + foreach($currentMessages->getItems() as $msg) { + if($msg->getType() != 'success') { + return; + } } - } - $messages = array(); + $messages = array(); - // Close connection to avoid mysql gone away errors - $res = Mage::getSingleton('core/resource'); - $res->getConnection('core_write')->closeConnection(); + // Close connection to avoid mysql gone away errors + $res = Mage::getSingleton('core/resource'); + $res->getConnection('core_write')->closeConnection(); - // Test connection - $storeId = Mage::app()->getStore(); - $urlConsole = Mage::getStoreConfig('mailup_newsletter/mailup/url_console'); - $usernameWs = Mage::getStoreConfig('mailup_newsletter/mailup/username_ws'); - $passwordWs = Mage::getStoreConfig('mailup_newsletter/mailup/password_ws'); - $retConn = Mage::helper('mailup')->testConnection($urlConsole, $usernameWs, $passwordWs, $storeId); - $messages = array_merge($messages, $retConn); + // Test connection + $storeId = Mage::app()->getStore(); + $urlConsole = Mage::getStoreConfig('mailup_newsletter/mailup/url_console'); + $usernameWs = Mage::getStoreConfig('mailup_newsletter/mailup/username_ws'); + $passwordWs = Mage::getStoreConfig('mailup_newsletter/mailup/password_ws'); + $retConn = Mage::helper('mailup')->testConnection($urlConsole, $usernameWs, $passwordWs, $storeId); + $messages = array_merge($messages, $retConn); - // Config tests - $retConfig = Mage::helper('mailup')->testConfig(); - $messages = array_merge($messages, $retConfig); + // Config tests + $retConfig = Mage::helper('mailup')->testConfig(); + $messages = array_merge($messages, $retConfig); - // Re-open connection to avoid mysql gone away errors - $res->getConnection('core_write')->getConnection(); + // Re-open connection to avoid mysql gone away errors + $res->getConnection('core_write')->getConnection(); - // Add messages from test - if (count($messages) > 0) { - foreach ($messages as $msg) { - $msgObj = Mage::getSingleton('core/message')->$msg['type']($msg['message']); - Mage::getSingleton('adminhtml/session')->addMessage($msgObj); + // Add messages from test + if(count($messages) > 0) { + foreach($messages as $msg) { + $msgObj = Mage::getSingleton('core/message')->$msg['type']($msg['message']); + Mage::getSingleton('adminhtml/session')->addMessage($msgObj); + } } } - } /** @@ -330,20 +334,21 @@ public function sendUser($observer) */ public function configCheck() { - $url_console = Mage::getStoreConfig('mailup_newsletter/mailup/url_console'); - $user = Mage::getStoreConfig('mailup_newsletter/mailup/username_ws'); - $password = Mage::getStoreConfig('mailup_newsletter/mailup/password_ws'); - $list = Mage::getStoreConfig('mailup_newsletter/mailup/list'); - - if (!strlen($url_console) or !strlen($user) or !strlen($password) or !strlen($list)) { - $url = Mage::getModel('adminhtml/url'); - $url = $url->getUrl("adminhtml/mailup_configuration"); - $message = Mage::helper("mailup")->__('MailUp configuration is not complete'); - $message = str_replace("href=''", "href='$url'", $message); - Mage::getSingleton('adminhtml/session')->addWarning($message); - - return; - } + /** @deprecated after 2.7.5 **/ + //$url_console = Mage::getStoreConfig('mailup_newsletter/mailup/url_console'); + //$user = Mage::getStoreConfig('mailup_newsletter/mailup/username_ws'); + //$password = Mage::getStoreConfig('mailup_newsletter/mailup/password_ws'); + //$list = Mage::getStoreConfig('mailup_newsletter/mailup/list'); + // + //if (!strlen($url_console) or !strlen($user) or !strlen($password) or !strlen($list)) { + // $url = Mage::getModel('adminhtml/url'); + // $url = $url->getUrl("adminhtml/mailup_configuration"); + // $message = Mage::helper("mailup")->__('MailUp configuration is not complete'); + // $message = str_replace("href=''", "href='$url'", $message); + // Mage::getSingleton('adminhtml/session')->addWarning($message); + // + // return; + //} $wsimport = new MailUpWsImport(); $mapping = $wsimport->getFieldsMapping(); From 4d45af8ca993234164e0078947bf1edadd83d678 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Mon, 7 Aug 2017 09:55:08 +0200 Subject: [PATCH 5/9] [dev] system config - add skip test console url --- .../local/MailUp/MailUpSync/Helper/Data.php | 691 +++++++++--------- .../local/MailUp/MailUpSync/etc/system.xml | 42 +- 2 files changed, 373 insertions(+), 360 deletions(-) diff --git a/src/app/code/local/MailUp/MailUpSync/Helper/Data.php b/src/app/code/local/MailUp/MailUpSync/Helper/Data.php index be5969a..cedc89d 100644 --- a/src/app/code/local/MailUp/MailUpSync/Helper/Data.php +++ b/src/app/code/local/MailUp/MailUpSync/Helper/Data.php @@ -5,7 +5,7 @@ /** * Data.php - * + * * @todo get rid of these static methods! */ class MailUp_MailUpSync_Helper_Data extends Mage_Core_Helper_Abstract @@ -32,50 +32,50 @@ class MailUp_MailUpSync_Helper_Data extends Mage_Core_Helper_Abstract * split customers into batches */ const BATCH_SIZE = 2000; - + /** * Get the Customer Data - * + * * @param array * @return array */ - public static function getCustomersData($customerCollection = null) - { + public static function getCustomersData($customerCollection = null) + { $config = Mage::getModel('mailup/config'); /* @var $config MailUp_MailUpSync_Model_Config */ - + if ($config->isLogEnabled()) { $config->log('Getting customers data'); } - + if(is_array($customerCollection) && empty($customerCollection)) { if ($config->isLogEnabled()) { $config->log('CustomerCollection is Empty!'); } } - - $dateFormat = 'm/d/y h:i:s'; - $lastDateTime = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-7*3600*24); - $thirtyDaysAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-30*3600*24); - $twelveMonthsAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-365*3600*24); - - $parseSubscribers = false; - $toSend = array(); - if ($customerCollection === null) { + + $dateFormat = 'm/d/y h:i:s'; + $lastDateTime = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-7*3600*24); + $thirtyDaysAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-30*3600*24); + $twelveMonthsAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-365*3600*24); + + $parseSubscribers = false; + $toSend = array(); + if ($customerCollection === null) { /** * @todo Change to only load form current store/website */ - $customerCollection = Mage::getModel('customer/customer')->getCollection(); - $parseSubscribers = true; + $customerCollection = Mage::getModel('customer/customer')->getCollection(); + $parseSubscribers = true; if ($config->isLogEnabled()) { $config->log('Parsing Subscribers, NULL collection passed.'); } - } - foreach ($customerCollection as $currentCustomerId) { - if (is_object($currentCustomerId)) { - $currentCustomerId = $currentCustomerId->getId(); - } - + } + foreach ($customerCollection as $currentCustomerId) { + if (is_object($currentCustomerId)) { + $currentCustomerId = $currentCustomerId->getId(); + } + if( ! $currentCustomerId) { if($config->isLogEnabled()) { $config->log('Skipping Empty Customer ID!'); @@ -86,127 +86,127 @@ public static function getCustomersData($customerCollection = null) if ($config->isLogEnabled()) { $config->log('Customer with id '.$currentCustomerId); } - $customer = Mage::getModel('customer/customer')->load($currentCustomerId); + $customer = Mage::getModel('customer/customer')->load($currentCustomerId); /* @var $customer Mage_Customer_Model_Customer */ - $i = $customer->getEmail(); + $i = $customer->getEmail(); - // Get order dates, numbers and totals for the current customer + // Get order dates, numbers and totals for the current customer //TODO: This would be more efficient with just a few SQL statements to gather this - $allOrdersTotalAmount = 0; - $allOrdersDateTimes = array(); - $allOrdersTotals = array(); - $allOrdersIds = array(); - $allProductsIds = array(); - $last30daysOrdersAmount = 0; - $last12monthsOrdersAmount = 0; - $lastShipmentOrderId = null; - $lastShipmentOrderDate = null; + $allOrdersTotalAmount = 0; + $allOrdersDateTimes = array(); + $allOrdersTotals = array(); + $allOrdersIds = array(); + $allProductsIds = array(); + $last30daysOrdersAmount = 0; + $last12monthsOrdersAmount = 0; + $lastShipmentOrderId = null; + $lastShipmentOrderDate = null; if ($config->isLogEnabled()) { $config->log('Parsing orders of customer with id '.$currentCustomerId); } // Setup collection to fetch orders for this customer and valid statuses - $orders = Mage::getResourceModel('sales/order_collection') - ->addAttributeToFilter('customer_id', $currentCustomerId); + $orders = Mage::getResourceModel('sales/order_collection') + ->addAttributeToFilter('customer_id', $currentCustomerId); Mage::helper('mailup/order')->addStatusFilterToOrders($orders); - foreach ($orders as $order) { + foreach ($orders as $order) { if ($config->isLogEnabled()) { $config->log("ORDER STATUS: {$order->getState()} / {$order->getStatus()}"); } // Get current and total orders - $currentOrderTotal = floatval($order->getGrandTotal()); - $allOrdersTotalAmount += $currentOrderTotal; - - $currentOrderCreationDate = $order->getCreatedAt(); - if ($currentOrderCreationDate > $thirtyDaysAgo) { - $last30daysOrdersAmount += $currentOrderTotal; - } - if ($currentOrderCreationDate > $twelveMonthsAgo) { - $last12monthsOrdersAmount += $currentOrderTotal; - } - - $currentOrderTotal = self::_formatPrice($currentOrderTotal); - $currentOrderId = $order->getIncrementId(); - $allOrdersTotals[$currentOrderId] = $currentOrderTotal; - $allOrdersDateTimes[$currentOrderId] = $currentOrderCreationDate; - $allOrdersIds[$currentOrderId] = $currentOrderId; - - if ($order->hasShipments() and ($order->getId()>$lastShipmentOrderId)) { - $lastShipmentOrderId = $order->getId(); - $lastShipmentOrderDate = self::_retriveDateFromDatetime($order->getCreatedAt()); - } - - $items = $order->getAllItems(); - foreach ($items as $item) { - $allProductsIds[] = $item->getProductId(); - } - } - - $toSend[$i]['TotaleFatturatoUltimi30gg'] = self::_formatPrice($last30daysOrdersAmount); - $toSend[$i]['TotaleFatturatoUltimi12Mesi'] = self::_formatPrice($last12monthsOrdersAmount); - $toSend[$i]['IDTuttiProdottiAcquistati'] = implode(',', $allProductsIds); - - ksort($allOrdersDateTimes); - ksort($allOrdersTotals); - ksort($allOrdersIds); - - //recupero i carrelli abbandonati del cliente + $currentOrderTotal = floatval($order->getGrandTotal()); + $allOrdersTotalAmount += $currentOrderTotal; + + $currentOrderCreationDate = $order->getCreatedAt(); + if ($currentOrderCreationDate > $thirtyDaysAgo) { + $last30daysOrdersAmount += $currentOrderTotal; + } + if ($currentOrderCreationDate > $twelveMonthsAgo) { + $last12monthsOrdersAmount += $currentOrderTotal; + } + + $currentOrderTotal = self::_formatPrice($currentOrderTotal); + $currentOrderId = $order->getIncrementId(); + $allOrdersTotals[$currentOrderId] = $currentOrderTotal; + $allOrdersDateTimes[$currentOrderId] = $currentOrderCreationDate; + $allOrdersIds[$currentOrderId] = $currentOrderId; + + if ($order->hasShipments() and ($order->getId()>$lastShipmentOrderId)) { + $lastShipmentOrderId = $order->getId(); + $lastShipmentOrderDate = self::_retriveDateFromDatetime($order->getCreatedAt()); + } + + $items = $order->getAllItems(); + foreach ($items as $item) { + $allProductsIds[] = $item->getProductId(); + } + } + + $toSend[$i]['TotaleFatturatoUltimi30gg'] = self::_formatPrice($last30daysOrdersAmount); + $toSend[$i]['TotaleFatturatoUltimi12Mesi'] = self::_formatPrice($last12monthsOrdersAmount); + $toSend[$i]['IDTuttiProdottiAcquistati'] = implode(',', $allProductsIds); + + ksort($allOrdersDateTimes); + ksort($allOrdersTotals); + ksort($allOrdersIds); + + //recupero i carrelli abbandonati del cliente if($config->isLogEnabled()) { $config->log('Parsing abandoned carts of customer with id '.$currentCustomerId); } - $cartCollection = Mage::getResourceModel('reports/quote_collection'); + $cartCollection = Mage::getResourceModel('reports/quote_collection'); $cartCollection->prepareForAbandonedReport($config->getAllStoreIds()); - $cartCollection->addFieldToFilter('customer_id', $currentCustomerId); - $cartCollection->load(); + $cartCollection->addFieldToFilter('customer_id', $currentCustomerId); + $cartCollection->load(); - $datetimeCart = null; - if ( ! empty($cartCollection)) { + $datetimeCart = null; + if ( ! empty($cartCollection)) { $lastCart = $cartCollection->getLastItem(); - $toSend[$i]['TotaleCarrelloAbbandonato'] = ''; - $toSend[$i]['DataCarrelloAbbandonato'] = ''; - $toSend[$i]['IDCarrelloAbbandonato'] = ''; + $toSend[$i]['TotaleCarrelloAbbandonato'] = ''; + $toSend[$i]['DataCarrelloAbbandonato'] = ''; + $toSend[$i]['IDCarrelloAbbandonato'] = ''; - if ( ! empty($lastCart)) { + if ( ! empty($lastCart)) { if ($config->isLogEnabled()) { $config->log('Customer with id '.$currentCustomerId .' has abandoned cart'); } - $datetimeCart = $lastCart->getUpdatedAt(); - //$toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getGrandTotal()); + $datetimeCart = $lastCart->getUpdatedAt(); + //$toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getGrandTotal()); $toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getSubtotal()); - $toSend[$i]['DataCarrelloAbbandonato'] = self::_retriveDateFromDatetime($datetimeCart); - $toSend[$i]['IDCarrelloAbbandonato'] = $lastCart->getId(); - } + $toSend[$i]['DataCarrelloAbbandonato'] = self::_retriveDateFromDatetime($datetimeCart); + $toSend[$i]['IDCarrelloAbbandonato'] = $lastCart->getId(); + } else { if ($config->isLogEnabled()) { $config->log('Customer with id '.$currentCustomerId .' has empty LAST CART'); } } - } + } else { if ($config->isLogEnabled()) { $config->log('Customer id '.$currentCustomerId .' has empty abandoned cart collection'); } } - $toSend[$i]['IDUltimoOrdineSpedito'] = $lastShipmentOrderId; - $toSend[$i]['DataUltimoOrdineSpedito'] = $lastShipmentOrderDate; + $toSend[$i]['IDUltimoOrdineSpedito'] = $lastShipmentOrderId; + $toSend[$i]['DataUltimoOrdineSpedito'] = $lastShipmentOrderDate; - $lastOrderDateTime = end($allOrdersDateTimes); + $lastOrderDateTime = end($allOrdersDateTimes); - if ($customer->getUpdatedAt() > $lastDateTime - || $lastOrderDateTime > $lastDateTime - || ($datetimeCart && $datetimeCart > $lastDateTime)) - { + if ($customer->getUpdatedAt() > $lastDateTime + || $lastOrderDateTime > $lastDateTime + || ($datetimeCart && $datetimeCart > $lastDateTime)) + { if ($config->isLogEnabled()) { $config->log('Adding customer with id '.$currentCustomerId); } - $toSend[$i]['nome'] = $customer->getFirstname(); - $toSend[$i]['cognome'] = $customer->getLastname(); - $toSend[$i]['email'] = $customer->getEmail(); - $toSend[$i]['IDCliente'] = $currentCustomerId; + $toSend[$i]['nome'] = $customer->getFirstname(); + $toSend[$i]['cognome'] = $customer->getLastname(); + $toSend[$i]['email'] = $customer->getEmail(); + $toSend[$i]['IDCliente'] = $currentCustomerId; // Custom customer attributes $customerAttributes = Mage::helper('mailup/customer')->getCustomCustomerAttrCollection(); @@ -230,130 +230,130 @@ public static function getCustomersData($customerCollection = null) } } - $toSend[$i]['registeredDate'] = self::_retriveDateFromDatetime($customer->getCreatedAt()); + $toSend[$i]['registeredDate'] = self::_retriveDateFromDatetime($customer->getCreatedAt()); - //controllo se iscritto o meno alla newsletter - if (Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->isSubscribed()) { - $toSend[$i]['subscribed'] = 'yes'; - } + //controllo se iscritto o meno alla newsletter + if (Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->isSubscribed()) { + $toSend[$i]['subscribed'] = 'yes'; + } else { - $toSend[$i]['subscribed'] = 'no'; - } - - //recupero i dati dal default billing address - $customerAddressId = $customer->getDefaultBilling(); - if ($customerAddressId) { - $address = Mage::getModel('customer/address')->load($customerAddressId); - $toSend[$i]['azienda'] = $address->getData('company'); - $toSend[$i]['paese'] = $address->getCountry(); - $toSend[$i]['città'] = $address->getData('city'); - $toSend[$i]['regione'] = $address->getData('region'); - $regionId = $address->getData('region_id'); - $regionModel = Mage::getModel('directory/region')->load($regionId); - $regionCode = $regionModel->getCode(); - $toSend[$i]['provincia'] = $regionCode; - $toSend[$i]['cap'] = $address->getData('postcode'); - $toSend[$i]['indirizzo'] = $address->getData('street'); - $toSend[$i]['fax'] = $address->getData('fax'); - $toSend[$i]['telefono'] = $address->getData('telephone'); - } + $toSend[$i]['subscribed'] = 'no'; + } + + //recupero i dati dal default billing address + $customerAddressId = $customer->getDefaultBilling(); + if ($customerAddressId) { + $address = Mage::getModel('customer/address')->load($customerAddressId); + $toSend[$i]['azienda'] = $address->getData('company'); + $toSend[$i]['paese'] = $address->getCountry(); + $toSend[$i]['città'] = $address->getData('city'); + $toSend[$i]['regione'] = $address->getData('region'); + $regionId = $address->getData('region_id'); + $regionModel = Mage::getModel('directory/region')->load($regionId); + $regionCode = $regionModel->getCode(); + $toSend[$i]['provincia'] = $regionCode; + $toSend[$i]['cap'] = $address->getData('postcode'); + $toSend[$i]['indirizzo'] = $address->getData('street'); + $toSend[$i]['fax'] = $address->getData('fax'); + $toSend[$i]['telefono'] = $address->getData('telephone'); + } else { $toSend[$i]['azienda'] = ''; - $toSend[$i]['paese'] = ''; - $toSend[$i]['città'] = ''; - $toSend[$i]['regione'] = ''; - $toSend[$i]['provincia'] = ''; - $toSend[$i]['cap'] = ''; - $toSend[$i]['indirizzo'] = ''; - $toSend[$i]['fax'] = ''; - $toSend[$i]['telefono'] = ''; + $toSend[$i]['paese'] = ''; + $toSend[$i]['città'] = ''; + $toSend[$i]['regione'] = ''; + $toSend[$i]['provincia'] = ''; + $toSend[$i]['cap'] = ''; + $toSend[$i]['indirizzo'] = ''; + $toSend[$i]['fax'] = ''; + $toSend[$i]['telefono'] = ''; } - $toSend[$i]['DataUltimoOrdine'] = self::_retriveDateFromDatetime($lastOrderDateTime); - $toSend[$i]['TotaleUltimoOrdine'] = end($allOrdersTotals); - $toSend[$i]['IDUltimoOrdine'] = end($allOrdersIds); - - $toSend[$i]['TotaleFatturato'] = self::_formatPrice($allOrdersTotalAmount); - - //ottengo gli id di prodotti e categorie (dell'ultimo ordine) - $lastOrder = Mage::getModel('sales/order')->loadByIncrementId(end($allOrdersIds)); - $items = $lastOrder->getAllItems(); - $productIds = array(); - $categoryIds = array(); - foreach ($items as $item) { - $productId = $item->getProductId(); - $productIds[] = $productId; - $product = Mage::getModel('catalog/product')->load($productId); - if ($product->getCategoryIds()) { - $categoryIds[] = implode(',', $product->getCategoryIds()); - } - } - - $toSend[$i]['IDProdottiUltimoOrdine'] = implode(',', $productIds); - if ($toSend[$i]['IDProdottiUltimoOrdine']) { + $toSend[$i]['DataUltimoOrdine'] = self::_retriveDateFromDatetime($lastOrderDateTime); + $toSend[$i]['TotaleUltimoOrdine'] = end($allOrdersTotals); + $toSend[$i]['IDUltimoOrdine'] = end($allOrdersIds); + + $toSend[$i]['TotaleFatturato'] = self::_formatPrice($allOrdersTotalAmount); + + //ottengo gli id di prodotti e categorie (dell'ultimo ordine) + $lastOrder = Mage::getModel('sales/order')->loadByIncrementId(end($allOrdersIds)); + $items = $lastOrder->getAllItems(); + $productIds = array(); + $categoryIds = array(); + foreach ($items as $item) { + $productId = $item->getProductId(); + $productIds[] = $productId; + $product = Mage::getModel('catalog/product')->load($productId); + if ($product->getCategoryIds()) { + $categoryIds[] = implode(',', $product->getCategoryIds()); + } + } + + $toSend[$i]['IDProdottiUltimoOrdine'] = implode(',', $productIds); + if ($toSend[$i]['IDProdottiUltimoOrdine']) { $toSend[$i]['IDProdottiUltimoOrdine'] = ",{$toSend[$i]['IDProdottiUltimoOrdine']},"; } - $toSend[$i]['IDCategorieUltimoOrdine'] = implode(',', $categoryIds); - if ($toSend[$i]['IDCategorieUltimoOrdine']) { + $toSend[$i]['IDCategorieUltimoOrdine'] = implode(',', $categoryIds); + if ($toSend[$i]['IDCategorieUltimoOrdine']) { $toSend[$i]['IDCategorieUltimoOrdine'] = ",{$toSend[$i]['IDCategorieUltimoOrdine']},"; } - } - + } + $toSend[$i]['DateOfBirth'] = self::_retriveDobFromDatetime($customer->getDob()); $toSend[$i]['Gender'] = $customer->getAttribute('gender')->getSource()->getOptionText($customer->getGender()); - //unsetto la variabile - unset($customer); - } - - /* - * disabled cause useless in segmentation - if ($parseSubscribers) { - if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) Mage::log('Parsing subscribers', 0); - $subscriberCollection = Mage::getModel('newsletter/subscriber') - ->getCollection() - ->useOnlySubscribed() - ->addFieldToFilter('customer_id', 0); - - foreach ($subscriberCollection as $subscriber) { - $subscriber = Mage::getModel('newsletter/subscriber')->load($subscriber->getId()); - $i = $subscriber->getEmail(); - if (strlen($i)) continue; - if (isset($toSend[$i])) continue; - $toSend[$i]['nome'] = ''; - $toSend[$i]['cognome'] = ''; - $toSend[$i]['email'] = $i; - $toSend[$i]['subscribed'] = 'yes'; - } - } - */ + //unsetto la variabile + unset($customer); + } + + /* + * disabled cause useless in segmentation + if ($parseSubscribers) { + if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) Mage::log('Parsing subscribers', 0); + $subscriberCollection = Mage::getModel('newsletter/subscriber') + ->getCollection() + ->useOnlySubscribed() + ->addFieldToFilter('customer_id', 0); + + foreach ($subscriberCollection as $subscriber) { + $subscriber = Mage::getModel('newsletter/subscriber')->load($subscriber->getId()); + $i = $subscriber->getEmail(); + if (strlen($i)) continue; + if (isset($toSend[$i])) continue; + $toSend[$i]['nome'] = ''; + $toSend[$i]['cognome'] = ''; + $toSend[$i]['email'] = $i; + $toSend[$i]['subscribed'] = 'yes'; + } + } + */ if($config->isLogEnabled()) { $config->log('End getting customers data'); } - - return $toSend; - } - + + return $toSend; + } + /** * Send Customer Data - * + * * @param array $mailupCustomerIds * @param array * @param int * @return int|FALSE ReturnCode */ - public static function generateAndSendCustomers($mailupCustomerIds, $post = null, $storeId = NULL) - { + public static function generateAndSendCustomers($mailupCustomerIds, $post = null, $storeId = NULL) + { $config = Mage::getModel('mailup/config'); /* @var $config MailUp_MailUpSync_Model_Config */ - - $wsSend = new MailUpWsSend($storeId); - require_once dirname(__FILE__) . "/../Model/MailUpWsImport.php"; - $wsImport = new MailUpWsImport($storeId); - $accessKey = $wsSend->loginFromId(); - if (empty($mailupCustomerIds)) { + $wsSend = new MailUpWsSend($storeId); + require_once dirname(__FILE__) . "/../Model/MailUpWsImport.php"; + $wsImport = new MailUpWsImport($storeId); + $accessKey = $wsSend->loginFromId(); + + if (empty($mailupCustomerIds)) { if($config->isLogEnabled($storeId)) { $config->log('generateAndSendCustomers [Empty Customer ID Array]'); } @@ -364,33 +364,33 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null $jobModel = Mage::getModel('mailup/job')->load($post['id']); /* @var $jobModel MailUp_MailUpSync_Model_Job */ - if ($accessKey === false) { - Mage::throwException('no access key returned'); - } + if ($accessKey === false) { + Mage::throwException('no access key returned'); + } - $fields_mapping = $wsImport->getFieldsMapping($storeId); // Pass StoreId + $fields_mapping = $wsImport->getFieldsMapping($storeId); // Pass StoreId if (count($fields_mapping) == 0) { if($config->isLogEnabled($storeId)) $config->log('No mappings set, so cannot sync customers'); return false; } - // Define the group we're adding customers to - $groupId = $post['mailupGroupId']; - $listGUID = $post['mailupListGUID']; - $idList = $post['mailupIdList']; + // Define the group we're adding customers to + $groupId = $post['mailupGroupId']; + $listGUID = $post['mailupListGUID']; + $idList = $post['mailupIdList']; /** * Create a new Mailup Group. */ - if ($post['mailupNewGroup'] == 1) { - $newGroup = array( - "idList" => $idList, - "listGUID" => $listGUID, - "newGroupName" => $post['mailupNewGroupName'] - ); - $groupId = $wsImport->CreaGruppo($newGroup); - } + if ($post['mailupNewGroup'] == 1) { + $newGroup = array( + "idList" => $idList, + "listGUID" => $listGUID, + "newGroupName" => $post['mailupNewGroupName'] + ); + $groupId = $wsImport->CreaGruppo($newGroup); + } // If message_id set, then pass this to define which message is sent to customers if (isset($post['message_id']) && $post['message_id'] !== null) { @@ -415,28 +415,28 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null "replaceGroups" => 0, "idConfirmNL" => $idConfirmNL ); - + $xmlData = ''; - $subscribers_counter = 0; - $totalCustomers = sizeof($mailupCustomerIds); - foreach ($mailupCustomerIds as $customerId) { - $subscribers_counter++; + $subscribers_counter = 0; + $totalCustomers = sizeof($mailupCustomerIds); + foreach ($mailupCustomerIds as $customerId) { + $subscribers_counter++; $xmlCurrentCust = self::_getCustomerXml($customerId, $fields_mapping, $storeId); if ($xmlCurrentCust !== false) $xmlData .= $xmlCurrentCust; - } - /** + } + /** * We have Valid Data to send */ - if(strlen($xmlData) > 0) { - $importProcessData["xmlDoc"] = "$xmlData"; - $xmlData = ""; - $subscribers_counter = 0; - if ($config->isLogEnabled($storeId)) { + if(strlen($xmlData) > 0) { + $importProcessData["xmlDoc"] = "$xmlData"; + $xmlData = ""; + $subscribers_counter = 0; + if ($config->isLogEnabled($storeId)) { Mage::log('ImportProcessData'); Mage::log($importProcessData, 0); } - $processID = $wsImport->newImportProcess($importProcessData); + $processID = $wsImport->newImportProcess($importProcessData); /** * Failure */ @@ -453,7 +453,7 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null $config->dbLog(sprintf("newImportProcess [SUCCESS] [ProcessID: %d]", $processID), $jobId, $storeId); $jobModel->setProcessId($processID); } - } + } /** * Build Data for StartImportProcesses */ @@ -472,11 +472,11 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null "idConfirmNL" => $idConfirmNL ); - if ($config->isLogEnabled($storeId)) { + if ($config->isLogEnabled($storeId)) { $config->log("mailup: StartImportProcesses (STORE: {$storeId})", $storeId); $config->log($startImportProcessesData); } - $startProcessesReturnCode = $wsImport->StartImportProcesses($startImportProcessesData); + $startProcessesReturnCode = $wsImport->StartImportProcesses($startImportProcessesData); /** * Save the Job Model, and update the tries as we've just tried to Start the Process */ @@ -487,31 +487,31 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null catch(Exception $e) { Mage::log($e->getMessage()); } - if ($config->isLogEnabled($storeId)) { + if ($config->isLogEnabled($storeId)) { if($startProcessesReturnCode < 0) { $config->dbLog(sprintf("StartImportProcesses [ReturnCode] [ERROR] [%d]", $startProcessesReturnCode), $jobId, $storeId); - } + } else { $config->dbLog(sprintf("StartImportProcesses [ReturnCode] [SUCCESS] [%d]", $startProcessesReturnCode), $jobId, $storeId); } } - - return (int) $startProcessesReturnCode; - } + + return (int) $startProcessesReturnCode; + } public function newImportProcess() { - + } - + public function startImportProcess() { - + } - + /** * Get a single customers XML data. - * + * * @param int $customerId * @param array $fields_mapping * @param int $storeId @@ -524,7 +524,7 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId $xmlData = ''; $mappedData = array(); $subscriber = self::getCustomersData(array($customerId)); - + if(is_array($subscriber) && empty($subscriber)) { if($config->isLogEnabled($storeId)) { $config->log('getCustomersData [EMPTY]'); @@ -547,12 +547,12 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId foreach($subscriber as $k => $v) { if ( ! strlen($subscriber[$k])) { $subscriber[$k] = ' '; // blank it out in mailup - } + } else { $subscriber[$k] = str_replace(array("\r\n", "\r", "\n"), " ", $v); } } - + /** * Map from Customer Data to Mailup Fields. */ @@ -593,7 +593,7 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId $code = $attribute->getAttributeCode() . '_custom_customer_attributes'; $mappings[$code] = $code; } - + foreach($mappings as $mapTo => $mapFrom) { if (isset($fields_mapping[$mapTo]) && !empty($fields_mapping[$mapTo])) { $mappedData[$fields_mapping[$mapTo]] = ''. "". ''; @@ -607,7 +607,7 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId return false; } $last_field = max(array_keys($mappedData)); - + for($i=1; $i < $last_field; $i++) { if( ! isset($mappedData[$i]) && ! empty($i)) { /** @@ -617,7 +617,7 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId $mappedData[$i] = "" ." ". ""; } } - + ksort($mappedData); $custDataStr = implode("", $mappedData); /** All field values are handled as strings, character '|' (pipe) is not allowed and may lead to "-402" error codes **/ @@ -628,14 +628,14 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId /** * @todo REMOVE */ - $config->log($xmlData); - + $config->log($xmlData); + return $xmlData; } - + /** * Run a particular job - * + * * @param int */ public function runJob($jobId) @@ -652,18 +652,18 @@ public function runJob($jobId) $customer_entity_table_name = Mage::getSingleton('core/resource')->getTableName('customer_entity'); $jobModel = Mage::getModel('mailup/job')->load($jobId); /* @var $jobModel MailUp_MailUpSync_Model_Job */ - + if( ! $jobModel) { throw new Mage_Exception('No Job Exists: ' . $jobId); } - + $job = $jobModel->getData(); $stmt = $db_write->query( "UPDATE {$jobsTableName} SET status='started', start_datetime='" . gmdate("Y-m-d H:i:s") . "' WHERE id={$job["id"]}" ); - $storeId = isset($job['store_id']) ? $job['store_id'] : NULL; + $storeId = isset($job['store_id']) ? $job['store_id'] : NULL; //$storeId = Mage::app()->getDefaultStoreView()->getStoreId(); // Fallback incase not set?!? $customers = array(); $job['mailupNewGroup'] = 0; @@ -686,7 +686,7 @@ public function runJob($jobId) break; } } - unset($tmp); + unset($tmp); unset($t); $stmt = $db_read->query(" SELECT ms.*, ce.email @@ -734,10 +734,10 @@ public function runJob($jobId) } } } - + /** * Get sub Categories of a Category - * + * * @param int * @return array|string */ @@ -746,13 +746,13 @@ public function getSubCategories($categoryId) // Not sure what version this was introduced. $parent = Mage::getModel('catalog/category')->load($categoryId); $children = $parent->getAllChildren(TRUE); - + if( ! empty($children) && is_array($children)) { return $children; } - + return array(); - + // // Maybe fall back to this in older versions? // $ids = array(); // $children = Mage::getModel('catalog/category')->getCategories($categoryId); @@ -763,117 +763,117 @@ public function getSubCategories($categoryId) // // return $ids; } - + /** * Format the Price - * + * * @param float * @return string */ - private static function _formatPrice($price) + private static function _formatPrice($price) { - return number_format($price, 2, ',', ''); - } + return number_format($price, 2, ',', ''); + } /** * Get Date from DateTime - * + * * @param type $datetime * @return string */ - private static function _retriveDateFromDatetime($datetime) + private static function _retriveDateFromDatetime($datetime) { - if (empty($datetime)) return ""; - return date("Y-m-d H:i:s", strtotime($datetime)); - } - + if (empty($datetime)) return ""; + return date("Y-m-d H:i:s", strtotime($datetime)); + } + /** * Get DOB Format from DateTime - * + * * @param string $datetime * @return string */ - private static function _retriveDobFromDatetime($datetime) + private static function _retriveDobFromDatetime($datetime) { - if (empty($datetime)) { + if (empty($datetime)) { return ""; } - return date("d/m/Y", strtotime($datetime)); - } - - public static function _convertUTCToStoreTimezone($datetime) - { - if (empty($datetime)) return ""; - - $TIMEZONE_STORE = new DateTimeZone(Mage::getStoreConfig("general/locale/timezone")); - $TIMEZONE_UTC = new DateTimeZone("UTC"); - - $datetime = new DateTime($datetime, $TIMEZONE_UTC); - $datetime->setTimezone($TIMEZONE_STORE); - $datetime = (string)$datetime->format("Y-m-d H:i:s"); - - return $datetime; - } - - public static function _convertUTCToStoreTimezoneAndFormatForMailup($datetime) - { - if (empty($datetime)) return ""; - $datetime = self::_convertUTCToStoreTimezone($datetime); - return date("d/m/Y", strtotime($datetime)); - } - + return date("d/m/Y", strtotime($datetime)); + } + + public static function _convertUTCToStoreTimezone($datetime) + { + if (empty($datetime)) return ""; + + $TIMEZONE_STORE = new DateTimeZone(Mage::getStoreConfig("general/locale/timezone")); + $TIMEZONE_UTC = new DateTimeZone("UTC"); + + $datetime = new DateTime($datetime, $TIMEZONE_UTC); + $datetime->setTimezone($TIMEZONE_STORE); + $datetime = (string)$datetime->format("Y-m-d H:i:s"); + + return $datetime; + } + + public static function _convertUTCToStoreTimezoneAndFormatForMailup($datetime) + { + if (empty($datetime)) return ""; + $datetime = self::_convertUTCToStoreTimezone($datetime); + return date("d/m/Y", strtotime($datetime)); + } + /** * Clean the Resource Table - * + * * @return void */ public function cleanResourceTable() { $sql = "DELETE FROM `core_resource` WHERE `code` = 'mailup_setup';"; - $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); + $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); try { $connection->query($sql); die('deleted module in core_resource!'); - } + } catch(Exception $e){ Mage::log($e->getMessage()); } } - + /** * Clean the Resource Table - * + * * @return void */ public function showResourceTable() { $sql = "SELECT * FROM `core_resource`"; - $connection = Mage::getSingleton('core/resource')->getConnection('core_read'); + $connection = Mage::getSingleton('core/resource')->getConnection('core_read'); try { $result = $connection->fetchAll($sql); foreach($result as $row) { echo $row['code'] . "
"; } - } + } catch(Exception $e){ echo $e->getMessage(); } } - + /** * Get all product attributes - * + * * Note if we don't use a keyed array below the first item with key 0 * gets replaced by an empty option by magento. this results in a missing attribute * from the list! - * + * * @reutrn array */ public function getAllProductAttributes() { //$attributes = Mage::getModel('catalog/product')->getAttributes(); $attributes = Mage::getSingleton('eav/config') - ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection() + ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection() ; // Localize attribute label (if you need it) $attributes->addStoreLabel(Mage::app()->getStore()->getId()); @@ -887,23 +887,23 @@ public function getAllProductAttributes() ); } } - return $attributeArray; + return $attributeArray; } - + /** * Get all product attributes - * + * * Note if we don't use a keyed array below the first item with key 0 * gets replaced by an empty option by magento. this results in a missing attribute * from the list! - * + * * @reutrn array */ public function getAllCustomerAttributes() { //$attributes = Mage::getModel('catalog/product')->getAttributes(); $attributes = Mage::getSingleton('eav/config') - ->getEntityType('customer')->getAttributeCollection() + ->getEntityType('customer')->getAttributeCollection() ; // Localize attribute label (if you need it) $attributes->addStoreLabel(Mage::app()->getStore()->getId()); @@ -917,12 +917,12 @@ public function getAllCustomerAttributes() ); } } - return $attributeArray; + return $attributeArray; } - + /** * Is someone a subscriber? - * + * * @param int * @param int * @return bool @@ -988,10 +988,10 @@ protected function _isSubscriberInStatus($customerId, array $statuses, $storeId) return false; } - + /** * Schedule a Task - * + * * @param string * @param string */ @@ -1005,7 +1005,7 @@ public function scheduleTask($when, $type = 'MailUp_MailUpSync') "scheduled_at" => $when )); } - + /** * Retrieve Attribute Id Data By Id or Code * @@ -1018,7 +1018,7 @@ public function getAttributeId($id, $entityTypeId = NULL) if($entityTypeId == NULL) { $entityTypeId = Mage::getModel('catalog/product')->getResource()->getEntityType()->getId(); } - + $installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup'); if ( ! is_numeric($id)) { $id = $installer->getAttribute($entityTypeId, $id, 'attribute_id'); @@ -1027,7 +1027,7 @@ public function getAttributeId($id, $entityTypeId = NULL) //throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Wrong attribute ID.')); return FALSE; } - + return $id; } @@ -1174,30 +1174,33 @@ public function testConfig() */ protected function _testConnectionConsole($urlConsole) { - // Set endpoint of API - $ws = "http://{$urlConsole}/frontend/Xmlchksubscriber.aspx"; - - // Add parameters to request - $ws .= "?ListGuid=" . rawurlencode('e347gh87347gh374hg34'); - $ws .= "&List=" . rawurlencode(1); - $ws .= "&Email=" . rawurlencode('logintest@test.com'); - - // Make request - $result = ''; - try { - if(Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) { - Mage::log("Testing Connection - console: $ws"); - } - $result = @file_get_contents($ws); - if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) { - Mage::log("Testing Connection - console: $result"); + if (Mage::getStoreConfig('mailup_newsletter/mailup/skip_check') == false) { + // Set endpoint of API + $ws = "http://{$urlConsole}/frontend/Xmlchksubscriber.aspx"; + + // Add parameters to request + $ws .= "?ListGuid=".rawurlencode('e347gh87347gh374hg34'); + $ws .= "&List=".rawurlencode(1); + $ws .= "&Email=".rawurlencode('logintest@test.com'); + + // Make request + $result = ''; + try { + if(Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) { + Mage::log("Testing Connection - console: $ws"); + } + $result = @file_get_contents($ws); + if(Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) { + Mage::log("Testing Connection - console: $result"); + } + } catch(Exception $e) { + Mage::logException($e); } - } catch (Exception $e) { - Mage::logException($e); - } - // Test that request returns 1 (with an allowance for whitespace) - return (preg_match('/^1\s*$/', $result) == 1); + // Test that request returns 1 (with an allowance for whitespace) + return (preg_match('/^1\s*$/', $result) == 1); + } + return true; } /** diff --git a/src/app/code/local/MailUp/MailUpSync/etc/system.xml b/src/app/code/local/MailUp/MailUpSync/etc/system.xml index ba17ae9..7143ff3 100644 --- a/src/app/code/local/MailUp/MailUpSync/etc/system.xml +++ b/src/app/code/local/MailUp/MailUpSync/etc/system.xml @@ -1,7 +1,7 @@ - - + + @@ -9,7 +9,7 @@ 300 - + mailup-tab @@ -40,7 +40,7 @@ 1 1 It's the domain portion of the URL to your MailUp Admin console (e.g. g4a0.s03.it) - mailup/adminhtml_system_config_consoleurlvalidator + mailup/adminhtml_system_config_consoleurlvalidator @@ -49,7 +49,7 @@ 1 1 1 - mailup/adminhtml_system_config_webserviceusernamevalidator + mailup/adminhtml_system_config_webserviceusernamevalidator @@ -61,6 +61,16 @@ mailup/adminhtml_system_config_webservicepwdvalidator For assistance visit http://help.mailup.com/x/PgAy + + + select + adminhtml/system_config_source_yesno + 41 + 1 + 1 + 1 + Attention! Use only temporarily if you receive 'Error in console URL' but your MailUp console works normally.]]> + button @@ -89,15 +99,15 @@ 1 Used as default group in all subscriptions that do not have a manual group set - - - select - adminhtml/system_config_source_yesno - 70 + + + select + adminhtml/system_config_source_yesno + 70 1 1 1 - + select @@ -202,7 +212,7 @@ 1 1 1 - mailup/adminhtml_system_source_fields + mailup/adminhtml_system_source_fields @@ -212,7 +222,7 @@ 1 1 - mailup/adminhtml_system_source_fields + mailup/adminhtml_system_source_fields @@ -221,7 +231,7 @@ 1 1 1 - mailup/adminhtml_system_source_fields + mailup/adminhtml_system_source_fields @@ -230,7 +240,7 @@ 1 1 1 - mailup/adminhtml_system_source_fields + mailup/adminhtml_system_source_fields
@@ -239,7 +249,7 @@ 1 1 1 - mailup/adminhtml_system_source_fields + mailup/adminhtml_system_source_fields
From 56f07d681f88596494a63d9b5d7509ff5dac3c22 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Mon, 7 Aug 2017 10:01:33 +0200 Subject: [PATCH 6/9] [dev] changelog and readme - upgrade version - update changelog - update readme --- CHANGELOG.md | 4 ++++ README.md | 11 ++++++----- composer.json | 3 ++- src/app/code/local/MailUp/MailUpSync/etc/config.xml | 2 +- 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d86274d..7e518e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ CHANGELOG ========= +- [fix] admin config | close save config only to mailup section +- [fix] admin config | refactoring field check +- [dev] admin config | add skip test console url option + ## 2.7.5 - 10/07/2017 - [dev] ip filter | send client ip for spam checking - [fix] SUPEE-6788 | Fix adminhtml url diff --git a/README.md b/README.md index 4ff8d3c..2026561 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,19 @@ Official Magento 1 CE Extension.
MailUp is your complete email delivery solution. It combines strong campaign management features (multi-list platform, advanced segmentation, dynamic content, A/B testing, detailed statistics, etc.) with automated messaging and a free SMTP relay service. It uses an innovative, flat-rate pricing policy that provides great flexibility and guarantees substantial savings over competing solutions. ## Stable version -2.7.5 +2.7.6 ## Magento version - (tested) - CE 1.6.x - CE 1.7.x - CE 1.8.x - CE 1.9.x (last version tested 1.9.3.3) +## PHP Version +We only support php >=5.5.x +Actually we don't support php 7 + ## Install via - composer - modman @@ -22,7 +25,6 @@ MailUp is your complete email delivery solution. It combines strong campaign man mailup/magento ## Contributing - Any contribution to the development is welcome. The best possibility to provide any code is to open a [pull request on GitHub](https://help.github.com/articles/using-pull-requests).
You can also open an issue to advice any kind of error. @@ -30,5 +32,4 @@ You can also open an issue to advice any kind of error. --- ### Privacy Policy - -Please look at *privacy_policy.md* \ No newline at end of file +Please look at [privacy_policy.md](privacy_policy.md) \ No newline at end of file diff --git a/composer.json b/composer.json index 52b31a4..4cf72e3 100644 --- a/composer.json +++ b/composer.json @@ -19,6 +19,7 @@ } ], "require": { - "magento-hackathon/magento-composer-installer": "*" + "magento-hackathon/magento-composer-installer": "*", + "php": ">=5.5.0" } } \ No newline at end of file diff --git a/src/app/code/local/MailUp/MailUpSync/etc/config.xml b/src/app/code/local/MailUp/MailUpSync/etc/config.xml index e2ff3c9..e0bae84 100644 --- a/src/app/code/local/MailUp/MailUpSync/etc/config.xml +++ b/src/app/code/local/MailUp/MailUpSync/etc/config.xml @@ -2,7 +2,7 @@ - 2.7.5 + 2.7.6 From 80b6e4a148696ba6a8a7d30d7db018c63932e167 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Mon, 7 Aug 2017 10:07:03 +0200 Subject: [PATCH 7/9] polish --- .../local/MailUp/MailUpSync/Helper/Data.php | 612 +++++++++--------- 1 file changed, 313 insertions(+), 299 deletions(-) diff --git a/src/app/code/local/MailUp/MailUpSync/Helper/Data.php b/src/app/code/local/MailUp/MailUpSync/Helper/Data.php index cedc89d..2126120 100644 --- a/src/app/code/local/MailUp/MailUpSync/Helper/Data.php +++ b/src/app/code/local/MailUp/MailUpSync/Helper/Data.php @@ -1,7 +1,7 @@ isLogEnabled()) { + if($config->isLogEnabled()) { $config->log('Getting customers data'); } if(is_array($customerCollection) && empty($customerCollection)) { - if ($config->isLogEnabled()) { + if($config->isLogEnabled()) { $config->log('CustomerCollection is Empty!'); } } - $dateFormat = 'm/d/y h:i:s'; - $lastDateTime = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-7*3600*24); - $thirtyDaysAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-30*3600*24); - $twelveMonthsAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-365*3600*24); + $dateFormat = 'm/d/y h:i:s'; + $lastDateTime = date($dateFormat, Mage::getModel('core/date')->timestamp(time()) - 7 * 3600 * 24); + $thirtyDaysAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time()) - 30 * 3600 * 24); + $twelveMonthsAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time()) - 365 * 3600 * 24); $parseSubscribers = false; - $toSend = array(); - if ($customerCollection === null) { + $toSend = array(); + if($customerCollection === null) { /** * @todo Change to only load form current store/website */ $customerCollection = Mage::getModel('customer/customer')->getCollection(); - $parseSubscribers = true; - if ($config->isLogEnabled()) { + $parseSubscribers = true; + if($config->isLogEnabled()) { $config->log('Parsing Subscribers, NULL collection passed.'); } } - foreach ($customerCollection as $currentCustomerId) { - if (is_object($currentCustomerId)) { + foreach($customerCollection as $currentCustomerId) { + if(is_object($currentCustomerId)) { $currentCustomerId = $currentCustomerId->getId(); } - if( ! $currentCustomerId) { + if(!$currentCustomerId) { if($config->isLogEnabled()) { $config->log('Skipping Empty Customer ID!'); continue; } } - if ($config->isLogEnabled()) { + if($config->isLogEnabled()) { $config->log('Customer with id '.$currentCustomerId); } $customer = Mage::getModel('customer/customer')->load($currentCustomerId); @@ -92,17 +93,17 @@ public static function getCustomersData($customerCollection = null) // Get order dates, numbers and totals for the current customer //TODO: This would be more efficient with just a few SQL statements to gather this - $allOrdersTotalAmount = 0; - $allOrdersDateTimes = array(); - $allOrdersTotals = array(); - $allOrdersIds = array(); - $allProductsIds = array(); - $last30daysOrdersAmount = 0; + $allOrdersTotalAmount = 0; + $allOrdersDateTimes = array(); + $allOrdersTotals = array(); + $allOrdersIds = array(); + $allProductsIds = array(); + $last30daysOrdersAmount = 0; $last12monthsOrdersAmount = 0; - $lastShipmentOrderId = null; - $lastShipmentOrderDate = null; + $lastShipmentOrderId = null; + $lastShipmentOrderDate = null; - if ($config->isLogEnabled()) { + if($config->isLogEnabled()) { $config->log('Parsing orders of customer with id '.$currentCustomerId); } // Setup collection to fetch orders for this customer and valid statuses @@ -110,43 +111,43 @@ public static function getCustomersData($customerCollection = null) ->addAttributeToFilter('customer_id', $currentCustomerId); Mage::helper('mailup/order')->addStatusFilterToOrders($orders); - foreach ($orders as $order) { - if ($config->isLogEnabled()) { + foreach($orders as $order) { + if($config->isLogEnabled()) { $config->log("ORDER STATUS: {$order->getState()} / {$order->getStatus()}"); } // Get current and total orders - $currentOrderTotal = floatval($order->getGrandTotal()); + $currentOrderTotal = floatval($order->getGrandTotal()); $allOrdersTotalAmount += $currentOrderTotal; $currentOrderCreationDate = $order->getCreatedAt(); - if ($currentOrderCreationDate > $thirtyDaysAgo) { + if($currentOrderCreationDate > $thirtyDaysAgo) { $last30daysOrdersAmount += $currentOrderTotal; } - if ($currentOrderCreationDate > $twelveMonthsAgo) { + if($currentOrderCreationDate > $twelveMonthsAgo) { $last12monthsOrdersAmount += $currentOrderTotal; } - $currentOrderTotal = self::_formatPrice($currentOrderTotal); - $currentOrderId = $order->getIncrementId(); - $allOrdersTotals[$currentOrderId] = $currentOrderTotal; + $currentOrderTotal = self::_formatPrice($currentOrderTotal); + $currentOrderId = $order->getIncrementId(); + $allOrdersTotals[$currentOrderId] = $currentOrderTotal; $allOrdersDateTimes[$currentOrderId] = $currentOrderCreationDate; - $allOrdersIds[$currentOrderId] = $currentOrderId; + $allOrdersIds[$currentOrderId] = $currentOrderId; - if ($order->hasShipments() and ($order->getId()>$lastShipmentOrderId)) { - $lastShipmentOrderId = $order->getId(); + if($order->hasShipments() and ($order->getId() > $lastShipmentOrderId)) { + $lastShipmentOrderId = $order->getId(); $lastShipmentOrderDate = self::_retriveDateFromDatetime($order->getCreatedAt()); } $items = $order->getAllItems(); - foreach ($items as $item) { + foreach($items as $item) { $allProductsIds[] = $item->getProductId(); } } - $toSend[$i]['TotaleFatturatoUltimi30gg'] = self::_formatPrice($last30daysOrdersAmount); + $toSend[$i]['TotaleFatturatoUltimi30gg'] = self::_formatPrice($last30daysOrdersAmount); $toSend[$i]['TotaleFatturatoUltimi12Mesi'] = self::_formatPrice($last12monthsOrdersAmount); - $toSend[$i]['IDTuttiProdottiAcquistati'] = implode(',', $allProductsIds); + $toSend[$i]['IDTuttiProdottiAcquistati'] = implode(',', $allProductsIds); ksort($allOrdersDateTimes); ksort($allOrdersTotals); @@ -162,64 +163,62 @@ public static function getCustomersData($customerCollection = null) $cartCollection->load(); $datetimeCart = null; - if ( ! empty($cartCollection)) { - $lastCart = $cartCollection->getLastItem(); + if(!empty($cartCollection)) { + $lastCart = $cartCollection->getLastItem(); $toSend[$i]['TotaleCarrelloAbbandonato'] = ''; - $toSend[$i]['DataCarrelloAbbandonato'] = ''; - $toSend[$i]['IDCarrelloAbbandonato'] = ''; + $toSend[$i]['DataCarrelloAbbandonato'] = ''; + $toSend[$i]['IDCarrelloAbbandonato'] = ''; - if ( ! empty($lastCart)) { - if ($config->isLogEnabled()) { - $config->log('Customer with id '.$currentCustomerId .' has abandoned cart'); + if(!empty($lastCart)) { + if($config->isLogEnabled()) { + $config->log('Customer with id '.$currentCustomerId.' has abandoned cart'); } $datetimeCart = $lastCart->getUpdatedAt(); //$toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getGrandTotal()); $toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getSubtotal()); - $toSend[$i]['DataCarrelloAbbandonato'] = self::_retriveDateFromDatetime($datetimeCart); - $toSend[$i]['IDCarrelloAbbandonato'] = $lastCart->getId(); - } - else { - if ($config->isLogEnabled()) { - $config->log('Customer with id '.$currentCustomerId .' has empty LAST CART'); + $toSend[$i]['DataCarrelloAbbandonato'] = self::_retriveDateFromDatetime($datetimeCart); + $toSend[$i]['IDCarrelloAbbandonato'] = $lastCart->getId(); + } else { + if($config->isLogEnabled()) { + $config->log('Customer with id '.$currentCustomerId.' has empty LAST CART'); } } - } - else { - if ($config->isLogEnabled()) { - $config->log('Customer id '.$currentCustomerId .' has empty abandoned cart collection'); + } else { + if($config->isLogEnabled()) { + $config->log('Customer id '.$currentCustomerId.' has empty abandoned cart collection'); } } - $toSend[$i]['IDUltimoOrdineSpedito'] = $lastShipmentOrderId; + $toSend[$i]['IDUltimoOrdineSpedito'] = $lastShipmentOrderId; $toSend[$i]['DataUltimoOrdineSpedito'] = $lastShipmentOrderDate; $lastOrderDateTime = end($allOrdersDateTimes); - if ($customer->getUpdatedAt() > $lastDateTime + if($customer->getUpdatedAt() > $lastDateTime || $lastOrderDateTime > $lastDateTime - || ($datetimeCart && $datetimeCart > $lastDateTime)) - { - if ($config->isLogEnabled()) { + || ($datetimeCart && $datetimeCart > $lastDateTime) + ) { + if($config->isLogEnabled()) { $config->log('Adding customer with id '.$currentCustomerId); } - $toSend[$i]['nome'] = $customer->getFirstname(); - $toSend[$i]['cognome'] = $customer->getLastname(); - $toSend[$i]['email'] = $customer->getEmail(); + $toSend[$i]['nome'] = $customer->getFirstname(); + $toSend[$i]['cognome'] = $customer->getLastname(); + $toSend[$i]['email'] = $customer->getEmail(); $toSend[$i]['IDCliente'] = $currentCustomerId; // Custom customer attributes $customerAttributes = Mage::helper('mailup/customer')->getCustomCustomerAttrCollection(); - foreach ($customerAttributes as $attribute) { - $code = $attribute->getAttributeCode() . '_custom_customer_attributes'; + foreach($customerAttributes as $attribute) { + $code = $attribute->getAttributeCode().'_custom_customer_attributes'; $value = $customer->getData($attribute->getAttributeCode()); - if ($attribute->usesSource()) { + if($attribute->usesSource()) { /* Attempt to get source model. As we cannot trust customers to have not leave broken attributes with invalid source models around, we will test this directly */ $source = Mage::getModel($attribute->getSourceModel()); - if ($source == false) { - if ($config->isLogEnabled()) { - $config->log('Invalid source model for attribute ' . $attribute->getAttributeCode()); + if($source == false) { + if($config->isLogEnabled()) { + $config->log('Invalid source model for attribute '.$attribute->getAttributeCode()); } $toSend[$i][$code] = null; } else { @@ -233,74 +232,73 @@ public static function getCustomersData($customerCollection = null) $toSend[$i]['registeredDate'] = self::_retriveDateFromDatetime($customer->getCreatedAt()); //controllo se iscritto o meno alla newsletter - if (Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->isSubscribed()) { + if(Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->isSubscribed()) { $toSend[$i]['subscribed'] = 'yes'; - } - else { + } else { $toSend[$i]['subscribed'] = 'no'; } //recupero i dati dal default billing address $customerAddressId = $customer->getDefaultBilling(); - if ($customerAddressId) { - $address = Mage::getModel('customer/address')->load($customerAddressId); - $toSend[$i]['azienda'] = $address->getData('company'); - $toSend[$i]['paese'] = $address->getCountry(); - $toSend[$i]['città'] = $address->getData('city'); - $toSend[$i]['regione'] = $address->getData('region'); - $regionId = $address->getData('region_id'); - $regionModel = Mage::getModel('directory/region')->load($regionId); - $regionCode = $regionModel->getCode(); + if($customerAddressId) { + $address = Mage::getModel('customer/address')->load($customerAddressId); + $toSend[$i]['azienda'] = $address->getData('company'); + $toSend[$i]['paese'] = $address->getCountry(); + $toSend[$i]['città'] = $address->getData('city'); + $toSend[$i]['regione'] = $address->getData('region'); + $regionId = $address->getData('region_id'); + $regionModel = Mage::getModel('directory/region')->load($regionId); + $regionCode = $regionModel->getCode(); $toSend[$i]['provincia'] = $regionCode; - $toSend[$i]['cap'] = $address->getData('postcode'); + $toSend[$i]['cap'] = $address->getData('postcode'); $toSend[$i]['indirizzo'] = $address->getData('street'); - $toSend[$i]['fax'] = $address->getData('fax'); - $toSend[$i]['telefono'] = $address->getData('telephone'); - } - else { - $toSend[$i]['azienda'] = ''; - $toSend[$i]['paese'] = ''; - $toSend[$i]['città'] = ''; - $toSend[$i]['regione'] = ''; + $toSend[$i]['fax'] = $address->getData('fax'); + $toSend[$i]['telefono'] = $address->getData('telephone'); + } else { + $toSend[$i]['azienda'] = ''; + $toSend[$i]['paese'] = ''; + $toSend[$i]['città'] = ''; + $toSend[$i]['regione'] = ''; $toSend[$i]['provincia'] = ''; - $toSend[$i]['cap'] = ''; + $toSend[$i]['cap'] = ''; $toSend[$i]['indirizzo'] = ''; - $toSend[$i]['fax'] = ''; - $toSend[$i]['telefono'] = ''; + $toSend[$i]['fax'] = ''; + $toSend[$i]['telefono'] = ''; } - $toSend[$i]['DataUltimoOrdine'] = self::_retriveDateFromDatetime($lastOrderDateTime); + $toSend[$i]['DataUltimoOrdine'] = self::_retriveDateFromDatetime($lastOrderDateTime); $toSend[$i]['TotaleUltimoOrdine'] = end($allOrdersTotals); - $toSend[$i]['IDUltimoOrdine'] = end($allOrdersIds); + $toSend[$i]['IDUltimoOrdine'] = end($allOrdersIds); $toSend[$i]['TotaleFatturato'] = self::_formatPrice($allOrdersTotalAmount); //ottengo gli id di prodotti e categorie (dell'ultimo ordine) - $lastOrder = Mage::getModel('sales/order')->loadByIncrementId(end($allOrdersIds)); - $items = $lastOrder->getAllItems(); - $productIds = array(); + $lastOrder = Mage::getModel('sales/order')->loadByIncrementId(end($allOrdersIds)); + $items = $lastOrder->getAllItems(); + $productIds = array(); $categoryIds = array(); - foreach ($items as $item) { - $productId = $item->getProductId(); + foreach($items as $item) { + $productId = $item->getProductId(); $productIds[] = $productId; - $product = Mage::getModel('catalog/product')->load($productId); - if ($product->getCategoryIds()) { + $product = Mage::getModel('catalog/product')->load($productId); + if($product->getCategoryIds()) { $categoryIds[] = implode(',', $product->getCategoryIds()); } } $toSend[$i]['IDProdottiUltimoOrdine'] = implode(',', $productIds); - if ($toSend[$i]['IDProdottiUltimoOrdine']) { + if($toSend[$i]['IDProdottiUltimoOrdine']) { $toSend[$i]['IDProdottiUltimoOrdine'] = ",{$toSend[$i]['IDProdottiUltimoOrdine']},"; } $toSend[$i]['IDCategorieUltimoOrdine'] = implode(',', $categoryIds); - if ($toSend[$i]['IDCategorieUltimoOrdine']) { + if($toSend[$i]['IDCategorieUltimoOrdine']) { $toSend[$i]['IDCategorieUltimoOrdine'] = ",{$toSend[$i]['IDCategorieUltimoOrdine']},"; } } $toSend[$i]['DateOfBirth'] = self::_retriveDobFromDatetime($customer->getDob()); - $toSend[$i]['Gender'] = $customer->getAttribute('gender')->getSource()->getOptionText($customer->getGender()); + $toSend[$i]['Gender'] = $customer->getAttribute('gender')->getSource() + ->getOptionText($customer->getGender()); //unsetto la variabile unset($customer); @@ -339,61 +337,64 @@ public static function getCustomersData($customerCollection = null) * Send Customer Data * * @param array $mailupCustomerIds - * @param array - * @param int + * @param array + * @param int + * * @return int|FALSE ReturnCode */ - public static function generateAndSendCustomers($mailupCustomerIds, $post = null, $storeId = NULL) + public static function generateAndSendCustomers($mailupCustomerIds, $post = null, $storeId = null) { $config = Mage::getModel('mailup/config'); /* @var $config MailUp_MailUpSync_Model_Config */ $wsSend = new MailUpWsSend($storeId); - require_once dirname(__FILE__) . "/../Model/MailUpWsImport.php"; - $wsImport = new MailUpWsImport($storeId); + require_once dirname(__FILE__)."/../Model/MailUpWsImport.php"; + $wsImport = new MailUpWsImport($storeId); $accessKey = $wsSend->loginFromId(); - if (empty($mailupCustomerIds)) { + if(empty($mailupCustomerIds)) { if($config->isLogEnabled($storeId)) { $config->log('generateAndSendCustomers [Empty Customer ID Array]'); } + return false; } - $jobId = $post['id']; + $jobId = $post['id']; $jobModel = Mage::getModel('mailup/job')->load($post['id']); /* @var $jobModel MailUp_MailUpSync_Model_Job */ - if ($accessKey === false) { + if($accessKey === false) { Mage::throwException('no access key returned'); } $fields_mapping = $wsImport->getFieldsMapping($storeId); // Pass StoreId - if (count($fields_mapping) == 0) { + if(count($fields_mapping) == 0) { if($config->isLogEnabled($storeId)) $config->log('No mappings set, so cannot sync customers'); + return false; } // Define the group we're adding customers to - $groupId = $post['mailupGroupId']; + $groupId = $post['mailupGroupId']; $listGUID = $post['mailupListGUID']; - $idList = $post['mailupIdList']; + $idList = $post['mailupIdList']; /** * Create a new Mailup Group. */ - if ($post['mailupNewGroup'] == 1) { + if($post['mailupNewGroup'] == 1) { $newGroup = array( - "idList" => $idList, - "listGUID" => $listGUID, - "newGroupName" => $post['mailupNewGroupName'] + "idList" => $idList, + "listGUID" => $listGUID, + "newGroupName" => $post['mailupNewGroupName'] ); - $groupId = $wsImport->CreaGruppo($newGroup); + $groupId = $wsImport->CreaGruppo($newGroup); } // If message_id set, then pass this to define which message is sent to customers - if (isset($post['message_id']) && $post['message_id'] !== null) { + if(isset($post['message_id']) && $post['message_id'] !== null) { $idConfirmNL = $post['message_id']; } else { // Default to 0 (ignored) @@ -401,28 +402,28 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null } $importProcessData = array( - "idList" => $idList, - "listGUID" => $listGUID, - "idGroup" => $groupId, - "xmlDoc" => "", - "idGroups" => $groupId, - "importType" => self::IMPORT_TYPE_REPLACE_EMPTY_ONLY_EMAIL, + "idList" => $idList, + "listGUID" => $listGUID, + "idGroup" => $groupId, + "xmlDoc" => "", + "idGroups" => $groupId, + "importType" => self::IMPORT_TYPE_REPLACE_EMPTY_ONLY_EMAIL, "mobileInputType" => self::MOBILE_INPUT_TYPE_SPLIT_INTL_CODE, - "asPending" => $jobModel->getAsPending() ? 1 : 0, - "ConfirmEmail" => $jobModel->getSendOptin() ? 1 : 0, - "asOptOut" => 0, - "forceOptIn" => 0, // Dangerous to use as this can over-write pending/un-subscribe statuses - "replaceGroups" => 0, - "idConfirmNL" => $idConfirmNL + "asPending" => $jobModel->getAsPending() ? 1 : 0, + "ConfirmEmail" => $jobModel->getSendOptin() ? 1 : 0, + "asOptOut" => 0, + "forceOptIn" => 0, // Dangerous to use as this can over-write pending/un-subscribe statuses + "replaceGroups" => 0, + "idConfirmNL" => $idConfirmNL ); - $xmlData = ''; + $xmlData = ''; $subscribers_counter = 0; - $totalCustomers = sizeof($mailupCustomerIds); - foreach ($mailupCustomerIds as $customerId) { + $totalCustomers = sizeof($mailupCustomerIds); + foreach($mailupCustomerIds as $customerId) { $subscribers_counter++; $xmlCurrentCust = self::_getCustomerXml($customerId, $fields_mapping, $storeId); - if ($xmlCurrentCust !== false) + if($xmlCurrentCust !== false) $xmlData .= $xmlCurrentCust; } /** @@ -430,9 +431,9 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null */ if(strlen($xmlData) > 0) { $importProcessData["xmlDoc"] = "$xmlData"; - $xmlData = ""; - $subscribers_counter = 0; - if ($config->isLogEnabled($storeId)) { + $xmlData = ""; + $subscribers_counter = 0; + if($config->isLogEnabled($storeId)) { Mage::log('ImportProcessData'); Mage::log($importProcessData, 0); } @@ -440,13 +441,13 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null /** * Failure */ - if($processID === FALSE || $processID < 0) { + if($processID === false || $processID < 0) { if($config->isLogEnabled($storeId)) { $config->dbLog(sprintf('newImportProcess [ERROR] [%d]', $processID), $jobId, $storeId); } + return $processID; - } - /** + } /** * Success */ else { @@ -458,21 +459,21 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null * Build Data for StartImportProcesses */ $startImportProcessesData = array( - 'listsIDs' => $post['mailupIdList'], - 'listsGUIDs' => $post['mailupListGUID'], - 'groupsIDs' => $groupId, - "idList" => $idList, - "importType" => self::IMPORT_TYPE_REPLACE_EMPTY_ONLY_EMAIL, + 'listsIDs' => $post['mailupIdList'], + 'listsGUIDs' => $post['mailupListGUID'], + 'groupsIDs' => $groupId, + "idList" => $idList, + "importType" => self::IMPORT_TYPE_REPLACE_EMPTY_ONLY_EMAIL, "mobileInputType" => self::MOBILE_INPUT_TYPE_SPLIT_INTL_CODE, - "asPending" => $jobModel->getAsPending() ? 1 : 0, - "ConfirmEmail" => $jobModel->getSendOptin() ? 1 : 0, - "asOptOut" => 0, - "forceOptIn" => 0, // Dangerous to use as this can over-write pending/un-subscribe statuses - "replaceGroups" => 0, - "idConfirmNL" => $idConfirmNL + "asPending" => $jobModel->getAsPending() ? 1 : 0, + "ConfirmEmail" => $jobModel->getSendOptin() ? 1 : 0, + "asOptOut" => 0, + "forceOptIn" => 0, // Dangerous to use as this can over-write pending/un-subscribe statuses + "replaceGroups" => 0, + "idConfirmNL" => $idConfirmNL ); - if ($config->isLogEnabled($storeId)) { + if($config->isLogEnabled($storeId)) { $config->log("mailup: StartImportProcesses (STORE: {$storeId})", $storeId); $config->log($startImportProcessesData); } @@ -483,20 +484,18 @@ public static function generateAndSendCustomers($mailupCustomerIds, $post = null $jobModel->incrementTries(); try { $jobModel->save(); - } - catch(Exception $e) { + } catch(Exception $e) { Mage::log($e->getMessage()); } - if ($config->isLogEnabled($storeId)) { + if($config->isLogEnabled($storeId)) { if($startProcessesReturnCode < 0) { $config->dbLog(sprintf("StartImportProcesses [ReturnCode] [ERROR] [%d]", $startProcessesReturnCode), $jobId, $storeId); - } - else { + } else { $config->dbLog(sprintf("StartImportProcesses [ReturnCode] [SUCCESS] [%d]", $startProcessesReturnCode), $jobId, $storeId); } } - return (int) $startProcessesReturnCode; + return (int)$startProcessesReturnCode; } public function newImportProcess() @@ -512,16 +511,17 @@ public function startImportProcess() /** * Get a single customers XML data. * - * @param int $customerId + * @param int $customerId * @param array $fields_mapping - * @param int $storeId + * @param int $storeId + * * @return string|false */ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId) { $config = Mage::getModel('mailup/config'); /* @var $config MailUp_MailUpSync_Model_Config */ - $xmlData = ''; + $xmlData = ''; $mappedData = array(); $subscriber = self::getCustomersData(array($customerId)); @@ -536,8 +536,8 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId $subscriber["DataCarrelloAbbandonato"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataCarrelloAbbandonato"]); $subscriber["DataUltimoOrdineSpedito"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataUltimoOrdineSpedito"]); - $subscriber["registeredDate"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["registeredDate"]); - $subscriber["DataUltimoOrdine"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataUltimoOrdine"]); + $subscriber["registeredDate"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["registeredDate"]); + $subscriber["DataUltimoOrdine"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataUltimoOrdine"]); /** * As mobileInputType = 2 we need this format: Prefix="+001" Number="8889624587" @@ -545,10 +545,9 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId $xmlData .= ''; foreach($subscriber as $k => $v) { - if ( ! strlen($subscriber[$k])) { + if(!strlen($subscriber[$k])) { $subscriber[$k] = ' '; // blank it out in mailup - } - else { + } else { $subscriber[$k] = str_replace(array("\r\n", "\r", "\n"), " ", $v); } } @@ -557,64 +556,65 @@ protected static function _getCustomerXml($customerId, $fields_mapping, $storeId * Map from Customer Data to Mailup Fields. */ $mappings = array( - 'Name' => 'nome', - 'Last' => 'cognome', - "Company" => 'azienda', - "City" => 'città', - "Province" => 'provincia', - "ZIP" => 'cap', - "Region" => 'regione', - "Country" => 'paese', - "Address" => 'indirizzo', - "Fax" => 'fax', - "Phone" => 'telefono', - "CustomerID" => 'IDCliente', - "LatestOrderID" => 'IDUltimoOrdine', - "LatestOrderDate" => 'DataUltimoOrdine', - "LatestOrderAmount" => 'TotaleUltimoOrdine', - "LatestOrderProductIDs" => 'IDProdottiUltimoOrdine', - "LatestOrderCategoryIDs" => 'IDCategorieUltimoOrdine', - "LatestShippedOrderDate" => 'DataUltimoOrdineSpedito', - "LatestShippedOrderID" => 'IDUltimoOrdineSpedito', - "LatestAbandonedCartDate" => 'DataCarrelloAbbandonato', - "LatestAbandonedCartTotal" => 'TotaleCarrelloAbbandonato', - "LatestAbandonedCartID" => 'IDCarrelloAbbandonato', - "TotalOrdered" => 'TotaleFatturato', - "TotalOrderedLast12m" => 'TotaleFatturatoUltimi12Mesi', - "TotalOrderedLast30d" => 'TotaleFatturatoUltimi30gg', - "AllOrderedProductIDs" => 'IDTuttiProdottiAcquistati', - 'DateOfBirth' => 'DateOfBirth', - 'Gender' => 'Gender', + 'Name' => 'nome', + 'Last' => 'cognome', + "Company" => 'azienda', + "City" => 'città', + "Province" => 'provincia', + "ZIP" => 'cap', + "Region" => 'regione', + "Country" => 'paese', + "Address" => 'indirizzo', + "Fax" => 'fax', + "Phone" => 'telefono', + "CustomerID" => 'IDCliente', + "LatestOrderID" => 'IDUltimoOrdine', + "LatestOrderDate" => 'DataUltimoOrdine', + "LatestOrderAmount" => 'TotaleUltimoOrdine', + "LatestOrderProductIDs" => 'IDProdottiUltimoOrdine', + "LatestOrderCategoryIDs" => 'IDCategorieUltimoOrdine', + "LatestShippedOrderDate" => 'DataUltimoOrdineSpedito', + "LatestShippedOrderID" => 'IDUltimoOrdineSpedito', + "LatestAbandonedCartDate" => 'DataCarrelloAbbandonato', + "LatestAbandonedCartTotal" => 'TotaleCarrelloAbbandonato', + "LatestAbandonedCartID" => 'IDCarrelloAbbandonato', + "TotalOrdered" => 'TotaleFatturato', + "TotalOrderedLast12m" => 'TotaleFatturatoUltimi12Mesi', + "TotalOrderedLast30d" => 'TotaleFatturatoUltimi30gg', + "AllOrderedProductIDs" => 'IDTuttiProdottiAcquistati', + 'DateOfBirth' => 'DateOfBirth', + 'Gender' => 'Gender', ); // Add any custom customer attributes $customerAttributes = Mage::helper('mailup/customer')->getCustomCustomerAttrCollection(); - foreach ($customerAttributes as $attribute) { - $code = $attribute->getAttributeCode() . '_custom_customer_attributes'; + foreach($customerAttributes as $attribute) { + $code = $attribute->getAttributeCode().'_custom_customer_attributes'; $mappings[$code] = $code; } foreach($mappings as $mapTo => $mapFrom) { - if (isset($fields_mapping[$mapTo]) && !empty($fields_mapping[$mapTo])) { - $mappedData[$fields_mapping[$mapTo]] = ''. "". ''; + if(isset($fields_mapping[$mapTo]) && !empty($fields_mapping[$mapTo])) { + $mappedData[$fields_mapping[$mapTo]] = ''."".''; } } // No point in continuing if there is no mapped data - if (count($mappedData) == 0) { + if(count($mappedData) == 0) { if($config->isLogEnabled($storeId)) $config->log('No mappings set, so cannot sync customers'); + return false; } $last_field = max(array_keys($mappedData)); - for($i=1; $i < $last_field; $i++) { - if( ! isset($mappedData[$i]) && ! empty($i)) { + for($i = 1; $i < $last_field; $i++) { + if(!isset($mappedData[$i]) && !empty($i)) { /** * If we leave a space it will blank the value out in mail up. * if we leave it empty, it will leave the old value alone! */ - $mappedData[$i] = "" ." ". ""; + $mappedData[$i] = ""." ".""; } } @@ -642,47 +642,47 @@ public function runJob($jobId) { $config = Mage::getModel('mailup/config'); /* @var $config MailUp_MailUpSync_Model_Config */ - require_once dirname(__FILE__) . '/../Helper/Data.php'; - $db_read = Mage::getSingleton('core/resource')->getConnection('core_read'); - $db_write = Mage::getSingleton('core/resource')->getConnection('core_write'); + require_once dirname(__FILE__).'/../Helper/Data.php'; + $db_read = Mage::getSingleton('core/resource')->getConnection('core_read'); + $db_write = Mage::getSingleton('core/resource')->getConnection('core_write'); $syncTableName = Mage::getSingleton('core/resource')->getTableName('mailup/sync'); $jobsTableName = Mage::getSingleton('core/resource')->getTableName('mailup/job'); - $lastsync = gmdate("Y-m-d H:i:s"); + $lastsync = gmdate("Y-m-d H:i:s"); // reading customers (jobid == 0, their updates) $customer_entity_table_name = Mage::getSingleton('core/resource')->getTableName('customer_entity'); - $jobModel = Mage::getModel('mailup/job')->load($jobId); + $jobModel = Mage::getModel('mailup/job')->load($jobId); /* @var $jobModel MailUp_MailUpSync_Model_Job */ - if( ! $jobModel) { - throw new Mage_Exception('No Job Exists: ' . $jobId); + if(!$jobModel) { + throw new Mage_Exception('No Job Exists: '.$jobId); } - $job = $jobModel->getData(); - $stmt = $db_write->query( + $job = $jobModel->getData(); + $stmt = $db_write->query( "UPDATE {$jobsTableName} - SET status='started', start_datetime='" . gmdate("Y-m-d H:i:s") . "' + SET status='started', start_datetime='".gmdate("Y-m-d H:i:s")."' WHERE id={$job["id"]}" ); - $storeId = isset($job['store_id']) ? $job['store_id'] : NULL; + $storeId = isset($job['store_id']) ? $job['store_id'] : null; //$storeId = Mage::app()->getDefaultStoreView()->getStoreId(); // Fallback incase not set?!? - $customers = array(); - $job['mailupNewGroup'] = 0; - $job['mailupIdList'] = Mage::getStoreConfig('mailup_newsletter/mailup/list', $storeId); - $job["mailupGroupId"] = $job["mailupgroupid"]; + $customers = array(); + $job['mailupNewGroup'] = 0; + $job['mailupIdList'] = Mage::getStoreConfig('mailup_newsletter/mailup/list', $storeId); + $job["mailupGroupId"] = $job["mailupgroupid"]; $job["send_optin_email_to_new_subscribers"] = $job["send_optin"]; // If group is 0 and there is a default group, set group to this group $defaultGroupId = Mage::getStoreConfig('mailup_newsletter/mailup/default_group'); - if ($job["mailupGroupId"] == 0 && $defaultGroupId !== null) { + if($job["mailupGroupId"] == 0 && $defaultGroupId !== null) { $job["mailupGroupId"] = $defaultGroupId; } $tmp = Mage::getSingleton('mailup/source_lists'); $tmp = $tmp->toOptionArray($storeId); // pass store id! - foreach ($tmp as $t) { - if ($t["value"] == $job['mailupIdList']) { + foreach($tmp as $t) { + if($t["value"] == $job['mailupIdList']) { $job['mailupListGUID'] = $t["guid"]; - $job["groups"] = $t["groups"]; + $job["groups"] = $t["groups"]; break; } } @@ -697,7 +697,7 @@ public function runJob($jobId) AND ms.entity='customer' AND job_id={$job["id"]}" ); - while ($row = $stmt->fetch()) { + while($row = $stmt->fetch()) { $customers[] = $row["customer_id"]; } /** @@ -717,12 +717,11 @@ public function runJob($jobId) $config->dbLog("Job Task [update] [Synced] [customer count:{$customerCount}]", $job["id"], $storeId); // finishing the job also $db_write->query(" - UPDATE {$jobsTableName} SET status='finished', finish_datetime='" . gmdate("Y-m-d H:i:s") . "' + UPDATE {$jobsTableName} SET status='finished', finish_datetime='".gmdate("Y-m-d H:i:s")."' WHERE id={$job["id"]}" ); $config->dbLog("Jobs [Update] [Complete] [{$job["id"]}]", $job["id"], $storeId); - } - /** + } /** * Only successfull if we get 0 back. False is also a fail. */ else { @@ -739,15 +738,16 @@ public function runJob($jobId) * Get sub Categories of a Category * * @param int + * * @return array|string */ public function getSubCategories($categoryId) { // Not sure what version this was introduced. - $parent = Mage::getModel('catalog/category')->load($categoryId); - $children = $parent->getAllChildren(TRUE); + $parent = Mage::getModel('catalog/category')->load($categoryId); + $children = $parent->getAllChildren(true); - if( ! empty($children) && is_array($children)) { + if(!empty($children) && is_array($children)) { return $children; } @@ -768,6 +768,7 @@ public function getSubCategories($categoryId) * Format the Price * * @param float + * * @return string */ private static function _formatPrice($price) @@ -779,11 +780,13 @@ private static function _formatPrice($price) * Get Date from DateTime * * @param type $datetime + * * @return string */ private static function _retriveDateFromDatetime($datetime) { - if (empty($datetime)) return ""; + if(empty($datetime)) return ""; + return date("Y-m-d H:i:s", strtotime($datetime)); } @@ -791,22 +794,24 @@ private static function _retriveDateFromDatetime($datetime) * Get DOB Format from DateTime * * @param string $datetime + * * @return string */ private static function _retriveDobFromDatetime($datetime) { - if (empty($datetime)) { + if(empty($datetime)) { return ""; } + return date("d/m/Y", strtotime($datetime)); } public static function _convertUTCToStoreTimezone($datetime) { - if (empty($datetime)) return ""; + if(empty($datetime)) return ""; $TIMEZONE_STORE = new DateTimeZone(Mage::getStoreConfig("general/locale/timezone")); - $TIMEZONE_UTC = new DateTimeZone("UTC"); + $TIMEZONE_UTC = new DateTimeZone("UTC"); $datetime = new DateTime($datetime, $TIMEZONE_UTC); $datetime->setTimezone($TIMEZONE_STORE); @@ -817,8 +822,9 @@ public static function _convertUTCToStoreTimezone($datetime) public static function _convertUTCToStoreTimezoneAndFormatForMailup($datetime) { - if (empty($datetime)) return ""; + if(empty($datetime)) return ""; $datetime = self::_convertUTCToStoreTimezone($datetime); + return date("d/m/Y", strtotime($datetime)); } @@ -829,13 +835,12 @@ public static function _convertUTCToStoreTimezoneAndFormatForMailup($datetime) */ public function cleanResourceTable() { - $sql = "DELETE FROM `core_resource` WHERE `code` = 'mailup_setup';"; + $sql = "DELETE FROM `core_resource` WHERE `code` = 'mailup_setup';"; $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); try { $connection->query($sql); die('deleted module in core_resource!'); - } - catch(Exception $e){ + } catch(Exception $e) { Mage::log($e->getMessage()); } } @@ -847,15 +852,14 @@ public function cleanResourceTable() */ public function showResourceTable() { - $sql = "SELECT * FROM `core_resource`"; + $sql = "SELECT * FROM `core_resource`"; $connection = Mage::getSingleton('core/resource')->getConnection('core_read'); try { $result = $connection->fetchAll($sql); foreach($result as $row) { - echo $row['code'] . "
"; + echo $row['code']."
"; } - } - catch(Exception $e){ + } catch(Exception $e) { echo $e->getMessage(); } } @@ -873,8 +877,7 @@ public function getAllProductAttributes() { //$attributes = Mage::getModel('catalog/product')->getAttributes(); $attributes = Mage::getSingleton('eav/config') - ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection() - ; + ->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection(); // Localize attribute label (if you need it) $attributes->addStoreLabel(Mage::app()->getStore()->getId()); $attributeArray = array(); @@ -887,6 +890,7 @@ public function getAllProductAttributes() ); } } + return $attributeArray; } @@ -903,8 +907,7 @@ public function getAllCustomerAttributes() { //$attributes = Mage::getModel('catalog/product')->getAttributes(); $attributes = Mage::getSingleton('eav/config') - ->getEntityType('customer')->getAttributeCollection() - ; + ->getEntityType('customer')->getAttributeCollection(); // Localize attribute label (if you need it) $attributes->addStoreLabel(Mage::app()->getStore()->getId()); $attributeArray = array(); @@ -917,6 +920,7 @@ public function getAllCustomerAttributes() ); } } + return $attributeArray; } @@ -925,6 +929,7 @@ public function getAllCustomerAttributes() * * @param int * @param int + * * @return bool */ public function isSubscriber($customerId, $storeId) @@ -932,6 +937,7 @@ public function isSubscriber($customerId, $storeId) $statuses = array( Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED ); + return $this->_isSubscriberInStatus($customerId, $statuses, $storeId); } @@ -940,6 +946,7 @@ public function isSubscriber($customerId, $storeId) * * @param int * @param int + * * @return bool */ public function isSubscriberOrWaiting($customerId, $storeId) @@ -948,6 +955,7 @@ public function isSubscriberOrWaiting($customerId, $storeId) Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED, Mage_Newsletter_Model_Subscriber::STATUS_UNCONFIRMED ); + return $this->_isSubscriberInStatus($customerId, $statuses, $storeId); } @@ -955,34 +963,34 @@ public function isSubscriberOrWaiting($customerId, $storeId) * Is the given customer a subscriber with the given status? * Note that an empty set of statuses will just return true * - * @param $customerId + * @param $customerId * @param array $statuses - * @param $storeId + * @param $storeId + * * @return bool|mixed */ protected function _isSubscriberInStatus($customerId, array $statuses, $storeId) { - $customerId = (int) $customerId; - $storeId = (int) $storeId; + $customerId = (int)$customerId; + $storeId = (int)$storeId; // If no status set given, just return true - if (empty($statuses)) + if(empty($statuses)) return true; - $table = Mage::getSingleton('core/resource')->getTableName('newsletter_subscriber'); + $table = Mage::getSingleton('core/resource')->getTableName('newsletter_subscriber'); $connection = Mage::getSingleton('core/resource')->getConnection('core_read'); - $sql = "SELECT * FROM {$table} WHERE customer_id = '{$customerId}'"; + $sql = "SELECT * FROM {$table} WHERE customer_id = '{$customerId}'"; try { $result = $connection->fetchAll($sql); // array if(count($result) == 0) { - return FALSE; + return false; } $result = $result[0]; // Return whether status is in given set return (array_search($result['subscriber_status'], $statuses) !== false); - } - catch(Exception $e){ + } catch(Exception $e) { Mage::log($e->getMessage()); } @@ -999,10 +1007,10 @@ public function scheduleTask($when, $type = 'MailUp_MailUpSync') { $write = Mage::getSingleton('core/resource')->getConnection('core_write'); $write->insert(Mage::getSingleton('core/resource')->getTableName('cron_schedule'), array( - "job_code" => $type, - "status" => "pending", - "created_at" => gmdate("Y-m-d H:i:s"), - "scheduled_at" => $when + "job_code" => $type, + "status" => "pending", + "created_at" => gmdate("Y-m-d H:i:s"), + "scheduled_at" => $when )); } @@ -1011,21 +1019,22 @@ public function scheduleTask($when, $type = 'MailUp_MailUpSync') * * @param mixed * @param int + * * @return int */ - public function getAttributeId($id, $entityTypeId = NULL) + public function getAttributeId($id, $entityTypeId = null) { - if($entityTypeId == NULL) { + if($entityTypeId == null) { $entityTypeId = Mage::getModel('catalog/product')->getResource()->getEntityType()->getId(); } $installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup'); - if ( ! is_numeric($id)) { + if(!is_numeric($id)) { $id = $installer->getAttribute($entityTypeId, $id, 'attribute_id'); } - if ( ! is_numeric($id)) { + if(!is_numeric($id)) { //throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Wrong attribute ID.')); - return FALSE; + return false; } return $id; @@ -1035,25 +1044,26 @@ public function getAttributeId($id, $entityTypeId = NULL) * Get ListGuid (Alphanumeric code associated to a distribution list) for given list * * @param $listId + * * @return false|string */ public function getListGuid($listId) { - $wsImport = new MailUpWsImport(); + $wsImport = new MailUpWsImport(); $xmlString = $wsImport->GetNlList(); - if (!$xmlString) return $this; + if(!$xmlString) return $this; - $xmlString = html_entity_decode($xmlString); + $xmlString = html_entity_decode($xmlString); $startLists = strpos($xmlString, ''); - $endPos = strpos($xmlString, ''); - $endLists = $endPos + strlen('') - $startLists; - $xmlLists = substr($xmlString, $startLists, $endLists); - $xmlLists = str_replace("&", "&", $xmlLists); - $xml = simplexml_load_string($xmlLists); + $endPos = strpos($xmlString, ''); + $endLists = $endPos + strlen('') - $startLists; + $xmlLists = substr($xmlString, $startLists, $endLists); + $xmlLists = str_replace("&", "&", $xmlLists); + $xml = simplexml_load_string($xmlLists); $listGUID = false; - foreach ($xml->List as $list) { - if ($list['idList'] == $listId) { + foreach($xml->List as $list) { + if($list['idList'] == $listId) { $listGUID = $list["listGUID"]; break; } @@ -1077,19 +1087,19 @@ public function clearAbandonmentFields($email) ); // Gather list parameters - $console = Mage::getStoreConfig('mailup_newsletter/mailup/url_console'); - $listId = Mage::getStoreConfig('mailup_newsletter/mailup/list'); + $console = Mage::getStoreConfig('mailup_newsletter/mailup/url_console'); + $listId = Mage::getStoreConfig('mailup_newsletter/mailup/list'); $listGUID = $this->getListGuid($listId); // Set endpoint of API - $ws = "http://{$console}/frontend/XmlUpdSubscriber.aspx"; + $ws = "http://{$console}/frontend/XmlUpdSubscriber.aspx"; // Add parameters to request - $ws .= "?ListGuid=" . rawurlencode($listGUID); - $ws .= "&List=" . rawurlencode($listId); - $ws .= "&Email=" . rawurlencode($email); - $ws .= "&csvFldNames=" . join(';', array_keys($fields)); - $ws .= "&csvFldValues=" . join(';', array_values($fields)); + $ws .= "?ListGuid=".rawurlencode($listGUID); + $ws .= "&List=".rawurlencode($listId); + $ws .= "&Email=".rawurlencode($email); + $ws .= "&csvFldNames=".join(';', array_keys($fields)); + $ws .= "&csvFldValues=".join(';', array_values($fields)); // Make request try { @@ -1097,10 +1107,10 @@ public function clearAbandonmentFields($email) Mage::log("Cancelling abandonment: $ws"); } $result = @file_get_contents($ws); - if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) { + if(Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) { Mage::log("Cancelling abandonment result: $result"); } - } catch (Exception $e) { + } catch(Exception $e) { Mage::logException($e); } } @@ -1112,6 +1122,7 @@ public function clearAbandonmentFields($email) * @param $usernameWs * @param $passwordWs * @param $storeId + * * @return array Return array of messages (success or errors) */ public function testConnection($urlConsole, $usernameWs, $passwordWs, $storeId) @@ -1119,24 +1130,24 @@ public function testConnection($urlConsole, $usernameWs, $passwordWs, $storeId) $messages = array(); // Run test for url console - if ($this->_testConnectionConsole($urlConsole) === false) { + if($this->_testConnectionConsole($urlConsole) === false) { $messages[] = array( 'message' => $this->__('Error in console URL'), - 'type' => 'error' + 'type' => 'error' ); } // Run test for username and password - if ($this->_testConnectionUserPassword($usernameWs, $passwordWs, $storeId) === false) { + if($this->_testConnectionUserPassword($usernameWs, $passwordWs, $storeId) === false) { $messages[] = array( 'message' => $this->__('Error in username / password'), - 'type' => 'error' + 'type' => 'error' ); } - if (empty($messages)) { + if(empty($messages)) { $messages[] = array( 'message' => $this->__('Success! Connection established with MailUp with given details'), - 'type' => 'success' + 'type' => 'success' ); } @@ -1154,12 +1165,12 @@ public function testConfig() // Mysql timeout $timeout = ini_get('mysql.connect_timeout'); - if ($timeout !== false && $timeout < 60) { + if($timeout !== false && $timeout < 60) { $messages[] = array( - 'message' => $this->__('Config warning: mysql.connect_timeout is %d which is a bit low. ' . - 'This may cause intermittent issues when connecting with MailUp. ' . + 'message' => $this->__('Config warning: mysql.connect_timeout is %d which is a bit low. '. + 'This may cause intermittent issues when connecting with MailUp. '. 'Please contact your Web host to discuss an increase in the timeout setting.', $timeout), - 'type' => 'warning' + 'type' => 'warning' ); } @@ -1170,11 +1181,12 @@ public function testConfig() * Test the URL console address by making an http call * * @param $urlConsole + * * @return bool */ protected function _testConnectionConsole($urlConsole) { - if (Mage::getStoreConfig('mailup_newsletter/mailup/skip_check') == false) { + if(Mage::getStoreConfig('mailup_newsletter/mailup/skip_check') == false) { // Set endpoint of API $ws = "http://{$urlConsole}/frontend/Xmlchksubscriber.aspx"; @@ -1200,6 +1212,7 @@ protected function _testConnectionConsole($urlConsole) // Test that request returns 1 (with an allowance for whitespace) return (preg_match('/^1\s*$/', $result) == 1); } + return true; } @@ -1209,6 +1222,7 @@ protected function _testConnectionConsole($urlConsole) * @param $usernameWs * @param $passwordWs * @param $storeId + * * @return boolean */ protected function _testConnectionUserPassword($usernameWs, $passwordWs, $storeId) From 24585b627b9f0fce5cfce4a60671bb91cbed7ff7 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Mon, 7 Aug 2017 10:09:38 +0200 Subject: [PATCH 8/9] [dev] changelog - update --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e518e4..f727118 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ CHANGELOG ========= +(date follow ISO format - 06 is for June) +## 2.7.6 - [fix] admin config | close save config only to mailup section - [fix] admin config | refactoring field check - [dev] admin config | add skip test console url option From 6833cc9c7dec107ac90beca572ddde0a92780ea5 Mon Sep 17 00:00:00 2001 From: Giuseppe Morelli Date: Mon, 11 Sep 2017 09:55:21 +0200 Subject: [PATCH 9/9] [imp] gitignore - move IDE project ignore to global - edit changelog --- .gitignore | 1 - CHANGELOG.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 757fee3..e69de29 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +0,0 @@ -/.idea \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f727118..77e2747 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ CHANGELOG - [fix] admin config | close save config only to mailup section - [fix] admin config | refactoring field check - [dev] admin config | add skip test console url option +- [imp] gitignore | move IDE project ignore to global [https://help.github.com/articles/ignoring-files/#create-a-global-gitignore](https://help.github.com/articles/ignoring-files/#create-a-global-gitignore) ## 2.7.5 - 10/07/2017 - [dev] ip filter | send client ip for spam checking