TS_Auto_Login_MailChimp - Version 1.0.24

Version Notes

Fix:
- Stop to log in user even if there were a error to identify a user.
- updated and compatible with MageMonkey - MailChimp Integration by ebizmarts 1.0.23

Download this release

Release Info

Developer Thiago Santos
Extension TS_Auto_Login_MailChimp
Version 1.0.24
Comparing to
See all releases


Code changes from version 1.0.23 to 1.0.24

app/code/local/ThiagoSantos/LoginAutomatico/Helper/MonkeyData.php CHANGED
@@ -6,7 +6,6 @@
6
  * @category ThiagoSantos
7
  * @package ThiagoSantos_LoginAutomatico
8
  */
9
-
10
  /**
11
  * Mage Monkey default helper
12
  *
@@ -14,18 +13,18 @@
14
  * @package Ebizmarts_MageMonkey
15
  * @author Ebizmarts Team <info@ebizmarts.com>
16
  */
17
- class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonkey_Helper_Data
18
  {
19
 
20
- /**
21
- * Utility to check if admin is logged in
22
- *
23
- * @return bool
24
- */
25
- public function isAdmin()
26
- {
27
- return Mage::getSingleton('admin/session')->isLoggedIn();
28
- }
29
 
30
  /**
31
  * Check if Magento is EE
@@ -37,268 +36,268 @@ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonke
37
  return is_object(Mage::getConfig()->getNode('global/models/enterprise_enterprise'));
38
  }
39
 
40
- /**
41
- * Return Webhooks security key for given store
42
- *
43
- * @param mixed $store Store object, or Id, or code
44
- * @param string $listId Optional listid to retrieve store code from it
45
- * @return string
46
- */
47
- public function getWebhooksKey($store, $listId = null)
48
- {
49
- if( !is_null($listId) ){
50
- $store = $this->getStoreByList($listId, TRUE);
51
- }
52
 
53
- $crypt = md5((string)Mage::getConfig()->getNode('global/crypt/key'));
54
- $key = substr($crypt, 0, (strlen($crypt)/2));
55
 
56
- return ($key . $store);
57
- }
58
 
59
- public function filterShowGroupings($interestGroupings)
60
- {
61
- if(is_array($interestGroupings)){
62
 
63
- $customGroupings = Mage::getConfig()->getNode('default/monkey/custom_groupings')
64
- ->asArray();
65
 
66
- foreach($interestGroupings as $key => $group){
67
 
68
- if(TRUE === in_array($group['name'], $customGroupings)){
69
- unset($interestGroupings[$key]);
70
- }
71
 
72
- }
73
  }
 
74
 
75
- return $interestGroupings;
76
- }
77
-
78
- /**
79
- * Check if CustomerGroup grouping already exists on MC
80
- *
81
- * @param array $groupings
82
- * @return bool
83
- */
84
- public function customerGroupGroupingExists($interestGroupings)
85
- {
86
- $exists = FALSE;
87
- if(is_array($interestGroupings)){
88
- foreach($interestGroupings as $group){
89
- if($group['name'] == $this->getCustomerGroupingName()){
90
- $exists = TRUE;
91
- break;
92
- }
93
- }
94
- }
95
 
96
- return $exists;
97
- }
98
-
99
- /**
100
- * Return customer groping name to be used when creating a grouping to store
101
- * Magento customer groups
102
- *
103
- * @return string
104
- */
105
- public function getCustomerGroupingName()
106
- {
107
- return (string)Mage::getConfig()->getNode('default/monkey/custom_groupings/customer_grouping_name');
108
- }
109
-
110
- /**
111
- * Get module User-Agent to use on API requests
112
- *
113
- * @return string
114
- */
115
- public function getUserAgent()
116
- {
117
- $modules = Mage::getConfig()->getNode('modules')->children();
118
- $modulesArray = (array)$modules;
119
-
120
- $aux = (array_key_exists('Enterprise_Enterprise',$modulesArray))? 'EE' : 'CE' ;
121
- $v = (string)Mage::getConfig()->getNode('modules/Ebizmarts_MageMonkey/version');
122
- $version = strpos(Mage::getVersion(),'-')? substr(Mage::getVersion(),0,strpos(Mage::getVersion(),'-')) : Mage::getVersion();
123
- return (string)'MageMonkey'.$v.'/Mage'.$aux.$version;
124
- }
125
-
126
- /**
127
- * Return Mandrill API key
128
- *
129
- * @param string $store
130
- * @return string Api Key
131
- */
132
- public function getMandrillApiKey($store = null)
133
- {
134
- if(is_null($store)){
135
- $key = $this->config('mandrill_apikey');
136
- }else{
137
- $curstore = Mage::app()->getStore();
138
- Mage::app()->setCurrentStore($store);
139
- $key = $this->config('mandrill_apikey', $store);
140
- Mage::app()->setCurrentStore($curstore);
141
  }
 
142
 
143
- return $key;
144
- }
145
-
146
- /**
147
- * Return MC API key for given store, if none is given
148
- * default key is returned
149
- *
150
- * @param string $store
151
- * @return string Api Key
152
- */
153
- public function getApiKey($store = null)
154
- {
155
- if(is_null($store)){
156
- $key = $this->config('apikey');
157
- }else{
158
- $curstore = Mage::app()->getStore();
159
- Mage::app()->setCurrentStore($store);
160
- $key = $this->config('apikey', $store);
161
- Mage::app()->setCurrentStore($curstore);
162
- }
163
 
164
- return $key;
165
- }
166
-
167
- /**
168
- * Logging facility
169
- *
170
- * @param mixed $data Message to save to file
171
- * @param string $filename log filename, default is <Monkey.log>
172
- * @return Mage_Core_Model_Log_Adapter
173
- */
174
- public function log($data, $filename = 'Monkey.log')
175
- {
176
- return Mage::getModel('core/log_adapter', $filename)->log($data);
177
- }
178
-
179
- /**
180
- * Get module configuration value
181
- *
182
- * @param string $value
183
- * @param string $store
184
- * @return mixed Configuration setting
185
- */
186
- public function config($value, $store = null)
187
- {
188
- $store = is_null($store) ? Mage::app()->getStore() : $store;
189
-
190
- $configscope = Mage::app()->getRequest()->getParam('store');
191
- if( $configscope && ($configscope !== 'undefined') ){
192
- $store = $configscope;
193
- }
194
 
195
- return Mage::getStoreConfig("monkey/general/$value", $store);
196
- }
197
-
198
- /**
199
- * Check if config setting <checkout_subscribe> is enabled
200
- *
201
- * @return bool
202
- */
203
- public function canCheckoutSubscribe()
204
- {
205
- return $this->config('checkout_subscribe');
206
- }
207
-
208
- /**
209
- * Check if an email is subscribed on MailChimp
210
- *
211
- * @param string $email
212
- * @param string $listId
213
- * @return bool
214
- */
215
- public function subscribedToList($email, $listId = null)
216
- {
217
- $on = FALSE;
218
-
219
- if($email){
220
- $member = Mage::getSingleton('monkey/api')
221
- ->listMemberInfo($listId, $email);
222
-
223
- if(!is_string($member) && $member['success'] && ($member['data'][0]['status'] == 'subscribed' || $member['data'][0]['status'] == 'pending')){
224
- $on = TRUE;
225
- }
226
- }
227
 
228
- return $on;
229
- }
230
-
231
- /**
232
- * Check if Ecommerce360 integration is enabled
233
- *
234
- * @return bool
235
- */
236
- public function ecommerce360Active()
237
- {
238
- return (bool)($this->config('ecommerce360') != 0);
239
- }
240
-
241
- /**
242
- * Check if Transactional Email via MC is enabled
243
- *
244
- * @return bool
245
- */
246
- public function useTransactionalService()
247
- {
248
- return Mage::getStoreConfigFlag("monkey/general/transactional_emails");
249
- }
250
-
251
- /**
252
- * Check if Ebizmarts_MageMonkey module is enabled
253
- *
254
- * @return bool
255
- */
256
- public function canMonkey()
257
- {
258
- return (bool)((int)$this->config('active') !== 0);
259
- }
260
-
261
- /**
262
- * Get default MC listId for given storeId
263
- *
264
- * @param string $store
265
- * @return string $list
266
- */
267
- public function getDefaultList($store)
268
- {
269
  $curstore = Mage::app()->getStore();
270
  Mage::app()->setCurrentStore($store);
271
- $list = $this->config('list', $store);
272
  Mage::app()->setCurrentStore($curstore);
273
- return $list;
274
- }
275
-
276
- /**
277
- * Get additional Lists by storeId
278
- *
279
- * @param string $store
280
- * @return string $list
281
- */
282
- public function getAdditionalList($store)
283
- {
 
 
 
 
 
 
284
  $curstore = Mage::app()->getStore();
285
  Mage::app()->setCurrentStore($store);
286
- $list = $this->config('additional_lists', $store);
287
  Mage::app()->setCurrentStore($curstore);
288
- return $list;
289
- }
290
-
291
- /**
292
- * Get which store is associated to given $mcListId
293
- *
294
- * @param string $mcListId
295
- * @param bool $includeDefault Include <default> store or not on result
296
- * @return string $store
297
- */
298
- public function getStoreByList($mcListId, $includeDefault = FALSE)
299
- {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  $list = Mage::getModel('core/config_data')->getCollection()
301
- ->addValueFilter($mcListId)->getFirstItem();
302
 
303
  $store = null;
304
  if($list->getId()){
@@ -306,293 +305,289 @@ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonke
306
  //$isDefault = (bool)($list->getScope() == 'default');
307
  $isDefault = (bool)($list->getScope() == Mage::app()->getDefaultStoreView()->getCode());
308
  if(!$isDefault && !$includeDefault){
309
- $store = (string)Mage::app()->getStore($list->getScopeId())->getCode();
310
  }else{
311
- $store = $list->getScope();
312
  }
313
 
314
  }
315
 
316
  return $store;
317
- }
318
-
319
- /**
320
- * Check if current request is a Webhooks request
321
- *
322
- * @return bool
323
- */
324
- public function isWebhookRequest()
325
- {
326
- $rq = Mage::app()->getRequest();
327
- $monkeyRequest = (string)'monkeywebhookindex';
328
- $thisRequest = (string)($rq->getRequestedRouteName() . $rq->getRequestedControllerName() . $rq->getRequestedActionName());
329
-
330
- return (bool)($monkeyRequest === $thisRequest);
331
- }
332
-
333
- /**
334
- * Get config setting <map_fields>
335
- *
336
- * @return array|FALSE
337
- */
338
- public function getMergeMaps($storeId)
339
- {
340
- return unserialize( $this->config('map_fields', $storeId) );
341
- }
342
-
343
- /**
344
- * Get progress bar HTML code
345
- *
346
- * @param integer $complete Processed qty so far
347
- * @param integer $total Total qty to process
348
- * @return string
349
- */
350
- public function progressbar($complete, $total)
351
- {
352
- if($total == 0){
353
- return;
354
- }
355
- $percentage = round(($complete * 100) / $total, 0);
356
 
357
- $barStyle = '';
358
- if($percentage > 0){
359
- $barStyle = " style=\"width: $percentage%\"";
360
- }
 
 
 
 
 
 
 
 
 
361
 
362
- $html = "<div id=\"bar-progress-bar\" class=\"bar-all-rounded\">\n";
363
- $html .= "<div id=\"bar-progress-bar-percentage\" class=\"bar-all-rounded\"$barStyle>";
364
- $html .= "$percentage% ($complete of $total)";
365
- //<progress value="75" max="100">3/4 complete</progress>
366
- //if ($percentage > 5) {$html .= "$percentage% ($complete of $total)";} else {$html .= "<div class=\"bar-spacer\">&nbsp;</div>";}
367
- $html .= "</div></div>";
368
-
369
- return $html;
370
- }
371
-
372
- /**
373
- * Return Merge Fields mapped to Magento attributes
374
- *
375
- * @param object $customer
376
- * @param bool $includeEmail
377
- * @param integer $websiteId
378
- * @return array
379
- */
380
- public function getMergeVars($customer, $includeEmail = FALSE, $websiteId = NULL)
381
- {
382
- $merge_vars = array();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
  $maps = $this->getMergeMaps($customer->getStoreId());
384
 
385
- if(!$maps){
386
- return;
387
- }
388
 
389
- $request = Mage::app()->getRequest();
390
 
391
- //Add Customer data to Subscriber if is Newsletter_Subscriber is Customer
392
- if($customer->getCustomerId()){
393
- $customer->addData(Mage::getModel('customer/customer')->load($customer->getCustomerId())
394
- ->toArray());
395
- }
 
 
 
 
 
 
 
396
 
397
- foreach($maps as $map){
398
-
399
- $customAtt = $map['magento'];
400
- $chimpTag = $map['mailchimp'];
401
-
402
- if($chimpTag && $customAtt){
403
-
404
- $key = strtoupper($chimpTag);
405
-
406
- switch ($customAtt) {
407
- case 'gender':
408
- $val = (int)$customer->getData(strtolower($customAtt));
409
- if($val == 1){
410
- $merge_vars[$key] = 'Male';
411
- }elseif($val == 2){
412
- $merge_vars[$key] = 'Female';
413
- }
414
- break;
415
- case 'dob':
416
- $dob = (string)$customer->getData(strtolower($customAtt));
417
- if($dob){
418
- $merge_vars[$key] = (substr($dob, 5, 2) . '/' . substr($dob, 8, 2));
419
- }
420
- break;
421
- case 'billing_address':
422
- case 'shipping_address':
423
-
424
- $addr = explode('_', $customAtt);
425
- $address = $customer->{'getPrimary'.ucfirst($addr[0]).'Address'}();
426
- if($address){
427
- $merge_vars[$key] = array(
428
- 'addr1' => $address->getStreet(1),
429
- 'addr2' => $address->getStreet(2),
430
- 'city' => $address->getCity(),
431
- 'state' => (!$address->getRegion() ? $address->getCity() : $address->getRegion()),
432
- 'zip' => $address->getPostcode(),
433
- 'country' => $address->getCountryId()
434
- );
435
- }
436
-
437
- break;
438
- case 'date_of_purchase':
439
-
440
- $last_order = Mage::getResourceModel('sales/order_collection')
441
- ->addFieldToFilter('customer_email', $customer->getEmail())
442
- ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
443
- ->setOrder('created_at', 'desc')
444
- ->getFirstItem();
445
- if ( $last_order->getId() ){
446
- $merge_vars[$key] = Mage::helper('core')->formatDate($last_order->getCreatedAt());
447
- }
448
-
449
- break;
450
- case 'ee_customer_balance':
451
-
452
- $merge_vars[$key] = '';
453
-
454
- if($this->isEnterprise() && $customer->getId()){
455
-
456
- $_customer = Mage::getModel('customer/customer')->load($customer->getId());
457
- if($_customer->getId()){
458
- if (Mage::app()->getStore()->isAdmin()) {
459
- $websiteId = is_null($websiteId) ? Mage::app()->getStore()->getWebsiteId() : $websiteId;
460
- }
461
-
462
- $balance = Mage::getModel('enterprise_customerbalance/balance')
463
- ->setWebsiteId($websiteId)
464
- ->setCustomerId($_customer->getId())
465
- ->loadByCustomer();
466
-
467
- $merge_vars[$key] = $balance->getAmount();
468
- }
469
-
470
- }
471
-
472
- break;
473
- case 'custshash':
474
- $merge_vars[$key] = '';
475
- $cryptdata = Mage::helper('loginautomatico') -> encrypt($customer);
476
- $merge_vars[$key] = urlencode($cryptdata);
477
- break;
478
- default:
479
-
480
- if( ($value = (string)$customer->getData(strtolower($customAtt)))
481
- OR ($value = (string)$request->getPost(strtolower($customAtt))) ){
482
- $merge_vars[$key] = $value;
483
- }
484
-
485
- break;
486
  }
487
 
488
- }
489
- }
490
 
491
- //GUEST
492
- if( !$customer->getId() ){
493
- $guestFirstName = $this->config('guest_name', $customer->getStoreId());
494
- $guestLastName = $this->config('guest_lastname', $customer->getStoreId());
495
-
496
- if($guestFirstName){
497
- $merge_vars['FNAME'] = $guestFirstName;
498
- }
499
- if($guestLastName){
500
- $merge_vars['LNAME'] = $guestLastName;
501
- }
502
- }
503
- //GUEST
504
 
505
- if($includeEmail){
506
- $merge_vars['EMAIL'] = $customer->getEmail();
507
- }
508
 
509
- $groups = $customer->getListGroups();
510
- $groupings = array();
511
- if(is_array($groups) && count($groups)){
512
- foreach($groups as $groupId => $grupoptions){
513
- $groupings[] = array(
514
- 'id' => $groupId,
515
- 'groups' => (is_array($grupoptions) ? implode(', ', $grupoptions) : $grupoptions)
516
- );
517
- }
518
- }
519
 
520
- //Add customer group for logged in customers
521
- if( $customer->getId() && $customer->getMcListId()){
522
 
523
- $groupId = (int)Mage::getStoreConfig("monkey/groupings/list_" . $customer->getMcListId(), $customer->getStoreId());
524
- if($groupId){
525
- $groups = Mage::helper('customer')->getGroups()->toOptionHash();
526
- $groupings[] = array(
527
- 'id' => $groupId,
528
- 'groups' => $groups[$customer->getGroupId()],
529
- );
530
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
 
532
  }
 
533
 
534
- $merge_vars['GROUPINGS'] = $groupings;
 
 
 
535
 
536
- //magemonkey_mergevars_after
537
- $blank = new Varien_Object;
538
- Mage::dispatchEvent('magemonkey_mergevars_after',
539
- array('vars' => $merge_vars, 'customer' => $customer, 'newvars' => $blank));
540
- if($blank->hasData()){
541
- $merge_vars = array_merge($merge_vars, $blank->toArray());
542
  }
543
- //magemonkey_mergevars_after
544
-
545
- return $merge_vars;
546
- }
547
-
548
- /**
549
- * Register on Magento's registry GUEST customer data for MergeVars for on checkout subscribe
550
- *
551
- * @param Mage_Sales_Model_Order $order
552
- * @return void
553
- */
554
- public function registerGuestCustomer($order)
555
- {
556
-
557
- if( Mage::registry('mc_guest_customer') ){
558
- return;
559
  }
 
 
560
 
561
- $customer = new Varien_Object;
 
 
562
 
563
- $customer->setId('guest' . time());
564
- $customer->setEmail($order->getBillingAddress()->getEmail());
565
- $customer->setStoreId($order->getStoreId());
566
- $customer->setFirstname($order->getBillingAddress()->getFirstname());
567
- $customer->setLastname($order->getBillingAddress()->getLastname());
568
- $customer->setPrimaryBillingAddress($order->getBillingAddress());
569
- $customer->setPrimaryShippingAddress($order->getShippingAddress());
570
 
571
- Mage::register('mc_guest_customer', $customer, TRUE);
 
 
 
 
 
 
 
572
 
573
- }
574
 
 
 
 
 
 
 
 
 
575
 
576
- /**
577
- * Create a Magento's customer account for given data
578
- *
579
- * @param array $accountData
580
- * @param integer $websiteId ID of website to associate customer to
581
- * @return Mage_Customer_Model_Customer
582
- */
583
- public function createCustomerAccount($accountData, $websiteId)
584
- {
585
- $customer = Mage::getModel('customer/customer')->setWebsiteId($websiteId);
586
 
587
- if(!isset($accountData['firstname']) OR empty($accountData['firstname'])){
588
- $accountData['firstname'] = $this->__('Store');
589
- }
590
- if(!isset($accountData['lastname']) OR empty($accountData['lastname'])){
591
- $accountData['lastname'] = $this->__('Guest');
592
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593
 
594
- $customerForm = Mage::getModel('customer/form');
595
- $customerForm->setFormCode('customer_account_create')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
596
  ->setEntity($customer)
597
  ->initDefaultValues();
598
  // emulate request
@@ -600,9 +595,9 @@ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonke
600
  $customerData = $customerForm->extractData($request);
601
  $customerForm->restoreData($customerData);
602
 
603
- $customerErrors = $customerForm->validateData($customerData);
604
 
605
- if($customerErrors){
606
  $customerForm->compactData($customerData);
607
 
608
  $pwd = $customer->generatePassword(8);
@@ -610,19 +605,19 @@ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonke
610
  $customer->setConfirmation($pwd);
611
 
612
 
613
- /**
614
- * Handle Address related Data
615
- */
616
- $billing = $shipping = null;
617
- if(isset($accountData['billing_address']) && !empty($accountData['billing_address'])){
618
- $this->_McAddressToMage($accountData, 'billing', $customer);
619
- }
620
- if(isset($accountData['shipping_address']) && !empty($accountData['shipping_address'])){
621
- $this->_McAddressToMage($accountData, 'shipping', $customer);
622
- }
623
- /**
624
- * Handle Address related Data
625
- */
626
 
627
  $customerErrors = $customer->validate();
628
  if (is_array($customerErrors) && count($customerErrors)) {
@@ -630,45 +625,45 @@ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonke
630
  //TODO: Do something with errors.
631
 
632
  }else{
633
- $customer->save();
634
 
635
- if ( $customer->isConfirmationRequired() ){
636
  $customer->sendNewAccountEmail('confirmation');
637
- }
638
 
639
  }
640
- }
 
 
 
641
 
642
- return $customer;
643
- }
644
-
645
- /**
646
- * Parse MailChimp <address> MergeField type to Magento's address object
647
- *
648
- * @param array $data MC address data
649
- * @param string $type billing or shipping
650
- * @param Mage_Customer_Model_Customer $customer
651
- * @return array Empty if noy errors, or a list of errors in an Array
652
- */
653
- protected function _McAddressToMage(array $data, $type, $customer)
654
- {
655
- $addressData = $data["{$type}_address"];
656
- $address = explode(str_repeat(chr(32), 2), $addressData);
657
- list($addr1, $addr2, $city, $state, $zip, $country) = $address;
658
-
659
- $region = Mage::getModel('directory/region')->loadByName($state, $country);
660
-
661
- $mgAddress = array(
662
- 'firstname' => $data['firstname'],
663
- 'lastname' => $data['lastname'],
664
- 'street' => array($addr1, $addr2),
665
- 'city' => $city,
666
- 'country_id' => $country,
667
- 'region' => $state,
668
- 'region_id' => (!is_null($region->getId()) ? $region->getId() : null),
669
- 'postcode' => $zip,
670
- 'telephone' => 'not_provided',
671
- );
672
 
673
  /* @var $address Mage_Customer_Model_Address */
674
  $address = Mage::getModel('customer/address');
@@ -677,14 +672,14 @@ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonke
677
  $addressForm->setFormCode('customer_register_address')
678
  ->setEntity($address);
679
 
680
- $addrrequest = $addressForm->prepareRequest($mgAddress);
681
  $addressData = $addressForm->extractData($addrrequest);
682
  $addressErrors = $addressForm->validateData($addressData);
683
 
684
  $errors = array();
685
  if ($addressErrors === true) {
686
  $address->setId(null)
687
- ->setData("is_default_{$type}", TRUE);
688
  $addressForm->compactData($addressData);
689
  $customer->addAddress($address);
690
 
@@ -696,144 +691,144 @@ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Ebizmarts_MageMonke
696
  $errors = array_merge($errors, $addressErrors);
697
  }
698
 
699
- return $errors;
700
- }
701
 
702
- /**
703
- * Handle additional lists subscription on form posts like Customer Create Account
704
- *
705
- * @param Mage_Customer_Model_Customer $customer
706
- */
707
- public function additionalListsSubscription($customer = null, $post = null)
708
- {
709
- $request = Mage::app()->getRequest();
710
 
711
- if( !$request->isPost() && is_null($post) ){
712
- return false;
713
- }
714
 
715
- $allowedPost = array('/customer/account/createpost/');
716
- $requestString = $request->getRequestString();
717
 
718
- if( in_array($requestString, $allowedPost) OR !is_null($post) ){
719
- if(!is_null($post)){
720
- $request = $post;
721
- }
722
- $this->handlePost($request, $customer->getEmail());
723
  }
 
 
724
 
725
- }
726
-
727
- /**
728
- * Handle subscription posts, (additional lists)
729
- *
730
- * @param Mage_Core_Controller_Request_Http $request
731
- * @param string $guestEmail
732
- * @return void
733
- */
734
- public function handlePost($request, $guestEmail)
735
- {
736
- //<state> param is an html serialized field containing the default form state
737
- //before submission, we need to parse it as a request in order to save it to $odata and process it
738
- parse_str($request->getPost('state'), $odata);
739
 
740
- $curlists = (TRUE === array_key_exists('list', $odata)) ? $odata['list'] : array();
741
- $lists = $request->getPost('list', array());
 
 
 
 
 
 
 
 
 
 
742
 
743
- $defaultList = $this->getDefaultList(Mage::app()->getStore());
 
744
 
745
- $api = Mage::getSingleton('monkey/api');
746
- $customer = Mage::helper('customer')->getCustomer();
747
- $email = $guestEmail ? $guestEmail : $customer->getEmail();
748
 
749
- $loggedIn = Mage::helper('customer')->isLoggedIn();
 
 
750
 
751
- if( !empty($curlists) ){
752
 
753
- //Handle Unsubscribe and groups update actions
754
- foreach($curlists as $listId => $list){
755
 
756
- if(FALSE === array_key_exists($listId, $lists)){
 
757
 
758
- //Unsubscribe Email
759
- if($defaultList == $listId){
760
 
761
- $item = Mage::getModel('monkey/monkey')->loadByEmail($email);
762
- if(!$item->getId()){
763
- $item = Mage::getModel('newsletter/subscriber')
764
- ->loadByEmail($email);
765
- }
766
- if($item->getSubscriberEmail()){
767
- $item->unsubscribe();
768
- }
769
 
770
- }else{
771
- //Unsubscribe Email
772
- $api->listUnsubscribe($listId, $email);
773
- }
 
 
 
 
774
 
775
- }else{
 
 
 
776
 
777
- $groupings = $lists[$listId];
778
- unset($groupings['subscribed']);
779
- $customerLists = $api->listMemberInfo($listId,$email);
780
- $customerLists = isset($customerLists['data'][0]['merges']['GROUPINGS']) ?$customerLists['data'][0]['merges']['GROUPINGS'] :array();
781
 
782
- foreach ($customerLists as $clkey => $cl)
783
- {
784
- if (!isset($groupings[$cl['id']]))
785
- {
786
- $groupings[$cl['id']][] = '';
787
- }
788
- }
789
 
790
- $customer->setMcListId($listId);
791
- $customer->setListGroups($groupings);
792
- $mergeVars = Mage::helper('monkey')->getMergeVars($customer);
 
 
 
 
793
 
794
- //Handle groups update
795
- $api->listUpdateMember($listId, $email, $mergeVars);
 
796
 
797
- }
 
798
 
799
- }
800
 
801
  }
802
 
803
- //Subscribe to new lists
804
- if(is_array($lists) && is_array($curlists)){
805
- $subscribe = array_diff_key($lists, $curlists);
806
- if( !empty($subscribe) ){
 
 
807
 
808
- foreach($subscribe as $listId => $slist){
809
 
810
- if(!isset($slist['subscribed'])){
811
- continue;
812
- }
813
 
814
- $groupings = $lists[$listId];
815
- unset($groupings['subscribed']);
816
 
817
- if($defaultList == $listId){
818
- $subscriber = Mage::getModel('newsletter/subscriber');
819
 
820
- $subscriber->setListGroups($groupings);
821
- $subscriber->setMcListId($listId);
822
  $subscriber->setMcStoreId(Mage::app()->getStore()->getId());
823
 
824
- $subscriber->subscribe($email);
825
- }else{
826
 
827
- $customer->setListGroups($groupings);
828
- $customer->setMcListId($listId);
829
- $mergeVars = Mage::helper('monkey')->getMergeVars($customer);
830
- $api->listSubscribe($listId, $email, $mergeVars, 'html', ($loggedIn ? false : true));
831
 
832
- }
833
 
834
- }
835
 
836
- }
837
  }
838
- }
 
839
  }
6
  * @category ThiagoSantos
7
  * @package ThiagoSantos_LoginAutomatico
8
  */
 
9
  /**
10
  * Mage Monkey default helper
11
  *
13
  * @package Ebizmarts_MageMonkey
14
  * @author Ebizmarts Team <info@ebizmarts.com>
15
  */
16
+ class ThiagoSantos_LoginAutomatico_Helper_MonkeyData extends Mage_Core_Helper_Abstract
17
  {
18
 
19
+ /**
20
+ * Utility to check if admin is logged in
21
+ *
22
+ * @return bool
23
+ */
24
+ public function isAdmin()
25
+ {
26
+ return Mage::getSingleton('admin/session')->isLoggedIn();
27
+ }
28
 
29
  /**
30
  * Check if Magento is EE
36
  return is_object(Mage::getConfig()->getNode('global/models/enterprise_enterprise'));
37
  }
38
 
39
+ /**
40
+ * Return Webhooks security key for given store
41
+ *
42
+ * @param mixed $store Store object, or Id, or code
43
+ * @param string $listId Optional listid to retrieve store code from it
44
+ * @return string
45
+ */
46
+ public function getWebhooksKey($store, $listId = null)
47
+ {
48
+ if( !is_null($listId) ){
49
+ $store = $this->getStoreByList($listId, TRUE);
50
+ }
51
 
52
+ $crypt = md5((string)Mage::getConfig()->getNode('global/crypt/key'));
53
+ $key = substr($crypt, 0, (strlen($crypt)/2));
54
 
55
+ return ($key . $store);
56
+ }
57
 
58
+ public function filterShowGroupings($interestGroupings)
59
+ {
60
+ if(is_array($interestGroupings)){
61
 
62
+ $customGroupings = Mage::getConfig()->getNode('default/monkey/custom_groupings')
63
+ ->asArray();
64
 
65
+ foreach($interestGroupings as $key => $group){
66
 
67
+ if(TRUE === in_array($group['name'], $customGroupings)){
68
+ unset($interestGroupings[$key]);
69
+ }
70
 
 
71
  }
72
+ }
73
 
74
+ return $interestGroupings;
75
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ /**
78
+ * Check if CustomerGroup grouping already exists on MC
79
+ *
80
+ * @param array $groupings
81
+ * @return bool
82
+ */
83
+ public function customerGroupGroupingExists($interestGroupings)
84
+ {
85
+ $exists = FALSE;
86
+ if(is_array($interestGroupings)){
87
+ foreach($interestGroupings as $group){
88
+ if($group['name'] == $this->getCustomerGroupingName()){
89
+ $exists = TRUE;
90
+ break;
91
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  }
93
+ }
94
 
95
+ return $exists;
96
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
+ /**
99
+ * Return customer groping name to be used when creating a grouping to store
100
+ * Magento customer groups
101
+ *
102
+ * @return string
103
+ */
104
+ public function getCustomerGroupingName()
105
+ {
106
+ return (string)Mage::getConfig()->getNode('default/monkey/custom_groupings/customer_grouping_name');
107
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
+ /**
110
+ * Get module User-Agent to use on API requests
111
+ *
112
+ * @return string
113
+ */
114
+ public function getUserAgent()
115
+ {
116
+ $modules = Mage::getConfig()->getNode('modules')->children();
117
+ $modulesArray = (array)$modules;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
+ $aux = (array_key_exists('Enterprise_Enterprise',$modulesArray))? 'EE' : 'CE' ;
120
+ $v = (string)Mage::getConfig()->getNode('modules/Ebizmarts_MageMonkey/version');
121
+ $version = strpos(Mage::getVersion(),'-')? substr(Mage::getVersion(),0,strpos(Mage::getVersion(),'-')) : Mage::getVersion();
122
+ return (string)'MageMonkey'.$v.'/Mage'.$aux.$version;
123
+ }
124
+
125
+ /**
126
+ * Return Mandrill API key
127
+ *
128
+ * @param string $store
129
+ * @return string Api Key
130
+ */
131
+ public function getMandrillApiKey($store = null)
132
+ {
133
+ if(is_null($store)){
134
+ $key = $this->config('mandrill_apikey');
135
+ }else{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  $curstore = Mage::app()->getStore();
137
  Mage::app()->setCurrentStore($store);
138
+ $key = $this->config('mandrill_apikey', $store);
139
  Mage::app()->setCurrentStore($curstore);
140
+ }
141
+
142
+ return $key;
143
+ }
144
+
145
+ /**
146
+ * Return MC API key for given store, if none is given
147
+ * default key is returned
148
+ *
149
+ * @param string $store
150
+ * @return string Api Key
151
+ */
152
+ public function getApiKey($store = null)
153
+ {
154
+ if(is_null($store)){
155
+ $key = $this->config('apikey');
156
+ }else{
157
  $curstore = Mage::app()->getStore();
158
  Mage::app()->setCurrentStore($store);
159
+ $key = $this->config('apikey', $store);
160
  Mage::app()->setCurrentStore($curstore);
161
+ }
162
+
163
+ return $key;
164
+ }
165
+
166
+ /**
167
+ * Logging facility
168
+ *
169
+ * @param mixed $data Message to save to file
170
+ * @param string $filename log filename, default is <Monkey.log>
171
+ * @return Mage_Core_Model_Log_Adapter
172
+ */
173
+ public function log($data, $filename = 'Monkey.log')
174
+ {
175
+ return Mage::getModel('core/log_adapter', $filename)->log($data);
176
+ }
177
+
178
+ /**
179
+ * Get module configuration value
180
+ *
181
+ * @param string $value
182
+ * @param string $store
183
+ * @return mixed Configuration setting
184
+ */
185
+ public function config($value, $store = null)
186
+ {
187
+ $store = is_null($store) ? Mage::app()->getStore() : $store;
188
+
189
+ $configscope = Mage::app()->getRequest()->getParam('store');
190
+ if( $configscope && ($configscope !== 'undefined') ){
191
+ $store = $configscope;
192
+ }
193
+
194
+ return Mage::getStoreConfig("monkey/general/$value", $store);
195
+ }
196
+
197
+ /**
198
+ * Check if config setting <checkout_subscribe> is enabled
199
+ *
200
+ * @return bool
201
+ */
202
+ public function canCheckoutSubscribe()
203
+ {
204
+ return $this->config('checkout_subscribe');
205
+ }
206
+
207
+ /**
208
+ * Check if an email is subscribed on MailChimp
209
+ *
210
+ * @param string $email
211
+ * @param string $listId
212
+ * @return bool
213
+ */
214
+ public function subscribedToList($email, $listId = null)
215
+ {
216
+ $on = FALSE;
217
+
218
+ if($email){
219
+ $member = Mage::getSingleton('monkey/api')
220
+ ->listMemberInfo($listId, $email);
221
+
222
+ if(!is_string($member) && $member['success'] && ($member['data'][0]['status'] == 'subscribed' || $member['data'][0]['status'] == 'pending')){
223
+ $on = TRUE;
224
+ }
225
+ }
226
+
227
+ return $on;
228
+ }
229
+
230
+ /**
231
+ * Check if Ecommerce360 integration is enabled
232
+ *
233
+ * @return bool
234
+ */
235
+ public function ecommerce360Active()
236
+ {
237
+ return (bool)($this->config('ecommerce360') != 0);
238
+ }
239
+
240
+ /**
241
+ * Check if Transactional Email via MC is enabled
242
+ *
243
+ * @return bool
244
+ */
245
+ public function useTransactionalService()
246
+ {
247
+ return Mage::getStoreConfigFlag("monkey/general/transactional_emails");
248
+ }
249
+
250
+ /**
251
+ * Check if Ebizmarts_MageMonkey module is enabled
252
+ *
253
+ * @return bool
254
+ */
255
+ public function canMonkey()
256
+ {
257
+ return (bool)((int)$this->config('active') !== 0);
258
+ }
259
+
260
+ /**
261
+ * Get default MC listId for given storeId
262
+ *
263
+ * @param string $store
264
+ * @return string $list
265
+ */
266
+ public function getDefaultList($store)
267
+ {
268
+ $curstore = Mage::app()->getStore();
269
+ Mage::app()->setCurrentStore($store);
270
+ $list = $this->config('list', $store);
271
+ Mage::app()->setCurrentStore($curstore);
272
+ return $list;
273
+ }
274
+
275
+ /**
276
+ * Get additional Lists by storeId
277
+ *
278
+ * @param string $store
279
+ * @return string $list
280
+ */
281
+ public function getAdditionalList($store)
282
+ {
283
+ $curstore = Mage::app()->getStore();
284
+ Mage::app()->setCurrentStore($store);
285
+ $list = $this->config('additional_lists', $store);
286
+ Mage::app()->setCurrentStore($curstore);
287
+ return $list;
288
+ }
289
+
290
+ /**
291
+ * Get which store is associated to given $mcListId
292
+ *
293
+ * @param string $mcListId
294
+ * @param bool $includeDefault Include <default> store or not on result
295
+ * @return string $store
296
+ */
297
+ public function getStoreByList($mcListId, $includeDefault = FALSE)
298
+ {
299
  $list = Mage::getModel('core/config_data')->getCollection()
300
+ ->addValueFilter($mcListId)->getFirstItem();
301
 
302
  $store = null;
303
  if($list->getId()){
305
  //$isDefault = (bool)($list->getScope() == 'default');
306
  $isDefault = (bool)($list->getScope() == Mage::app()->getDefaultStoreView()->getCode());
307
  if(!$isDefault && !$includeDefault){
308
+ $store = (string)Mage::app()->getStore($list->getScopeId())->getCode();
309
  }else{
310
+ $store = $list->getScope();
311
  }
312
 
313
  }
314
 
315
  return $store;
316
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
+ /**
319
+ * Check if current request is a Webhooks request
320
+ *
321
+ * @return bool
322
+ */
323
+ public function isWebhookRequest()
324
+ {
325
+ $rq = Mage::app()->getRequest();
326
+ $monkeyRequest = (string)'monkeywebhookindex';
327
+ $thisRequest = (string)($rq->getRequestedRouteName() . $rq->getRequestedControllerName() . $rq->getRequestedActionName());
328
+
329
+ return (bool)($monkeyRequest === $thisRequest);
330
+ }
331
 
332
+ /**
333
+ * Get config setting <map_fields>
334
+ *
335
+ * @return array|FALSE
336
+ */
337
+ public function getMergeMaps($storeId)
338
+ {
339
+ return unserialize( $this->config('map_fields', $storeId) );
340
+ }
341
+
342
+ /**
343
+ * Get progress bar HTML code
344
+ *
345
+ * @param integer $complete Processed qty so far
346
+ * @param integer $total Total qty to process
347
+ * @return string
348
+ */
349
+ public function progressbar($complete, $total)
350
+ {
351
+ if($total == 0){
352
+ return;
353
+ }
354
+ $percentage = round(($complete * 100) / $total, 0);
355
+
356
+ $barStyle = '';
357
+ if($percentage > 0){
358
+ $barStyle = " style=\"width: $percentage%\"";
359
+ }
360
+
361
+ $html = "<div id=\"bar-progress-bar\" class=\"bar-all-rounded\">\n";
362
+ $html .= "<div id=\"bar-progress-bar-percentage\" class=\"bar-all-rounded\"$barStyle>";
363
+ $html .= "$percentage% ($complete of $total)";
364
+ //<progress value="75" max="100">3/4 complete</progress>
365
+ //if ($percentage > 5) {$html .= "$percentage% ($complete of $total)";} else {$html .= "<div class=\"bar-spacer\">&nbsp;</div>";}
366
+ $html .= "</div></div>";
367
+
368
+ return $html;
369
+ }
370
+
371
+ /**
372
+ * Return Merge Fields mapped to Magento attributes
373
+ *
374
+ * @param object $customer
375
+ * @param bool $includeEmail
376
+ * @param integer $websiteId
377
+ * @return array
378
+ */
379
+ public function getMergeVars($customer, $includeEmail = FALSE, $websiteId = NULL)
380
+ {
381
+ $merge_vars = array();
382
  $maps = $this->getMergeMaps($customer->getStoreId());
383
 
384
+ if(!$maps){
385
+ return;
386
+ }
387
 
388
+ $request = Mage::app()->getRequest();
389
 
390
+ //Add Customer data to Subscriber if is Newsletter_Subscriber is Customer
391
+ if($customer->getCustomerId()){
392
+ $customer->addData(Mage::getModel('customer/customer')->load($customer->getCustomerId())
393
+ ->toArray());
394
+ }
395
+
396
+ foreach($maps as $map){
397
+
398
+ $customAtt = $map['magento'];
399
+ $chimpTag = $map['mailchimp'];
400
+
401
+ if($chimpTag && $customAtt){
402
 
403
+ $key = strtoupper($chimpTag);
404
+
405
+ switch ($customAtt) {
406
+ case 'gender':
407
+ $val = (int)$customer->getData(strtolower($customAtt));
408
+ if($val == 1){
409
+ $merge_vars[$key] = 'Male';
410
+ }elseif($val == 2){
411
+ $merge_vars[$key] = 'Female';
412
+ }
413
+ break;
414
+ case 'dob':
415
+ $dob = (string)$customer->getData(strtolower($customAtt));
416
+ if($dob){
417
+ $merge_vars[$key] = (substr($dob, 5, 2) . '/' . substr($dob, 8, 2));
418
+ }
419
+ break;
420
+ case 'billing_address':
421
+ case 'shipping_address':
422
+
423
+ $addr = explode('_', $customAtt);
424
+ $address = $customer->{'getPrimary'.ucfirst($addr[0]).'Address'}();
425
+ if($address){
426
+ $merge_vars[$key] = array(
427
+ 'addr1' => $address->getStreet(1),
428
+ 'addr2' => $address->getStreet(2),
429
+ 'city' => $address->getCity(),
430
+ 'state' => (!$address->getRegion() ? $address->getCity() : $address->getRegion()),
431
+ 'zip' => $address->getPostcode(),
432
+ 'country' => $address->getCountryId()
433
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  }
435
 
436
+ break;
437
+ case 'date_of_purchase':
438
 
439
+ $last_order = Mage::getResourceModel('sales/order_collection')
440
+ ->addFieldToFilter('customer_email', $customer->getEmail())
441
+ ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
442
+ ->setOrder('created_at', 'desc')
443
+ ->getFirstItem();
444
+ if ( $last_order->getId() ){
445
+ $merge_vars[$key] = Mage::helper('core')->formatDate($last_order->getCreatedAt());
446
+ }
 
 
 
 
 
447
 
448
+ break;
449
+ case 'ee_customer_balance':
 
450
 
451
+ $merge_vars[$key] = '';
 
 
 
 
 
 
 
 
 
452
 
453
+ if($this->isEnterprise() && $customer->getId()){
 
454
 
455
+ $_customer = Mage::getModel('customer/customer')->load($customer->getId());
456
+ if($_customer->getId()){
457
+ if (Mage::app()->getStore()->isAdmin()) {
458
+ $websiteId = is_null($websiteId) ? Mage::app()->getStore()->getWebsiteId() : $websiteId;
459
+ }
460
+
461
+ $balance = Mage::getModel('enterprise_customerbalance/balance')
462
+ ->setWebsiteId($websiteId)
463
+ ->setCustomerId($_customer->getId())
464
+ ->loadByCustomer();
465
+
466
+ $merge_vars[$key] = $balance->getAmount();
467
+ }
468
+
469
+ }
470
+
471
+ break;
472
+ case 'custshash':
473
+ $merge_vars[$key] = '';
474
+ $cryptdata = Mage::helper('loginautomatico') -> encrypt($customer);
475
+ $merge_vars[$key] = urlencode($cryptdata);
476
+ break;
477
+ case 'group_id':
478
+ $group_id = (int)$customer->getData(strtolower($customAtt));
479
+ $customerGroup = Mage::helper('customer')->getGroups()->toOptionHash();
480
+ if($group_id == 0){
481
+ $merge_vars[$key] = 'NOT LOGGED IN';
482
+ }else{
483
+ $merge_vars[$key] = $customerGroup[$group_id];
484
+ }
485
+ break;
486
+ default:
487
+
488
+ if( ($value = (string)$customer->getData(strtolower($customAtt)))
489
+ OR ($value = (string)$request->getPost(strtolower($customAtt))) ){
490
+ $merge_vars[$key] = $value;
491
+ }
492
+
493
+ break;
494
+ }
495
 
496
  }
497
+ }
498
 
499
+ //GUEST
500
+ if( !$customer->getId() && (!$request->getPost('firstname') || !$request->getPost('lastname'))){
501
+ $guestFirstName = $this->config('guest_name', $customer->getStoreId());
502
+ $guestLastName = $this->config('guest_lastname', $customer->getStoreId());
503
 
504
+ if($guestFirstName){
505
+ $merge_vars['FNAME'] = $guestFirstName;
 
 
 
 
506
  }
507
+ if($guestLastName){
508
+ $merge_vars['LNAME'] = $guestLastName;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
  }
510
+ }
511
+ //GUEST
512
 
513
+ if($includeEmail){
514
+ $merge_vars['EMAIL'] = $customer->getEmail();
515
+ }
516
 
517
+ $groups = $customer->getListGroups();
518
+ $groupings = array();
 
 
 
 
 
519
 
520
+ if(is_array($groups) && count($groups)){
521
+ foreach($groups as $groupId => $grupoptions){
522
+ $groupings[] = array(
523
+ 'id' => $groupId,
524
+ 'groups' => (is_array($grupoptions) ? implode(', ', $grupoptions) : $grupoptions)
525
+ );
526
+ }
527
+ }
528
 
529
+ $merge_vars['GROUPINGS'] = $groupings;
530
 
531
+ //magemonkey_mergevars_after
532
+ $blank = new Varien_Object;
533
+ Mage::dispatchEvent('magemonkey_mergevars_after',
534
+ array('vars' => $merge_vars, 'customer' => $customer, 'newvars' => $blank));
535
+ if($blank->hasData()){
536
+ $merge_vars = array_merge($merge_vars, $blank->toArray());
537
+ }
538
+ //magemonkey_mergevars_after
539
 
540
+ return $merge_vars;
541
+ }
 
 
 
 
 
 
 
 
542
 
543
+ /**
544
+ * Register on Magento's registry GUEST customer data for MergeVars for on checkout subscribe
545
+ *
546
+ * @param Mage_Sales_Model_Order $order
547
+ * @return void
548
+ */
549
+ public function registerGuestCustomer($order)
550
+ {
551
+
552
+ if( Mage::registry('mc_guest_customer') ){
553
+ return;
554
+ }
555
+
556
+ $customer = new Varien_Object;
557
+
558
+ $customer->setId('guest' . time());
559
+ $customer->setEmail($order->getBillingAddress()->getEmail());
560
+ $customer->setStoreId($order->getStoreId());
561
+ $customer->setFirstname($order->getBillingAddress()->getFirstname());
562
+ $customer->setLastname($order->getBillingAddress()->getLastname());
563
+ $customer->setPrimaryBillingAddress($order->getBillingAddress());
564
+ $customer->setPrimaryShippingAddress($order->getShippingAddress());
565
 
566
+ Mage::register('mc_guest_customer', $customer, TRUE);
567
+
568
+ }
569
+
570
+
571
+ /**
572
+ * Create a Magento's customer account for given data
573
+ *
574
+ * @param array $accountData
575
+ * @param integer $websiteId ID of website to associate customer to
576
+ * @return Mage_Customer_Model_Customer
577
+ */
578
+ public function createCustomerAccount($accountData, $websiteId)
579
+ {
580
+ $customer = Mage::getModel('customer/customer')->setWebsiteId($websiteId);
581
+
582
+ if(!isset($accountData['firstname']) OR empty($accountData['firstname'])){
583
+ $accountData['firstname'] = $this->__('Store');
584
+ }
585
+ if(!isset($accountData['lastname']) OR empty($accountData['lastname'])){
586
+ $accountData['lastname'] = $this->__('Guest');
587
+ }
588
+
589
+ $customerForm = Mage::getModel('customer/form');
590
+ $customerForm->setFormCode('customer_account_create')
591
  ->setEntity($customer)
592
  ->initDefaultValues();
593
  // emulate request
595
  $customerData = $customerForm->extractData($request);
596
  $customerForm->restoreData($customerData);
597
 
598
+ $customerErrors = $customerForm->validateData($customerData);
599
 
600
+ if($customerErrors){
601
  $customerForm->compactData($customerData);
602
 
603
  $pwd = $customer->generatePassword(8);
605
  $customer->setConfirmation($pwd);
606
 
607
 
608
+ /**
609
+ * Handle Address related Data
610
+ */
611
+ $billing = $shipping = null;
612
+ if(isset($accountData['billing_address']) && !empty($accountData['billing_address'])){
613
+ $this->_McAddressToMage($accountData, 'billing', $customer);
614
+ }
615
+ if(isset($accountData['shipping_address']) && !empty($accountData['shipping_address'])){
616
+ $this->_McAddressToMage($accountData, 'shipping', $customer);
617
+ }
618
+ /**
619
+ * Handle Address related Data
620
+ */
621
 
622
  $customerErrors = $customer->validate();
623
  if (is_array($customerErrors) && count($customerErrors)) {
625
  //TODO: Do something with errors.
626
 
627
  }else{
628
+ $customer->save();
629
 
630
+ if ( $customer->isConfirmationRequired() ){
631
  $customer->sendNewAccountEmail('confirmation');
632
+ }
633
 
634
  }
635
+ }
636
+
637
+ return $customer;
638
+ }
639
 
640
+ /**
641
+ * Parse MailChimp <address> MergeField type to Magento's address object
642
+ *
643
+ * @param array $data MC address data
644
+ * @param string $type billing or shipping
645
+ * @param Mage_Customer_Model_Customer $customer
646
+ * @return array Empty if noy errors, or a list of errors in an Array
647
+ */
648
+ protected function _McAddressToMage(array $data, $type, $customer)
649
+ {
650
+ $addressData = $data["{$type}_address"];
651
+ $address = explode(str_repeat(chr(32), 2), $addressData);
652
+ list($addr1, $addr2, $city, $state, $zip, $country) = $address;
653
+
654
+ $region = Mage::getModel('directory/region')->loadByName($state, $country);
655
+
656
+ $mgAddress = array(
657
+ 'firstname' => $data['firstname'],
658
+ 'lastname' => $data['lastname'],
659
+ 'street' => array($addr1, $addr2),
660
+ 'city' => $city,
661
+ 'country_id' => $country,
662
+ 'region' => $state,
663
+ 'region_id' => (!is_null($region->getId()) ? $region->getId() : null),
664
+ 'postcode' => $zip,
665
+ 'telephone' => 'not_provided',
666
+ );
 
 
 
667
 
668
  /* @var $address Mage_Customer_Model_Address */
669
  $address = Mage::getModel('customer/address');
672
  $addressForm->setFormCode('customer_register_address')
673
  ->setEntity($address);
674
 
675
+ $addrrequest = $addressForm->prepareRequest($mgAddress);
676
  $addressData = $addressForm->extractData($addrrequest);
677
  $addressErrors = $addressForm->validateData($addressData);
678
 
679
  $errors = array();
680
  if ($addressErrors === true) {
681
  $address->setId(null)
682
+ ->setData("is_default_{$type}", TRUE);
683
  $addressForm->compactData($addressData);
684
  $customer->addAddress($address);
685
 
691
  $errors = array_merge($errors, $addressErrors);
692
  }
693
 
694
+ return $errors;
695
+ }
696
 
697
+ /**
698
+ * Handle additional lists subscription on form posts like Customer Create Account
699
+ *
700
+ * @param Mage_Customer_Model_Customer $customer
701
+ */
702
+ public function additionalListsSubscription($customer = null, $post = null)
703
+ {
704
+ $request = Mage::app()->getRequest();
705
 
706
+ if( !$request->isPost() && is_null($post) ){
707
+ return false;
708
+ }
709
 
710
+ $allowedPost = array('/customer/account/createpost/');
711
+ $requestString = $request->getRequestString();
712
 
713
+ if( in_array($requestString, $allowedPost) OR !is_null($post) ){
714
+ if(!is_null($post)){
715
+ $request = $post;
 
 
716
  }
717
+ $this->handlePost($request, $customer->getEmail());
718
+ }
719
 
720
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
721
 
722
+ /**
723
+ * Handle subscription posts, (additional lists)
724
+ *
725
+ * @param Mage_Core_Controller_Request_Http $request
726
+ * @param string $guestEmail
727
+ * @return void
728
+ */
729
+ public function handlePost($request, $guestEmail)
730
+ {
731
+ //<state> param is an html serialized field containing the default form state
732
+ //before submission, we need to parse it as a request in order to save it to $odata and process it
733
+ parse_str($request->getPost('state'), $odata);
734
 
735
+ $curlists = (TRUE === array_key_exists('list', $odata)) ? $odata['list'] : array();
736
+ $lists = $request->getPost('list', array());
737
 
738
+ $defaultList = $this->getDefaultList(Mage::app()->getStore());
 
 
739
 
740
+ $api = Mage::getSingleton('monkey/api');
741
+ $customer = Mage::helper('customer')->getCustomer();
742
+ $email = $guestEmail ? $guestEmail : $customer->getEmail();
743
 
744
+ $loggedIn = Mage::helper('customer')->isLoggedIn();
745
 
746
+ if( !empty($curlists) ){
 
747
 
748
+ //Handle Unsubscribe and groups update actions
749
+ foreach($curlists as $listId => $list){
750
 
751
+ if(FALSE === array_key_exists($listId, $lists)){
 
752
 
753
+ //Unsubscribe Email
754
+ if($defaultList == $listId){
 
 
 
 
 
 
755
 
756
+ $item = Mage::getModel('monkey/monkey')->loadByEmail($email);
757
+ if(!$item->getId()){
758
+ $item = Mage::getModel('newsletter/subscriber')
759
+ ->loadByEmail($email);
760
+ }
761
+ if($item->getSubscriberEmail()){
762
+ $item->unsubscribe();
763
+ }
764
 
765
+ }else{
766
+ //Unsubscribe Email
767
+ $api->listUnsubscribe($listId, $email);
768
+ }
769
 
770
+ }else{
 
 
 
771
 
772
+ $groupings = $lists[$listId];
773
+ unset($groupings['subscribed']);
774
+ $customerLists = $api->listMemberInfo($listId,$email);
775
+ $customerLists = isset($customerLists['data'][0]['merges']['GROUPINGS']) ?$customerLists['data'][0]['merges']['GROUPINGS'] :array();
 
 
 
776
 
777
+ foreach ($customerLists as $clkey => $cl)
778
+ {
779
+ if (!isset($groupings[$cl['id']]))
780
+ {
781
+ $groupings[$cl['id']][] = '';
782
+ }
783
+ }
784
 
785
+ $customer->setMcListId($listId);
786
+ $customer->setListGroups($groupings);
787
+ $mergeVars = Mage::helper('monkey')->getMergeVars($customer);
788
 
789
+ //Handle groups update
790
+ $api->listUpdateMember($listId, $email, $mergeVars);
791
 
792
+ }
793
 
794
  }
795
 
796
+ }
797
+
798
+ //Subscribe to new lists
799
+ if(is_array($lists) && is_array($curlists)){
800
+ $subscribe = array_diff_key($lists, $curlists);
801
+ if( !empty($subscribe) ){
802
 
803
+ foreach($subscribe as $listId => $slist){
804
 
805
+ if(!isset($slist['subscribed'])){
806
+ continue;
807
+ }
808
 
809
+ $groupings = $lists[$listId];
810
+ unset($groupings['subscribed']);
811
 
812
+ if($defaultList == $listId){
813
+ $subscriber = Mage::getModel('newsletter/subscriber');
814
 
815
+ $subscriber->setListGroups($groupings);
816
+ $subscriber->setMcListId($listId);
817
  $subscriber->setMcStoreId(Mage::app()->getStore()->getId());
818
 
819
+ $subscriber->subscribe($email);
820
+ }else{
821
 
822
+ $customer->setListGroups($groupings);
823
+ $customer->setMcListId($listId);
824
+ $mergeVars = Mage::helper('monkey')->getMergeVars($customer);
825
+ $api->listSubscribe($listId, $email, $mergeVars, 'html', ($loggedIn ? false : true));
826
 
827
+ }
828
 
829
+ }
830
 
 
831
  }
832
+ }
833
+ }
834
  }
app/code/local/ThiagoSantos/LoginAutomatico/Model/Pageload/Observer.php CHANGED
@@ -1,55 +1,63 @@
1
  <?php
2
-
3
- class ThiagoSantos_LoginAutomatico_Model_Pageload_Observer {
4
-
5
- public function __construct() {
6
- // echo "thiago";
7
- }
8
-
9
- protected function _getSession() {
10
- return Mage::getSingleton('customer/session');
11
- }
12
-
13
- protected function getRequest(){
14
- return Mage::app()->getRequest();
15
- }
16
-
17
- /**
18
- * _init manager referer information from the user
19
- * @param Varien_Event_Observer $observer
20
- * @return Xyz_Catalog_Model_Price_Observer
21
- */
22
- public function _init($observer) {
23
-
24
- $session = $this -> _getSession();
25
- $id = $this -> getRequest() -> getParam('c');
26
- $url = $this -> getRequest() -> getParam('r');
27
- $store = $this -> getRequest() -> getParam('___store');
28
-
29
- if(isset($id)){
30
- /*if (!isset($id)) {
31
- $session -> addError('Invalid parameter or nonexistent user.');
32
- }*/
33
-
34
- //0 - id //1 - email
35
- $csv = Mage::helper('loginautomatico') -> decrypt($id);
36
- $_customerinfo = explode(';', $csv);
37
-
38
- $customer = Mage::getModel('customer/customer') -> load($_customerinfo[0]);
39
-
40
- //Verifica se o email bate com o email que foi criptografado
41
- if (!$customer -> getId() || $customer -> getEmail() != trim($_customerinfo[1])) {
42
- $session -> addError('Invalid or nonexistentuser.');
43
- //$this -> _redirect('/');
44
- }
45
-
46
- $session = Mage::getSingleton('customer/session');
47
- //logout - necessário!
48
- $session -> logout();
49
- //logando novamente
50
- $session -> setCustomer($customer);
 
 
51
  }
52
-
53
- }
 
 
 
 
 
 
54
 
55
  }
1
  <?php
2
+ /**
3
+ * Pereira, Thiago Santos
4
+ * http://thiagosantos.com/
5
+ *
6
+ * @category ThiagoSantos
7
+ * @package ThiagoSantos_LoginAutomatico
8
+ */
9
+ class ThiagoSantos_LoginAutomatico_Model_Pageload_Observer
10
+ {
11
+
12
+ public function __construct()
13
+ {
14
+
15
+ }
16
+
17
+ protected function _getSession()
18
+ {
19
+ return Mage::getSingleton('customer/session');
20
+ }
21
+
22
+ protected function getRequest()
23
+ {
24
+ return Mage::app()->getRequest();
25
+ }
26
+
27
+ /**
28
+ * _init manager referer information from the user
29
+ * @param Varien_Event_Observer $observer
30
+ * @return ThiagoSantos_LoginAutomatico_Model_Pageload_Observer
31
+ */
32
+ public function _init($observer)
33
+ {
34
+
35
+ $session = $this->_getSession();
36
+ $id = $this->getRequest()->getParam('c');
37
+ $url = $this->getRequest()->getParam('r');
38
+ $store = $this->getRequest()->getParam('___store');
39
+
40
+ if (isset($id)) {
41
+
42
+ //0 - id //1 - email
43
+ $csv = Mage::helper('loginautomatico')->decrypt($id);
44
+ $_customerinfo = explode(';', $csv);
45
+
46
+
47
+ $customer = Mage::getModel('customer/customer')->load((int)$_customerinfo[0]);
48
+
49
+ //Verifica se o email bate com o email que foi criptografado
50
+ if (!$customer->getId() || $customer->getEmail() != trim($_customerinfo[1])) {
51
+ $session->addError('User invalid or does not exist');
52
+ $session->logout();
53
  }
54
+ else{
55
+ //logout - necessário!
56
+ $session->logout();
57
+ //logando novamente
58
+ $session->setCustomer($customer);
59
+ }
60
+ }
61
+ }
62
 
63
  }
package.xml CHANGED
@@ -1,23 +1,23 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>TS_Auto_Login_MailChimp</name>
4
- <version>1.0.23</version>
5
  <stability>stable</stability>
6
- <license>GNU General Public License</license>
7
  <channel>community</channel>
8
  <extends/>
9
- <summary>Auto login for MailChimp on Magento Store</summary>
10
- <description>With this extension you will be able to export a custom Merge Tag for MailChimp and use as a parameters to logged in your customer on you store. This extesion use Magento Crypt to crypt and decrypt the value of the Merge Tag. For those dont know about it, each Magento installation have a unique phrase used to crypt some data. So "thiagosantos" string crypted using my Magento instalation will have a diferent return string, of doing the same on your own store. This make my extension much secured and very usefull.</description>
11
- <notes>Fix: Stop showing message of "Invalid parameter or nonexistent user." and "Invalid or nonexistente user."&#xD;
12
  &#xD;
13
- Now its possible to log in on Magento through a simple url not need anymore to link to the controller.&#xD;
14
- &#xD;
15
- Update with the last version of Ebizmarts 1.0.23.&#xD;
 
16
  </notes>
17
  <authors><author><name>Thiago Santos</name><user>thiagosantos</user><email>thiagorow@gmail.com</email></author></authors>
18
- <date>2012-11-26</date>
19
- <time>11:46:49</time>
20
- <contents><target name="magelocal"><dir name="ThiagoSantos"><dir name="LoginAutomatico"><dir name="Helper"><file name="Data.php" hash="16e7f6ff44e1b4b2d232bebb5ea796e7"/><file name="MonkeyData.php" hash="689e322b12f84b75c161323ba26853e1"/></dir><dir name="Model"><dir name="Pageload"><file name="Observer.php" hash="b9f030d34e21932cf8de7d535cddb37d"/></dir></dir><dir name="controllers"><file name="AController.php" hash="ac825fbe7d20a48094b838d8bdd45a9b"/></dir><dir name="etc"><file name="config.xml" hash="3648f71839bf96a387702dda6dae9d8a"/></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="ThiagoSantos_LoginAutomatico.xml" hash="0329b656ce44c8b877d5ff267fbd2406"/></dir></target></contents>
21
  <compatible/>
22
- <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php></required></dependencies>
23
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>TS_Auto_Login_MailChimp</name>
4
+ <version>1.0.24</version>
5
  <stability>stable</stability>
6
+ <license>GPL</license>
7
  <channel>community</channel>
8
  <extends/>
9
+ <summary>With this free extension your users will enter in your store logged in.</summary>
10
+ <description>With this extension you will be able to export a custom hash from Magento to Merge Tag on MailChimp and use as a parameters to log in your customer on you store, after they click them on e-mail.&#xD;
 
11
  &#xD;
12
+ This extesion use Magento Crypt to crypt and decrypt the value of the Merge Tag. For those don't knew about it, each Magento installation have a unique phrase used to crypt some data. So "thiagosantos" string crypted using my Magento instalation will have a diferent return string, of doing the same on your own store. This make my extension much secured and very usefull, for AutoLogin</description>
13
+ <notes>Fix: &#xD;
14
+ - Stop to log in user even if there were a error to identify a user.&#xD;
15
+ - updated and compatible with MageMonkey - MailChimp Integration by ebizmarts 1.0.23&#xD;
16
  </notes>
17
  <authors><author><name>Thiago Santos</name><user>thiagosantos</user><email>thiagorow@gmail.com</email></author></authors>
18
+ <date>2013-01-22</date>
19
+ <time>00:38:35</time>
20
+ <contents><target name="magelocal"><dir name="ThiagoSantos"><dir name="LoginAutomatico"><dir name="Helper"><file name="Data.php" hash="16e7f6ff44e1b4b2d232bebb5ea796e7"/><file name="MonkeyData.php" hash="cb3739261a98c81bd5373ee75e9af970"/></dir><dir name="Model"><dir name="Pageload"><file name="Observer.php" hash="e3dd7a6e44ef7530eaad4c45e6119aa8"/></dir></dir><dir name="controllers"><file name="AController.php" hash="ac825fbe7d20a48094b838d8bdd45a9b"/></dir><dir name="etc"><file name="config.xml" hash="3648f71839bf96a387702dda6dae9d8a"/></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="ThiagoSantos_LoginAutomatico.xml" hash="0329b656ce44c8b877d5ff267fbd2406"/></dir></target></contents>
21
  <compatible/>
22
+ <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php><package><name>MageMonkey</name><channel>community</channel><min>1.0.22</min><max>1.0.23</max></package></required></dependencies>
23
  </package>