Camiloo_Channelunity - Version 1.0.0.1

Version Notes

The ChannelUnity connector kit for Magento.

Download this release

Release Info

Developer Magento Core Team
Extension Camiloo_Channelunity
Version 1.0.0.1
Comparing to
See all releases


Code changes from version 1.0.0.0 to 1.0.0.1

app/code/community/Camiloo/Channelunity/Model/Entity.php ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Camiloo_Channelunity_Model_Entity extends Mage_Eav_Model_Entity_Setup {
4
+
5
+
6
+ }
7
+
8
+
9
+
10
+ ?>
app/code/community/Camiloo/Channelunity/Model/Orders.php CHANGED
@@ -63,9 +63,12 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
63
 
64
  foreach ($collection as $txn) {
65
  $infoArray = $txn->getAdditionalInformation();
66
- $orderXml .= "<SubscriptionID>{$infoArray['SubscriptionId']}</SubscriptionID>\n";
67
- $orderXml .= "<OrderID>{$infoArray['RemoteOrderID']}</OrderID>\n";
68
-
 
 
 
69
  break;
70
  }
71
  $orderXml .= "<OrderStatus>$orderStatus</OrderStatus>\n";
@@ -103,59 +106,11 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
103
  return $in_str;
104
  }
105
 
106
- public function doCreate($dataArray) {
107
-
108
-
109
- /**********
110
- * TODO: Make this handle the HasTax flags and calculate ex tax as necessary.
111
- ****
112
-
113
- <MerchantName /> The unique merchant name
114
- <SubscriptionID /> The subscription ID to which this message relates
115
- <ServiceSKU /> The channel subscribed to CU_AMZ_UK
116
- <Orders> Group containing one or more orders
117
- + <Order> Top level order element
118
- + + <OrderId /> Channel Specific order ID 203-7998859-0936342
119
- + + <PurchaseDate /> Date and time on which the order was placed on the Channel 2011-05-24T22:40:24+00:00
120
- + + <Currency /> The currency the order was purchased in GBP
121
- + + <OrderItems> Group of one or more ordered items
122
- + + + <Item> Information about a line item
123
- + + + + <SKU /> Stock keeping unit ITEM2424
124
- + + + + <Name /> Name of the product Chocolate Bar
125
- + + + + <Quantity /> The quantity purchased 1
126
- + + + + <Price /> The price of each individual item including any applicable taxes 1.99
127
- + + + + <Tax /> The amount of the price which is tax 0.22
128
- + + + </Item>
129
- + + </OrderItems>
130
- + + <ShippingInfo> Parent element for the shipping information
131
- + + + <RecipientName /> Name of the recipient for delivery
132
- + + + <Address1 /> Line 1 of delivery address
133
- + + + <Address2 /> Line 2 of delivery address
134
- + + + <Address3 /> Line 3 of delivery address
135
- + + + <City /> Delivery city Manchester
136
- + + + <State /> Delivery state (or county for UK) Lancs
137
- + + + <PostalCode /> Delivery postal code or ZIP code M1 1AA
138
- + + + <Country /> Two letter delivery country code GB
139
- + + + <PhoneNumber /> Phone number for the delivery location 01619321015
140
- + + + <ShippingPrice /> Price paid for delivery including tax 1.99
141
- + + + <ShippingTax /> The amount of the shipping price which was tax 0.22
142
- + + + <Service /> The delivery service (e.g. first class, recorded delivery, expedited, etc.) Standard
143
- + + + <DeliveryInstructions /> Instructions for the delivery driver
144
- + + + <GiftWrapPrice /> Price paid for gift wrapping including tax
145
- + + + <GiftWrapTax /> Amount of the gift wrap price which was tax
146
- + + + <GiftWrapType /> Channel Specific gift wrap type
147
- + + + <GiftMessage /> Gift message for the item
148
- + + </ShippingInfo>
149
-
150
- + </Order>
151
- </Orders>
152
-
153
- *******/
154
-
155
  // this method takes an array of correct structure and creates a valid order creation
156
  // request within Magento.
157
 
158
- foreach ($dataArray->Orders->Order as $order) {
159
 
160
  echo "<Info>Next order: {$order->OrderId} Create Quote</Info>";
161
 
@@ -240,10 +195,7 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
240
 
241
  // add product(s)
242
  foreach ($order->OrderItems->Item as $orderitem) {
243
- $product = Mage::getModel('catalog/product')->loadByAttribute('sku', (string) $orderitem->SKU);
244
-
245
-
246
- // TODO check what SKU is mapped to - or is this taken care of at CU end?
247
 
248
  if (is_object($product)) {
249
 
@@ -293,7 +245,9 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
293
  'firstname' => $this->fixEncoding($this->getFirstName((string) $order->BillingInfo->Name)),
294
  'lastname' => $this->fixEncoding($this->getLastName((string) $order->BillingInfo->Name)),
295
  'email' => (string) $order->BillingInfo->Email,
296
- 'telephone' => (string) $order->BillingInfo->PhoneNumber,
 
 
297
 
298
  'street' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1."\n"
299
  .(string) $order->ShippingInfo->Address2
@@ -354,7 +308,7 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
354
  $shippingAddress->setShippingDescription((string) $order->ShippingInfo->Service);
355
  $shippingAddress->setPaymentMethod('channelunitypayment');
356
 
357
- $quote->getPayment()->importData(array(
358
  'method' => 'channelunitypayment'
359
  ));
360
  $quote->collectTotals()->save();
@@ -371,7 +325,7 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
371
 
372
  if (!is_object($newOrder)) {
373
  echo "<NotImported>".((string) $order->OrderId)."</NotImported>";
374
- continue;
375
  }
376
  else {
377
  echo "<Imported>".((string) $order->OrderId)."</Imported>";
@@ -380,10 +334,24 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
380
  } catch (Exception $x) {
381
  echo "<Exception><![CDATA[".$x->getMessage()."]]></Exception>";
382
  echo "<NotImported>".((string) $order->OrderId)."</NotImported>";
383
- continue;
384
  }
385
-
386
- $newOrder->setState('processing', 'processing', 'Order imported from ChannelUnity', false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
 
388
  // This order will have been paid for, otherwise it won't have imported
389
 
@@ -407,6 +375,7 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
407
  $transaction->setOrderPaymentObject($newOrder->getPayment());
408
  $transaction->setOrder($newOrder);
409
  $transaction->setTxnType('capture');
 
410
  $transaction->setAdditionalInformation('SubscriptionId', (string) $dataArray->SubscriptionId);
411
  $transaction->setAdditionalInformation('RemoteOrderID', (string) $order->OrderId);
412
 
@@ -465,9 +434,9 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
465
  $newOrder->setData('gift_message_id', $gift_message_id);
466
  }
467
 
468
- $newOrder->setCreatedAt(strtotime((string) $order->PurchaseDate));
469
  $newOrder->save();
470
- }
471
 
472
  }
473
 
@@ -536,13 +505,212 @@ class Camiloo_Channelunity_Model_Orders extends Camiloo_Channelunity_Model_Abstr
536
  return "___";
537
  }
538
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
539
 
540
  public function doUpdate($dataArray) {
541
-
542
- }
543
-
544
-
545
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
546
  }
547
 
548
  ?>
63
 
64
  foreach ($collection as $txn) {
65
  $infoArray = $txn->getAdditionalInformation();
66
+ if (isset($infoArray['SubscriptionId'])) {
67
+ $orderXml .= "<SubscriptionID>{$infoArray['SubscriptionId']}</SubscriptionID>\n";
68
+ }
69
+ if (isset($infoArray['RemoteOrderID'])) {
70
+ $orderXml .= "<OrderID>{$infoArray['RemoteOrderID']}</OrderID>\n";
71
+ }
72
  break;
73
  }
74
  $orderXml .= "<OrderStatus>$orderStatus</OrderStatus>\n";
106
  return $in_str;
107
  }
108
 
109
+ public function doCreate($dataArray, $order) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  // this method takes an array of correct structure and creates a valid order creation
111
  // request within Magento.
112
 
113
+
114
 
115
  echo "<Info>Next order: {$order->OrderId} Create Quote</Info>";
116
 
195
 
196
  // add product(s)
197
  foreach ($order->OrderItems->Item as $orderitem) {
198
+ $product = Mage::getModel('catalog/product')->loadByAttribute((string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
 
 
 
199
 
200
  if (is_object($product)) {
201
 
245
  'firstname' => $this->fixEncoding($this->getFirstName((string) $order->BillingInfo->Name)),
246
  'lastname' => $this->fixEncoding($this->getLastName((string) $order->BillingInfo->Name)),
247
  'email' => (string) $order->BillingInfo->Email,
248
+ 'telephone' => ( (string) $order->BillingInfo->PhoneNumber == "" ?
249
+ (string) $order->ShippingInfo->PhoneNumber :
250
+ (string) $order->BillingInfo->PhoneNumber),
251
 
252
  'street' => (string) $this->fixEncoding((string) $order->ShippingInfo->Address1."\n"
253
  .(string) $order->ShippingInfo->Address2
308
  $shippingAddress->setShippingDescription((string) $order->ShippingInfo->Service);
309
  $shippingAddress->setPaymentMethod('channelunitypayment');
310
 
311
+ $quote->getPayment()->importData(array(
312
  'method' => 'channelunitypayment'
313
  ));
314
  $quote->collectTotals()->save();
325
 
326
  if (!is_object($newOrder)) {
327
  echo "<NotImported>".((string) $order->OrderId)."</NotImported>";
328
+ return;
329
  }
330
  else {
331
  echo "<Imported>".((string) $order->OrderId)."</Imported>";
334
  } catch (Exception $x) {
335
  echo "<Exception><![CDATA[".$x->getMessage()."]]></Exception>";
336
  echo "<NotImported>".((string) $order->OrderId)."</NotImported>";
337
+ return;
338
  }
339
+
340
+ $ordStatus = $this->CUOrderStatusToMagentoStatus((string) $order->OrderStatus);
341
+
342
+ try {
343
+ $newOrder->setState($ordStatus, $ordStatus, 'Order imported from ChannelUnity', false);
344
+
345
+ }
346
+ catch (Exception $x1) {
347
+
348
+ try {
349
+ $newOrder->setState('closed', 'closed', 'Order imported from ChannelUnity', false);
350
+
351
+ }
352
+ catch (Exception $x2) {
353
+ }
354
+ }
355
 
356
  // This order will have been paid for, otherwise it won't have imported
357
 
375
  $transaction->setOrderPaymentObject($newOrder->getPayment());
376
  $transaction->setOrder($newOrder);
377
  $transaction->setTxnType('capture');
378
+ $transaction->setTxnId((string) $order->OrderId); // TODO check this avail in Mage vers
379
  $transaction->setAdditionalInformation('SubscriptionId', (string) $dataArray->SubscriptionId);
380
  $transaction->setAdditionalInformation('RemoteOrderID', (string) $order->OrderId);
381
 
434
  $newOrder->setData('gift_message_id', $gift_message_id);
435
  }
436
 
437
+ $newOrder->setCreatedAt(((string) $order->PurchaseDate));
438
  $newOrder->save();
439
+
440
 
441
  }
442
 
505
  return "___";
506
  }
507
  }
508
+
509
+ public function CUOrderStatusToMagentoStatus($orderStatus) {
510
+ if ($orderStatus == 'Processing') {
511
+ $orderStatus = "processing";
512
+ }
513
+ else if ($orderStatus == 'OnHold') {
514
+ $orderStatus = "holded";
515
+ }
516
+ else if ($orderStatus == 'Complete') {
517
+ $orderStatus = "complete";
518
+ }
519
+ else {
520
+ $orderStatus = "canceled";
521
+ }
522
+
523
+ return $orderStatus;
524
+ }
525
+
526
+ private function doSingleOrder($singleOrder, $newOrder) {
527
+ /* // 1. Update shipping address
528
+
529
+ $postcode = $this->fixEncoding((string) $singleOrder->ShippingInfo->PostalCode);
530
+ $postcode = str_replace("-", "_", $postcode); // can throw exception if - in postcode
531
+
532
+ $shippingId = $newOrder->getShippingAddress()->getId();
533
+ $shipAddress = Mage::getModel('sales/order_address')->load($shippingId);
534
+ $shipAddress->setFirstname($this->fixEncoding(
535
+ $this->getFirstName((string) $singleOrder->ShippingInfo->RecipientName)));
536
+ $shipAddress->setLastname($this->fixEncoding($this->getLastName((string) $singleOrder->ShippingInfo->RecipientName)));
537
+ $shipAddress->setStreet((string) $this->fixEncoding(
538
+ (string) $singleOrder->ShippingInfo->Address1
539
+ ."\n".(string) $singleOrder->ShippingInfo->Address2
540
+ ."\n".(string) $singleOrder->ShippingInfo->Address3));
541
+ $shipAddress->setCity($this->fixEncoding((string) $singleOrder->ShippingInfo->City));
542
+ $shipAddress->setPostcode($postcode);
543
+ $shipAddress->setRegion((string) $singleOrder->ShippingInfo->State);
544
+ $shipAddress->setRegionId((string) $singleOrder->ShippingInfo->State);
545
+ $shipAddress->setCountryId((string) $singleOrder->ShippingInfo->Country);
546
+ $shipAddress->setTelephone((string) $singleOrder->ShippingInfo->PhoneNumber);
547
+ $shipAddress->save();
548
+
549
+ // 2. Update billing address
550
+ */
551
+ // 3. Update order status
552
+ $ordStatus = $this->CUOrderStatusToMagentoStatus((string) $singleOrder->OrderStatus);
553
+
554
+ try {
555
+ $newOrder->setState($ordStatus, $ordStatus, 'Order updated from ChannelUnity', false);
556
+
557
+ }
558
+ catch (Exception $x1) {
559
+
560
+ try {
561
+ $newOrder->setState('closed', 'closed', 'Order updated from ChannelUnity', false);
562
+
563
+ }
564
+ catch (Exception $x2) {
565
+ }
566
+ }
567
+ /*
568
+ // 4. Update item prices and currency
569
+
570
+ echo "<InfoUpdate>Order currency {$singleOrder->Currency}</InfoUpdate>";
571
+ $newOrder->getStore()->setCurrentCurrencyCode((string) $singleOrder->Currency);
572
+ $storeCurrency = $newOrder->getStore()->getBaseCurrencyCode();
573
+ echo "<InfoUpdate>Store currency $storeCurrency</InfoUpdate>";
574
+
575
+ $currencyObject = Mage::getModel('directory/currency');
576
+ $reverseRate = $currencyObject->getResource()->getRate($storeCurrency, (string) $singleOrder->Currency);
577
+
578
+ if ($reverseRate == "") {
579
+ $reverseRate = 1.0;
580
+ }
581
+
582
+ echo "<ConversionRate>$reverseRate</ConversionRate>";
583
+
584
+
585
+
586
+
587
+ $itemColl = $newOrder->getItemsCollection();
588
+ foreach ($itemColl as $orderItem) {
589
+
590
+ foreach ($singleOrder->OrderItems->Item as $orderitem1) {
591
+
592
+ if (((string) $orderitem1->SKU) == $orderItem->getSku()) {
593
+
594
+ // -- check what SKU is mapped to
595
+
596
+ $priceTemp = ((string) $orderitem1->Price) / $reverseRate;
597
+ $qtyTemp = (string) $orderitem1->Quantity;
598
+
599
+ $orderItem->setPrice($priceTemp);
600
+ $orderItem->setQtyOrdered($qtyTemp);
601
+ $orderItem->setOriginalPrice($priceTemp);
602
+ $orderItem->setRowTotal($priceTemp * $qtyTemp);
603
+ $orderItem->setSubTotal($priceTemp * $qtyTemp);
604
+
605
+ break;
606
+ }
607
+
608
+ }
609
+ }
610
+ */
611
+ $newOrder->save();
612
+ }
613
+
614
+ public function reserveStock($dataArray, $order) {
615
+ foreach ($order->OrderItems->Item as $orderitem) {
616
+
617
+ $product = Mage::getModel('catalog/product')->loadByAttribute(
618
+ (string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
619
+
620
+ if (is_object($product)) {
621
+ $qty = (string) $orderitem->Quantity;
622
+
623
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId()); // Load the stock for this product
624
+ $stock->setQty($stock->getQty() - $qty); // Set to new Qty
625
+ $stock->save(); // Save
626
+ }
627
+ }
628
+ }
629
+
630
+ public function releaseStock($dataArray, $order) {
631
+ foreach ($order->OrderItems->Item as $orderitem) {
632
+
633
+ $product = Mage::getModel('catalog/product')->loadByAttribute(
634
+ (string) $dataArray->SkuAttribute, (string) $orderitem->SKU);
635
+
636
+ if (is_object($product)) {
637
+ $qty = (string) $orderitem->Quantity;
638
+
639
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId()); // Load the stock for this product
640
+ $stock->setQty($stock->getQty() + $qty); // Set to new Qty
641
+ $stock->save(); // Save
642
+ }
643
+ }
644
+ }
645
 
646
  public function doUpdate($dataArray) {
647
+
648
+ foreach ($dataArray->Orders->Order as $order) {
649
+
650
+ $bOrderExisted = false;
651
+
652
+ try {
653
+ $transaction = Mage::getModel('sales/order_payment_transaction')
654
+ ->loadByTxnId((string) $order->OrderId);
655
+
656
+ $newOrder = $transaction->getOrder();
657
+ if (is_object($newOrder)) {
658
+ $this->doSingleOrder($order, $newOrder);
659
+ $bOrderExisted = true;
660
+ }
661
+ }
662
+ catch (Exception $x1) {
663
+
664
+ }
665
+ // Additional information good for failsafe
666
+ if (!$bOrderExisted) {
667
+ $oid = (string) $order->OrderId;
668
+
669
+ $transaction = Mage::getModel('sales/order_payment_transaction')->getCollection()
670
+ ->addFieldToFilter('additional_information',
671
+ array('like'=>'%s:13:"RemoteOrderID";s:'.strlen($oid).':"'.$oid.'"%'))->getFirstItem();
672
+
673
+ $newOrder = $transaction->getOrder();
674
+ if (is_object($newOrder)) {
675
+ $this->doSingleOrder($order, $newOrder);
676
+ $bOrderExisted = true;
677
+ }
678
+ }
679
+
680
+ if (!$bOrderExisted) {
681
+ if (((string) $order->OrderStatus) == "Processing") {
682
+ // if the stock isn't already decreased, decrease it
683
+
684
+ if (!isset($order->StockReservedCart) || ((string) $order->StockReservedCart) == "0") {
685
+ echo "<StockReserved>".((string) $order->OrderId)."</StockReserved>";
686
+
687
+ $this->reserveStock($dataArray, $order);
688
+ }
689
+
690
+ $this->doCreate($dataArray, $order);
691
+ }
692
+ else if (((string) $order->OrderStatus) == "OnHold") {
693
+ // Reserve the stock
694
+ echo "<Imported>".((string) $order->OrderId)."</Imported>";
695
+ echo "<StockReserved>".((string) $order->OrderId)."</StockReserved>";
696
+
697
+ $this->reserveStock($dataArray, $order);
698
+ }
699
+ else {
700
+ // Just create the order (e.g. previously completed)
701
+ $this->doCreate($dataArray, $order);
702
+ }
703
+ }
704
+
705
+ if ($bOrderExisted) {
706
+ if (((string) $order->OrderStatus) == "Cancelled") {
707
+ // Put back our stock
708
+ $this->releaseStock($dataArray, $order);
709
+ }
710
+ echo "<Imported>".((string) $order->OrderId)."</Imported>";
711
+ }
712
+ }
713
+ }
714
  }
715
 
716
  ?>
app/code/community/Camiloo/Channelunity/Model/Products.php CHANGED
@@ -1,56 +1,56 @@
1
  <?php
2
-
3
- class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abstract
4
- {
5
- protected $_collection = 'catalog/product';
6
- private $starttime;
7
- private $endtime;
8
- private $runtime = 0;
9
- private $beforeMemory;
10
- private $maxMemory;
11
- private $maxMemoryChar;
12
- private $maxruntime = 30;
13
- private $changeMemory = 0;
14
- private $upperLimit = 250;
15
- private $countCurr = 0;
16
- private $rangeNext = 0;
17
- private $premExit = false;
18
-
19
- public function postProductTypesToCU($request) {
20
-
21
- $url = (string) $request->URL;
22
- $putData = tmpfile();
23
- $bytes = 0;
24
 
25
- $messageToSend = "";
26
-
27
- $prodAttrEntType = Mage::getModel('catalog/product')
28
- ->getResource()->getEntityType()->getId();
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- $attrColl = Mage::getResourceModel('eav/entity_attribute_set_collection')
31
- ->setEntityTypeFilter($prodAttrEntType);
 
32
 
33
- $messageToSend = "<URL>$url</URL>\n";
34
- $bytes = $bytes + fwrite($putData, $messageToSend);
35
-
36
- $messageToSend = "<ProductTypes>\n";
37
- $bytes = $bytes + fwrite($putData, $messageToSend);
38
- foreach ($attrColl as $attrModel) {
39
 
40
- $messageToSend = "<ProductType>\n";
41
- $bytes = $bytes + fwrite($putData, $messageToSend);
42
-
43
- $attribute_set_id = $attrModel->getData('attribute_set_id');
44
- $attribute_set_name = $attrModel->getData('attribute_set_name');
45
 
46
- $messageToSend = " <ProductTypeId>$attribute_set_id</ProductTypeId>\n";
47
- $bytes = $bytes + fwrite($putData, $messageToSend);
48
- $messageToSend = " <ProductTypeName><![CDATA[{$attribute_set_name}]]></ProductTypeName>\n";
49
- $bytes = $bytes + fwrite($putData, $messageToSend);
50
 
 
 
51
 
52
- $messageToSend = " <AttributeGroups>\n";
53
- $bytes = $bytes + fwrite($putData, $messageToSend);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  $product = Mage::getModel('catalog/product')->getCollection()
56
  ->addFieldToFilter('attribute_set_id', array('eq' => $attribute_set_id))
@@ -58,313 +58,313 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
58
  $product->getSelect()->limit(1);
59
  $product = $product->getFirstItem();
60
 
61
-
62
-
63
- $prodIdOfAttrSet = $product->getId();
64
- $atrGrpColl = Mage::getModel('eav/entity_attribute_group')->getCollection()
65
- ->addFieldToFilter('attribute_set_id', array('eq' => $attribute_set_id));
66
- foreach ($atrGrpColl as $atGrModel) {
67
- $attribute_group_name = $atGrModel->getData('attribute_group_name');
68
- $attribute_group_id = $atGrModel->getData('attribute_group_id');
69
 
70
- $messageToSend = " <AttributeGroup>\n";
71
- $bytes = $bytes + fwrite($putData, $messageToSend);
72
- $messageToSend = " <GroupName><![CDATA[{$attribute_group_name}]]></GroupName>\n";
73
- $bytes = $bytes + fwrite($putData, $messageToSend);
74
 
75
- $messageToSend = " <Attributes>\n";
76
- $bytes = $bytes + fwrite($putData, $messageToSend);
77
-
78
- if ($prodIdOfAttrSet != 0) {
79
- $product = Mage::getModel('catalog/product')->load($prodIdOfAttrSet);
80
-
81
- $collection = $product->getAttributes($attribute_group_id, false);
82
- foreach ($collection as $attribute) {
83
- $messageToSend = " <AttributeCode>" . $attribute->getAttributeCode() . "</AttributeCode>\n";
84
- $bytes = $bytes + fwrite($putData, $messageToSend);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  }
86
 
 
 
 
 
 
87
  }
88
 
89
- $messageToSend = " </Attributes>\n";
90
  $bytes = $bytes + fwrite($putData, $messageToSend);
91
-
92
- $messageToSend = " </AttributeGroup>\n";
93
- $bytes = $bytes + fwrite($putData, $messageToSend);
94
- }
95
-
96
- $messageToSend = " </AttributeGroups>\n";
97
- $bytes = $bytes + fwrite($putData, $messageToSend);
98
- $messageToSend = "</ProductType>\n";
99
- $bytes = $bytes + fwrite($putData, $messageToSend);
 
 
 
 
100
  }
101
 
102
- $messageToSend = "</ProductTypes>\n";
103
- $bytes = $bytes + fwrite($putData, $messageToSend);
104
-
105
- fseek($putData, 0);
106
- $senditnow = fread($putData, $bytes);
107
-
108
- $this->postToChannelUnity($senditnow, "ProductTypes");
109
-
110
- fclose($putData);
111
- }
112
-
113
- public function postAttributesToCU() {
114
-
115
- $putData = tmpfile();
116
- $bytes = 0;
117
-
118
- $messageToSend = "<ProductAttributes>\n";
119
-
120
- $bytes = $bytes + fwrite($putData, $messageToSend);
121
- $product = Mage::getModel('catalog/product');
122
- $attributes = Mage::getResourceModel('eav/entity_attribute_collection')
123
  ->setEntityTypeFilter($product->getResource()->getTypeId())
124
  ->load(false);
125
 
126
- foreach($attributes as $attribute){
127
-
128
- $attr = $attribute->getData('attribute_code');
129
-
130
- if ($attr != 'name' && $attr != 'description' && $attr != 'sku' && $attr != 'price' && $attr != 'qty' && $attr != 'stock_item') {
131
-
132
  $attrType = trim($attribute->getBackendType());
133
  $friendlyName = trim($attribute->getFrontendLabel());
134
-
135
  $messageToSend = " <Attribute><Name>$attr</Name><Type>$attrType</Type>
136
- <FriendlyName><![CDATA[{$friendlyName}]]></FriendlyName></Attribute>\n";
137
-
138
  $bytes = $bytes + fwrite($putData, $messageToSend);
139
- }
140
-
141
- }
142
-
143
- $messageToSend = "</ProductAttributes>\n";
144
- $bytes = $bytes + fwrite($putData, $messageToSend);
145
-
146
- fseek($putData, 0);
147
- $senditnow = fread($putData, $bytes);
148
- fclose($putData);
149
- $result = $this->postToChannelUnity($senditnow, "ProductAttributes");
150
- $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
151
-
152
- if (isset($xml->Status)) {
153
- return $xml->Status;
154
- }
155
- else if (isset($xml->status)) {
156
- return $xml->status;
157
- }
158
- else {
159
- return "Error - unexpected response";
160
- }
161
- }
162
-
163
- public function generateCuXmlForSingleProduct($productId, $storeId) {
164
- $productXml = "";
165
-
166
- $product = Mage::getModel('catalog/product');
167
- $product->setStoreId($storeId)->load($productId);
168
-
169
- try {
170
- $imageUrl = $product->getImageUrl();
171
- } catch (Exception $e) {
172
- $imageUrl = '';
173
- }
174
-
175
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
176
- $qty = $stock->getData('qty');
177
-
178
- $catids = implode(',', $product->getCategoryIds());
179
- $categories = $product->getCategoryIds();
180
- $catnames = "";
181
-
182
- foreach ($categories as $k => $_category_id) {
183
- $_category = Mage::getModel('catalog/category')->load($_category_id);
184
- $catnames .= ($_category->getName()) . ", ";
185
  }
186
 
187
- $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
188
- $attributeSetModel->load($product->getData('attribute_set_id'));
189
- $attributeSetName = $attributeSetModel->getAttributeSetName();
190
-
191
- $productXml = "<Product>\n";
192
- $productXml .= " <RemoteId>".$product->getId()."</RemoteId>\n";
193
- $productXml .= " <ProductType>".$attributeSetName."</ProductType>\n";
194
- $productXml .= " <Title><![CDATA[{$product->getData('name')} ]]></Title>\n";
195
- $productXml .= " <Description><![CDATA[{$product->getData('description')} ]]></Description>\n";
196
- $productXml .= " <SKU><![CDATA[{$product->getData('sku')}]]></SKU>\n";
197
- $productXml .= " <Price>{$product->getData('price')}</Price>\n";
198
- $productXml .= " <Quantity>{$qty}</Quantity>\n";
199
- $productXml .= " <Category>{$catids}</Category>\n";
200
- $productXml .= " <CategoryName><![CDATA[{$catnames} ]]></CategoryName>\n";
201
- $productXml .= " <Image><![CDATA[{$imageUrl}]]></Image>\n";
202
-
203
- // Add associated/child product references if applicable
204
- $productXml .= " <RelatedSKUs>\n";
205
-
206
- $variationXml = " <Variations>\n";
207
-
208
- if ($product->getData("type_id") == 'configurable') {
209
 
210
- $childProducts = Mage::getModel('catalog/product_type_configurable')
211
- ->getUsedProducts(null, $product);
212
 
213
- foreach ($childProducts as $cp) {
214
-
215
- $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
 
216
  }
217
 
218
- $confAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
 
219
 
220
- // Get the attribute(s) which vary
221
- if (is_array($confAttributes)) {
222
- foreach ($confAttributes as $cattr) {
223
- $cattr = serialize($cattr);
224
-
225
- $findTemp = "\"attribute_code\";";
226
-
227
- $cattr = explode($findTemp, $cattr);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
- if (isset($cattr[1])) {
 
 
 
 
 
 
 
 
 
 
230
 
231
- $cattr = explode("\"", $cattr[1]);
232
 
233
  if (isset($cattr[1])) {
234
 
235
- $variationXml .= "<Variation><![CDATA[{$cattr[1]}]]></Variation>\n";
236
 
 
 
 
 
 
237
  }
238
  }
239
  }
 
 
 
 
 
 
 
 
 
 
 
240
  }
241
 
242
- }
243
- else if ($product->getTypeId() == 'grouped') {
 
244
 
245
- // TODO need to do variations?
246
 
247
- $childProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);
248
- foreach ($childProducts as $cp) {
249
-
250
- $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
251
- }
252
- }
253
-
254
- $variationXml .= " </Variations>\n";
255
- $productXml .= " </RelatedSKUs>\n";
256
- $productXml .= $variationXml;
257
-
258
- $productXml .= " <Custom>\n";
259
-
260
- // Enumerate all other attribute values
261
-
262
- $attributeNames = array_keys($product->getData());
263
-
264
- foreach ($attributeNames as $k => $attr) {
265
 
266
- if ($attr != 'name' && $attr != 'description' && $attr != 'sku'
267
- && $attr != 'price' && $attr != 'qty'
268
- && $attr != 'stock_item' && $attr != 'tier_price') {
269
 
270
- if ($attribute = $product->getResource()->getAttribute($attr)) {
271
-
272
- $myval = $product->getData($attr);
273
 
274
- if (is_array($myval)) {
275
- $myval = serialize($myval);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  }
277
 
278
- $prodDataValue = $attribute->getSource()
279
- ->getOptionText($myval);
280
-
281
- if ($prodDataValue == '') {
282
-
283
- $prodDataValue = $myval;
284
  }
285
- } else {
286
- $prodDataValue = $product->getData($attr);
287
- }
288
-
289
- if (is_object($prodDataValue)) {
290
- if ('Varien_Object' == get_class($prodDataValue)) {
291
 
292
- $prodDataValue = $prodDataValue->toXml();
 
293
  }
294
- }
295
- if (is_array($prodDataValue)) {
296
-
297
- $prodDataValue = $product->getData($attr);
298
- $productXml .= " <$attr><![CDATA[$prodDataValue]]></$attr>\n";
299
- }
300
- else {
301
-
302
- if (!is_object($prodDataValue)) {
303
- $productXml .= " <$attr><![CDATA[".$prodDataValue."]]></$attr>\n";
304
- } else if ('Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Type_Configurable_Attribute_Collection'
305
- == get_class($prodDataValue)) {
306
- $productXml .= " <$attr><![CDATA[Mage_Core_Model_Mysql4_Collection_Abstract]]></$attr>\n";
307
  }
308
  }
309
  }
 
 
 
 
 
 
 
310
  }
311
 
312
- $productXml .= " </Custom>\n";
313
- $productXml .= "</Product>\n";
314
-
315
- unset($product);
316
-
317
- return $productXml;
318
- }
319
-
320
- public function generateCuXmlForProductEcho($args) {
321
- echo $this->generateCuXmlForProduct($args);
322
- }
323
 
324
- public function generateCuXmlForProduct($args) {
325
- $productXml = '';
326
- $this->countCurr++;
327
-
328
- $this->maxMemory = $this->return_bytes(ini_get('memory_limit'));
329
-
330
- if ($this->runtime < $this->maxruntime
331
- && (memory_get_peak_usage() + $this->changeMemory) < $this->maxMemory
332
- && $this->countCurr <= $this->upperLimit)
333
- {
334
- $row = $args['row'];
335
- $this->rangeNext = $row["entity_id"] + 1;
336
-
337
- $productXml .= $this->generateCuXmlForSingleProduct($row["entity_id"], $args["storeId"]);
338
 
339
- // after....
340
- $this->endtime = $this->microtime_float();
341
- $this->runtime = round($this->endtime - $this->starttime);
342
 
343
- $tmpval = memory_get_peak_usage() - $this->beforeMemory;
344
- if ($tmpval > $this->changeMemory) {
345
- $this->changeMemory = $tmpval;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  }
347
-
348
- } else {
349
-
350
- $this->premExit = true; // i.e. exited before got through all prods
351
-
352
  }
353
-
354
- return $productXml;
355
- }
356
-
357
- public function microtime_float() {
358
- list ($msec, $sec) = explode(' ', microtime());
359
- $microtime = (float)$msec + (float)$sec;
360
- return $microtime;
361
- }
362
-
363
- function return_bytes($val) {
364
- $val = trim($val);
365
- $last = strtolower($val[strlen($val)-1]);
366
  switch($last) {
367
- // The 'G' modifier is available since PHP 5.1.0
368
  case 'g':
369
  $val *= 1024;
370
  case 'm':
@@ -372,76 +372,115 @@ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abs
372
  case 'k':
373
  $val *= 1024;
374
  }
375
-
376
- return $val;
377
- }
378
-
379
- /**
380
- * Return a set of product data to CU.
381
- */
382
- public function doRead($request) {
383
- $rangeFrom = (string) $request->RangeFrom;
384
- $rangeTo = (string) $request->RangeTo;
385
- $storeId = (string) $request->StoreviewId;
386
-
387
- $this->starttime = $this->microtime_float();
388
- $this->endtime = $this->microtime_float();
389
- $this->runtime = round($this->endtime - $this->starttime);
390
- $this->beforeMemory = memory_get_peak_usage();
391
- $this->maxMemory = ini_get('memory_limit');
392
- $this->maxMemoryChar = substr($this->maxMemory,strlen($this->maxMemory)-1,1);
393
-
394
- echo "<Products>\n";
395
-
396
- // get the highest product ID
397
- $collectionOfProduct = Mage::getModel($this->_collection)->getCollection()->setStoreId($storeId);
398
- $collectionOfProduct->setOrder('entity_id', 'DESC');
399
- $collectionOfProduct->setPageSize(1);
400
- $collectionOfProduct->setCurPage(1);
401
- $totp = $collectionOfProduct->getFirstItem();
402
- $totp = $totp->getId();
403
-
404
- $collectionOfProduct = Mage::getModel($this->_collection)->getCollection()->setStoreId($storeId);
405
-
406
- $totalNumProducts = $collectionOfProduct->count(); // TODO not loading whole collection is it???
407
-
408
- $collectionOfProduct->addAttributeToFilter("entity_id", array('gteq' => $rangeFrom))
409
- ->setOrder('entity_id','ASC');
410
-
411
- $collectionOfProduct->addAttributeToFilter("entity_id", array('lt' => $rangeFrom + $this->upperLimit))
412
- ->setOrder('entity_id','ASC');
413
-
414
- // monitor memory and max exec
415
- if ($this->maxMemoryChar == "M") {
416
- $this->maxMemory = str_replace("M", "", $this->maxMemory);
417
- $this->maxMemory = $this->maxMemory * 1024 * 1024;
418
- } else if($this->maxMemoryChar == "G") {
419
- $this->maxMemory = str_replace("G", "", $maxMemory);
420
- $this->maxMemory = $this->maxMemory * 1024 * 1024 * 1024;
421
- }
422
-
423
- if ($this->maxMemory < 100) {
424
- $this->maxMemory = 10000000000;
425
  }
426
 
427
- Mage::getSingleton('core/resource_iterator')->walk($collectionOfProduct->getSelect(),
428
- array(array($this, 'generateCuXmlForProductEcho')),
429
- array('storeId' => $storeId));
430
-
431
- // Let the cloud know where to start from the next time it calls
432
- // for product data
433
-
434
- if ($this->rangeNext <= $totp) {
435
- echo "<RangeNext>".$this->rangeNext."</RangeNext>\n";
436
- } else {
437
- // Start from beginning next time
438
- echo "<RangeNext>0</RangeNext>\n";
439
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
 
441
- echo "<TotalProducts>$totalNumProducts</TotalProducts>\n";
442
-
443
- echo "</Products>\n";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
  }
445
- }
446
-
447
  ?>
1
  <?php
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ class Camiloo_Channelunity_Model_Products extends Camiloo_Channelunity_Model_Abstract
4
+ {
5
+ protected $_collection = 'catalog/product';
6
+ private $starttime;
7
+ private $endtime;
8
+ private $runtime = 0;
9
+ private $beforeMemory;
10
+ private $maxMemory;
11
+ private $maxMemoryChar;
12
+ private $maxruntime = 30;
13
+ private $changeMemory = 0;
14
+ private $upperLimit = 250;
15
+ private $countCurr = 0;
16
+ private $rangeNext = 0;
17
+ private $premExit = false;
18
+
19
+ public function postProductTypesToCU($request) {
20
 
21
+ $url = (string) $request->URL;
22
+ $putData = tmpfile();
23
+ $bytes = 0;
24
 
25
+ $messageToSend = "";
 
 
 
 
 
26
 
27
+ $prodAttrEntType = Mage::getModel('catalog/product')
28
+ ->getResource()->getEntityType()->getId();
 
 
 
29
 
30
+ $attrColl = Mage::getResourceModel('eav/entity_attribute_set_collection')
31
+ ->setEntityTypeFilter($prodAttrEntType);
 
 
32
 
33
+ $messageToSend = "<URL>$url</URL>\n";
34
+ $bytes = $bytes + fwrite($putData, $messageToSend);
35
 
36
+ $messageToSend = "<ProductTypes>\n";
37
+ $bytes = $bytes + fwrite($putData, $messageToSend);
38
+ foreach ($attrColl as $attrModel) {
39
+
40
+ $messageToSend = "<ProductType>\n";
41
+ $bytes = $bytes + fwrite($putData, $messageToSend);
42
+
43
+ $attribute_set_id = $attrModel->getData('attribute_set_id');
44
+ $attribute_set_name = $attrModel->getData('attribute_set_name');
45
+
46
+ $messageToSend = " <ProductTypeId>$attribute_set_id</ProductTypeId>\n";
47
+ $bytes = $bytes + fwrite($putData, $messageToSend);
48
+ $messageToSend = " <ProductTypeName><![CDATA[{$attribute_set_name}]]></ProductTypeName>\n";
49
+ $bytes = $bytes + fwrite($putData, $messageToSend);
50
+
51
+
52
+ $messageToSend = " <AttributeGroups>\n";
53
+ $bytes = $bytes + fwrite($putData, $messageToSend);
54
 
55
  $product = Mage::getModel('catalog/product')->getCollection()
56
  ->addFieldToFilter('attribute_set_id', array('eq' => $attribute_set_id))
58
  $product->getSelect()->limit(1);
59
  $product = $product->getFirstItem();
60
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
62
 
63
+ $prodIdOfAttrSet = $product->getId();
64
+ $atrGrpColl = Mage::getModel('eav/entity_attribute_group')->getCollection()
65
+ ->addFieldToFilter('attribute_set_id', array('eq' => $attribute_set_id));
66
+ foreach ($atrGrpColl as $atGrModel) {
67
+ $attribute_group_name = $atGrModel->getData('attribute_group_name');
68
+ $attribute_group_id = $atGrModel->getData('attribute_group_id');
69
+
70
+ $messageToSend = " <AttributeGroup>\n";
71
+ $bytes = $bytes + fwrite($putData, $messageToSend);
72
+ $messageToSend = " <GroupName><![CDATA[{$attribute_group_name}]]></GroupName>\n";
73
+ $bytes = $bytes + fwrite($putData, $messageToSend);
74
+
75
+ $messageToSend = " <Attributes>\n";
76
+ $bytes = $bytes + fwrite($putData, $messageToSend);
77
+
78
+ if ($prodIdOfAttrSet != 0) {
79
+ $product = Mage::getModel('catalog/product')->load($prodIdOfAttrSet);
80
+
81
+ $collection = $product->getAttributes($attribute_group_id, false);
82
+ foreach ($collection as $attribute) {
83
+ $messageToSend = " <AttributeCode>" . $attribute->getAttributeCode() . "</AttributeCode>\n";
84
+ $bytes = $bytes + fwrite($putData, $messageToSend);
85
+ }
86
+
87
  }
88
 
89
+ $messageToSend = " </Attributes>\n";
90
+ $bytes = $bytes + fwrite($putData, $messageToSend);
91
+
92
+ $messageToSend = " </AttributeGroup>\n";
93
+ $bytes = $bytes + fwrite($putData, $messageToSend);
94
  }
95
 
96
+ $messageToSend = " </AttributeGroups>\n";
97
  $bytes = $bytes + fwrite($putData, $messageToSend);
98
+ $messageToSend = "</ProductType>\n";
99
+ $bytes = $bytes + fwrite($putData, $messageToSend);
100
+ }
101
+
102
+ $messageToSend = "</ProductTypes>\n";
103
+ $bytes = $bytes + fwrite($putData, $messageToSend);
104
+
105
+ fseek($putData, 0);
106
+ $senditnow = fread($putData, $bytes);
107
+
108
+ $this->postToChannelUnity($senditnow, "ProductTypes");
109
+
110
+ fclose($putData);
111
  }
112
 
113
+ public function postAttributesToCU() {
114
+
115
+ $putData = tmpfile();
116
+ $bytes = 0;
117
+
118
+ $messageToSend = "<ProductAttributes>\n";
119
+
120
+ $bytes = $bytes + fwrite($putData, $messageToSend);
121
+ $product = Mage::getModel('catalog/product');
122
+ $attributes = Mage::getResourceModel('eav/entity_attribute_collection')
 
 
 
 
 
 
 
 
 
 
 
123
  ->setEntityTypeFilter($product->getResource()->getTypeId())
124
  ->load(false);
125
 
126
+ foreach($attributes as $attribute){
127
+
128
+ $attr = $attribute->getData('attribute_code');
129
+
130
+ if ($attr != 'name' && $attr != 'description' && $attr != 'sku' && $attr != 'price' && $attr != 'qty' && $attr != 'stock_item') {
131
+
132
  $attrType = trim($attribute->getBackendType());
133
  $friendlyName = trim($attribute->getFrontendLabel());
134
+
135
  $messageToSend = " <Attribute><Name>$attr</Name><Type>$attrType</Type>
136
+ <FriendlyName><![CDATA[{$friendlyName}]]></FriendlyName></Attribute>\n";
137
+
138
  $bytes = $bytes + fwrite($putData, $messageToSend);
139
+ }
140
+
141
+ }
142
+
143
+ $messageToSend = "</ProductAttributes>\n";
144
+ $bytes = $bytes + fwrite($putData, $messageToSend);
145
+
146
+ fseek($putData, 0);
147
+ $senditnow = fread($putData, $bytes);
148
+ fclose($putData);
149
+ $result = $this->postToChannelUnity($senditnow, "ProductAttributes");
150
+ $xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
151
+
152
+ if (isset($xml->Status)) {
153
+ return $xml->Status;
154
+ }
155
+ else if (isset($xml->status)) {
156
+ return $xml->status;
157
+ }
158
+ else {
159
+ return "Error - unexpected response";
160
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  }
162
 
163
+ public function generateCuXmlForSingleProduct($productId, $storeId) {
164
+ $productXml = "";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
+ $product = Mage::getModel('catalog/product');
167
+ $product->setStoreId($storeId)->load($productId);
168
 
169
+ try {
170
+ $imageUrl = $product->getImageUrl();
171
+ } catch (Exception $e) {
172
+ $imageUrl = '';
173
  }
174
 
175
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getId());
176
+ $qty = $stock->getData('qty');
177
 
178
+ $catids = implode(',', $product->getCategoryIds());
179
+ $categories = $product->getCategoryIds();
180
+ $catnames = "";
181
+
182
+ foreach ($categories as $k => $_category_id) {
183
+ $_category = Mage::getModel('catalog/category')->load($_category_id);
184
+ $catnames .= ($_category->getName()) . ", ";
185
+ }
186
+
187
+ $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
188
+ $attributeSetModel->load($product->getData('attribute_set_id'));
189
+ $attributeSetName = $attributeSetModel->getAttributeSetName();
190
+
191
+ $productXml = "<Product>\n";
192
+ $productXml .= " <RemoteId>".$product->getId()."</RemoteId>\n";
193
+ $productXml .= " <ProductType>".$attributeSetName."</ProductType>\n";
194
+ $productXml .= " <Title><![CDATA[{$product->getData('name')} ]]></Title>\n";
195
+ $productXml .= " <Description><![CDATA[{$product->getData('description')} ]]></Description>\n";
196
+ $productXml .= " <SKU><![CDATA[{$product->getData('sku')}]]></SKU>\n";
197
+ $productXml .= " <Price>{$product->getData('price')}</Price>\n";
198
+ $productXml .= " <Quantity>{$qty}</Quantity>\n";
199
+ $productXml .= " <Category>{$catids}</Category>\n";
200
+ $productXml .= " <CategoryName><![CDATA[{$catnames} ]]></CategoryName>\n";
201
+ $productXml .= " <Image><![CDATA[{$imageUrl}]]></Image>\n";
202
+
203
+ // Add associated/child product references if applicable
204
+ $productXml .= " <RelatedSKUs>\n";
205
+
206
+ $variationXml = " <Variations>\n";
207
+
208
+ if ($product->getData("type_id") == 'configurable') {
209
+
210
+ $childProducts = Mage::getModel('catalog/product_type_configurable')
211
+ ->getUsedProducts(null, $product);
212
+
213
+ foreach ($childProducts as $cp) {
214
 
215
+ $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
216
+ }
217
+
218
+ $confAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
219
+
220
+ // Get the attribute(s) which vary
221
+ if (is_array($confAttributes)) {
222
+ foreach ($confAttributes as $cattr) {
223
+ $cattr = serialize($cattr);
224
+
225
+ $findTemp = "\"attribute_code\";";
226
 
227
+ $cattr = explode($findTemp, $cattr);
228
 
229
  if (isset($cattr[1])) {
230
 
231
+ $cattr = explode("\"", $cattr[1]);
232
 
233
+ if (isset($cattr[1])) {
234
+
235
+ $variationXml .= "<Variation><![CDATA[{$cattr[1]}]]></Variation>\n";
236
+
237
+ }
238
  }
239
  }
240
  }
241
+
242
+ }
243
+ else if ($product->getTypeId() == 'grouped') {
244
+
245
+ // Do we need to do variations?
246
+
247
+ $childProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);
248
+ foreach ($childProducts as $cp) {
249
+
250
+ $productXml .= " <SKU><![CDATA[{$cp->getData('sku')}]]></SKU>\n";
251
+ }
252
  }
253
 
254
+ $variationXml .= " </Variations>\n";
255
+ $productXml .= " </RelatedSKUs>\n";
256
+ $productXml .= $variationXml;
257
 
258
+ $productXml .= " <Custom>\n";
259
 
260
+ // Enumerate all other attribute values
261
+
262
+ $attributeNames = array_keys($product->getData());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
+ foreach ($attributeNames as $k => $attr) {
 
 
265
 
266
+ if ($attr != 'name' && $attr != 'description' && $attr != 'sku'
267
+ && $attr != 'price' && $attr != 'qty'
268
+ && $attr != 'stock_item' && $attr != 'tier_price') {
269
 
270
+ if ($attribute = $product->getResource()->getAttribute($attr)) {
271
+
272
+ $myval = $product->getData($attr);
273
+
274
+ if (is_array($myval)) {
275
+ $myval = serialize($myval);
276
+ }
277
+
278
+ $prodDataValue = $attribute->getSource()
279
+ ->getOptionText($myval);
280
+
281
+ if ($prodDataValue == '') {
282
+
283
+ $prodDataValue = $myval;
284
+ }
285
+ } else {
286
+ $prodDataValue = $product->getData($attr);
287
  }
288
 
289
+ if (is_object($prodDataValue)) {
290
+ if ('Varien_Object' == get_class($prodDataValue)) {
291
+
292
+ $prodDataValue = $prodDataValue->toXml();
293
+ }
 
294
  }
295
+ if (is_array($prodDataValue)) {
 
 
 
 
 
296
 
297
+ $prodDataValue = $product->getData($attr);
298
+ $productXml .= " <$attr><![CDATA[$prodDataValue]]></$attr>\n";
299
  }
300
+ else {
301
+
302
+ if (!is_object($prodDataValue)) {
303
+ $productXml .= " <$attr><![CDATA[".$prodDataValue."]]></$attr>\n";
304
+ } else if ('Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Type_Configurable_Attribute_Collection'
305
+ == get_class($prodDataValue)) {
306
+ $productXml .= " <$attr><![CDATA[Mage_Core_Model_Mysql4_Collection_Abstract]]></$attr>\n";
307
+ }
 
 
 
 
 
308
  }
309
  }
310
  }
311
+
312
+ $productXml .= " </Custom>\n";
313
+ $productXml .= "</Product>\n";
314
+
315
+ unset($product);
316
+
317
+ return $productXml;
318
  }
319
 
320
+ public function generateCuXmlForProductEcho($args) {
321
+ echo $this->generateCuXmlForProduct($args);
322
+ }
 
 
 
 
 
 
 
 
323
 
324
+ public function generateCuXmlForProduct($args) {
325
+ $productXml = '';
326
+ $this->countCurr++;
 
 
 
 
 
 
 
 
 
 
 
327
 
328
+ $this->maxMemory = $this->return_bytes(ini_get('memory_limit'));
 
 
329
 
330
+ if ($this->runtime < $this->maxruntime
331
+ && (memory_get_peak_usage() + $this->changeMemory) < $this->maxMemory
332
+ && $this->countCurr <= $this->upperLimit)
333
+ {
334
+ $row = $args['row'];
335
+ $this->rangeNext = $row["entity_id"] + 1;
336
+
337
+ $productXml .= $this->generateCuXmlForSingleProduct($row["entity_id"], $args["storeId"]);
338
+
339
+ // after....
340
+ $this->endtime = $this->microtime_float();
341
+ $this->runtime = round($this->endtime - $this->starttime);
342
+
343
+ $tmpval = memory_get_peak_usage() - $this->beforeMemory;
344
+ if ($tmpval > $this->changeMemory) {
345
+ $this->changeMemory = $tmpval;
346
+ }
347
+
348
+ } else {
349
+
350
+ $this->premExit = true; // i.e. exited before got through all prods
351
+
352
  }
353
+
354
+ return $productXml;
 
 
 
355
  }
356
+
357
+ public function microtime_float() {
358
+ list ($msec, $sec) = explode(' ', microtime());
359
+ $microtime = (float)$msec + (float)$sec;
360
+ return $microtime;
361
+ }
362
+
363
+ function return_bytes($val) {
364
+ $val = trim($val);
365
+ $last = strtolower($val[strlen($val)-1]);
 
 
 
366
  switch($last) {
367
+ // The 'G' modifier is available since PHP 5.1.0
368
  case 'g':
369
  $val *= 1024;
370
  case 'm':
372
  case 'k':
373
  $val *= 1024;
374
  }
375
+
376
+ return $val;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  }
378
 
379
+ /**
380
+ * Return a set of product data to CU.
381
+ */
382
+ public function doRead($request) {
383
+ $rangeFrom = (string) $request->RangeFrom;
384
+ $rangeTo = (string) $request->RangeTo;
385
+ $storeId = (string) $request->StoreviewId;
386
+
387
+ $this->starttime = $this->microtime_float();
388
+ $this->endtime = $this->microtime_float();
389
+ $this->runtime = round($this->endtime - $this->starttime);
390
+ $this->beforeMemory = memory_get_peak_usage();
391
+ $this->maxMemory = ini_get('memory_limit');
392
+ $this->maxMemoryChar = substr($this->maxMemory,strlen($this->maxMemory)-1,1);
393
+
394
+ echo "<Products>\n";
395
+
396
+ try {
397
+
398
+ // get the highest product ID
399
+ $collectionOfProduct = Mage::getModel($this->_collection)->getCollection()->setStoreId($storeId);
400
+ $collectionOfProduct->setOrder('entity_id', 'DESC');
401
+ $collectionOfProduct->setPageSize(1);
402
+ $collectionOfProduct->setCurPage(1);
403
+ $totp = $collectionOfProduct->getFirstItem();
404
+ $totp = $totp->getEntityId();
405
+
406
+ $collectionOfProduct = Mage::getModel($this->_collection)->getCollection()->setStoreId($storeId);
407
+
408
+ $totalNumProducts = $this->executeQueryScalar(str_replace("SELECT", "SELECT count(*) as count_cu, ", $collectionOfProduct->getSelect()), 'count_cu');
409
+
410
+ $collectionOfProduct->addAttributeToFilter("entity_id", array('gteq' => $rangeFrom))
411
+ ->setOrder('entity_id', 'ASC');
412
+
413
+ // monitor memory and max exec
414
+ if ($this->maxMemoryChar == "M") {
415
+ $this->maxMemory = str_replace("M", "", $this->maxMemory);
416
+ $this->maxMemory = $this->maxMemory * 1024 * 1024;
417
+ } else if ($this->maxMemoryChar == "G") {
418
+ $this->maxMemory = str_replace("G", "", $maxMemory);
419
+ $this->maxMemory = $this->maxMemory * 1024 * 1024 * 1024;
420
+ }
421
+
422
+ if ($this->maxMemory < 100) {
423
+ $this->maxMemory = 10000000000;
424
+ }
425
+
426
+ $query = str_replace("INNER JOIN", "LEFT JOIN", $collectionOfProduct->getSelect());
427
+
428
+ echo "<Query><![CDATA[$query]]></Query>\n";
429
+
430
+ try {
431
+
432
+ Mage::getSingleton('core/resource_iterator')->walk($query,
433
+ array(array($this, 'generateCuXmlForProductEcho')),
434
+ array('storeId' => $storeId),
435
+ $collectionOfProduct->getSelect()->getAdapter());
436
+
437
+ }
438
+ catch (Exception $x1) {
439
+ Mage::getSingleton('core/resource_iterator')->walk($collectionOfProduct->getSelect(),
440
+ array(array($this, 'generateCuXmlForProductEcho')),
441
+ array('storeId' => $storeId));
442
+ }
443
+
444
+ // Let the cloud know where to start from the next time it calls
445
+ // for product data
446
+
447
+ if ($this->rangeNext <= $totp) {
448
+ echo "<RangeNext>".$this->rangeNext."</RangeNext>\n";
449
+ } else {
450
+ // Start from beginning next time
451
+ echo "<RangeNext>0</RangeNext>\n";
452
+ }
453
+
454
+ echo "<TotalProducts>$totalNumProducts</TotalProducts>\n";
455
+ }
456
+ catch (Exception $x) {
457
+ echo "<Error><![CDATA[".$x->getTraceAsString()."]]></Error>\n";
458
+ }
459
+ echo "</Products>\n";
460
+ }
461
 
462
+ private function executeQuery($sql) {
463
+ $db = Mage::getSingleton("core/resource")->getConnection("core_write");
464
+
465
+ $result = $db->query($sql);
466
+
467
+ $resultArray = array();
468
+
469
+ foreach ($result as $row) {
470
+
471
+ $resultArray[] = $row;
472
+ }
473
+
474
+ return $resultArray;
475
+ }
476
+ private function executeQueryScalar($sql, $column) {
477
+ $result = $this->executeQuery($sql);
478
+
479
+ foreach ($result as $row) {
480
+ return $row[$column];
481
+ }
482
+ return -1;
483
+ }
484
  }
485
+
 
486
  ?>
app/code/community/Camiloo/Channelunity/controllers/ApiController.php CHANGED
@@ -10,105 +10,171 @@ class Camiloo_Channelunity_ApiController extends Mage_Core_Controller_Front_Acti
10
  echo ' </ChannelUnity>';
11
  die;
12
  }
13
-
14
-
15
- /**
16
- * This is the main API beacon for the connector module
17
- * It will verify the request the pass it onto the model
18
- **/
19
- public function indexAction(){
20
-
21
- $xml = $this->getRequest()->getPost('xml');
22
- if (!isset($xml)) {
23
-
24
- $this->terminate("Error - could not find XML within request");
25
-
26
- } else {
27
- $xml = urldecode($xml);
28
-
29
- // load the XML into the simplexml parser
30
- $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
31
-
32
- // we now need to verify that this message is genuine. We do this by calling
33
- // to ChannelUnity HQ with just the contents of the signedmessage element in
34
- // the XML message.
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  $payload = (string) $xml->Notification->Payload;
37
 
38
  if ($payload == '') {
39
  $payload = (string) $xml->Notification->payload;
40
  }
41
-
42
-
43
  // we pass the signedmessage, intact, to the ChannelUnity API
44
  // by posting it as signedmessage. Verifypost will only return
45
  // to the variable if the response was successful. It will fail
46
  // on invalid messages, so we won't have to worry about that here.
47
  // It will return a simplexml object too, so we can get straight
48
  // down to work.
49
-
50
  $payload = trim($payload);
51
-
52
  if ($payload != '') {
53
-
54
- $request = Mage::getModel('channelunity/products')->verifypost($payload);
55
  }
56
  else {
57
  $request = "";
58
  }
59
- // RequestHeader contains the request type. Lets find out what type of request
60
- // we are handling by creating a switch.
61
-
62
- $type = (string) $xml->Notification->Type;
63
- if ($type == '') {
64
- $type = (string) $xml->Notification->type;
65
- }
66
-
67
- ini_set("display_errors","1");
68
- error_reporting(E_ALL);
69
-
70
- echo '<?xml version="1.0" encoding="utf-8" ?>';
71
- echo ' <ChannelUnity>';
72
- echo ' <RequestType>'.$type.'</RequestType>';
73
-
74
- switch ($type) {
 
 
 
 
75
 
76
- case "Ping":
 
 
77
 
78
- Mage::getModel('channelunity/orders')->verifyMyself($request);
 
 
 
 
79
 
80
  break;
81
 
82
- case "OrderNotification":
83
- Mage::getModel('channelunity/orders')->doCreate($request);
84
- break;
 
 
 
85
 
86
- case "ProductData":
87
- error_reporting(E_ALL);
88
- ini_set("display_errors","On");
89
- $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
90
- Mage::getModel('channelunity/products')->postProductTypesToCU($request);
91
- Mage::getModel('channelunity/products')->doRead($request);
92
-
93
  break;
94
 
95
- case "CartDataRequest":
96
 
97
- // get URL out of the CartDataRequest
98
- $myStoreURL = $xml->Notification->URL;
99
- $storeStatus = Mage::getModel('channelunity/stores')->postStoresToCU($myStoreURL);
100
- $categoryStatus = Mage::getModel('channelunity/categories')->postCategoriesToCU($myStoreURL);
101
- $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
 
 
 
 
102
 
103
- echo "<StoreStatus>$storeStatus</StoreStatus>
104
- <CategoryStatus>$categoryStatus</CategoryStatus>
105
- <ProductAttributeStatus>$attributeStatus</ProductAttributeStatus>";
106
-
107
  break;
108
 
109
- }
 
 
 
110
 
111
- echo ' </ChannelUnity>';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  die;
113
  }
114
 
10
  echo ' </ChannelUnity>';
11
  die;
12
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ public function ordertestAction() {
15
+
16
+ $xml = <<<EOD
17
+ <?xml version="1.0" encoding="utf-8" ?><ChannelUnity><Notification><ID>1334834111876</ID><Timestamp>Thu Apr 19 12:15:11 BST 2012</Timestamp><Type>OrderNotification</Type><Payload><MerchantName>marktest</MerchantName><SourceId>10</SourceId><FriendlyName>English</FriendlyName><URL>http://__.camiloo.co.uk/channelunity/api/index</URL><MainCountry>United Kingdom</MainCountry><FrameworkType>Magento</FrameworkType><WebsiteId>1</WebsiteId><StoreId>1</StoreId><StoreviewId>1</StoreviewId><SubscriptionId>304</SubscriptionId><SkuAttribute>sku</SkuAttribute><Orders>
18
+ <Order>
19
+ <ServiceSku>CU_AMZ_UK</ServiceSku>
20
+ <OrderId>202-8888888-0277161</OrderId>
21
+ <PurchaseDate>2012-04-10T01:33:10+00:00</PurchaseDate>
22
+ <Currency>GBP</Currency>
23
+ <OrderFlags></OrderFlags>
24
+ <OrderStatus>Processing</OrderStatus>
25
+ <StockReservedCart>0</StockReservedCart>
26
+ <ShippingInfo>
27
+ <RecipientName><![CDATA[Mrs Ship]]></RecipientName>
28
+ <Email><![CDATA[ship@ship.com]]></Email>
29
+ <Address1><![CDATA[1 High St]]></Address1>
30
+ <Address2><![CDATA[]]></Address2>
31
+ <Address3><![CDATA[]]></Address3>
32
+ <City><![CDATA[Manchester]]></City>
33
+ <State>none</State>
34
+ <PostalCode>M1 1AA</PostalCode>
35
+ <Country><![CDATA[UK]]></Country>
36
+ <PhoneNumber><![CDATA[01981 239329]]></PhoneNumber>
37
+ <ShippingPrice>2.00</ShippingPrice>
38
+ <ShippingTax>0.00</ShippingTax>
39
+ <Service><![CDATA[Std UK Europe 2]]></Service>
40
+ <DeliveryInstructions><![CDATA[]]></DeliveryInstructions>
41
+ <GiftWrapPrice>0.00</GiftWrapPrice>
42
+ <GiftWrapTax>0.00</GiftWrapTax>
43
+ <GiftWrapType></GiftWrapType>
44
+ <GiftMessage><![CDATA[]]></GiftMessage>
45
+ </ShippingInfo>
46
+ <BillingInfo>
47
+ <Name><![CDATA[Mr Billing]]></Name>
48
+ <Email><![CDATA[b@c.com]]></Email>
49
+ <PhoneNumber><![CDATA[01987 228228]]></PhoneNumber>
50
+ </BillingInfo>
51
+ <OrderItems>
52
+ <Item>
53
+ <SKU><![CDATA[XRIT250]]></SKU>
54
+ <Name><![CDATA[X-Rite ColorChecker Passport]]></Name>
55
+ <Quantity>1.000</Quantity>
56
+ <Price>1.00</Price>
57
+ <Tax>0.00</Tax>
58
+ </Item>
59
+ </OrderItems></Order></Orders></Payload></Notification></ChannelUnity>
60
+ EOD;
61
+
62
+ $this->doApiProcess($xml, true);
63
+ }
64
+
65
+ public function doApiProcess($xml, $testMode = false) {
66
+
67
+ // print_r($xml);die;
68
+
69
+ // load the XML into the simplexml parser
70
+ $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
71
+
72
+
73
+
74
+ // we now need to verify that this message is genuine. We do this by calling
75
+ // to ChannelUnity HQ with just the contents of the signedmessage element in
76
+ // the XML message.
77
+
78
+ if (!$testMode) {
79
+
80
  $payload = (string) $xml->Notification->Payload;
81
 
82
  if ($payload == '') {
83
  $payload = (string) $xml->Notification->payload;
84
  }
85
+
 
86
  // we pass the signedmessage, intact, to the ChannelUnity API
87
  // by posting it as signedmessage. Verifypost will only return
88
  // to the variable if the response was successful. It will fail
89
  // on invalid messages, so we won't have to worry about that here.
90
  // It will return a simplexml object too, so we can get straight
91
  // down to work.
92
+
93
  $payload = trim($payload);
94
+
95
  if ($payload != '') {
96
+ $request = Mage::getModel('channelunity/products')->verifypost($payload);
 
97
  }
98
  else {
99
  $request = "";
100
  }
101
+ }
102
+ else {
103
+ $request = $xml->Notification->Payload;
104
+ }
105
+ // RequestHeader contains the request type. Lets find out what type of request
106
+ // we are handling by creating a switch.
107
+
108
+ $type = (string) $xml->Notification->Type;
109
+ if ($type == '') {
110
+ $type = (string) $xml->Notification->type;
111
+ }
112
+
113
+ ini_set("display_errors", "1");
114
+ error_reporting(E_ALL);
115
+
116
+ echo '<?xml version="1.0" encoding="utf-8" ?>';
117
+ echo ' <ChannelUnity>';
118
+ echo ' <RequestType>'.$type.'</RequestType>';
119
+
120
+ switch ($type) {
121
 
122
+ case "Ping":
123
+ Mage::getModel('channelunity/orders')->verifyMyself($request);
124
+ break;
125
 
126
+ case "OrderNotification":
127
+ Mage::getModel('channelunity/orders')->doUpdate($request);
128
+ break;
129
+
130
+ case "OrderDataUpdate":
131
 
132
  break;
133
 
134
+ case "ProductData":
135
+ error_reporting(E_ALL);
136
+ ini_set("display_errors", "On");
137
+ $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
138
+ Mage::getModel('channelunity/products')->postProductTypesToCU($request);
139
+ Mage::getModel('channelunity/products')->doRead($request);
140
 
 
 
 
 
 
 
 
141
  break;
142
 
143
+ case "CartDataRequest":
144
 
145
+ // get URL out of the CartDataRequest
146
+ $myStoreURL = $xml->Notification->URL;
147
+ $storeStatus = Mage::getModel('channelunity/stores')->postStoresToCU($myStoreURL);
148
+ $categoryStatus = Mage::getModel('channelunity/categories')->postCategoriesToCU($myStoreURL);
149
+ $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
150
+
151
+ echo "<StoreStatus>$storeStatus</StoreStatus>
152
+ <CategoryStatus>$categoryStatus</CategoryStatus>
153
+ <ProductAttributeStatus>$attributeStatus</ProductAttributeStatus>";
154
 
 
 
 
 
155
  break;
156
 
157
+ }
158
+
159
+ echo ' </ChannelUnity>';
160
+ }
161
 
162
+ /**
163
+ * This is the main API beacon for the connector module
164
+ * It will verify the request then pass it onto the model.
165
+ **/
166
+ public function indexAction() {
167
+
168
+ $xml = $this->getRequest()->getPost('xml');
169
+ if (!isset($xml)) {
170
+
171
+ $this->terminate("Error - could not find XML within request");
172
+
173
+ } else {
174
+ $xml = urldecode($xml);
175
+
176
+ $this->doApiProcess($xml);
177
+
178
  die;
179
  }
180
 
app/code/community/Camiloo/Channelunity/controllers/ApiController.php.old.php ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class Camiloo_Channelunity_ApiController extends Mage_Core_Controller_Front_Action
4
+ {
5
+ private function terminate($message) {
6
+
7
+ echo '<?xml version="1.0" encoding="utf-8" ?>';
8
+ echo ' <ChannelUnity>';
9
+ echo ' <Status>'.$message.'</Status>';
10
+ echo ' </ChannelUnity>';
11
+ die;
12
+ }
13
+
14
+
15
+ /**
16
+ * This is the main API beacon for the connector module
17
+ * It will verify the request the pass it onto the model
18
+ **/
19
+ public function indexAction(){
20
+
21
+ $xml = $this->getRequest()->getPost('xml');
22
+ if (!isset($xml)) {
23
+
24
+ $this->terminate("Error - could not find XML within request");
25
+
26
+ } else {
27
+ $xml = urldecode($xml);
28
+
29
+ // load the XML into the simplexml parser
30
+ $xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
31
+
32
+ // we now need to verify that this message is genuine. We do this by calling
33
+ // to ChannelUnity HQ with just the contents of the signedmessage element in
34
+ // the XML message.
35
+
36
+ $payload = (string) $xml->Notification->Payload;
37
+
38
+ if ($payload == '') {
39
+ $payload = (string) $xml->Notification->payload;
40
+ }
41
+
42
+
43
+ // we pass the signedmessage, intact, to the ChannelUnity API
44
+ // by posting it as signedmessage. Verifypost will only return
45
+ // to the variable if the response was successful. It will fail
46
+ // on invalid messages, so we won't have to worry about that here.
47
+ // It will return a simplexml object too, so we can get straight
48
+ // down to work.
49
+
50
+ $payload = trim($payload);
51
+
52
+ if ($payload != '') {
53
+ $request = Mage::getModel('channelunity/products')->verifypost($payload);
54
+ }
55
+ else {
56
+ $request = "";
57
+ }
58
+ // RequestHeader contains the request type. Lets find out what type of request
59
+ // we are handling by creating a switch.
60
+
61
+ $type = (string) $xml->Notification->Type;
62
+ if ($type == '') {
63
+ $type = (string) $xml->Notification->type;
64
+ }
65
+
66
+ ini_set("display_errors","1");
67
+ error_reporting(E_ALL);
68
+
69
+ echo '<?xml version="1.0" encoding="utf-8" ?>';
70
+ echo ' <ChannelUnity>';
71
+ echo ' <RequestType>'.$type.'</RequestType>';
72
+
73
+ switch ($type) {
74
+
75
+ case "Ping":
76
+ Mage::getModel('channelunity/orders')->verifyMyself($request);
77
+ break;
78
+
79
+ case "OrderNotification":
80
+ Mage::getModel('channelunity/orders')->doUpdate($request);
81
+ break;
82
+
83
+ case "OrderDataUpdate":
84
+
85
+ break;
86
+
87
+ case "ProductData":
88
+ error_reporting(E_ALL);
89
+ ini_set("display_errors", "On");
90
+ $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
91
+ Mage::getModel('channelunity/products')->postProductTypesToCU($request);
92
+ Mage::getModel('channelunity/products')->doRead($request);
93
+
94
+ break;
95
+
96
+ case "CartDataRequest":
97
+
98
+ // get URL out of the CartDataRequest
99
+ $myStoreURL = $xml->Notification->URL;
100
+ $storeStatus = Mage::getModel('channelunity/stores')->postStoresToCU($myStoreURL);
101
+ $categoryStatus = Mage::getModel('channelunity/categories')->postCategoriesToCU($myStoreURL);
102
+ $attributeStatus = Mage::getModel('channelunity/products')->postAttributesToCU();
103
+
104
+ echo "<StoreStatus>$storeStatus</StoreStatus>
105
+ <CategoryStatus>$categoryStatus</CategoryStatus>
106
+ <ProductAttributeStatus>$attributeStatus</ProductAttributeStatus>";
107
+
108
+ break;
109
+
110
+ }
111
+
112
+ echo ' </ChannelUnity>';
113
+ die;
114
+ }
115
+
116
+
117
+
118
+ }
119
+
120
+ }
app/code/community/Camiloo/Channelunity/etc/config.xml CHANGED
@@ -89,10 +89,10 @@
89
  </models>
90
  <resources>
91
  <channelunity_setup>
92
- <!-- <setup>
93
  <module>Camiloo_Channelunity</module>
94
- <class>Camiloo_Channelunity_Model_Entity_Setup</class>
95
- </setup> -->
96
  <connection>
97
  <use>core_setup</use>
98
  </connection>
@@ -130,13 +130,23 @@
130
  </observers>
131
  </catalog_product_save_after>
132
  <controller_action_postdispatch>
133
-                <observers>
134
-
135
                     <controller_action_after>
136
-
137
                         <class>channelunity/observer</class>
138
-
139
 
140
                         <method>hookToControllerActionPostDispatch</method>
141
-
142
 
143
 
144
                     </controller_action_after>
145
-
146
 
147
 
148
                 </observers>
149
-
150
 
151
 
152
 
153
             </controller_action_postdispatch>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  <sales_order_place_after>
155
  <observers>
156
  <channelunity>
89
  </models>
90
  <resources>
91
  <channelunity_setup>
92
+ <setup>
93
  <module>Camiloo_Channelunity</module>
94
+ <class>Camiloo_Channelunity_Model_Entity</class>
95
+ </setup>
96
  <connection>
97
  <use>core_setup</use>
98
  </connection>
130
  </observers>
131
  </catalog_product_save_after>
132
  <controller_action_postdispatch>
 
 
133
                     <controller_action_after>
 
134
                         <class>channelunity/observer</class>
 
135
 
136
                         <method>hookToControllerActionPostDispatch</method>
 
137
 
138
 
139
                     </controller_action_after>
 
140
 
141
 
142
                 </observers>
 
143
 
144
 
145
 
146
             </controller_action_postdispatch>
147
+ <observers>
148
+
149
+ <controller_action_after>
150
+
151
+ <class>channelunity/observer</class>
152
+
153
+
154
+ <method>hookToControllerActionPostDispatch</method>
155
+
156
+
157
+
158
+ </controller_action_after>
159
+
160
+
161
+ </observers>
162
+
163
+ </controller_action_postdispatch>
164
  <sales_order_place_after>
165
  <observers>
166
  <channelunity>
app/code/community/Camiloo/Channelunity/sql/channelunity_setup/install-1.0.0.php ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ $installer = $this;
4
+ $installer->startSetup();
5
+
6
+ $installer->addAttribute('quote_payment', 'channelunity_orderid', array());
7
+ $installer->addAttribute('quote_payment', 'channelunity_remoteorderid', array());
8
+ $installer->addAttribute('quote_payment', 'channelunity_remotechannelname', array());
9
+ $installer->addAttribute('quote_payment', 'channelunity_subscriptionid', array());
10
+
11
+ $installer->addAttribute('order_payment', 'channelunity_orderid', array());
12
+ $installer->addAttribute('order_payment', 'channelunity_remoteorderid', array());
13
+ $installer->addAttribute('order_payment', 'channelunity_remotechannelname', array());
14
+ $installer->addAttribute('order_payment', 'channelunity_subscriptionid', array());
15
+
16
+ $installer->endSetup();
17
+
18
+ $adminSession = Mage::getSingleton('admin/session');
19
+ $adminSession->unsetAll();
20
+ $adminSession->getCookie()->delete($adminSession->getSessionName());
21
+
22
+ ?>
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Camiloo_Channelunity</name>
4
- <version>1.0.0.0</version>
5
  <stability>stable</stability>
6
  <license uri="http://www.camiloo.co.uk/license.txt">Camiloo EULA</license>
7
  <channel>community</channel>
@@ -12,9 +12,9 @@
12
  Should you need any help getting started, please email support@camiloo.co.uk</description>
13
  <notes>The ChannelUnity connector kit for Magento.</notes>
14
  <authors><author><name>Camiloo Limited</name><user>auto-converted</user><email>hello@camiloo.co.uk</email></author></authors>
15
- <date>2012-03-16</date>
16
- <time>14:22:35</time>
17
- <contents><target name="magedesign"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="template"><dir name="channelunity"><file name="configheader.phtml" hash="5d21d8ef92b2dc28e952eeddf9a391fa"/><file name="paymentinfo.phtml" hash="60967f7ab38fe17c879b272eed25f986"/></dir></dir></dir></dir></dir></target><target name="magecommunity"><dir name="Camiloo"><dir name="Channelunity"><dir name="Block"><file name="Configheader.php" hash="6d7de078f04901e94b8b9675bcd9e4ac"/><file name="Paymentform.php" hash="1f3e79556f15a57b9761c3665a103103"/><file name="Paymentinfo.php" hash="6c3c36d92592dd802fb8045dc065d231"/></dir><dir name="controllers"><file name="ApiController.php" hash="ac2c584cc5f99e3fe48eab73fe0932be"/></dir><dir name="etc"><file name="config.xml" hash="34a31001eaa40d4bb3cf262eaeb4a1e0"/><file name="system.xml" hash="b43f861f8ab3dadca3c122be10790609"/></dir><dir name="Helper"><file name="Data.php" hash="1ccace887d4a09eca0b641394c65d35f"/></dir><dir name="Model"><file name="Abstract.php" hash="dde32099ae2fc34f9cd7e9c2ae23bc3c"/><file name="Attributes.php" hash="b6428ef515e083e172ccf0b6e07e32fe"/><file name="Categories.php" hash="0d741f1a1384bca8b26b933e5fa23157"/><file name="Checkforupdates.php" hash="6fcf97b37aa3f3a1e0149f7761975925"/><file name="Customrate.php" hash="5dab412e72c869599c8cfb670519da65"/><file name="Observer.php" hash="66bfe119a54fad8c2a80f7fa6e33c238"/><file name="Ordercreatebackport.php" hash="3b696fb97ce6550a967d76436a3d131c"/><file name="Orders.php" hash="d52d65438a54f8d76bc22a030d61714b"/><file name="Payment.php" hash="7fe570cf0aaf7c2bcdf1982b6e69caa6"/><file name="Paymentinfo.php" hash="e11658c9fa02420557441f5c8a41f8a0"/><file name="Paymentmethoduk.php" hash="a99409ed4ee5f7e426df4eaf793482d6"/><file name="Products.php" hash="66e07b920f76337aae9739e5cbc10eee"/><file name="Stores.php" hash="a8dad8786c9f188d2435d6c5b8222cad"/></dir><dir name="sql"><dir name="channelunity_setup"><file name="mysql4-install-0.0.1.php" hash="f8c841babd0c387f710c3404b70de08f"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Camiloo_Channelunity.xml" hash="cccfbce64ee176372c5afecb8676fab0"/></dir></target></contents>
18
  <compatible/>
19
  <dependencies/>
20
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>Camiloo_Channelunity</name>
4
+ <version>1.0.0.1</version>
5
  <stability>stable</stability>
6
  <license uri="http://www.camiloo.co.uk/license.txt">Camiloo EULA</license>
7
  <channel>community</channel>
12
  Should you need any help getting started, please email support@camiloo.co.uk</description>
13
  <notes>The ChannelUnity connector kit for Magento.</notes>
14
  <authors><author><name>Camiloo Limited</name><user>auto-converted</user><email>hello@camiloo.co.uk</email></author></authors>
15
+ <date>2012-04-20</date>
16
+ <time>14:59:17</time>
17
+ <contents><target name="magedesign"><dir name="adminhtml"><dir name="default"><dir name="default"><dir name="template"><dir name="channelunity"><file name="configheader.phtml" hash="5d21d8ef92b2dc28e952eeddf9a391fa"/><file name="paymentinfo.phtml" hash="60967f7ab38fe17c879b272eed25f986"/></dir></dir></dir></dir></dir></target><target name="magecommunity"><dir name="Camiloo"><dir name="Channelunity"><dir name="Block"><file name="Configheader.php" hash="6d7de078f04901e94b8b9675bcd9e4ac"/><file name="Paymentform.php" hash="1f3e79556f15a57b9761c3665a103103"/><file name="Paymentinfo.php" hash="6c3c36d92592dd802fb8045dc065d231"/></dir><dir name="controllers"><file name="ApiController.php" hash="f21ce3f7c5ef302579219eaef57f6ee9"/><file name="ApiController.php.old.php" hash="01ff34c2cf5798a82cfc11b19ab6decd"/></dir><dir name="etc"><file name="config.xml" hash="94c1ec56968437ee64488eabc4451b0f"/><file name="system.xml" hash="b43f861f8ab3dadca3c122be10790609"/></dir><dir name="Helper"><file name="Data.php" hash="1ccace887d4a09eca0b641394c65d35f"/></dir><dir name="Model"><file name="Abstract.php" hash="dde32099ae2fc34f9cd7e9c2ae23bc3c"/><file name="Attributes.php" hash="b6428ef515e083e172ccf0b6e07e32fe"/><file name="Categories.php" hash="0d741f1a1384bca8b26b933e5fa23157"/><file name="Checkforupdates.php" hash="6fcf97b37aa3f3a1e0149f7761975925"/><file name="Customrate.php" hash="5dab412e72c869599c8cfb670519da65"/><file name="Entity.php" hash="8ff876068c52106c589a5079cc0f9215"/><file name="Observer.php" hash="66bfe119a54fad8c2a80f7fa6e33c238"/><file name="Ordercreatebackport.php" hash="3b696fb97ce6550a967d76436a3d131c"/><file name="Orders.php" hash="fe348754144f623bd61b40a4b4bbc127"/><file name="Payment.php" hash="7fe570cf0aaf7c2bcdf1982b6e69caa6"/><file name="Paymentinfo.php" hash="e11658c9fa02420557441f5c8a41f8a0"/><file name="Paymentmethoduk.php" hash="a99409ed4ee5f7e426df4eaf793482d6"/><file name="Products.php" hash="6ee2b3ad8383e4f560eefa66bdeea2c9"/><file name="Stores.php" hash="a8dad8786c9f188d2435d6c5b8222cad"/></dir><dir name="sql"><dir name="channelunity_setup"><file name="install-1.0.0.php" hash="362396ea358cbfd7d64ce07c4d4fab1a"/><file name="mysql4-install-0.0.1.php" hash="f8c841babd0c387f710c3404b70de08f"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Camiloo_Channelunity.xml" hash="cccfbce64ee176372c5afecb8676fab0"/></dir></target></contents>
18
  <compatible/>
19
  <dependencies/>
20
  </package>