MailUp - Version 2.3.1

Version Notes

Added support for multi-store installations

Settings, including field mappings, can now be set at the store view level

Added date/time stamp of latest data sync

Updated some areas of the extension to improve performance

Download this release

Release Info

Developer MailUp
Extension MailUp
Version 2.3.1
Comparing to
See all releases


Code changes from version 2.2.1 to 2.3.1

Files changed (53) hide show
  1. app/code/local/SevenLike/MailUp/Block/.DS_Store +0 -0
  2. app/code/local/SevenLike/MailUp/Block/Filters.php +25 -0
  3. app/code/local/SevenLike/MailUp/Helper/.DS_Store +0 -0
  4. app/code/local/SevenLike/MailUp/Helper/Data.php +602 -446
  5. app/code/local/SevenLike/MailUp/Model/Adminhtml/System/Source/Cron/Frequency.php +37 -37
  6. app/code/local/SevenLike/MailUp/Model/Adminhtml/System/Source/Cron/Hours.php +18 -18
  7. app/code/local/SevenLike/MailUp/Model/Adminhtml/System/Source/Fields.php +63 -0
  8. app/code/local/SevenLike/MailUp/Model/Config.php +205 -0
  9. app/code/local/SevenLike/MailUp/Model/Consoleurlvalidator.php +18 -18
  10. app/code/local/SevenLike/MailUp/Model/Cron.php +161 -86
  11. app/code/local/SevenLike/MailUp/Model/Lists.php +96 -54
  12. app/code/local/SevenLike/MailUp/Model/MailUp.php +9 -9
  13. app/code/local/SevenLike/MailUp/Model/MailUpWsImport.php +1001 -658
  14. app/code/local/SevenLike/MailUp/Model/Mysql14/MailUp.php +8 -8
  15. app/code/local/SevenLike/MailUp/Model/Mysql14/MailUp/Collection.php +9 -9
  16. app/code/local/SevenLike/MailUp/Model/Observer.php +348 -264
  17. app/code/local/SevenLike/MailUp/Model/Subscriber.php +73 -0
  18. app/code/local/SevenLike/MailUp/Model/Webserviceusernamevalidator.php +17 -17
  19. app/code/local/SevenLike/MailUp/Model/Ws.php +2 -2
  20. app/code/local/SevenLike/MailUp/Model/Wssend.php +348 -305
  21. app/code/local/SevenLike/MailUp/controllers/.DS_Store +0 -0
  22. app/code/local/SevenLike/MailUp/controllers/Adminhtml/.DS_Store +0 -0
  23. app/code/local/SevenLike/MailUp/controllers/Adminhtml/ConfigurationController.php +14 -14
  24. app/code/local/SevenLike/MailUp/controllers/Adminhtml/FieldsmappingController.php +29 -27
  25. app/code/local/SevenLike/MailUp/controllers/Adminhtml/FilterController.php +265 -222
  26. app/code/local/SevenLike/MailUp/controllers/Adminhtml/ViewdatatransferlogController.php +13 -13
  27. app/code/local/SevenLike/MailUp/controllers/IndexController.php +60 -0
  28. app/code/local/SevenLike/MailUp/controllers/WebhookController.php +166 -147
  29. app/code/local/SevenLike/MailUp/etc/.DS_Store +0 -0
  30. app/code/local/SevenLike/MailUp/etc/config.xml +281 -246
  31. app/code/local/SevenLike/MailUp/etc/system.xml +403 -98
  32. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-install-0.1.0.php +2 -2
  33. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-install-2.3.0.php +36 -0
  34. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-upgrade-0.1.0-1.0.0.php +2 -2
  35. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-upgrade-0.3.0-1.0.0.php +10 -10
  36. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-upgrade-1.0.0-1.5.2.php +10 -10
  37. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-upgrade-2.1.3-2.2.0.php +24 -24
  38. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-upgrade-2.2.0-2.3.0.php +47 -0
  39. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-upgrade-2.2.1-2.3.0.php +47 -0
  40. app/code/local/SevenLike/MailUp/sql/mailup_setup/mysql4-upgrade-2.3.0-2.3.1.php +14 -0
  41. app/design/adminhtml/default/default/layout/mailup.xml +14 -1
  42. app/design/adminhtml/default/default/template/sevenlike/mailup/confirm.phtml +194 -181
  43. app/design/adminhtml/default/default/template/sevenlike/mailup/fieldsmapping.phtml +60 -54
  44. app/design/adminhtml/default/default/template/sevenlike/mailup/filter.phtml +526 -497
  45. app/design/adminhtml/default/default/template/sevenlike/mailup/filter_.phtml +526 -0
  46. app/design/adminhtml/default/default/template/sevenlike/mailup/viewdatatransferlog.phtml +71 -71
  47. app/design/frontend/base/default/layout/mailup.xml +8 -0
  48. app/design/frontend/base/default/template/mailup/subscribe.phtml +39 -0
  49. app/design/frontend/enterprise/default/layout/mailup.xml +8 -0
  50. app/design/frontend/enterprise/default/template/mailup/subscribe.phtml +39 -0
  51. package.xml +50 -95
  52. skin/adminhtml/default/default/sevenlike/mailup/images/MailUp_300_200_transparent_small.png +0 -0
  53. skin/adminhtml/default/default/sevenlike/mailup/mailup.css +1 -21
app/code/local/SevenLike/MailUp/Block/.DS_Store DELETED
Binary file
app/code/local/SevenLike/MailUp/Block/Filters.php ADDED
@@ -0,0 +1,25 @@
1
+ <?php
2
+ /**
3
+ * Filters.php
4
+ *
5
+ * Adminhtml block for the filters section
6
+ */
7
+ class SevenLike_MailUp_Block_Filters extends Mage_Core_Block_Template
8
+ {
9
+ public function _toHtml()
10
+ {
11
+ return parent::_toHtml();
12
+ }
13
+
14
+ /**
15
+ * Get an array of all stores
16
+ *
17
+ * @return array
18
+ */
19
+ protected function _getStoresArray()
20
+ {
21
+ $config = Mage::getModel('mailup/config');
22
+ /* @var $config SevenLike_Mailup_Model_Config */
23
+ return $config->getStoreArray();
24
+ }
25
+ }
app/code/local/SevenLike/MailUp/Helper/.DS_Store DELETED
Binary file
app/code/local/SevenLike/MailUp/Helper/Data.php CHANGED
@@ -1,447 +1,603 @@
1
- <?php
2
-
3
- class SevenLike_MailUp_Helper_Data extends Mage_Core_Helper_Abstract
4
- {
5
- public static function getCustomersData($customerCollection = null)
6
- {
7
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Getting customers data', 0);
8
- $dateFormat = 'm/d/y h:i:s';
9
- $lastDateTime = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-7*3600*24);
10
- $thirtyDaysAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-30*3600*24);
11
- $twelveMonthsAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-365*3600*24);
12
-
13
- $parseSubscribers = false;
14
- $toSend = array();
15
- if ($customerCollection === null) {
16
- $customerCollection = Mage::getModel('customer/customer')->getCollection();
17
- $parseSubscribers = true;
18
- }
19
- foreach ($customerCollection as $currentCustomerId) {
20
- if (is_object($currentCustomerId)) {
21
- $currentCustomerId = $currentCustomerId->getId();
22
- }
23
-
24
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Customer with id '.$currentCustomerId, 0);
25
- $customer = Mage::getModel('customer/customer')->load($currentCustomerId);
26
- $i = $customer->getEmail();
27
-
28
- //recupero gli ordini del cliente corrente
29
- $allOrdersTotalAmount = 0;
30
- $allOrdersDateTimes = array();
31
- $allOrdersTotals = array();
32
- $allOrdersIds = array();
33
- $allProductsIds = array();
34
- $last30daysOrdersAmount = 0;
35
- $last12monthsOrdersAmount = 0;
36
- $lastShipmentOrderId = null;
37
- $lastShipmentOrderDate = null;
38
-
39
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Parsing orders of customer with id '.$currentCustomerId, 0);
40
- $orders = Mage::getModel('sales/order')
41
- ->getCollection()
42
- ->addAttributeToFilter('customer_id', $currentCustomerId);
43
- foreach ($orders as $order) {
44
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log("ORDINE IN STATUS: " . $order->getStatus());
45
- if (!in_array($order->getStatus(), array("closed", "complete", "processing"))) continue;
46
- $currentOrderTotal = floatval($order->getGrandTotal());
47
- $allOrdersTotalAmount += $currentOrderTotal;
48
-
49
- $currentOrderCreationDate = $order->getCreatedAt();
50
- if ($currentOrderCreationDate > $thirtyDaysAgo) {
51
- $last30daysOrdersAmount += $currentOrderTotal;
52
-
53
- }
54
- if ($currentOrderCreationDate > $twelveMonthsAgo) {
55
- $last12monthsOrdersAmount += $currentOrderTotal;
56
- }
57
-
58
- $currentOrderTotal = self::_formatPrice($currentOrderTotal);
59
-
60
- $currentOrderId = $order->getIncrementId();
61
- $allOrdersTotals[$currentOrderId] = $currentOrderTotal;
62
- $allOrdersDateTimes[$currentOrderId] = $currentOrderCreationDate;
63
- $allOrdersIds[$currentOrderId] = $currentOrderId;
64
-
65
- if ($order->hasShipments() and ($order->getId()>$lastShipmentOrderId)) {
66
- $lastShipmentOrderId = $order->getId();
67
- $lastShipmentOrderDate = self::_retriveDateFromDatetime($order->getCreatedAt());
68
- }
69
-
70
- $items = $order->getAllItems();
71
- foreach ($items as $item) {
72
- $allProductsIds[] = $item->getProductId();
73
- }
74
- }
75
-
76
- $toSend[$i]['TotaleFatturatoUltimi30gg'] = self::_formatPrice($last30daysOrdersAmount);
77
- $toSend[$i]['TotaleFatturatoUltimi12Mesi'] = self::_formatPrice($last12monthsOrdersAmount);
78
- $toSend[$i]['IDTuttiProdottiAcquistati'] = implode(',', $allProductsIds);
79
-
80
- ksort($allOrdersDateTimes);
81
- ksort($allOrdersTotals);
82
- ksort($allOrdersIds);
83
-
84
- //recupero i carrelli abbandonati del cliente
85
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Parsing abandoned carts of customer with id '.$currentCustomerId, 0);
86
- $cartCollection = Mage::getResourceModel('reports/quote_collection');
87
- $cartCollection->prepareForAbandonedReport(array(1));
88
- $cartCollection->addFieldToFilter('customer_id', $currentCustomerId);
89
- $cartCollection->load();
90
-
91
- $datetimeCart = null;
92
- if (! empty($cartCollection)) {
93
- $lastCart = end($cartCollection);
94
-
95
- $toSend[$i]['TotaleCarrelloAbbandonato'] = '';
96
- $toSend[$i]['DataCarrelloAbbandonato'] = '';
97
- $toSend[$i]['IDCarrelloAbbandonato'] = '';
98
-
99
- if (! empty($lastCart)) {
100
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Customer with id '.$currentCustomerId .' has abandoned cart', 0);
101
- $datetimeCart = $lastCart->getUpdatedAt();
102
- $toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getGrandTotal());
103
- $toSend[$i]['DataCarrelloAbbandonato'] = self::_retriveDateFromDatetime($datetimeCart);
104
- $toSend[$i]['IDCarrelloAbbandonato'] = $lastCart->getId();
105
- }
106
- }
107
-
108
- $toSend[$i]['IDUltimoOrdineSpedito'] = $lastShipmentOrderId;
109
- $toSend[$i]['DataUltimoOrdineSpedito'] = $lastShipmentOrderDate;
110
-
111
- $lastOrderDateTime = end($allOrdersDateTimes);
112
-
113
- if ($customer->getUpdatedAt() > $lastDateTime
114
- || $lastOrderDateTime > $lastDateTime
115
- || ($datetimeCart && $datetimeCart > $lastDateTime))
116
- {
117
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Adding customer with id '.$currentCustomerId, 0);
118
-
119
- $toSend[$i]['nome'] = $customer->getFirstname();
120
- $toSend[$i]['cognome'] = $customer->getLastname();
121
- $toSend[$i]['email'] = $customer->getEmail();
122
- $toSend[$i]['IDCliente'] = $currentCustomerId;
123
-
124
- $toSend[$i]['registeredDate'] = self::_retriveDateFromDatetime($customer->getCreatedAt());
125
-
126
- //controllo se iscritto o meno alla newsletter
127
- if (Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->isSubscribed()) {
128
- $toSend[$i]['subscribed'] = 'yes';
129
- } else {
130
- $toSend[$i]['subscribed'] = 'no';
131
- }
132
-
133
- //recupero i dati dal default billing address
134
- $customerAddressId = $customer->getDefaultBilling();
135
- if ($customerAddressId) {
136
- $address = Mage::getModel('customer/address')->load($customerAddressId);
137
- $toSend[$i]['azienda'] = $address->getData('company');
138
- $toSend[$i]['paese'] = $address->getCountry();
139
- $toSend[$i]['città'] = $address->getData('city');
140
- $toSend[$i]['regione'] = $address->getData('region');
141
- $regionId = $address->getData('region_id');
142
- $regionModel = Mage::getModel('directory/region')->load($regionId);
143
- $regionCode = $regionModel->getCode();
144
- $toSend[$i]['provincia'] = $regionCode;
145
- $toSend[$i]['cap'] = $address->getData('postcode');
146
- $toSend[$i]['indirizzo'] = $address->getData('street');
147
- $toSend[$i]['fax'] = $address->getData('fax');
148
- $toSend[$i]['telefono'] = $address->getData('telephone');
149
- }
150
-
151
- $toSend[$i]['DataUltimoOrdine'] = self::_retriveDateFromDatetime($lastOrderDateTime);
152
- $toSend[$i]['TotaleUltimoOrdine'] = end($allOrdersTotals);
153
- $toSend[$i]['IDUltimoOrdine'] = end($allOrdersIds);
154
-
155
- $toSend[$i]['TotaleFatturato'] = self::_formatPrice($allOrdersTotalAmount);
156
-
157
- //ottengo gli id di prodotti e categorie (dell'ultimo ordine)
158
- $lastOrder = Mage::getModel('sales/order')->loadByIncrementId(end($allOrdersIds));
159
- $items = $lastOrder->getAllItems();
160
- $productIds = array();
161
- $categoryIds = array();
162
- foreach ($items as $item) {
163
- $productId = $item->getProductId();
164
- $productIds[] = $productId;
165
- $product = Mage::getModel('catalog/product')->load($productId);
166
- if ($product->getCategoryIds()) {
167
- $categoryIds[] = implode(',', $product->getCategoryIds());
168
- }
169
- }
170
-
171
- $toSend[$i]['IDProdottiUltimoOrdine'] = implode(',', $productIds);
172
- if ($toSend[$i]['IDProdottiUltimoOrdine']) $toSend[$i]['IDProdottiUltimoOrdine'] = ",{$toSend[$i]['IDProdottiUltimoOrdine']},";
173
- $toSend[$i]['IDCategorieUltimoOrdine'] = implode(',', $categoryIds);
174
- if ($toSend[$i]['IDCategorieUltimoOrdine']) $toSend[$i]['IDCategorieUltimoOrdine'] = ",{$toSend[$i]['IDCategorieUltimoOrdine']},";
175
- }
176
-
177
- //unsetto la variabile
178
- unset($customer);
179
- }
180
-
181
- /*
182
- * disabled cause useless in segmentation
183
- if ($parseSubscribers) {
184
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Parsing subscribers', 0);
185
- $subscriberCollection = Mage::getModel('newsletter/subscriber')
186
- ->getCollection()
187
- ->useOnlySubscribed()
188
- ->addFieldToFilter('customer_id', 0);
189
-
190
- foreach ($subscriberCollection as $subscriber) {
191
- $subscriber = Mage::getModel('newsletter/subscriber')->load($subscriber->getId());
192
- $i = $subscriber->getEmail();
193
- if (strlen($i)) continue;
194
- if (isset($toSend[$i])) continue;
195
- $toSend[$i]['nome'] = '';
196
- $toSend[$i]['cognome'] = '';
197
- $toSend[$i]['email'] = $i;
198
- $toSend[$i]['subscribed'] = 'yes';
199
- }
200
- }
201
- */
202
-
203
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('End getting customers data', 0);
204
- return $toSend;
205
- }
206
-
207
- public static function generateAndSendCustomers($mailupCustomerIds, $post = null, $newsletter_subscribers = null)
208
- {
209
- $wsSend = new MailUpWsSend();
210
- require_once dirname(__FILE__) . "/../Model/MailUpWsImport.php";
211
- $wsImport = new MailUpWsImport();
212
- $accessKey = $wsSend->loginFromId();
213
-
214
- if (empty($mailupCustomerIds)) return false;
215
- if ($post === null) {
216
- // chiamata da cron, popolo con i dati del gruppo "magento" di default
217
- $post['mailupNewGroup'] = 0;
218
- $post['mailupIdList'] = Mage::getStoreConfig('newsletter/mailup/list');
219
-
220
- $tmp = new SevenLike_MailUp_Model_Lists;
221
- $tmp = $tmp->toOptionArray();
222
- foreach ($tmp as $t) {
223
- if ($t["value"] == $post['mailupIdList']) {
224
- $post['mailupListGUID'] = $t["guid"];
225
- $post["groups"] = $t["groups"];
226
- break;
227
- }
228
- }
229
- unset($tmp); unset($t);
230
-
231
- $post['mailupGroupId'] = "";
232
- foreach ($post["groups"] as $tmp_id_group=>$tmp_group_name) {
233
- if ($tmp_group_name == "MAGENTO") {
234
- $post['mailupGroupId'] = $tmp_id_group;
235
- break;
236
- }
237
- }
238
- unset($tmp_id_group); unset($tmp_group_name);
239
-
240
- if (!strlen($post['mailupGroupId'])) {
241
- $newGroup = array(
242
- "idList" => $post['mailupIdList'],
243
- "listGUID" => $post['mailupListGUID'],
244
- "newGroupName" => "MAGENTO"
245
- );
246
-
247
- $post['mailupGroupId'] = $wsImport->CreaGruppo($newGroup);
248
- }
249
- }
250
-
251
- if ($accessKey === false) {
252
- Mage::throwException('no access key returned');
253
- }
254
- $fields = $wsSend->GetFields($accessKey);
255
- $fields_mapping = $wsImport->getFieldsMapping();
256
-
257
- //definisco il gruppo a cui aggiungere gli iscritti
258
- $groupId = $post['mailupGroupId'];
259
- $listGUID = $post['mailupListGUID'];
260
- $idList = $post['mailupIdList'];
261
-
262
- if ($post['mailupNewGroup'] == 1) {
263
- $newGroup = array(
264
- "idList" => $idList,
265
- "listGUID" => $listGUID,
266
- "newGroupName" => $post['mailupNewGroupName']
267
- );
268
-
269
- $groupId = $wsImport->CreaGruppo($newGroup);
270
- }
271
-
272
- if (isset($post["send_optin_email_to_new_subscribers"]) and $post["send_optin_email_to_new_subscribers"]) {
273
- $importProcessData = array(
274
- "idList" => $idList,
275
- "listGUID" => $listGUID,
276
- "idGroup" => $groupId,
277
- "xmlDoc" => "",
278
- "idGroups" => $groupId,
279
- "importType" => 1,
280
- "mobileInputType" => 2,
281
- "asPending" => false,
282
- "ConfirmEmail" => true,
283
- "asOptOut" => false,
284
- "forceOptIn" => false,
285
- "replaceGroups" => false,
286
- "idConfirmNL" => 0
287
- );
288
- } else {
289
- $importProcessData = array(
290
- "idList" => $idList,
291
- "listGUID" => $listGUID,
292
- "idGroup" => $groupId,
293
- "xmlDoc" => "",
294
- "idGroups" => $groupId,
295
- "importType" => 1,
296
- "mobileInputType" => 2,
297
- "asPending" => false,
298
- "ConfirmEmail" => false,
299
- "asOptOut" => false,
300
- "forceOptIn" => false,
301
- "replaceGroups" => false,
302
- "idConfirmNL" => 0
303
- );
304
- }
305
-
306
- //preparo l'xml degli iscritti da inviare a mailup (da gestire in base ai filtri)
307
- $xmlData = '';
308
- $subscribers_counter = 0;
309
- $total_subscribers_to_send = sizeof($mailupCustomerIds);
310
- foreach ($mailupCustomerIds as $customerId) {
311
- $tmp = array();
312
- $subscribers_counter++;
313
- $subscriber = self::getCustomersData(array($customerId));
314
- $subscriber = array_values($subscriber);
315
- $subscriber = $subscriber[0];
316
-
317
- $subscriber["DataCarrelloAbbandonato"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataCarrelloAbbandonato"]);
318
- $subscriber["DataUltimoOrdineSpedito"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataUltimoOrdineSpedito"]);
319
- $subscriber["registeredDate"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["registeredDate"]);
320
- $subscriber["DataUltimoOrdine"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataUltimoOrdine"]);
321
-
322
- $xmlData .= '<subscriber email="'.$subscriber['email'].'" Number="" Name="">';
323
-
324
- if (@$fields_mapping["Name"]) $tmp[$fields_mapping["Name"]] = '<campo'.$fields_mapping["Name"].'>'. ((!empty($subscriber['nome'])) ? $subscriber['nome'] : '') .'</campo'.$fields_mapping["Name"].'>';
325
- if (@$fields_mapping["Last"]) $tmp[$fields_mapping["Last"]] = '<campo'.$fields_mapping["Last"].'>'. ((!empty($subscriber['cognome'])) ? $subscriber['cognome'] : '') .'</campo'.$fields_mapping["Last"].'>';
326
-
327
- foreach ($subscriber as $k=>$v) {
328
- if (!strlen($subscriber[$k])) {
329
- $subscriber[$k] = "-";
330
- } else {
331
- $subscriber[$k] = str_replace(array("\r\n", "\r", "\n"), " ", $v);
332
- }
333
- }
334
-
335
- if (@$fields_mapping["Company"]) $tmp[$fields_mapping["Company"]] = '<campo'.$fields_mapping["Company"].'>'. $subscriber['azienda'] .'</campo'.$fields_mapping["Company"].'>';
336
- if (@$fields_mapping["City"]) $tmp[$fields_mapping["City"]] = '<campo'.$fields_mapping["City"].'>'. $subscriber['città'] .'</campo'.$fields_mapping["City"].'>';
337
- if (@$fields_mapping["Province"]) $tmp[$fields_mapping["Province"]] = '<campo'.$fields_mapping["Province"].'>'. $subscriber['provincia'] .'</campo'.$fields_mapping["Province"].'>';
338
- if (@$fields_mapping["ZIP"]) $tmp[$fields_mapping["ZIP"]] = '<campo'.$fields_mapping["ZIP"].'>'. $subscriber['cap'].'</campo'.$fields_mapping["ZIP"].'>';
339
- if (@$fields_mapping["Region"]) $tmp[$fields_mapping["Region"]] = '<campo'.$fields_mapping["Region"].'>'. $subscriber['regione'] .'</campo'.$fields_mapping["Region"].'>';
340
- if (@$fields_mapping["Country"]) $tmp[$fields_mapping["Country"]] = '<campo'.$fields_mapping["Country"].'>'. $subscriber['paese'] .'</campo'.$fields_mapping["Country"].'>';
341
- if (@$fields_mapping["Address"]) $tmp[$fields_mapping["Address"]] = '<campo'.$fields_mapping["Address"].'>'. $subscriber['indirizzo'] .'</campo'.$fields_mapping["Address"].'>';
342
- if (@$fields_mapping["Fax"]) $tmp[$fields_mapping["Fax"]] = '<campo'.$fields_mapping["Fax"].'>'. $subscriber['fax'] .'</campo'.$fields_mapping["Fax"].'>';
343
- if (@$fields_mapping["Phone"]) $tmp[$fields_mapping["Phone"]] = '<campo'.$fields_mapping["Phone"].'>'. $subscriber['telefono'] .'</campo'.$fields_mapping["Phone"].'>';
344
- if (@$fields_mapping["CustomerID"]) $tmp[$fields_mapping["CustomerID"]] = '<campo'.$fields_mapping["CustomerID"].'>'. $subscriber['IDCliente'] .'</campo'.$fields_mapping["CustomerID"].'>';
345
- if (@$fields_mapping["LatestOrderID"]) $tmp[$fields_mapping["LatestOrderID"]] = '<campo'.$fields_mapping["LatestOrderID"].'>'. $subscriber['IDUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderID"].'>';
346
- if (@$fields_mapping["LatestOrderDate"]) $tmp[$fields_mapping["LatestOrderDate"]] = '<campo'.$fields_mapping["LatestOrderDate"].'>'. $subscriber['DataUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderDate"].'>';
347
- if (@$fields_mapping["LatestOrderAmount"]) $tmp[$fields_mapping["LatestOrderAmount"]] = '<campo'.$fields_mapping["LatestOrderAmount"].'>'. $subscriber['TotaleUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderAmount"].'>';
348
- if (@$fields_mapping["LatestOrderProductIDs"]) $tmp[$fields_mapping["LatestOrderProductIDs"]] = '<campo'.$fields_mapping["LatestOrderProductIDs"].'>'. $subscriber['IDProdottiUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderProductIDs"].'>';
349
- if (@$fields_mapping["LatestOrderCategoryIDs"]) $tmp[$fields_mapping["LatestOrderCategoryIDs"]] = '<campo'.$fields_mapping["LatestOrderCategoryIDs"].'>'. $subscriber['IDCategorieUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderCategoryIDs"].'>';
350
- if (@$fields_mapping["LatestShippedOrderDate"]) $tmp[$fields_mapping["LatestShippedOrderDate"]] = '<campo'.$fields_mapping["LatestShippedOrderDate"].'>'. $subscriber['DataUltimoOrdineSpedito'] .'</campo'.$fields_mapping["LatestShippedOrderDate"].'>';
351
- if (@$fields_mapping["LatestShippedOrderID"]) $tmp[$fields_mapping["LatestShippedOrderID"]] = '<campo'.$fields_mapping["LatestShippedOrderID"].'>'. $subscriber['IDUltimoOrdineSpedito'] .'</campo'.$fields_mapping["LatestShippedOrderID"].'>';
352
- if (@$fields_mapping["LatestAbandonedCartDate"]) $tmp[$fields_mapping["LatestAbandonedCartDate"]] = '<campo'.$fields_mapping["LatestAbandonedCartDate"].'>'. $subscriber['DataCarrelloAbbandonato'] .'</campo'.$fields_mapping["LatestAbandonedCartDate"].'>';
353
- if (@$fields_mapping["LatestAbandonedCartTotal"]) $tmp[$fields_mapping["LatestAbandonedCartTotal"]] = '<campo'.$fields_mapping["LatestAbandonedCartTotal"].'>'. $subscriber['TotaleCarrelloAbbandonato'] .'</campo'.$fields_mapping["LatestAbandonedCartTotal"].'>';
354
- if (@$fields_mapping["LatestAbandonedCartID"]) $tmp[$fields_mapping["LatestAbandonedCartID"]] = '<campo'.$fields_mapping["LatestAbandonedCartID"].'>'. $subscriber['IDCarrelloAbbandonato'] .'</campo'.$fields_mapping["LatestAbandonedCartID"].'>';
355
- if (@$fields_mapping["TotalOrdered"]) $tmp[$fields_mapping["TotalOrdered"]] = '<campo'.$fields_mapping["TotalOrdered"].'>'. $subscriber['TotaleFatturato'] .'</campo'.$fields_mapping["TotalOrdered"].'>';
356
- if (@$fields_mapping["TotalOrderedLast12m"]) $tmp[$fields_mapping["TotalOrderedLast12m"]] = '<campo'.$fields_mapping["TotalOrderedLast12m"].'>'. $subscriber['TotaleFatturatoUltimi12Mesi'] .'</campo'.$fields_mapping["TotalOrderedLast12m"].'>';
357
- if (@$fields_mapping["TotalOrderedLast30d"]) $tmp[$fields_mapping["TotalOrderedLast30d"]] = '<campo'.$fields_mapping["TotalOrderedLast30d"].'>'. $subscriber['TotaleFatturatoUltimi30gg'] .'</campo'.$fields_mapping["TotalOrderedLast30d"].'>';
358
- if (@$fields_mapping["AllOrderedProductIDs"]) $tmp[$fields_mapping["AllOrderedProductIDs"]] = '<campo'.$fields_mapping["AllOrderedProductIDs"].'>'. $subscriber['IDTuttiProdottiAcquistati'] .'</campo'.$fields_mapping["AllOrderedProductIDs"].'>';
359
-
360
- $last_field = max(array_keys($tmp));
361
- for ($i=1; $i<$last_field; $i++) {
362
- if (!isset($tmp[$i])) $tmp[$i] = "<campo{$i}>-</campo{$i}>";
363
- }
364
- ksort($tmp);
365
- $tmp = implode("", $tmp);
366
- $xmlData .= $tmp;
367
- $xmlData .= "</subscriber>\n";
368
-
369
- // ogni 5000 utenti invio i dati
370
- if ($subscribers_counter == 5000) {
371
- $importProcessData["xmlDoc"] = "<subscribers>$xmlData</subscribers>";
372
- $xmlData = "";
373
- $subscribers_counter = 0;
374
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($importProcessData, 0);
375
- $processID = $wsImport->newImportProcess($importProcessData);
376
- if ($processID === false) return false;
377
- }
378
- }
379
-
380
- //invio gli ultimi utenti
381
- if (strlen($xmlData)) {
382
- $importProcessData["xmlDoc"] = "<subscribers>$xmlData</subscribers>";
383
- $xmlData = "";
384
- $subscribers_counter = 0;
385
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($importProcessData, 0);
386
- $processID = $wsImport->newImportProcess($importProcessData);
387
- if ($processID === false) return false;
388
- }
389
-
390
- if (isset($newsletter_subscribers) and is_array($newsletter_subscribers) and !empty($newsletter_subscribers)) {
391
- $subscribers_counter = 0;
392
- foreach ($newsletter_subscribers as $newsletter_subscriber) {
393
- $subscribers_counter++;
394
- $xmlData .= '<subscriber email="' . $newsletter_subscriber . '" Number="" Name=""></subscriber>';
395
- if ($subscribers_counter == 5000 or $subscribers_counter == $total_subscribers_to_send) {
396
- $importProcessData["xmlDoc"] = "<subscribers>$xmlData</subscribers>";
397
- $xmlData = "";
398
- $subscribers_counter = 0;
399
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($importProcessData, 0);
400
- $processID = $wsImport->newImportProcess($importProcessData);
401
- if ($processID === false) return false;
402
- }
403
- }
404
- }
405
-
406
- //avvio l'importazione su mailup
407
- unset($importProcessData["xmlDoc"]);
408
- $importProcessData["listsIDs"] = $post['mailupIdList'];
409
- $importProcessData["listsGUIDs"] = $post['mailupListGUID'];
410
- $importProcessData["groupsIDs"] = $groupId;
411
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log("mailup: StartImportProcesses", 0);
412
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($importProcessData, 0);
413
- $check = $wsImport->StartImportProcesses($importProcessData);
414
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($check, 0);
415
- return $check;
416
- }
417
-
418
- private static function _formatPrice($price) {
419
- return number_format($price, 2, ',', '');
420
- }
421
-
422
- private static function _retriveDateFromDatetime($datetime) {
423
- if (empty($datetime)) return "";
424
- return date("Y-m-d H:i:s", strtotime($datetime));
425
- }
426
-
427
- public static function _convertUTCToStoreTimezone($datetime)
428
- {
429
- if (empty($datetime)) return "";
430
-
431
- $TIMEZONE_STORE = new DateTimeZone(Mage::getStoreConfig("general/locale/timezone"));
432
- $TIMEZONE_UTC = new DateTimeZone("UTC");
433
-
434
- $datetime = new DateTime($datetime, $TIMEZONE_UTC);
435
- $datetime->setTimezone($TIMEZONE_STORE);
436
- $datetime = (string)$datetime->format("Y-m-d H:i:s");
437
-
438
- return $datetime;
439
- }
440
-
441
- public static function _convertUTCToStoreTimezoneAndFormatForMailup($datetime)
442
- {
443
- if (empty($datetime)) return "";
444
- $datetime = self::_convertUTCToStoreTimezone($datetime);
445
- return date("d/m/Y", strtotime($datetime));
446
- }
447
}
1
+ <?php
2
+
3
+ class SevenLike_MailUp_Helper_Data extends Mage_Core_Helper_Abstract
4
+ {
5
+ public static function getCustomersData($customerCollection = null)
6
+ {
7
+ $config = Mage::getModel('mailup/config');
8
+ /* @var $config SevenLike_Mailup_Model_Config */
9
+
10
+ if ($config->isLogEnabled()) {
11
+ Mage::log('Getting customers data', 0);
12
+ }
13
+
14
+ if(is_array($customerCollection) && empty($customerCollection)) {
15
+ if ($config->isLogEnabled()) {
16
+ Mage::log('CustomerCollection is Empty!');
17
+ }
18
+ }
19
+
20
+ $dateFormat = 'm/d/y h:i:s';
21
+ $lastDateTime = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-7*3600*24);
22
+ $thirtyDaysAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-30*3600*24);
23
+ $twelveMonthsAgo = date($dateFormat, Mage::getModel('core/date')->timestamp(time())-365*3600*24);
24
+
25
+ $parseSubscribers = false;
26
+ $toSend = array();
27
+ if ($customerCollection === null) {
28
+ /**
29
+ * @todo Change to only load form current store/website
30
+ */
31
+ $customerCollection = Mage::getModel('customer/customer')->getCollection();
32
+ $parseSubscribers = true;
33
+ if ($config->isLogEnabled()) {
34
+ Mage::log('Parsing Subscribers, NULL collection passed.');
35
+ }
36
+ }
37
+ foreach ($customerCollection as $currentCustomerId) {
38
+ if (is_object($currentCustomerId)) {
39
+ $currentCustomerId = $currentCustomerId->getId();
40
+ }
41
+
42
+ if( ! $currentCustomerId) {
43
+ if($config->isLogEnabled()) {
44
+ Mage::log('Skipping Empty Customer ID!');
45
+ continue;
46
+ }
47
+ }
48
+
49
+ if($config->isLogEnabled()) {
50
+ Mage::log('Customer with id '.$currentCustomerId, 0);
51
+ }
52
+ $customer = Mage::getModel('customer/customer')->load($currentCustomerId);
53
+ $i = $customer->getEmail();
54
+
55
+ //recupero gli ordini del cliente corrente
56
+ $allOrdersTotalAmount = 0;
57
+ $allOrdersDateTimes = array();
58
+ $allOrdersTotals = array();
59
+ $allOrdersIds = array();
60
+ $allProductsIds = array();
61
+ $last30daysOrdersAmount = 0;
62
+ $last12monthsOrdersAmount = 0;
63
+ $lastShipmentOrderId = null;
64
+ $lastShipmentOrderDate = null;
65
+
66
+ if($config->isLogEnabled()) {
67
+ Mage::log('Parsing orders of customer with id '.$currentCustomerId, 0);
68
+ }
69
+ $orders = Mage::getModel('sales/order')
70
+ ->getCollection()
71
+ ->addAttributeToFilter('customer_id', $currentCustomerId)
72
+ ;
73
+ foreach($orders as $order) {
74
+ if($config->isLogEnabled()) {
75
+ Mage::log("ORDINE IN STATUS: " . $order->getStatus());
76
+ }
77
+ if( ! in_array($order->getStatus(), array("closed", "complete", "processing"))) {
78
+ continue;
79
+ }
80
+ $currentOrderTotal = floatval($order->getGrandTotal());
81
+ $allOrdersTotalAmount += $currentOrderTotal;
82
+
83
+ $currentOrderCreationDate = $order->getCreatedAt();
84
+ if ($currentOrderCreationDate > $thirtyDaysAgo) {
85
+ $last30daysOrdersAmount += $currentOrderTotal;
86
+
87
+ }
88
+ if ($currentOrderCreationDate > $twelveMonthsAgo) {
89
+ $last12monthsOrdersAmount += $currentOrderTotal;
90
+ }
91
+
92
+ $currentOrderTotal = self::_formatPrice($currentOrderTotal);
93
+
94
+ $currentOrderId = $order->getIncrementId();
95
+ $allOrdersTotals[$currentOrderId] = $currentOrderTotal;
96
+ $allOrdersDateTimes[$currentOrderId] = $currentOrderCreationDate;
97
+ $allOrdersIds[$currentOrderId] = $currentOrderId;
98
+
99
+ if ($order->hasShipments() and ($order->getId()>$lastShipmentOrderId)) {
100
+ $lastShipmentOrderId = $order->getId();
101
+ $lastShipmentOrderDate = self::_retriveDateFromDatetime($order->getCreatedAt());
102
+ }
103
+
104
+ $items = $order->getAllItems();
105
+ foreach ($items as $item) {
106
+ $allProductsIds[] = $item->getProductId();
107
+ }
108
+ }
109
+
110
+ $toSend[$i]['TotaleFatturatoUltimi30gg'] = self::_formatPrice($last30daysOrdersAmount);
111
+ $toSend[$i]['TotaleFatturatoUltimi12Mesi'] = self::_formatPrice($last12monthsOrdersAmount);
112
+ $toSend[$i]['IDTuttiProdottiAcquistati'] = implode(',', $allProductsIds);
113
+
114
+ ksort($allOrdersDateTimes);
115
+ ksort($allOrdersTotals);
116
+ ksort($allOrdersIds);
117
+
118
+ //recupero i carrelli abbandonati del cliente
119
+ if($config->isLogEnabled()) {
120
+ Mage::log('Parsing abandoned carts of customer with id '.$currentCustomerId, 0);
121
+ }
122
+ $cartCollection = Mage::getResourceModel('reports/quote_collection');
123
+ $cartCollection->prepareForAbandonedReport($config->getAllStoreIds());
124
+ $cartCollection->addFieldToFilter('customer_id', $currentCustomerId);
125
+ $cartCollection->load();
126
+
127
+ $datetimeCart = null;
128
+ if ( ! empty($cartCollection)) {
129
+ $lastCart = $cartCollection->getLastItem();
130
+ $toSend[$i]['TotaleCarrelloAbbandonato'] = '';
131
+ $toSend[$i]['DataCarrelloAbbandonato'] = '';
132
+ $toSend[$i]['IDCarrelloAbbandonato'] = '';
133
+
134
+ if ( ! empty($lastCart)) {
135
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) {
136
+ Mage::log('Customer with id '.$currentCustomerId .' has abandoned cart', 0);
137
+ }
138
+ $datetimeCart = $lastCart->getUpdatedAt();
139
+ //$toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getGrandTotal());
140
+ $toSend[$i]['TotaleCarrelloAbbandonato'] = self::_formatPrice($lastCart->getSubtotal());
141
+ $toSend[$i]['DataCarrelloAbbandonato'] = self::_retriveDateFromDatetime($datetimeCart);
142
+ $toSend[$i]['IDCarrelloAbbandonato'] = $lastCart->getId();
143
+ }
144
+ else {
145
+ if ($config->isLogEnabled()) {
146
+ Mage::log('Customer with id '.$currentCustomerId .' has empty LAST CART', 0);
147
+ }
148
+ }
149
+ }
150
+ else {
151
+ if ($config->isLogEnabled()) {
152
+ Mage::log('Customer id '.$currentCustomerId .' has empty abandoned cart collection', 0);
153
+ }
154
+ }
155
+
156
+ $toSend[$i]['IDUltimoOrdineSpedito'] = $lastShipmentOrderId;
157
+ $toSend[$i]['DataUltimoOrdineSpedito'] = $lastShipmentOrderDate;
158
+
159
+ $lastOrderDateTime = end($allOrdersDateTimes);
160
+
161
+ if ($customer->getUpdatedAt() > $lastDateTime
162
+ || $lastOrderDateTime > $lastDateTime
163
+ || ($datetimeCart && $datetimeCart > $lastDateTime))
164
+ {
165
+ if ($config->isLogEnabled()) {
166
+ Mage::log('Adding customer with id '.$currentCustomerId, 0);
167
+ }
168
+
169
+ $toSend[$i]['nome'] = $customer->getFirstname();
170
+ $toSend[$i]['cognome'] = $customer->getLastname();
171
+ $toSend[$i]['email'] = $customer->getEmail();
172
+ $toSend[$i]['IDCliente'] = $currentCustomerId;
173
+
174
+ $toSend[$i]['registeredDate'] = self::_retriveDateFromDatetime($customer->getCreatedAt());
175
+
176
+ //controllo se iscritto o meno alla newsletter
177
+ if (Mage::getModel('newsletter/subscriber')->loadByCustomer($customer)->isSubscribed()) {
178
+ $toSend[$i]['subscribed'] = 'yes';
179
+ }
180
+ else {
181
+ $toSend[$i]['subscribed'] = 'no';
182
+ }
183
+
184
+ //recupero i dati dal default billing address
185
+ $customerAddressId = $customer->getDefaultBilling();
186
+ if ($customerAddressId) {
187
+ $address = Mage::getModel('customer/address')->load($customerAddressId);
188
+ $toSend[$i]['azienda'] = $address->getData('company');
189
+ $toSend[$i]['paese'] = $address->getCountry();
190
+ $toSend[$i]['città'] = $address->getData('city');
191
+ $toSend[$i]['regione'] = $address->getData('region');
192
+ $regionId = $address->getData('region_id');
193
+ $regionModel = Mage::getModel('directory/region')->load($regionId);
194
+ $regionCode = $regionModel->getCode();
195
+ $toSend[$i]['provincia'] = $regionCode;
196
+ $toSend[$i]['cap'] = $address->getData('postcode');
197
+ $toSend[$i]['indirizzo'] = $address->getData('street');
198
+ $toSend[$i]['fax'] = $address->getData('fax');
199
+ $toSend[$i]['telefono'] = $address->getData('telephone');
200
+ }
201
+
202
+ $toSend[$i]['DataUltimoOrdine'] = self::_retriveDateFromDatetime($lastOrderDateTime);
203
+ $toSend[$i]['TotaleUltimoOrdine'] = end($allOrdersTotals);
204
+ $toSend[$i]['IDUltimoOrdine'] = end($allOrdersIds);
205
+
206
+ $toSend[$i]['TotaleFatturato'] = self::_formatPrice($allOrdersTotalAmount);
207
+
208
+ //ottengo gli id di prodotti e categorie (dell'ultimo ordine)
209
+ $lastOrder = Mage::getModel('sales/order')->loadByIncrementId(end($allOrdersIds));
210
+ $items = $lastOrder->getAllItems();
211
+ $productIds = array();
212
+ $categoryIds = array();
213
+ foreach ($items as $item) {
214
+ $productId = $item->getProductId();
215
+ $productIds[] = $productId;
216
+ $product = Mage::getModel('catalog/product')->load($productId);
217
+ if ($product->getCategoryIds()) {
218
+ $categoryIds[] = implode(',', $product->getCategoryIds());
219
+ }
220
+ }
221
+
222
+ $toSend[$i]['IDProdottiUltimoOrdine'] = implode(',', $productIds);
223
+ if ($toSend[$i]['IDProdottiUltimoOrdine']) $toSend[$i]['IDProdottiUltimoOrdine'] = ",{$toSend[$i]['IDProdottiUltimoOrdine']},";
224
+ $toSend[$i]['IDCategorieUltimoOrdine'] = implode(',', $categoryIds);
225
+ if ($toSend[$i]['IDCategorieUltimoOrdine']) $toSend[$i]['IDCategorieUltimoOrdine'] = ",{$toSend[$i]['IDCategorieUltimoOrdine']},";
226
+ }
227
+
228
+ //unsetto la variabile
229
+ unset($customer);
230
+ }
231
+
232
+ /*
233
+ * disabled cause useless in segmentation
234
+ if ($parseSubscribers) {
235
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) Mage::log('Parsing subscribers', 0);
236
+ $subscriberCollection = Mage::getModel('newsletter/subscriber')
237
+ ->getCollection()
238
+ ->useOnlySubscribed()
239
+ ->addFieldToFilter('customer_id', 0);
240
+
241
+ foreach ($subscriberCollection as $subscriber) {
242
+ $subscriber = Mage::getModel('newsletter/subscriber')->load($subscriber->getId());
243
+ $i = $subscriber->getEmail();
244
+ if (strlen($i)) continue;
245
+ if (isset($toSend[$i])) continue;
246
+ $toSend[$i]['nome'] = '';
247
+ $toSend[$i]['cognome'] = '';
248
+ $toSend[$i]['email'] = $i;
249
+ $toSend[$i]['subscribed'] = 'yes';
250
+ }
251
+ }
252
+ */
253
+
254
+ if($config->isLogEnabled()) {
255
+ Mage::log('End getting customers data', 0);
256
+ }
257
+
258
+ return $toSend;
259
+ }
260
+
261
+ /**
262
+ * Sebd Customer Data
263
+ *
264
+ * @param type $mailupCustomerIds
265
+ * @param type $post
266
+ * @param type $newsletter_subscribers
267
+ * @param int
268
+ * @return boolean
269
+ */
270
+ public static function generateAndSendCustomers($mailupCustomerIds, $post = null, $newsletter_subscribers = null, $storeId = NULL)
271
+ {
272
+ $config = Mage::getModel('mailup/config');
273
+ /* @var $config SevenLike_Mailup_Model_Config */
274
+
275
+ $wsSend = new MailUpWsSend($storeId);
276
+ require_once dirname(__FILE__) . "/../Model/MailUpWsImport.php";
277
+ $wsImport = new MailUpWsImport($storeId);
278
+ $accessKey = $wsSend->loginFromId();
279
+
280
+ if (empty($mailupCustomerIds)) {
281
+ if($config->isLogEnabled($storeId)) {
282
+ Mage::log('Empty Customer ID Array');
283
+ }
284
+ return false;
285
+ }
286
+ /**
287
+ * Post EMPTY
288
+ */
289
+ if ($post === NULL) {
290
+ // chiamata da cron, popolo con i dati del gruppo "magento" di default
291
+ $post['mailupNewGroup'] = 0;
292
+ $post['mailupIdList'] = Mage::getStoreConfig('mailup_newsletter/mailup/list', $storeId);
293
+
294
+ $tmp = new SevenLike_MailUp_Model_Lists;
295
+ $tmp = $tmp->toOptionArray($storeId); // pass store id!
296
+
297
+ foreach ($tmp as $t) {
298
+ if ($t["value"] == $post['mailupIdList']) {
299
+ $post['mailupListGUID'] = $t["guid"];
300
+ $post["groups"] = $t["groups"];
301
+ break;
302
+ }
303
+ }
304
+
305
+ unset($tmp);
306
+ unset($t);
307
+
308
+ $post['mailupGroupId'] = "";
309
+ foreach ($post["groups"] as $tmp_id_group => $tmp_group_name) {
310
+ if ($tmp_group_name == "MAGENTO") {
311
+ $post['mailupGroupId'] = $tmp_id_group;
312
+ break;
313
+ }
314
+ }
315
+ unset($tmp_id_group); unset($tmp_group_name);
316
+
317
+ if (!strlen($post['mailupGroupId'])) {
318
+ $newGroup = array(
319
+ "idList" => $post['mailupIdList'],
320
+ "listGUID" => $post['mailupListGUID'],
321
+ "newGroupName" => "MAGENTO"
322
+ );
323
+
324
+ $post['mailupGroupId'] = $wsImport->CreaGruppo($newGroup);
325
+ }
326
+ }
327
+
328
+ if ($accessKey === false) {
329
+ Mage::throwException('no access key returned');
330
+ }
331
+
332
+ $fields = $wsSend->GetFields($accessKey);
333
+ $fields_mapping = $wsImport->getFieldsMapping($storeId); // Pass StoreId
334
+
335
+ //definisco il gruppo a cui aggiungere gli iscritti
336
+ $groupId = $post['mailupGroupId'];
337
+ $listGUID = $post['mailupListGUID'];
338
+ $idList = $post['mailupIdList'];
339
+
340
+ if ($post['mailupNewGroup'] == 1) {
341
+ $newGroup = array(
342
+ "idList" => $idList,
343
+ "listGUID" => $listGUID,
344
+ "newGroupName" => $post['mailupNewGroupName']
345
+ );
346
+
347
+ $groupId = $wsImport->CreaGruppo($newGroup);
348
+ }
349
+
350
+ if (isset($post["send_optin_email_to_new_subscribers"]) and $post["send_optin_email_to_new_subscribers"]) {
351
+ $importProcessData = array(
352
+ "idList" => $idList,
353
+ "listGUID" => $listGUID,
354
+ "idGroup" => $groupId,
355
+ "xmlDoc" => "",
356
+ "idGroups" => $groupId,
357
+ "importType" => 1,
358
+ "mobileInputType" => 2,
359
+ "asPending" => 0,
360
+ "ConfirmEmail" => 1,
361
+ "asOptOut" => 0,
362
+ "forceOptIn" => 0, //1,
363
+ "replaceGroups" => 0,
364
+ "idConfirmNL" => 0
365
+ );
366
+ }
367
+ else {
368
+ $importProcessData = array(
369
+ "idList" => $idList,
370
+ "listGUID" => $listGUID,
371
+ "idGroup" => $groupId,
372
+ "xmlDoc" => "",
373
+ "idGroups" => $groupId,
374
+ "importType" => 1,
375
+ "mobileInputType" => 2,
376
+ "asPending" => 0,
377
+ "ConfirmEmail" => 0,
378
+ "asOptOut" => 0,
379
+ "forceOptIn" => 0, //1,
380
+ "replaceGroups" => 0,
381
+ "idConfirmNL" => 0
382
+ );
383
+ }
384
+
385
+ //preparo l'xml degli iscritti da inviare a mailup (da gestire in base ai filtri)
386
+ $xmlData = '';
387
+ $subscribers_counter = 0;
388
+ $total_subscribers_to_send = sizeof($mailupCustomerIds);
389
+ foreach ($mailupCustomerIds as $customerId) {
390
+ $tmp = array();
391
+ $subscribers_counter++;
392
+ $subscriber = self::getCustomersData(array($customerId));
393
+
394
+ if(is_array($subscriber) && empty($subscriber)) {
395
+ if($config->isLogEnabled($storeId)) {
396
+ Mage::log('EMPTY DATA FROM getCustomersData');
397
+ }
398
+ }
399
+
400
+ $subscriber = array_values($subscriber);
401
+ $subscriber = $subscriber[0];
402
+
403
+ $subscriber["DataCarrelloAbbandonato"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataCarrelloAbbandonato"]);
404
+ $subscriber["DataUltimoOrdineSpedito"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataUltimoOrdineSpedito"]);
405
+ $subscriber["registeredDate"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["registeredDate"]);
406
+ $subscriber["DataUltimoOrdine"] = self::_convertUTCToStoreTimezoneAndFormatForMailup($subscriber["DataUltimoOrdine"]);
407
+
408
+ $xmlData .= '<subscriber email="'.$subscriber['email'].'" Number="" Name="">';
409
+
410
+ if (@$fields_mapping["Name"]) $tmp[$fields_mapping["Name"]] = '<campo'.$fields_mapping["Name"].'>'."<![CDATA[". ((!empty($subscriber['nome'])) ? $subscriber['nome'] : '') ."]]>".'</campo'.$fields_mapping["Name"].'>';
411
+ if (@$fields_mapping["Last"]) $tmp[$fields_mapping["Last"]] = '<campo'.$fields_mapping["Last"].'>'."<![CDATA[". ((!empty($subscriber['cognome'])) ? $subscriber['cognome'] : '') ."]]>".'</campo'.$fields_mapping["Last"].'>';
412
+
413
+
414
+ foreach ($subscriber as $k=>$v) {
415
+ if (!strlen($subscriber[$k])) {
416
+ $subscriber[$k] = "-";
417
+ }
418
+ else {
419
+ $subscriber[$k] = str_replace(array("\r\n", "\r", "\n"), " ", $v);
420
+ }
421
+ }
422
+
423
+ if (@$fields_mapping["Company"]) $tmp[$fields_mapping["Company"]] = '<campo'.$fields_mapping["Company"].'>'. "<![CDATA[". $subscriber['azienda'] ."]]>". '</campo'.$fields_mapping["Company"].'>';
424
+ if (@$fields_mapping["City"]) $tmp[$fields_mapping["City"]] = '<campo'.$fields_mapping["City"].'>'. "<![CDATA[" . $subscriber['città'] ."]]>". '</campo'.$fields_mapping["City"].'>';
425
+ if (@$fields_mapping["Province"]) $tmp[$fields_mapping["Province"]] = '<campo'.$fields_mapping["Province"].'>'. "<![CDATA[" . $subscriber['provincia'] ."]]>" . '</campo'.$fields_mapping["Province"].'>';
426
+ if (@$fields_mapping["ZIP"]) $tmp[$fields_mapping["ZIP"]] = '<campo'.$fields_mapping["ZIP"].'>'. $subscriber['cap'].'</campo'.$fields_mapping["ZIP"].'>';
427
+ if (@$fields_mapping["Region"]) $tmp[$fields_mapping["Region"]] = '<campo'.$fields_mapping["Region"].'>'. $subscriber['regione'] .'</campo'.$fields_mapping["Region"].'>';
428
+ if (@$fields_mapping["Country"]) $tmp[$fields_mapping["Country"]] = '<campo'.$fields_mapping["Country"].'>'. $subscriber['paese'] .'</campo'.$fields_mapping["Country"].'>';
429
+ if (@$fields_mapping["Address"]) $tmp[$fields_mapping["Address"]] = '<campo'.$fields_mapping["Address"].'>'."<![CDATA[". $subscriber['indirizzo'] ."]]>" .'</campo'.$fields_mapping["Address"].'>';
430
+ if (@$fields_mapping["Fax"]) $tmp[$fields_mapping["Fax"]] = '<campo'.$fields_mapping["Fax"].'>'. $subscriber['fax'] .'</campo'.$fields_mapping["Fax"].'>';
431
+ if (@$fields_mapping["Phone"]) $tmp[$fields_mapping["Phone"]] = '<campo'.$fields_mapping["Phone"].'>'. $subscriber['telefono'] .'</campo'.$fields_mapping["Phone"].'>';
432
+ if (@$fields_mapping["CustomerID"]) $tmp[$fields_mapping["CustomerID"]] = '<campo'.$fields_mapping["CustomerID"].'>'. $subscriber['IDCliente'] .'</campo'.$fields_mapping["CustomerID"].'>';
433
+ if (@$fields_mapping["LatestOrderID"]) $tmp[$fields_mapping["LatestOrderID"]] = '<campo'.$fields_mapping["LatestOrderID"].'>'. $subscriber['IDUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderID"].'>';
434
+ if (@$fields_mapping["LatestOrderDate"]) $tmp[$fields_mapping["LatestOrderDate"]] = '<campo'.$fields_mapping["LatestOrderDate"].'>'. $subscriber['DataUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderDate"].'>';
435
+ if (@$fields_mapping["LatestOrderAmount"]) $tmp[$fields_mapping["LatestOrderAmount"]] = '<campo'.$fields_mapping["LatestOrderAmount"].'>'. $subscriber['TotaleUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderAmount"].'>';
436
+ if (@$fields_mapping["LatestOrderProductIDs"]) $tmp[$fields_mapping["LatestOrderProductIDs"]] = '<campo'.$fields_mapping["LatestOrderProductIDs"].'>'. $subscriber['IDProdottiUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderProductIDs"].'>';
437
+ if (@$fields_mapping["LatestOrderCategoryIDs"]) $tmp[$fields_mapping["LatestOrderCategoryIDs"]] = '<campo'.$fields_mapping["LatestOrderCategoryIDs"].'>'. $subscriber['IDCategorieUltimoOrdine'] .'</campo'.$fields_mapping["LatestOrderCategoryIDs"].'>';
438
+ if (@$fields_mapping["LatestShippedOrderDate"]) $tmp[$fields_mapping["LatestShippedOrderDate"]] = '<campo'.$fields_mapping["LatestShippedOrderDate"].'>'. $subscriber['DataUltimoOrdineSpedito'] .'</campo'.$fields_mapping["LatestShippedOrderDate"].'>';
439
+ if (@$fields_mapping["LatestShippedOrderID"]) $tmp[$fields_mapping["LatestShippedOrderID"]] = '<campo'.$fields_mapping["LatestShippedOrderID"].'>'. $subscriber['IDUltimoOrdineSpedito'] .'</campo'.$fields_mapping["LatestShippedOrderID"].'>';
440
+ if (@$fields_mapping["LatestAbandonedCartDate"]) $tmp[$fields_mapping["LatestAbandonedCartDate"]] = '<campo'.$fields_mapping["LatestAbandonedCartDate"].'>'. $subscriber['DataCarrelloAbbandonato'] .'</campo'.$fields_mapping["LatestAbandonedCartDate"].'>';
441
+ if (@$fields_mapping["LatestAbandonedCartTotal"]) $tmp[$fields_mapping["LatestAbandonedCartTotal"]] = '<campo'.$fields_mapping["LatestAbandonedCartTotal"].'>'. $subscriber['TotaleCarrelloAbbandonato'] .'</campo'.$fields_mapping["LatestAbandonedCartTotal"].'>';
442
+ if (@$fields_mapping["LatestAbandonedCartID"]) $tmp[$fields_mapping["LatestAbandonedCartID"]] = '<campo'.$fields_mapping["LatestAbandonedCartID"].'>'. $subscriber['IDCarrelloAbbandonato'] .'</campo'.$fields_mapping["LatestAbandonedCartID"].'>';
443
+ if (@$fields_mapping["TotalOrdered"]) $tmp[$fields_mapping["TotalOrdered"]] = '<campo'.$fields_mapping["TotalOrdered"].'>'. $subscriber['TotaleFatturato'] .'</campo'.$fields_mapping["TotalOrdered"].'>';
444
+ if (@$fields_mapping["TotalOrderedLast12m"]) $tmp[$fields_mapping["TotalOrderedLast12m"]] = '<campo'.$fields_mapping["TotalOrderedLast12m"].'>'. $subscriber['TotaleFatturatoUltimi12Mesi'] .'</campo'.$fields_mapping["TotalOrderedLast12m"].'>';
445
+ if (@$fields_mapping["TotalOrderedLast30d"]) $tmp[$fields_mapping["TotalOrderedLast30d"]] = '<campo'.$fields_mapping["TotalOrderedLast30d"].'>'. $subscriber['TotaleFatturatoUltimi30gg'] .'</campo'.$fields_mapping["TotalOrderedLast30d"].'>';
446
+ if (@$fields_mapping["AllOrderedProductIDs"]) $tmp[$fields_mapping["AllOrderedProductIDs"]] = '<campo'.$fields_mapping["AllOrderedProductIDs"].'>'. $subscriber['IDTuttiProdottiAcquistati'] .'</campo'.$fields_mapping["AllOrderedProductIDs"].'>';
447
+
448
+ $last_field = max(array_keys($tmp));
449
+ for ($i=1; $i<$last_field; $i++) {
450
+ if (!isset($tmp[$i])) $tmp[$i] = "<campo{$i}>-</campo{$i}>";
451
+ }
452
+ ksort($tmp);
453
+ $tmp = implode("", $tmp);
454
+ $xmlData .= $tmp;
455
+ $xmlData .= "</subscriber>\n";
456
+
457
+ //if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log', $storeId)) Mage::log("Store ID before newImportProcess: {$storeId}");
458
+
459
+ // ogni 5000 utenti invio i dati
460
+ if ($subscribers_counter == 5000) {
461
+ $importProcessData["xmlDoc"] = "<subscribers>$xmlData</subscribers>";
462
+ $xmlData = "";
463
+ $subscribers_counter = 0;
464
+ if($config->isLogEnabled($storeId)) {
465
+ Mage::log('ImportProcessData SubscriberCounr == 5000');
466
+ Mage::log($importProcessData, 0);
467
+ }
468
+ $processID = $wsImport->newImportProcess($importProcessData);
469
+ if ($processID === false) {
470
+ return false;
471
+ }
472
+ }
473
+ }
474
+
475
+ //invio gli ultimi utenti
476
+ if (strlen($xmlData)) {
477
+ $importProcessData["xmlDoc"] = "<subscribers>$xmlData</subscribers>";
478
+
479
+ $xmlData = "";
480
+ $subscribers_counter = 0;
481
+ if($config->isLogEnabled($storeId)) {
482
+ Mage::log('ImportProcessData');
483
+ Mage::log($importProcessData, 0);
484
+ }
485
+ $processID = $wsImport->newImportProcess($importProcessData);
486
+ if($processID === FALSE) {
487
+ if($config->isLogEnabled($storeId)) {
488
+ Mage::log('newImportProcess B FALSE');
489
+ }
490
+ return FALSE;
491
+ }
492
+ }
493
+
494
+ if (isset($newsletter_subscribers) and is_array($newsletter_subscribers) and !empty($newsletter_subscribers)) {
495
+ $subscribers_counter = 0;
496
+ foreach ($newsletter_subscribers as $newsletter_subscriber) {
497
+ $subscribers_counter++;
498
+ $xmlData .= '<subscriber email="' . $newsletter_subscriber . '" Number="" Name=""></subscriber>';
499
+ if ($subscribers_counter == 5000 or $subscribers_counter == $total_subscribers_to_send) {
500
+ $importProcessData["xmlDoc"] = "<subscribers>$xmlData</subscribers>";
501
+ $xmlData = "";
502
+ $subscribers_counter = 0;
503
+ if($config->isLogEnabled($storeId)) {
504
+ Mage::log($importProcessData, 0);
505
+ }
506
+ $processID = $wsImport->newImportProcess($importProcessData);
507
+ if ($processID === FALSE) {
508
+ if($config->isLogEnabled($storeId)) {
509
+ Mage::log('newImportProcess C FALSE');
510
+ }
511
+ return FALSE;
512
+ }
513
+ }
514
+ }
515
+ }
516
+
517
+ /**
518
+ * This needs unset in the newer version of the API, we needed it in the old API backend.
519
+ */
520
+ unset($importProcessData["xmlDoc"]);
521
+
522
+ $importProcessData["listsIDs"] = $post['mailupIdList'];
523
+ $importProcessData["listsGUIDs"] = $post['mailupListGUID'];
524
+ $importProcessData["groupsIDs"] = $groupId;
525
+
526
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log', $storeId)) {
527
+ Mage::log("mailup: StartImportProcesses (STORE: {$storeId})", 0);
528
+ Mage::log($importProcessData, 0);
529
+ }
530
+
531
+ $check = $wsImport->StartImportProcesses($importProcessData);
532
+
533
+ if ($config->isLogEnabled($storeId)) {
534
+ Mage::log('StartImportProcesses Check: ' . $check, 0);
535
+ }
536
+
537
+ return $check;
538
+ }
539
+
540
+ private static function _formatPrice($price) {
541
+ return number_format($price, 2, ',', '');
542
+ }
543
+
544
+ private static function _retriveDateFromDatetime($datetime) {
545
+ if (empty($datetime)) return "";
546
+ return date("Y-m-d H:i:s", strtotime($datetime));
547
+ }
548
+
549
+ public static function _convertUTCToStoreTimezone($datetime)
550
+ {
551
+ if (empty($datetime)) return "";
552
+
553
+ $TIMEZONE_STORE = new DateTimeZone(Mage::getStoreConfig("general/locale/timezone"));
554
+ $TIMEZONE_UTC = new DateTimeZone("UTC");
555
+
556
+ $datetime = new DateTime($datetime, $TIMEZONE_UTC);
557
+ $datetime->setTimezone($TIMEZONE_STORE);
558
+ $datetime = (string)$datetime->format("Y-m-d H:i:s");
559
+
560
+ return $datetime;
561
+ }
562
+
563
+ public static function _convertUTCToStoreTimezoneAndFormatForMailup($datetime)
564
+ {
565
+ if (empty($datetime)) return "";
566
+ $datetime = self::_convertUTCToStoreTimezone($datetime);
567
+ return date("d/m/Y", strtotime($datetime));
568
+ }
569
+
570
+ /**
571
+ * Clean the Resource Table
572
+ */
573
+ public function cleanResourceTable()
574
+ {
575
+ $sql = "DELETE FROM `core_resource` WHERE `code` = 'mailup_setup';";
576
+ $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
577
+ try {
578
+ $connection->query($sql);
579
+ die('deleted module in core_resource!');
580
+ }
581
+ catch(Exception $e){
582
+ echo $e->getMessage();
583
+ }
584
+ }
585
+
586
+ /**
587
+ * Clean the Resource Table
588
+ */
589
+ public function showResourceTable()
590
+ {
591
+ $sql = "SELECT * FROM `core_resource`";
592
+ $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
593
+ try {
594
+ $result = $connection->fetchAll($sql);
595
+ foreach($result as $row) {
596
+ echo $row['code'] . "<br />";
597
+ }
598
+ }
599
+ catch(Exception $e){
600
+ echo $e->getMessage();
601
+ }
602
+ }
603
}
app/code/local/SevenLike/MailUp/Model/Adminhtml/System/Source/Cron/Frequency.php CHANGED
@@ -1,37 +1,37 @@
1
- <?php
2
-
3
- class SevenLike_MailUp_Model_Adminhtml_System_Source_Cron_Frequency
4
- {
5
- const HOURLY = 0;
6
- const EVERY_2_HOURS = 1;
7
- const EVERY_6_HOURS = 2;
8
- const EVERY_12_HOURS = 3;
9
- const DAILY = 4;
10
-
11
- /**
12
- * Fetch options array
13
- *
14
- * @return array
15
- */
16
- public function toOptionArray()
17
- {
18
- return array(
19
- array(
20
- 'label' => 'Hourly',
21
- 'value' => self::HOURLY),
22
- array(
23
- 'label' => 'Every 2 Hours',
24
- 'value' => self::EVERY_2_HOURS),
25
- array(
26
- 'label' => 'Every 6 hours',
27
- 'value' => self::EVERY_6_HOURS),
28
- array(
29
- 'label' => 'Every 12 hours',
30
- 'value' => self::EVERY_12_HOURS),
31
- array(
32
- 'label' => 'Daily',
33
- 'value' => self::DAILY),
34
-
35
- );
36
- }
37
- }
1
+ <?php
2
+
3
+ class SevenLike_MailUp_Model_Adminhtml_System_Source_Cron_Frequency
4
+ {
5
+ const HOURLY = 0;
6
+ const EVERY_2_HOURS = 1;
7
+ const EVERY_6_HOURS = 2;
8
+ const EVERY_12_HOURS = 3;
9
+ const DAILY = 4;
10
+
11
+ /**
12
+ * Fetch options array
13
+ *
14
+ * @return array
15
+ */
16
+ public function toOptionArray()
17
+ {
18
+ return array(
19
+ array(
20
+ 'label' => 'Hourly',
21
+ 'value' => self::HOURLY),
22
+ array(
23
+ 'label' => 'Every 2 Hours',
24
+ 'value' => self::EVERY_2_HOURS),
25
+ array(
26
+ 'label' => 'Every 6 hours',
27
+ 'value' => self::EVERY_6_HOURS),
28
+ array(
29
+ 'label' => 'Every 12 hours',
30
+ 'value' => self::EVERY_12_HOURS),
31
+ array(
32
+ 'label' => 'Daily',
33
+ 'value' => self::DAILY),
34
+
35
+ );
36
+ }
37
+ }
app/code/local/SevenLike/MailUp/Model/Adminhtml/System/Source/Cron/Hours.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- class SevenLike_MailUp_Model_Adminhtml_System_Source_Cron_Hours
4
- {
5
- /**
6
- * Fetch options array
7
- *
8
- * @return array
9
- */
10
- public function toOptionArray()
11
- {
12
- $hours = array();
13
- for ($i = 1; $i <= 24; $i++) {
14
- $hours[] = array('label' => $i, 'value' => $i);
15
- }
16
- return $hours;
17
- }
18
- }
1
+ <?php
2
+
3
+ class SevenLike_MailUp_Model_Adminhtml_System_Source_Cron_Hours
4
+ {
5
+ /**
6
+ * Fetch options array
7
+ *
8
+ * @return array
9
+ */
10
+ public function toOptionArray()
11
+ {
12
+ $hours = array();
13
+ for ($i = 1; $i <= 24; $i++) {
14
+ $hours[] = array('label' => $i, 'value' => $i);
15
+ }
16
+ return $hours;
17
+ }
18
+ }
app/code/local/SevenLike/MailUp/Model/Adminhtml/System/Source/Fields.php ADDED
@@ -0,0 +1,63 @@
1
+ <?php
2
+
3
+ class SevenLike_MailUp_Model_Adminhtml_System_Source_Fields
4
+ {
5
+ const CACHE_LIFETIME = 600; // 10 min
6
+ /**
7
+ * Options getter
8
+ *
9
+ * @return array
10
+ */
11
+ public function toOptionArray()
12
+ {
13
+ $websiteCode = Mage::app()->getRequest()->getParam('website');
14
+ $storeCode = Mage::app()->getRequest()->getParam('store');
15
+
16
+ if($storeCode) {
17
+ $storeId = Mage::app()->getStore($storeCode)->getId();
18
+ $cacheId = 'mailup_fields_array_store_'.$storeId;
19
+ }
20
+ elseif($websiteCode) {
21
+ $storeId = Mage::app()
22
+ ->getWebsite($websiteCode)
23
+ ->getDefaultGroup()
24
+ ->getDefaultStoreId()
25
+ ;
26
+ $cacheId = 'mailup_fields_array_store_'.$storeId;
27
+ }
28
+ else {
29
+ $storeId = NULL;
30
+ $cacheId = 'mailup_fields_array';
31
+ //$storeId = Mage::app()->getDefaultStoreView()->getStoreId();
32
+ }
33
+
34
+ // var_dump($storeCode);
35
+ // var_dump($websiteCode);
36
+ // var_dump($storeId);
37
+ // var_dump(Mage::app()->getStores());
38
+
39
+
40
+ $options = array(array('value' => '', 'label' => ''));
41
+ if(false !== ($data = Mage::app()->getCache()->load($cacheId))) {
42
+ $options = unserialize($data);
43
+ }
44
+ else {
45
+ $wsSend = new MailUpWsSend($storeId);
46
+ $accessKey = $wsSend->loginFromId();
47
+ if($accessKey !== false) {
48
+ $wsFields = $wsSend->getFields($accessKey);
49
+ //$wsFields = array('test' => 'test');
50
+ foreach ($wsFields as $label => $value) {
51
+ $options[] = array(
52
+ 'value' => $value,
53
+ 'label' => $label, //Mage::helper('adminhtml')->__($label)
54
+ );
55
+ }
56
+ }
57
+ Mage::app()->getCache()->save(serialize($options), $cacheId, array(), self::CACHE_LIFETIME);
58
+ }
59
+
60
+ return $options;
61
+ }
62
+
63
+ }
app/code/local/SevenLike/MailUp/Model/Config.php ADDED
@@ -0,0 +1,205 @@
1
+ <?php
2
+ /**
3
+ * Config.php
4
+ *
5
+ * Central config model
6
+ */
7
+ class SevenLike_MailUp_Model_Config
8
+ {
9
+ const XML_CONSOLE = 'mailup_newsletter/mailup/url_console';
10
+ const XML_LOG_ENABLE = 'mailup_newsletter/mailup/enable_log';
11
+ const XML_CRON_EXPORT_ENABLE = 'mailup_newsletter/mailup/enable_cron_export';
12
+ const XML_MAILUP_USERNAME = 'mailup_newsletter/mailup/username_ws';
13
+ const XML_MAILUP_PASSWORD = 'mailup_newsletter/mailup/password_ws';
14
+ const XML_MAILUP_LIST_ID = 'mailup_newsletter/mailup/list';
15
+ const XML_SUBSCRIBE_IN_CHECKOUT = 'mailup_newsletter/mailup/enable_subscribe_in_checkout';
16
+ const XML_CRON_FREQ = 'mailup_newsletter/mailup/mailup_cron_frequency';
17
+ const XML_WEBHOOK_KEY = 'mailup_newsletter/mailup/webhook_crypt_key';
18
+ const XML_DISABLE_NOTIFICATION = 'mailup_newsletter/mailup/disablenewslettersuccesses';
19
+
20
+ const XML_MAPPING_SECTION = 'mailup_newsletter/mailup_mapping';
21
+
22
+ /**
23
+ * Is the log enabled?
24
+ *
25
+ * @return bool
26
+ */
27
+ public function isLogEnabled($storeId = NULL)
28
+ {
29
+ return (int) Mage::getStoreConfig(self::XML_LOG_ENABLE, $storeId);
30
+ }
31
+
32
+ /**
33
+ * Disable Magnetos Newsletter Subscription Notifiactions??
34
+ *
35
+ * @param int
36
+ * @return bool
37
+ */
38
+ public function isNewsletterNotificationDisabled($storeId = NULL)
39
+ {
40
+ return (int) Mage::getStoreConfig(self::XML_DISABLE_NOTIFICATION, $storeId);
41
+ }
42
+
43
+ /**
44
+ * Get the url console url from Config
45
+ *
46
+ * @param int
47
+ * @return string
48
+ */
49
+ public function getUrlConsole($storeId = NULL)
50
+ {
51
+ return Mage::getStoreConfig(self::XML_CONSOLE, $storeId);
52
+ }
53
+
54
+ /**
55
+ * Is the cron enabled?
56
+ *
57
+ * @param int
58
+ * @return int
59
+ */
60
+ public function isCronExportEnabled($storeId = NULL)
61
+ {
62
+ return (int) Mage::getStoreConfig(self::XML_CRON_EXPORT_ENABLE, $storeId);
63
+ }
64
+
65
+ /**
66
+ * Get the list ID
67
+ *
68
+ * @param int
69
+ * @return int
70
+ */
71
+ public function getMailupListId($storeId = NULL)
72
+ {
73
+ return Mage::getStoreConfig(self::XML_MAILUP_LIST_ID, $storeId);
74
+ }
75
+
76
+ /**
77
+ * Get the username from Config
78
+ *
79
+ * @param int
80
+ * @return string
81
+ */
82
+ public function getUsername($storeId = NULL)
83
+ {
84
+ return Mage::getStoreConfig(self::XML_MAILUP_USERNAME, $storeId);
85
+ }
86
+
87
+ /**
88
+ * Get the password from Config
89
+ *
90
+ * @param int
91
+ * @return string
92
+ */
93
+ public function getPassword($storeId = NULL)
94
+ {
95
+ return Mage::getStoreConfig(self::XML_MAILUP_PASSWORD, $storeId);
96
+ }
97
+
98
+ /**
99
+ * Is Subscribe in checkout enabled?
100
+ *
101
+ * @param int
102
+ * @return int
103
+ */
104
+ public function isSubscribeInCheckout($storeId = NULL)
105
+ {
106
+ return (int) Mage::getStoreConfig(self::XML_SUBSCRIBE_IN_CHECKOUT, $storeId);
107
+ }
108
+
109
+ /**
110
+ * Get the cron freq settings
111
+ *
112
+ * @param int
113
+ * @return string
114
+ */
115
+ public function getCronFrequency($storeId = NULL)
116
+ {
117
+ return Mage::getStoreConfig(self::XML_CRON_FREQ, $storeId);
118
+ }
119
+
120
+ /**
121
+ * Get Field Mapping
122
+ *
123
+ * @todo Fix to use the config for mappings, per store..
124
+ * @param int
125
+ * @return array
126
+ */
127
+ public function getFieldsMapping($storeId = NULL)
128
+ {
129
+ return Mage::getStoreConfig(self::XML_MAPPING_SECTION, $storeId);
130
+
131
+ /*$return = array();
132
+
133
+ foreach(Mage::getStoreConfig(self::XML_MAPPING_SECTION, $storeId) as $key => $field) {
134
+ var_dump($key);
135
+ var_dump($field);
136
+ }
137
+
138
+ return $return;*/
139
+ }
140
+
141
+ /**
142
+ * Get an array of Stores, for use in a dropdown.
143
+ *
144
+ * array(
145
+ * id => code
146
+ * )
147
+ *
148
+ * @return array
149
+ */
150
+ public function getStoreArray()
151
+ {
152
+ //$storeModel = Mage::getSingleton('adminhtml/system_store');
153
+ /* @var $storeModel Mage_Adminhtml_Model_System_Store */
154
+ //$websiteCollection = $storeModel->getWebsiteCollection();
155
+ //$groupCollection = $storeModel->getGroupCollection();
156
+ //$storeCollection = $storeModel->getStoreCollection();
157
+ $storesArr = array();
158
+
159
+ /*$defaultStoreId = Mage::app()->getDefaultStoreView()->getStoreId();
160
+ $storesArr[$defaultStoreId] = array(
161
+ 'id' => $defaultStoreId,
162
+ 'code' => Mage::app()->getDefaultStoreView()->getCode(),
163
+ 'name' => Mage::app()->getDefaultStoreView()->getName(),
164
+ );*/
165
+
166
+ $storesArr[0] = array(
167
+ 'id' => 0,
168
+ 'code' => 'default',
169
+ 'name' => 'Default',
170
+ );
171
+
172
+ foreach (Mage::app()->getWebsites() as $website) {
173
+ foreach ($website->getGroups() as $group) {
174
+ $stores = $group->getStores();
175
+ foreach ($stores as $store) {
176
+ /* @var $store Mage_Core_Model_Store */
177
+ $storesArr[$store->getId()] = array(
178
+ 'id' => $store->getId(),
179
+ 'code' => $store->getCode(),
180
+ 'name' => $store->getName(),
181
+ );
182
+ }
183
+ }
184
+ }
185
+
186
+ return $storesArr;
187
+ }
188
+
189
+ /**
190
+ * Get an array of all store ids
191
+ *
192
+ * @reutrn array
193
+ */
194
+ public function getAllStoreIds()
195
+ {
196
+ $ids = array();
197
+
198
+ $allStores = Mage::app()->getStores();
199
+ foreach ($allStores as $storeId => $val) {
200
+ $ids[] = Mage::app()->getStore($storeId)->getId();
201
+ }
202
+
203
+ return $ids;
204
+ }
205
+ }
app/code/local/SevenLike/MailUp/Model/Consoleurlvalidator.php CHANGED
@@ -1,19 +1,19 @@
1
- <?php
2
-
3
- class SevenLike_MailUp_Model_Consoleurlvalidator extends Mage_Core_Model_Config_Data
4
- {
5
- public function save()
6
- {
7
- $value = $this->getValue();
8
- if (strlen($value) == 0) {
9
- Mage::throwException(Mage::helper("mailup")->__("Please fill the admin console URL"));
10
- }
11
-
12
- $validator = new Zend_Validate_Hostname();
13
- if (!$validator->isValid($value)) {
14
- Mage::throwException(Mage::helper("mailup")->__("Admin console URL is not in the right format"));
15
- }
16
-
17
- return parent::save();
18
- }
19
}
1
+ <?php
2
+
3
+ class SevenLike_MailUp_Model_Consoleurlvalidator extends Mage_Core_Model_Config_Data
4
+ {
5
+ public function save()
6
+ {
7
+ $value = $this->getValue();
8
+ if (strlen($value) == 0) {
9
+ Mage::throwException(Mage::helper("mailup")->__("Please fill the admin console URL"));
10
+ }
11
+
12
+ $validator = new Zend_Validate_Hostname();
13
+ if (!$validator->isValid($value)) {
14
+ Mage::throwException(Mage::helper("mailup")->__("Admin console URL is not in the right format"));
15
+ }
16
+
17
+ return parent::save();
18
+ }
19
}
app/code/local/SevenLike/MailUp/Model/Cron.php CHANGED
@@ -1,87 +1,162 @@
1
- <?php
2
-
3
- require_once dirname(__FILE__) . "/MailUpWsImport.php";
4
- require_once dirname(__FILE__) . "/Wssend.php";
5
- class SevenLike_MailUp_Model_Cron
6
- {
7
- public function run()
8
- {
9
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Cron mailup', 0);
10
-
11
- if (Mage::getStoreConfig('newsletter/mailup/enable_cron_export') == 1) {
12
- $indexProcess = new Mage_Index_Model_Process();
13
- $indexProcess->setId("mailupcronrun");
14
- if ($indexProcess->isLocked()) {
15
- Mage::log("MAILUP: cron already running or locked");
16
- return false;
17
- }
18
- $indexProcess->lockAndBlock();
19
-
20
- require_once dirname(__FILE__) . '/../Helper/Data.php';
21
- $db_read = Mage::getSingleton('core/resource')->getConnection('core_read');
22
- $db_write = Mage::getSingleton('core/resource')->getConnection('core_write');
23
- $lastsync = gmdate("Y-m-d H:i:s");
24
-
25
- // reading newsletter subscribers
26
- //$newsletter_subscriber_table_name = Mage::getSingleton('core/resource')->getTableName('newsletter_subscriber');
27
- //$newsletter_subscribers = $db_read->fetchAll("SELECT ms.*, ns.subscriber_email FROM mailup_sync ms JOIN $newsletter_subscriber_table_name ns ON (ms.customer_id = ns.subscriber_id) WHERE ms.needs_sync=1 AND ms.entity='subscriber'");
28
-
29
- // reading customers (jobid == 0, their updates)
30
- $customers = array();
31
- $customer_entity_table_name = Mage::getSingleton('core/resource')->getTableName('customer_entity');
32
- $stmt = $db_read->query("SELECT ms.*, ce.email FROM mailup_sync ms JOIN $customer_entity_table_name ce ON (ms.customer_id = ce.entity_id) WHERE ms.needs_sync=1 AND ms.entity='customer' AND job_id=0");
33
- while ($row = $stmt->fetch()) {
34
- $customers[] = $row["customer_id"];
35
- }
36
-
37
- // generating and sending data to mailup
38
- //SevenLike_MailUp_Helper_Data::generateAndSendCustomers($customers, null, $newsletter_subscribers);
39
- $check = SevenLike_MailUp_Helper_Data::generateAndSendCustomers($customers);
40
-
41
- // reading and processing jobs
42
- $jobs = $db_read->fetchAll("SELECT * FROM mailup_sync_jobs WHERE status='queued'");
43
- foreach ($jobs as $job) {
44
- $stmt = $db_write->query("UPDATE mailup_sync_jobs SET status='started', start_datetime='" . gmdate("Y-m-d H:i:s") . "' WHERE id={$job["id"]}");
45
- $customers = array();
46
- $job['mailupNewGroup'] = 0;
47
- $job['mailupIdList'] = Mage::getStoreConfig('newsletter/mailup/list');
48
- $job["mailupGroupId"] = $job["mailupgroupid"];
49
- $job["send_optin_email_to_new_subscribers"] = $job["send_optin"];
50
- $tmp = new SevenLike_MailUp_Model_Lists;
51
- $tmp = $tmp->toOptionArray();
52
- foreach ($tmp as $t) {
53
- if ($t["value"] == $job['mailupIdList']) {
54
- $job['mailupListGUID'] = $t["guid"];
55
- $job["groups"] = $t["groups"];
56
- break;
57
- }
58
- }
59
- unset($tmp); unset($t);
60
- $stmt = $db_read->query("SELECT ms.*, ce.email FROM mailup_sync ms JOIN $customer_entity_table_name ce ON (ms.customer_id = ce.entity_id) WHERE ms.needs_sync=1 AND ms.entity='customer' AND job_id={$job["id"]}");
61
- while ($row = $stmt->fetch()) {
62
- $customers[] = $row["customer_id"];
63
- }
64
- $check = SevenLike_MailUp_Helper_Data::generateAndSendCustomers($customers, $job);
65
- if ($check) {
66
- // saving sync state for customers
67
- foreach ($customers as $row) {
68
- $db_write->query("UPDATE mailup_sync SET needs_sync=0, last_sync='$lastsync' WHERE customer_id={$row} AND entity='customer'");
69
- }
70
-
71
- // finishing the job also
72
- $db_write->query("UPDATE mailup_sync_jobs SET status='finished', finish_datetime='" . gmdate("Y-m-d H:i:s") . "' WHERE id={$job["id"]}");
73
- }
74
- }
75
-
76
- $indexProcess->unlock();
77
- } else {
78
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Cron export not enabled', 0);
79
- }
80
-
81
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('Cron mailup finished', 0);
82
- }
83
-
84
- public static function resendConnectionErrors()
85
- {
86
- }
87
}
1
+ <?php
2
+ /**
3
+ * Cron.php
4
+ */
5
+ require_once dirname(__FILE__) . "/MailUpWsImport.php";
6
+ require_once dirname(__FILE__) . "/Wssend.php";
7
+
8
+ class SevenLike_MailUp_Model_Cron
9
+ {
10
+ public function run()
11
+ {
12
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) {
13
+ Mage::log('Cron mailup', 0);
14
+ }
15
+
16
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_cron_export') == 1) {
17
+ $indexProcess = new Mage_Index_Model_Process();
18
+ $indexProcess->setId("mailupcronrun");
19
+ if ($indexProcess->isLocked()) {
20
+ Mage::log("MAILUP: cron already running or locked");
21
+ return false;
22
+ }
23
+ $indexProcess->lockAndBlock();
24
+
25
+ require_once dirname(__FILE__) . '/../Helper/Data.php';
26
+ $db_read = Mage::getSingleton('core/resource')->getConnection('core_read');
27
+ $db_write = Mage::getSingleton('core/resource')->getConnection('core_write');
28
+ $lastsync = gmdate("Y-m-d H:i:s");
29
+
30
+ // reading newsletter subscribers
31
+ //$newsletter_subscriber_table_name = Mage::getSingleton('core/resource')->getTableName('newsletter_subscriber');
32
+ //$newsletter_subscribers = $db_read->fetchAll("SELECT ms.*, ns.subscriber_email FROM mailup_sync ms JOIN $newsletter_subscriber_table_name ns ON (ms.customer_id = ns.subscriber_id) WHERE ms.needs_sync=1 AND ms.entity='subscriber'");
33
+
34
+ // reading customers (jobid == 0, their updates)
35
+ $customer_entity_table_name = Mage::getSingleton('core/resource')->getTableName('customer_entity');
36
+
37
+ $stmt = $db_read->query("
38
+ SELECT ms.*, ce.email FROM mailup_sync ms
39
+ JOIN $customer_entity_table_name ce
40
+ ON (ms.customer_id = ce.entity_id)
41
+ WHERE
42
+ ms.needs_sync=1
43
+ AND ms.entity='customer'
44
+ AND job_id=0"
45
+ );
46
+
47
+ $storeArr = array();
48
+ $rows = $stmt->fetchAll();
49
+ /**
50
+ * Customer Updates, job_id = 0
51
+ */
52
+ foreach($rows as $row) {
53
+ $storeId = $row["store_id"];
54
+ /*if( ! isset($storeId)) {
55
+ Mage::log('StoreID Not Set On Cron Job');
56
+ //$storeId = Mage::app()->getDefaultStoreView()->getStoreId(); // Fallback incase not set?!?
57
+ }*/
58
+ /**
59
+ * Send/Group each stores data together.
60
+ */
61
+ $storeArr[$storeId][] = $row["customer_id"];
62
+ }
63
+
64
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) {
65
+ if(count($storeArr) > 0) {
66
+ Mage::log('STORE DATA ARRAY');
67
+ Mage::log($storeArr);
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Send each Store's data together!
73
+ */
74
+ foreach($storeArr as $singleStoreId => $customers) {
75
+ // generating and sending data to mailup
76
+ $check = SevenLike_MailUp_Helper_Data::generateAndSendCustomers($customers, NULL, NULL, $singleStoreId);
77
+ }
78
+
79
+ // reading and processing jobs
80
+ $jobs = $db_read->fetchAll("SELECT * FROM mailup_sync_jobs WHERE status='queued'");
81
+ /**
82
+ * Sync Jobs
83
+ */
84
+ foreach ($jobs as $job) {
85
+ $stmt = $db_write->query("UPDATE mailup_sync_jobs SET status='started', start_datetime='" . gmdate("Y-m-d H:i:s") . "' WHERE id={$job["id"]}");
86
+
87
+ $storeId = isset($job['store_id']) ? $job['store_id'] : NULL;
88
+ //if( ! isset($storeId)) {
89
+ //Mage::log('StoreID Not Set On Cron Job');
90
+ //$storeId = Mage::app()->getDefaultStoreView()->getStoreId(); // Fallback incase not set?!?
91
+ //}
92
+
93
+ $customers = array();
94
+ $job['mailupNewGroup'] = 0;
95
+ $job['mailupIdList'] = Mage::getStoreConfig('mailup_newsletter/mailup/list', $storeId);
96
+ $job["mailupGroupId"] = $job["mailupgroupid"];
97
+ $job["send_optin_email_to_new_subscribers"] = $job["send_optin"];
98
+
99
+ $tmp = new SevenLike_MailUp_Model_Lists;
100
+ $tmp = $tmp->toOptionArray($storeId); // pass store id!
101
+ foreach ($tmp as $t) {
102
+ if ($t["value"] == $job['mailupIdList']) {
103
+ $job['mailupListGUID'] = $t["guid"];
104
+ $job["groups"] = $t["groups"];
105
+ break;
106
+ }
107
+ }
108
+ unset($tmp); unset($t);
109
+ $stmt = $db_read->query("
110
+ SELECT ms.*, ce.email
111
+ FROM mailup_sync ms
112
+ JOIN $customer_entity_table_name ce
113
+ ON (ms.customer_id = ce.entity_id)
114
+ WHERE ms.needs_sync=1
115
+ AND ms.entity='customer'
116
+ AND job_id={$job["id"]}"
117
+ );
118
+ while ($row = $stmt->fetch()) {
119
+ $customers[] = $row["customer_id"];
120
+ }
121
+
122
+ $check = SevenLike_MailUp_Helper_Data::generateAndSendCustomers($customers, $job, NULL, $storeId);
123
+
124
+ /**
125
+ * @todo We need to check the result of the import, if there's an error
126
+ * we do not want to mark this ask Synced! we need to retry..
127
+ */
128
+ if ($check) {
129
+ // saving sync state for customers
130
+ foreach ($customers as $row) {
131
+ $db_write->query("
132
+ UPDATE mailup_sync SET needs_sync=0, last_sync='$lastsync'
133
+ WHERE customer_id={$row}
134
+ AND entity='customer'"
135
+ );
136
+ }
137
+
138
+ // finishing the job also
139
+ $db_write->query("
140
+ UPDATE mailup_sync_jobs SET status='finished', finish_datetime='" . gmdate("Y-m-d H:i:s") . "'
141
+ WHERE id={$job["id"]}"
142
+ );
143
+ }
144
+ }
145
+
146
+ $indexProcess->unlock();
147
+ }
148
+ else {
149
+ if(Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) {
150
+ Mage::log('Cron export not enabled', 0);
151
+ }
152
+ }
153
+
154
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log')) {
155
+ Mage::log('Cron mailup finished', 0);
156
+ }
157
+ }
158
+
159
+ public static function resendConnectionErrors()
160
+ {
161
+ }
162
}
app/code/local/SevenLike/MailUp/Model/Lists.php CHANGED
@@ -1,54 +1,96 @@
1
- <?php
2
-
3
- require_once dirname(__FILE__) . "/MailUpWsImport.php";
4
- require_once dirname(__FILE__) . "/Wssend.php";
5
- class SevenLike_MailUp_Model_Lists
6
- {
7
- public function toOptionArray() {
8
- //genero la select per Magento
9
- $selectLists = array();
10
-
11
- if (Mage::getStoreConfig('newsletter/mailup/url_console') && Mage::getStoreConfig('newsletter/mailup/username_ws') && Mage::getStoreConfig('newsletter/mailup/password_ws')) {
12
- $wsSend = new MailUpWsSend();
13
- $accessKey = $wsSend->loginFromId();
14
-
15
- if ($accessKey !== false) {
16
- require_once dirname(__FILE__) . "/MailUpWsImport.php";
17
- $wsImport = new MailUpWsImport();
18
-
19
- $xmlString = $wsImport->GetNlList();
20
-
21
- $selectLists[0] = array('value' => 0, 'label'=>'-- Select a list (if any) --');
22
-
23
- if ($xmlString) {
24
- $xmlString = html_entity_decode($xmlString);
25
-
26
- $startLists = strpos($xmlString, '<Lists>');
27
- $endPos = strpos($xmlString, '</Lists>');
28
- $endLists = $endPos + strlen('</Lists>') - $startLists;
29
-
30
- $xmlLists = substr($xmlString, $startLists, $endLists);
31
-
32
- $xmlLists = str_replace("&", "&amp;", $xmlLists);
33
-
34
- $xml = simplexml_load_string($xmlLists);
35
-
36
- $count = 1;
37
- foreach ($xml->List as $list) {
38
- $groups = array();
39
- foreach ($list->Groups->Group as $tmp) {
40
- $groups[(string)$tmp["idGroup"]] = (string)$tmp["groupName"];
41
- }
42
- $selectLists[$count] = array('value' => (string)$list['idList'], 'label'=> (string)$list['listName'], 'guid'=>(string)$list['listGUID'], "groups"=>$groups);
43
- $count++;
44
- }
45
- }
46
- } else {
47
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log('LoginFromId failed', 0);
48
- $selectLists[0] = array('value' => 0, 'label'=>$GLOBALS["__sl_mailup_login_error"]);
49
- }
50
- }
51
-
52
- return $selectLists;
53
- }
54
- }
1
+ <?php
2
+ /**
3
+ * Lists.php
4
+ */
5
+ require_once dirname(__FILE__) . "/MailUpWsImport.php";
6
+ require_once dirname(__FILE__) . "/Wssend.php";
7
+
8
+ class SevenLike_MailUp_Model_Lists
9
+ {
10
+ /**
11
+ * Get as options
12
+ *
13
+ * @todo Add Caching
14
+ * @return array
15
+ */
16
+ public function toOptionArray($storeId = NULL)
17
+ {
18
+ $websiteCode = Mage::app()->getRequest()->getParam('website');
19
+ $storeCode = Mage::app()->getRequest()->getParam('store');
20
+
21
+ if(isset($storeId) && $storeId != FALSE) {
22
+ $storeId = $storeId;
23
+ }
24
+ elseif($storeCode) {
25
+ $storeId = Mage::app()->getStore($storeCode)->getId();
26
+ $cacheId = 'mailup_fields_array_store_'.$storeId;
27
+ }
28
+ elseif($websiteCode) {
29
+ $storeId = Mage::app()
30
+ ->getWebsite($websiteCode)
31
+ ->getDefaultGroup()
32
+ ->getDefaultStoreId()
33
+ ;
34
+ $cacheId = 'mailup_fields_array_store_'.$storeId;
35
+ }
36
+ else {
37
+ $storeId = NULL;
38
+ $cacheId = 'mailup_fields_array';
39
+ //$storeId = Mage::app()->getDefaultStoreView()->getStoreId();
40
+ }
41
+
42
+ //genero la select per Magento
43
+ $selectLists = array();
44
+
45
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/url_console', $storeId)
46
+ && Mage::getStoreConfig('mailup_newsletter/mailup/username_ws', $storeId)
47
+ && Mage::getStoreConfig('mailup_newsletter/mailup/password_ws', $storeId)) {
48
+
49
+ $wsSend = new MailUpWsSend($storeId);
50
+ $accessKey = $wsSend->loginFromId();
51
+
52
+ if ($accessKey !== false) {
53
+ require_once dirname(__FILE__) . "/MailUpWsImport.php";
54
+ $wsImport = new MailUpWsImport($storeId);
55
+
56
+ $xmlString = $wsImport->GetNlList();
57
+
58
+ $selectLists[0] = array('value' => 0, 'label'=>'-- Select a list (if any) --');
59
+
60
+ if ($xmlString) {
61
+ $xmlString = html_entity_decode($xmlString);
62
+
63
+ $startLists = strpos($xmlString, '<Lists>');
64
+ $endPos = strpos($xmlString, '</Lists>');
65
+ $endLists = $endPos + strlen('</Lists>') - $startLists;
66
+
67
+ $xmlLists = substr($xmlString, $startLists, $endLists);
68
+
69
+ $xmlLists = str_replace("&", "&amp;", $xmlLists);
70
+
71
+ $xml = simplexml_load_string($xmlLists);
72
+
73
+ $count = 1;
74
+ foreach ($xml->List as $list) {
75
+ $groups = array();
76
+ foreach ($list->Groups->Group as $tmp) {
77
+ $groups[(string)$tmp["idGroup"]] = (string)$tmp["groupName"];
78
+ }
79
+ $selectLists[$count] = array(
80
+ 'value' => (string)$list['idList'],
81
+ 'label'=> (string)$list['listName'],
82
+ 'guid'=>(string)$list['listGUID'],
83
+ "groups"=>$groups
84
+ );
85
+ $count++;
86
+ }
87
+ }
88
+ } else {
89
+ if (Mage::getStoreConfig('mailup_newsletter/mailup/enable_log', $storeId)) Mage::log('LoginFromId failed', 0);
90
+ $selectLists[0] = array('value' => 0, 'label'=>$GLOBALS["__sl_mailup_login_error"]);
91
+ }
92
+ }
93
+
94
+ return $selectLists;
95
+ }
96
+ }
app/code/local/SevenLike/MailUp/Model/MailUp.php CHANGED
@@ -1,10 +1,10 @@
1
- <?php
2
-
3
- class SevenLike_MailUp_Model_MailUp extends Mage_Core_Model_Abstract
4
- {
5
- public function _construct()
6
- {
7
- parent::_construct();
8
- $this->_init('mailup/mailup');
9
- }
10
}
1
+ <?php
2
+
3
+ class SevenLike_MailUp_Model_MailUp extends Mage_Core_Model_Abstract
4
+ {
5
+ public function _construct()
6
+ {
7
+ parent::_construct();
8
+ $this->_init('mailup/mailup');
9
+ }
10
}
app/code/local/SevenLike/MailUp/Model/MailUpWsImport.php CHANGED
@@ -1,659 +1,1002 @@
1
- <?php
2
-
3
- class MailUpWsImport
4
- {
5
- protected $ns = "http://ws.mailupnet.it/";
6
-
7
- //protected $WSDLUrl = "http://g4a0.s03.it/services/WSMailUpImport.asmx?WSDL";
8
- //protected $headers = array("User" => "a7410", "Password" => "GA6VAN0W");
9
- protected $rCode;
10
- private $soapClient;
11
- private $xmlResponse;
12
- protected $domResult;
13
-
14
- function __construct() {
15
- $urlConsole = Mage::getStoreConfig('newsletter/mailup/url_console');
16
- $WSDLUrl = 'http://'. $urlConsole .'/services/WSMailUpImport.asmx?WSDL';
17
- $user = Mage::getStoreConfig('newsletter/mailup/username_ws');
18
- $password = Mage::getStoreConfig('newsletter/mailup/password_ws');
19
- $headers = array('User' => $user, 'Password' => $password);
20
- $this->header = new SOAPHeader($this->ns, 'Authentication', $headers);
21
-
22
- try {
23
- $this->soapClient = new SoapClient($WSDLUrl, array('trace' => 1, 'exceptions' => 1, 'connection_timeout' => 10));
24
- $this->soapClient->__setSoapHeaders($this->header);
25
- } catch (Exception $e) {
26
- Mage::getSingleton('adminhtml/session')->addError(Mage::helper("mailup")->__("Unable to connect to MailUp console"));
27
- }
28
- }
29
-
30
- function __destruct() {
31
- unset($this->soapClient);
32
- }
33
-
34
- public function getFunctions() {
35
- print_r($this->soapClient->__getFunctions());
36
- }
37
-
38
- public function creaGruppo($newGroup) {
39
- if (!is_object($this->soapClient)) return false;
40
- try {
41
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log("Mailup: creazione nuovo gruppo");
42
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($newGroup);
43
- $this->soapClient->CreateGroup($newGroup);
44
- $this->printLastRequest();
45
- $this->printLastResponse();
46
- return $this->readReturnCode('CreateGroup', 'ReturnCode');
47
- } catch (SoapFault $soapFault) {
48
- Mage::log('SOAP error', 0);
49
- Mage::log($soapFault, 0);
50
- }
51
- }
52
-
53
- public function GetNlList() {
54
- if (!is_object($this->soapClient)) return false;
55
- try {
56
- $this->soapClient->GetNlLists();
57
- $this->printLastRequest();
58
- $this->printLastResponse();
59
- $result = $this->soapClient->__getLastResponse();
60
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($result, 0);
61
- return $result;
62
- } catch (SoapFault $soapFault) {
63
- Mage::log('SOAP error', 0);
64
- Mage::log($soapFault, 0);
65
- }
66
- }
67
-
68
- public function newImportProcess($importProcessData) {
69
- if (!is_object($this->soapClient)) return false;
70
- try {
71
- $this->soapClient->NewImportProcess($importProcessData);
72
- $returncode = $this->readReturnCode('NewImportProcess', 'ReturnCode');
73
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log("mailup: newImportProcess result: $returncode", 0);
74
- return $returncode;
75
- } catch (SoapFault $soapFault) {
76
- Mage::log('SOAP error', 0);
77
- Mage::log($soapFault, 0);
78
- return false;
79
- }
80
- }
81
-
82
- public function startProcess($processData) {
83
- if (!is_object($this->soapClient)) return false;
84
- try {
85
- $this->soapClient->StartProcess($processData);
86
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log("mailup: ws: startimportprocess", 0);
87
- return true;
88
- } catch (SoapFault $soapFault) {
89
- Mage::log('SOAP error', 0);
90
- Mage::log($soapFault, 0);
91
- return false;
92
- }
93
- }
94
-
95
- public function getProcessDetail($processData) {
96
- if (!is_object($this->soapClient)) return false;
97
- try {
98
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) Mage::log($this->soapClient->GetProcessDetails($processData), 0);
99
- } catch (SoapFault $soapFault) {
100
- Mage::log('SOAP error', 0);
101
- Mage::log($soapFault, 0);
102
- }
103
- }
104
-
105
- public function startImportProcesses($processData) {
106
- if (!is_object($this->soapClient)) return false;
107
- try {
108
- $this->soapClient->StartImportProcesses($processData);
109
- $this->printLastRequest();
110
- $this->printLastResponse();
111
- return true;
112
- } catch (SoapFault $soapFault) {
113
- Mage::log('SOAP error', 0);
114
- Mage::log($soapFault, 0);
115
- return false;
116
- }
117
- }
118
-
119
- private function readReturnCode($func, $param) {
120
- if (!is_object($this->soapClient)) return false;
121
-
122
- static $func_in = ''; //static variable to test xmlResponse update
123
- if ($func_in != $func) {//(!isset($this->xmlResponse))
124
- $func_in = $func;
125
- //prendi l'XML di ritorno se non l'ho già preso
126
- $this->xmlResponse = $this->soapClient->__getLastResponse();
127
-
128
- $dom = new DomDocument();
129
- $dom->loadXML($this->xmlResponse) or die('File XML non valido!');
130
- $xmlResult = $dom->getElementsByTagName($func.'Result');
131
-
132
- $this->domResult = new DomDocument();
133
- $this->domResult->LoadXML(html_entity_decode($xmlResult->item(0)->nodeValue)) or die('File XML non valido!');
134
- }
135
- $rCode = $this->domResult->getElementsByTagName($param);
136
- return $rCode->item(0)->nodeValue;
137
- }
138
-
139
- private function printLastRequest()
140
- {
141
- return "";
142
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) $this->soapClient->__getLastRequest();
143
- }
144
-
145
- private function printLastResponse()
146
- {
147
- return "";
148
- if (Mage::getStoreConfig('newsletter/mailup/enable_log')) $this->soapClient->__getLastResponse();
149
- }
150
-
151
- public function getCustomersFiltered($request)
152
- {
153
- $TIMEZONE_STORE = new DateTimeZone(Mage::getStoreConfig("general/locale/timezone"));
154
- $TIMEZONE_UTC = new DateTimeZone("UTC");
155
-
156
- //inizializzo l'array dei clienti
157
- $customersFiltered = array();
158
-
159
- if (!$request->getRequest()->getParam('mailupCustomerFilteredMod')) {
160
- //ottengo la collection con tutti i clienti
161
- $customerCollection = Mage::getModel('customer/customer')
162
- ->getCollection()
163
- ->addAttributeToSelect('entity_id')
164
- ->addAttributeToSelect('group_id')
165
- ->addAttributeToSelect('created_at')
166
- ->getSelect()
167
- ->query();
168
-
169
- while ($row = $customerCollection->fetch()) {
170
- $customersFiltered[] = $row;
171
- }
172
-
173
- //se richiesto, seleziono solo quelli iscritti alla newsletter di Magento
174
- if ($request->getRequest()->getParam('mailupSubscribed') > 0) {
175
- $tempSubscribed = array();
176
- foreach ($customersFiltered as $customer) {
177
- $customerItem = Mage::getModel('customer/customer')->load($customer['entity_id']);
178
- if (Mage::getModel('newsletter/subscriber')->loadByCustomer($customerItem)->isSubscribed()) {
179
- $tempSubscribed[] = $customer;
180
- }
181
- }
182
- $customersFiltered = array_intersect($tempSubscribed, $customersFiltered);
183
- }
184
-
185
- //FILTRO 1 ACQUISTATO: in base al fatto se ha effettuato o meno acquisti: 0 = tutti, 1 = chi ha acquistato, 2 = chi non ha mai acquistato
186
- $count = 0;
187
- $result = array();
188
- $tempPurchased = array();
189
- $tempNoPurchased = array();
190
-
191
- if ($request->getRequest()->getParam('mailupCustomers') > 0) {
192
- foreach ($customersFiltered as $customer) {
193
- $result[] = $customer;
194
-
195
- //filtro gli ordini in base al customer id
196
- $orders = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_id', $result[$count]['entity_id']);
197
-
198
- //aggiungo il cliente ad un determinato array in base a se ha ordinato o meno
199
- if ($orders->getData()) {
200
- $tempPurchased[] = $result[$count];
201
- } else {
202
- $tempNoPurchased[] = $result[$count];
203
- }
204
-
205
- //unsetto la variabile
206
- unset($orders); //->unsetData();
207
-
208
- $count++;
209
- }
210
-
211
- if ($request->getRequest()->getParam('mailupCustomers') == 1) {
212
- $customersFiltered = array_intersect($tempPurchased, $customersFiltered);
213
- } elseif ($request->getRequest()->getParam('mailupCustomers') == 2) {
214
- $customersFiltered = array_intersect($tempNoPurchased, $customersFiltered);
215
- }
216
- }
217
- //FINE FILTRO 1 ACQUISTATO: testato OK
218
-
219
- //FILTRO 2 PRODOTTO ACQUISTATO: in base al fatto se ha acquistato un determinato prodotto
220
- $count = 0;
221
- $result = array();
222
- $tempProduct = array();
223
-
224
- if ($request->getRequest()->getParam('mailupProductSku')) {
225
- foreach ($customersFiltered as $customer) {
226
- $result[] = $customer;
227
-
228
- //filtro gli ordini in base al customer id
229
- $orders = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_id', $result[$count]['entity_id']);
230
- $purchasedProduct = 0;
231
-
232
- $mailupProductId = Mage::getModel('catalog/product')->getIdBySku($request->getRequest()->getParam('mailupProductSku'));
233
-
234
- foreach ($orders->getData() as $order) {
235
- if (!in_array($order["status"], array("closed", "complete", "processing"))) continue;
236
- $orderIncrementId = $order['increment_id'];
237
-
238
- //carico i dati di ogni ordine
239
- $orderData = Mage::getModel('sales/order')->loadByIncrementID($orderIncrementId);
240
- $items = $orderData->getAllItems();
241
- $ids = array();
242
- foreach ($items as $itemId => $item) {
243
- $ids[] = $item->getProductId();
244
- }
245
-
246
- if (in_array($mailupProductId, $ids)) {
247
- $purchasedProduct = 1;
248
- }
249
- }
250
-
251
- //aggiungo il cliente ad un determinato array in base a se ha ordinato o meno
252
- if ($purchasedProduct == 1) {
253
- $tempProduct[] = $result[$count];
254
- }
255
-
256
- //unsetto la variabile
257
- unset($orders); //->unsetData();
258
-
259
- $count++;
260
- }
261
-
262
- $customersFiltered = array_intersect($tempProduct, $customersFiltered);
263
- }
264
- //FINE FILTRO 2 PRODOTTO ACQUISTATO: testato OK
265
-
266
-
267
- //FILTRO 3 ACQUISTATO IN CATEGORIA: in base al fatto se ha acquistato almeno un prodotto in una determinata categoria
268
- $count = 0;
269
- $result = array();
270
- $tempCategory = array();
271
-
272
- if ($request->getRequest()->getParam('mailupCategoryId') > 0) {
273
- foreach ($customersFiltered as $customer) {
274
- $result[] = $customer;
275
-
276
- //filtro gli ordini in base al customer id
277
- $orders = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_id', $result[$count]['entity_id']);
278
- $purchasedCategory = 0;
279
-
280
- foreach ($orders->getData() as $order) {
281
- if (!in_array($order["status"], array("closed", "complete", "processing"))) continue;
282
- $orderIncrementId = $order['increment_id'];
283
-
284
- //carico i dati di ogni ordine
285
- $orderData = Mage::getModel('sales/order')->loadByIncrementID($orderIncrementId);
286
- $items = $orderData->getAllItems();
287
- $cat_ids = array();
288
- foreach ($items as $product) {
289
- if (in_array($request->getRequest()->getParam('mailupCategoryId'), Mage::getResourceSingleton('catalog/product')->getCategoryIds($product))) {
290
- $tempCategory[] = $result[$count];
291
- break 2;
292
- }
293
- }
294
- }
295
-
296
- unset($orders);
297
- $count++;
298
- }
299
-
300
- $customersFiltered = array_intersect($tempCategory, $customersFiltered);
301
- }
302
- //FINE FILTRO 3 ACQUISTATO IN CATEGORIA: testato ok
303
-
304
-
305
- //FILTRO 4 GRUPPO DI CLIENTI
306
- $count = 0;
307
- $result = array();
308
- $tempGroup = array();
309
-
310
- if ($request->getRequest()->getParam('mailupCustomerGroupId') > 0) {
311
- foreach ($customersFiltered as $customer) {
312
- if ($customer['group_id'] == $request->getRequest()->getParam('mailupCustomerGroupId')) {
313
- $tempGroup[] = $customer;
314
- }
315
- }
316
-
317
- $customersFiltered = array_intersect($tempGroup, $customersFiltered);
318
- }
319
- //FINE FILTRO 4 GRUPPO DI CLIENTI: testato ok
320
-
321
-
322
- //FILTRO 5 PAESE DI PROVENIENZA
323
- $count = 0;
324
- $result = array();
325
- $tempCountry = array();
326
-
327
- if ($request->getRequest()->getParam('mailupCountry') != '0') {
328
- foreach ($customersFiltered as $customer) {
329
- //ottengo la nazione del primary billing address
330
- $customerItem = Mage::getModel('customer/customer')->load($customer['entity_id']);
331
- $customerAddress = $customerItem->getPrimaryBillingAddress();
332
- $countryId = $customerAddress['country_id'];
333
-
334
- if ($countryId == $request->getRequest()->getParam('mailupCountry')) {
335
- $tempCountry[] = $customer;
336
- }
337
-
338
- //unsetto la variabile
339
- unset($customerItem); //->unsetData();
340
- }
341
-
342
- $customersFiltered = array_intersect($tempCountry, $customersFiltered);
343
- }
344
- //FINE FILTRO 5 PAESE DI PROVENIENZA: testato ok
345
-
346
-
347
- //FILTRO 6 CAP DI PROVENIENZA
348
- $count = 0;
349
- $result = array();
350
- $tempPostCode = array();
351
-
352
- if ($request->getRequest()->getParam('mailupPostCode')) {
353
- foreach ($customersFiltered as $customer) {
354
- //ottengo la nazione del primary billing address
355
- $customerItem = Mage::getModel('customer/customer')->load($customer['entity_id']);
356
- $customerAddress = $customerItem->getPrimaryBillingAddress();
357
- $postCode = $customerAddress['postcode'];
358
-
359
- if ($postCode == $request->getRequest()->getParam('mailupPostCode')) {
360
- $tempPostCode[] = $customer;
361
- }
362
-
363
- //unsetto la variabile
364
- unset($customerItem); //->unsetData();
365
- }
366
-
367
- $customersFiltered = array_intersect($tempPostCode, $customersFiltered);
368
- }
369
- //FINE FILTRO 6 CAP DI PROVENIENZA: testato ok
370
-
371
-
372
- //FILTRO 7 DATA CREAZIONE CLIENTE
373
- $count = 0;
374
- $result = array();
375
- $tempDate = array();
376
-
377
- if ($request->getRequest()->getParam('mailupCustomerStartDate') || $request->getRequest()->getParam('mailupCustomerEndDate') ) {
378
- foreach ($customersFiltered as $customer) {
379
- $createdAt = $customer['created_at'];
380
- $createdAt = new DateTime($createdAt, $TIMEZONE_UTC);
381
- $createdAt->setTimezone($TIMEZONE_STORE);
382
- $createdAt = (string)$createdAt->format("Y-m-d H:i:s");
383
- $filterStart = '';
384
- $filterEnd = '';
385
-
386
- if ($request->getRequest()->getParam('mailupCustomerStartDate')) {
387
- $date = Zend_Locale_Format::getDate($request->getRequest()->getParam('mailupCustomerStartDate'), array('locale'=>Mage::app()->getLocale()->getLocale(), 'date_format'=>Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT), 'fix_date'=>true));
388
- $date['month'] = str_pad($date['month'], 2, 0, STR_PAD_LEFT);
389
- $date['day'] = str_pad($date['day'], 2, 0, STR_PAD_LEFT);
390
- $filterStart = "{$date['year']}-{$date['month']}-{$date['day']} 00:00:00";
391
- }
392
- if ($request->getRequest()->getParam('mailupCustomerEndDate')) {
393
- $date = Zend_Locale_Format::getDate($request->getRequest()->getParam('mailupCustomerEndDate'), array('locale'=>Mage::app()->getLocale()->getLocale(), 'date_format'=>Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT), 'fix_date'=>true));
394
- $date['month'] = str_pad($date['month'], 2, 0, STR_PAD_LEFT);
395
- $date['day'] = str_pad($date['day'], 2, 0, STR_PAD_LEFT);
396
- $filterEnd = "{$date['year']}-{$date['month']}-{$date['day']} 23:59:59";
397
- }
398
- if ($filterStart && $filterEnd) {
399
- //compreso tra start e end date
400
- if ($createdAt >= $filterStart and $createdAt <= $filterEnd) {
401
- $tempDate[] = $customer;
402
- }
403
- } elseif ($filterStart) {
404
- // >= di start date
405
- if ($createdAt >= $filterStart) {
406
- $tempDate[] = $customer;
407
- }
408
- } else {
409
- // <= di end date
410
- if ($createdAt <= $filterEnd) {
411
- $tempDate[] = $customer;
412
- }
413
- }
414
- }
415
-
416
- $customersFiltered = array_intersect($tempDate, $customersFiltered);
417
- }
418
- //FINE FILTRO 7 DATA CREAZIONE CLIENTE: testato ok
419
-
420
-
421
- //FILTRO 8 TOTALE ACQUISTATO
422
- $count = 0;
423
- $result = array();
424
- $tempTotal = array();
425
-
426
- if ($request->getRequest()->getParam('mailupTotalAmountValue') > 0) {
427
- foreach ($customersFiltered as $customer) {
428
- $result[] = $customer;
429
-
430
- //filtro gli ordini in base al customer id
431
- $orders = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_id', $result[$count]['entity_id']);
432
-
433
- $totalOrdered = 0;
434
-
435
- foreach ($orders->getData() as $order) {
436
- if (!in_array($order["status"], array("closed", "complete", "processing"))) continue;
437
- $totalOrdered += $order['subtotal'];
438
- }
439
-
440
- if ($totalOrdered == $request->getRequest()->getParam('mailupTotalAmountValue') && $request->getRequest()->getParam('mailupTotalAmountCond') == "eq") {
441
- $tempTotal[] = $result[$count];
442
- }
443
-
444
- if ($totalOrdered > $request->getRequest()->getParam('mailupTotalAmountValue') && $request->getRequest()->getParam('mailupTotalAmountCond') == "gt") {
445
- $tempTotal[] = $result[$count];
446
- }
447
-
448
- if ($totalOrdered < $request->getRequest()->getParam('mailupTotalAmountValue') && $request->getRequest()->getParam('mailupTotalAmountCond') == "lt" ) {
449
- $tempTotal[] = $result[$count];
450
- }
451
-
452
- $count++;
453
-
454
- //unsetto la variabile
455
- unset($orders); //->unsetData();
456
- }
457
-
458
- $customersFiltered = array_intersect($tempTotal, $customersFiltered);
459
- }
460
- //FINE FILTRO 8 TOTALE ACQUISTATO: testato ok
461
-
462
-
463
- //FILTRO 9 DATA ACQUISTATO
464
- $count = 0;
465
- $result = array();
466
- $tempOrderedDateYes = array();
467
- $tempOrderedDateNo = array();
468
-
469
- if ($request->getRequest()->getParam('mailupOrderStartDate') || $request->getRequest()->getParam('mailupOrderEndDate') ) {
470
- foreach ($customersFiltered as $customer) {
471
- $result[] = $customer;
472
-
473
- //filtro gli ordini in base al customer id
474
- $orders = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_id', $result[$count]['entity_id']);
475
-
476
- $orderedDate = 0;
477
-
478
- foreach ($orders->getData() as $order) {
479
- if (!in_array($order["status"], array("closed", "complete", "processing"))) continue;
480
- $createdAt = $order['created_at'];
481
- $createdAt = new DateTime($createdAt, $TIMEZONE_UTC);
482
- $createdAt->setTimezone($TIMEZONE_STORE);
483
- $createdAt = (string)$createdAt->format("Y-m-d H:i:s");
484
- $filterStart = '';
485
- $filterEnd = '';
486
-
487
- if ($request->getRequest()->getParam('mailupOrderStartDate')) {
488
- $date = Zend_Locale_Format::getDate($request->getRequest()->getParam('mailupOrderStartDate'), array('locale'=>Mage::app()->getLocale()->getLocale(), 'date_format'=>Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT), 'fix_date'=>true));
489
- $date['month'] = str_pad($date['month'], 2, 0, STR_PAD_LEFT);
490
- $date['day'] = str_pad($date['day'], 2, 0, STR_PAD_LEFT);
491
- $filterStart = "{$date['year']}-{$date['month']}-{$date['day']} 00:00:00";
492
- }
493
- if ($request->getRequest()->getParam('mailupOrderEndDate')) {
494
- $date = Zend_Locale_Format::getDate($request->getRequest()->getParam('mailupOrderEndDate'), array('locale'=>Mage::app()->getLocale()->getLocale(), 'date_format'=>Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT), 'fix_date'=>true));
495
- $date['month'] = str_pad($date['month'], 2, 0, STR_PAD_LEFT);
496
- $date['day'] = str_pad($date['day'], 2, 0, STR_PAD_LEFT);
497
- $filterEnd = "{$date['year']}-{$date['month']}-{$date['day']} 23:59:59";
498
- }
499
-
500
- if ($filterStart and $filterEnd) {
501
- //compreso tra start e end date
502
- if ($createdAt >= $filterStart and $createdAt <= $filterEnd) {
503
- $orderedDate = 1;
504
- }
505
- } elseif ($filterStart) {
506
- // >= di start date
507
- if ($createdAt >= $filterStart) {
508
- $orderedDate = 1;
509
- }
510
- } else {
511
- // <= di end date
512
- if ($createdAt <= $filterEnd) {
513
- $orderedDate = 1;
514
- }
515
- }
516
-
517
- //unsetto la variabile
518
- unset($orders); //->unsetData();
519
- }
520
-
521
- if ($orderedDate == 1) {
522
- $tempOrderedDateYes[] = $result[$count];
523
- } else {
524
- $tempOrderedDateNo[] = $result[$count];
525
- }
526
-
527
- $count++;
528
- }
529
-
530
- if ($request->getRequest()->getParam('mailupOrderYesNo') == 'yes') {
531
- $customersFiltered = array_intersect($tempOrderedDateYes, $customersFiltered);
532
- } else {
533
- $customersFiltered = array_intersect($tempOrderedDateNo, $customersFiltered);
534
- }
535
- }
536
- //FINE FILTRO 9 DATA ACQUISTATO: testato ok
537
-
538
- } else {
539
- //GESTISCO LE MODIFICHE MANUALI
540
- $count = 0;
541
- $result = array();
542
- $tempMod = array();
543
-
544
- $emails = explode("\n", $request->getRequest()->getParam('mailupCustomerFilteredMod'));
545
-
546
- foreach ($emails as $email) {
547
- $email = trim($email);
548
-
549
- if (strstr($email, '@') !== false) {
550
- $customerModCollection = Mage::getModel('customer/customer')
551
- ->getCollection()
552
- ->addAttributeToSelect('email')
553
- ->addAttributeToFilter('email', $email);
554
-
555
- $added = 0;
556
-
557
- foreach ($customerModCollection as $customerMod) {
558
- $tempMod[] = $customerMod->toArray();
559
- $added = 1;
560
- }
561
-
562
- if ($added == 0) {
563
- $tempMod[] = array('entity_id'=>0, 'firstname'=>'', 'lastname'=>'', 'email'=>$email);
564
- }
565
- }
566
- }
567
-
568
- //$customersFiltered = array_intersect($tempMod, $customersFiltered);
569
- $customersFiltered = $tempMod;
570
- }
571
- //FINE GESTISCO LE MODIFICHE MANUALI
572
-
573
- return $customersFiltered;
574
- }
575
-
576
-
577
- public function getFilterHints() {
578
- $filter_hints = array();
579
- try {
580
- // fetch write database connection that is used in Mage_Core module
581
- $connectionRead = Mage::getSingleton('core/resource')->getConnection('core_read');
582
-
583
- // now $write is an instance of Zend_Db_Adapter_Abstract
584
- $result = $connectionRead->query("select * from mailup_filter_hints");
585
-
586
- while ($row = $