Advertisement
Guest User

good file

a guest
Feb 16th, 2016
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.76 KB | None | 0 0
  1. root@srv [/home/brighter/public_html]# cat shipworks3.php
  2. <?php
  3. /*
  4. |
  5. | This file and the source codes contained herein are the property
  6. | of Interapptive, Inc. Use of this file is restricted to the specific
  7. | terms and conditions in the License Agreement associated with this
  8. | file. Distribution of this file or portions of this file for uses
  9. | not covered by the License Agreement is not allowed without a written
  10. | agreement signed by an officer of Interapptive, Inc.
  11. |
  12. | The code contained herein may not be reproduced, copied or
  13. | redistributed in any form, as part of another product or otherwise.
  14. | Modified versions of this code may not be sold or redistributed.
  15. |
  16. | Copyright Interapptive, Inc. All rights reserved.
  17. | http://www.interapptive.com/
  18. |
  19. |
  20. */
  21. define('REQUIRE_SECURE', TRUE);
  22. $moduleVersion = "3.10.0.0";
  23. $schemaVersion = "1.0.0";
  24.  
  25. // include the Mage engine
  26. require_once 'app/Mage.php';
  27. umask(0);
  28.  
  29. // retrieve the store code
  30. $storeCode = '';
  31. if (isset($_REQUEST['storecode']))
  32. {
  33. $storeCode = $_REQUEST['storecode'];
  34. }
  35.  
  36. // using output buffering to get around headers that magento is setting after we've started output
  37. ob_start();
  38.  
  39. header("Content-Type: text/xml;charset=utf-8");
  40. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  41.  
  42. // HTTP/1.1
  43. header("Cache-Control: no-store, no-cache, must-revalidate");
  44. header("Cache-Control: post-check=0, pre-check=0", false);
  45.  
  46. // HTTP/1.0
  47. header("Pragma: no-cache");
  48.  
  49. // Tests the Magento version to see if it's greater than or equal to the targetVersion
  50. function MagentoVersionGreaterOrEqualTo($targetVersion)
  51. {
  52. $mageVersion = Mage::getVersion();
  53.  
  54. $currentParts = preg_split('[\.]', $mageVersion);
  55. $targetParts = preg_split('[\.]', $targetVersion);
  56.  
  57. $i = 0;
  58. foreach ($currentParts as $currentPart)
  59. {
  60. if ($i >= count($targetParts))
  61. {
  62. // gotten this far, means that current version of 1.4.0.1 > target version 1.4.0
  63. return true;
  64. }
  65.  
  66. $targetPart = $targetParts[$i];
  67.  
  68. // if this iteration's target version part is greater than the magento version part, we're done.
  69. if ((int)$targetPart > (int)$currentPart)
  70. {
  71. return false;
  72. }
  73. else if ((int)$targetPart < (int)$currentPart)
  74. {
  75. // the magento version part is greater, then we're done
  76. return true;
  77. }
  78.  
  79.  
  80. // otherwise to this point the two are equal, continue
  81. $i++;
  82. }
  83.  
  84. // got this far means the two are equal
  85. return true;
  86. }
  87.  
  88. // write xml documenta declaration
  89. function writeXmlDeclaration()
  90. {
  91. echo "<?xml version=\"1.0\" standalone=\"yes\" ?>";
  92. }
  93.  
  94. function writeStartTag($tag, $attributes = null)
  95. {
  96. echo '<' . $tag;
  97.  
  98. if ($attributes != null)
  99. {
  100. echo ' ';
  101.  
  102. foreach ($attributes as $name => $attribValue)
  103. {
  104. echo $name. '="'. htmlspecialchars($attribValue). '" ';
  105. }
  106. }
  107.  
  108. echo '>';
  109. }
  110.  
  111. // write closing xml tag
  112. function writeCloseTag($tag)
  113. {
  114. echo '</' . $tag . '>';
  115. }
  116.  
  117. // Output the given tag\value pair
  118. function writeElement($tag, $value)
  119. {
  120. writeStartTag($tag);
  121. echo htmlspecialchars($value);
  122. writeCloseTag($tag);
  123. }
  124.  
  125. // Outputs the given name/value pair as an xml tag with attributes
  126. function writeFullElement($tag, $value, $attributes)
  127. {
  128. echo '<'. $tag. ' ';
  129.  
  130. foreach ($attributes as $name => $attribValue)
  131. {
  132. echo $name. '="'. htmlspecialchars($attribValue). '" ';
  133. }
  134. echo '>';
  135. echo htmlspecialchars($value);
  136. writeCloseTag($tag);
  137. }
  138.  
  139.  
  140. // Function used to output an error and quit.
  141. function outputError($code, $error)
  142. {
  143. writeStartTag("Error");
  144. writeElement("Code", $code);
  145. writeElement("Description", $error);
  146. writeCloseTag("Error");
  147. }
  148.  
  149. $secure = false;
  150. try
  151. {
  152. if (isset($_SERVER['HTTPS']))
  153. {
  154. $secure = ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == '1');
  155. }
  156. }
  157. catch(Exception $e)
  158. {
  159. }
  160.  
  161. // Open the XML output and root
  162. writeXmlDeclaration();
  163. writeStartTag("ShipWorks", array("moduleVersion" => $moduleVersion, "schemaVersion" => $schemaVersion));
  164.  
  165. try
  166. {
  167. // start the mage engine
  168. Mage::app($storeCode);
  169. }
  170. catch (Mage_Core_Model_Store_Exception $e)
  171. {
  172. outputError(100, "Invalid Store Code.");
  173. writeCloseTag("ShipWorks");
  174. exit;
  175. }
  176.  
  177. // Enforse SSL
  178. if (!$secure && REQUIRE_SECURE)
  179. {
  180. outputError(10, 'A secure (https://) connection is required.');
  181. }
  182. else
  183. {
  184. // If the admin module is installed, we make use of it
  185. if (checkAdminLogin())
  186. {
  187. $action = (isset($_REQUEST['action']) ? $_REQUEST['action'] : '');
  188. switch (strtolower($action))
  189. {
  190. case 'getmodule': Action_GetModule(); break;
  191. case 'getstore': Action_GetStore(); break;
  192. case 'getcount': Action_GetCount(); break;
  193. case 'getorders': Action_GetOrders(); break;
  194. case 'getstatuscodes': Action_GetStatusCodes(); break;
  195. case 'updateorder': Action_UpdateOrder(); break;
  196. default:
  197. outputError(20, "'$action' is not supported.");
  198. }
  199. }
  200. }
  201.  
  202. // Close the output
  203. writeCloseTag("ShipWorks");
  204.  
  205. // Check to see if admin functions exist. And if so, determine if the user
  206. // has access.
  207. function checkAdminLogin()
  208. {
  209. $loginOK = false;
  210.  
  211. if (isset($_REQUEST['username']) && isset($_REQUEST['password']))
  212. {
  213. $username = $_REQUEST['username'];
  214. $password = $_REQUEST['password'];
  215.  
  216. $user = Mage::getSingleton('admin/session')->login($username, $password);
  217. if ($user && $user->getId())
  218. {
  219. $loginOK = true;
  220. }
  221. }
  222.  
  223. if (!$loginOK)
  224. {
  225. outputError(50, "The username or password is incorrect.");
  226. }
  227.  
  228. return $loginOK;
  229. }
  230.  
  231. function Action_GetModule()
  232. {
  233. writeStartTag("Module");
  234.  
  235. writeElement("Platform", "Magento");
  236. writeElement("Developer", "Interapptive, Inc. (support@interapptive.com)");
  237.  
  238. writeStartTag("Capabilities");
  239. writeElement("DownloadStrategy", "ByModifiedTime");
  240. writeFullElement("OnlineCustomerID", "", array("supported" => "true", "dataType" => "numeric"));
  241. writeFullElement("OnlineStatus", "", array("supported" => "true", "dataType" => "text", "downloadOnly" => "true" ));
  242. writeFullElement("OnlineShipmentUpdate", "", array("supported" => "false"));
  243. writeCloseTag("Capabilities");
  244.  
  245. writeCloseTag("Module");
  246. }
  247.  
  248. // Write store data
  249. function Action_GetStore()
  250. {
  251. // get state name
  252. $region_model = Mage::getModel('directory/region');
  253. if (is_object($region_model))
  254. {
  255. $state = $region_model->load(Mage::getStoreConfig('shipping/origin/region_id'))->getDefaultName();
  256. }
  257.  
  258. $name = Mage::getStoreConfig('system/store/name');
  259. $owner = Mage::getStoreConfig('trans_email/ident_general/name');
  260. $email = Mage::getStoreConfig('trans_email/ident_general/email');
  261. $country = Mage::getStoreConfig('shipping/origin/country_id');
  262. $website = Mage::getURL();
  263.  
  264. writeStartTag("Store");
  265. writeElement("Name", $name);
  266. writeElement("CompanyOrOwner", $owner);
  267. writeElement("Email", $email);
  268. writeElement("State", $state);
  269. writeElement("Country", $country);
  270. writeElement("Website", $website);
  271. writeCloseTag("Store");
  272. }
  273.  
  274. // Converts an xml datetime string to sql date time
  275. function toLocalSqlDate($sqlUtc)
  276. {
  277. $pattern = "/^(\d{4})-(\d{2})-(\d{2})\T(\d{2}):(\d{2}):(\d{2})$/i";
  278.  
  279. if (preg_match($pattern, $sqlUtc, $dt))
  280. {
  281. $unixUtc = gmmktime($dt[4], $dt[5], $dt[6], $dt[2], $dt[3], $dt[1]);
  282.  
  283. return date("Y-m-d H:i:s", $unixUtc);
  284. }
  285.  
  286. return $sqlUtc;
  287. }
  288.  
  289.  
  290. // Get the count of orders greater than the start ID
  291. function Action_GetCount()
  292. {
  293. $start = 0;
  294. $storeId = Mage::app()->getStore()->storeId;
  295.  
  296. if (isset($_REQUEST['start']))
  297. {
  298. $start = $_REQUEST['start'];
  299. }
  300.  
  301. // only get orders through 2 seconds ago
  302. $end = date("Y-m-d H:i:s", time() - 2);
  303.  
  304. // Convert to local SQL time
  305. $start = toLocalSqlDate($start);
  306.  
  307. // Write the params for easier diagnostics
  308. writeStartTag("Parameters");
  309. writeElement("Start", $start);
  310. writeCloseTag("Parameters");
  311.  
  312. $orders = Mage::getModel('sales/order')->getCollection();
  313. $orders->addAttributeToSelect("updated_at")->getSelect()->where("(updated_at > '$start' AND updated_at <= '$end' AND store_id = $storeId)");
  314. $count = $orders->count();
  315.  
  316. writeElement("OrderCount", $count);
  317. }
  318.  
  319. // Get all orders greater than the given start id, limited by max count
  320. function Action_GetOrders()
  321. {
  322. $storeId = Mage::app()->getStore()->storeId;
  323. $start = 0;
  324. $maxcount = 50;
  325.  
  326. if (isset($_REQUEST['start']))
  327. {
  328. $start = $_REQUEST['start'];
  329. }
  330.  
  331. if (isset($_REQUEST['maxcount']))
  332. {
  333. $maxcount = $_REQUEST['maxcount'];
  334. }
  335.  
  336. // Only get orders through 2 seconds ago.
  337. $end = date("Y-m-d H:i:s", time() - 2);
  338.  
  339. // Convert to local SQL time
  340. $start = toLocalSqlDate($start);
  341.  
  342. // Write the params for easier diagnostics
  343. writeStartTag("Parameters");
  344. writeElement("Start", $start);
  345. writeElement("End", $end);
  346. writeElement("MaxCount", $maxcount);
  347. writeCloseTag("Parameters");
  348.  
  349. // setup the query
  350. $orders = Mage::getModel('sales/order')->getCollection();
  351. $orders->addAttributeToSelect("*")
  352. ->getSelect()
  353. ->where("(updated_at > '$start' AND updated_at <= '$end' AND store_id = $storeId)")
  354. ->order('updated_at', 'asc');
  355.  
  356. // configure paging
  357. $orders->setCurPagE(1)
  358. ->setPageSize($maxcount)
  359. ->loadData();
  360.  
  361. writeStartTag("Orders");
  362.  
  363. $lastModified = null;
  364. $processedIds = "";
  365.  
  366. foreach ($orders as $order)
  367. {
  368. // keep track of the ids we've downloaded
  369. $lastModified = $order->getUpdatedAt();
  370.  
  371. if ($processedIds != "")
  372. {
  373. $processedIds .= ", ";
  374. }
  375. $processedIds .= $order->getEntityId();
  376.  
  377. WriteOrder($order);
  378. }
  379.  
  380. // if we processed some orders we may have to get some more
  381. if ($processedIds != "")
  382. {
  383. $orders = Mage::getModel('sales/order')->getCollection();
  384. $orders->addAttributeToSelect("*")->getSelect()->where("updated_at = '$lastModified' AND entity_id not in ($processedIds) AND store_id = $storeId");
  385.  
  386. foreach ($orders as $order)
  387. {
  388. WriteOrder($order);
  389. }
  390. }
  391.  
  392. writeCloseTag("Orders");
  393. }
  394.  
  395. // Output the order as xml
  396. function WriteOrder($order)
  397. {
  398. global $secure;
  399. writeStartTag("Order");
  400.  
  401. $incrementId = $order->getIncrementId();
  402.  
  403. $orderPrefix = '';
  404. $orderNumber = '';
  405. $orderPostfix = '';
  406. $ordernumberParts = '';
  407.  
  408. $numberArray = str_split($incrementId);
  409.  
  410. foreach($numberArray as $orderNumberPart)
  411. {
  412. if(!is_numeric($orderNumberPart) && $orderNumber == '')
  413. {
  414. $orderPrefix .= $orderNumberPart;
  415. }
  416. elseif(is_numeric($orderNumberPart) && $orderPostfix == '')
  417. {
  418. $orderNumber .= $orderNumberPart;
  419. }
  420. elseif($orderNumber != '')
  421. {
  422. $orderPostfix .= $orderNumberPart;
  423. }
  424. }
  425.  
  426. writeElement("OrderNumberPrefix", $orderPrefix);
  427. writeElement("OrderNumber", $orderNumber);
  428. writeElement("OrderNumberPostfix", $orderPostfix);
  429. writeElement("OrderDate", FormatDate($order->getCreatedAt()));
  430. writeElement("LastModified", FormatDate($order->getUpdatedAt()));
  431. writeElement("ShippingMethod", $order->getShippingDescription());
  432. writeElement("StatusCode", $order->getStatus());
  433. writeElement("CustomerID", $order->getCustomerId());
  434.  
  435. // check for order-level gift messages
  436. if ($order->getGiftMessageId())
  437. {
  438. $message = Mage::helper('giftmessage/message')->getGiftMessage($order->getGiftMessageId());
  439. $messageString = "Gift message for ". $message['recipient']. ": ". $message['message'];
  440.  
  441. writeStartTag("Notes");
  442. writeFullElement("Note", $messageString, array("public" => "true"));
  443. writeCloseTag("Notes");
  444. }
  445.  
  446. $address = $order->getBillingAddress();
  447. writeStartTag("BillingAddress");
  448. writeElement("FullName", $address->getName());
  449. writeElement("Company", $address->getCompany());
  450. writeElement("Street1", $address->getStreet(1));
  451. writeElement("Street2", $address->getStreet(2));
  452. writeElement("Street3", $address->getStreet(3));
  453. writeElement("City", $address->getCity());
  454. writeElement("State", $address->getRegionCode());
  455. writeElement("PostalCode", $address->getPostcode());
  456. writeElement("Country", $address->getCountryId());
  457. writeElement("Phone", $address->getTelephone());
  458. writeElement("Email", $order->getCustomerEmail());
  459. writeCloseTag("BillingAddress");
  460.  
  461.  
  462. $billFullName = $address->getName();
  463. $billStreet1 = $address->getStreet(1);
  464. $billCity = $address->getCity();
  465. $billZip = $address->getPostcode();
  466.  
  467. $address = $order->getShippingAddress();
  468. if (!$address)
  469. {
  470. // sometimes the shipping address isn't specified, so use billing
  471. $address = $order->getBillingAddress();
  472. }
  473.  
  474. writeStartTag("ShippingAddress");
  475. writeElement("FullName", $address->getName());
  476. writeElement("Company", $address->getCompany());
  477. writeElement("Street1", $address->getStreet(1));
  478. writeElement("Street2", $address->getStreet(2));
  479. writeElement("Street3", $address->getStreet(3));
  480. writeElement("City", $address->getCity());
  481. writeElement("State", $address->getRegionCode());
  482. writeElement("PostalCode", $address->getPostcode());
  483. writeElement("Country", $address->getCountryId());
  484. writeElement("Phone", $address->getTelephone());
  485.  
  486. // if the addressses appear to be the same, use customer email as shipping email too
  487. if ($address->getName() == $billFullName &&
  488. $address->getStreet(1) == $billStreet1 &&
  489. $address->getCity() == $billCity &&
  490. $address->getPostcode() == $billZip)
  491. {
  492. writeElement("Email", $order->getCustomerEmail());
  493. }
  494.  
  495. writeCloseTag("ShippingAddress");
  496.  
  497.  
  498. $payment = $order->getPayment();
  499.  
  500. // CC info
  501. if ($secure)
  502. {
  503. $cc_num = $payment->getCcNumber();
  504. }
  505. else
  506. {
  507. $cc_num = $payment->getCcLast4();
  508. if (!empty($cc_num))
  509. {
  510. $cc_num = '************'.$payment->getCcLast4();
  511. }
  512. }
  513. $cc_year = sprintf('%02u%s', $payment->getCcExpMonth(), substr($payment->getCcExpYear(), 2));
  514.  
  515.  
  516. writeStartTag("Payment");
  517. writeElement("Method", Mage::helper('payment')->getMethodInstance($payment->getMethod())->getTitle());
  518.  
  519. writeStartTag("CreditCard");
  520. writeElement("Type", $payment->getCcType());
  521. writeElement("Owner", $payment->getCcOwner());
  522. writeElement("Number", $cc_num);
  523. writeElement("Expires", $cc_year);
  524. writeCloseTag("CreditCard");
  525.  
  526. writeCloseTag("Payment");
  527.  
  528. WriteOrderItems($order->getAllItems());
  529.  
  530. WriteOrderTotals($order);
  531.  
  532. writeStartTag("Debug");
  533. writeElement("OrderID", $order->getEntityId());
  534. writeElement("OrderNumberPostfix", $orderPostfix);
  535. writeCloseTag("Debug");
  536.  
  537. writeCloseTag("Order");
  538. }
  539.  
  540. // writes a single order total
  541. function WriteOrderTotal($name, $value, $class, $impact = "add")
  542. {
  543. if ($value > 0)
  544. {
  545. writeFullElement("Total", $value, array("name" => $name, "class" => $class, "impact" => $impact));
  546. }
  547. }
  548.  
  549. // Write all totals lines for the order
  550. function WriteOrderTotals($order)
  551. {
  552. writeStartTag("Totals");
  553.  
  554. WriteOrderTotal("Order Subtotal", $order->getSubtotal(), "ot_subtotal", "none");
  555. WriteOrderTotal("Shipping and Handling", $order->getShippingAmount(), "shipping", "add");
  556.  
  557. if ($order->getTaxAmount() > 0)
  558. {
  559. WriteOrderTotal("Tax", $order->getTaxAmount(), "tax", "add");
  560. }
  561.  
  562. // Magento 1.4 started storing discounts as negative values
  563. if (MagentoVersionGreaterOrEqualTo('1.4.0') && $order->getDiscountAmount() < 0)
  564. {
  565. $couponcode = $order->getCouponCode();
  566. WriteOrderTotal("Discount ($couponcode)", -1 * $order->getDiscountAmount(), "discount", "subtract");
  567. }
  568.  
  569. if (!MagentoVersionGreaterOrEqualTo('1.4.0') && $order->getDiscountAmount() > 0)
  570. {
  571. $couponcode = $order->getCouponCode();
  572. WriteOrderTotal("Discount ($couponcode)", $order->getDiscountAmount(), "discount", "subtract");
  573. }
  574.  
  575. if ($order->getGiftcertAmount() > 0)
  576. {
  577. WriteOrderTotal("Gift Certificate", $order->getGiftcertAmount(), "giftcertificate", "subtract");
  578. }
  579.  
  580. if ($order->getAdjustmentPositive())
  581. {
  582. WriteOrderTotal("Adjustment Refund", $order->getAdjustmentPositive(), "refund", "subtract");
  583. }
  584.  
  585. if ($order->getAdjustmentNegative())
  586. {
  587. WriteOrderTotal("Adjustment Fee", $order->getAdjustmentPositive(), "fee", "add");
  588. }
  589.  
  590. WriteOrderTotal("Grand Total", $order->getGrandTotal(), "total", "none");
  591.  
  592. writeCloseTag("Totals");
  593. }
  594.  
  595. // Gets the price of an order item
  596. function getCalculationPrice($item)
  597. {
  598. if ($item instanceof Mage_Sales_Model_Order_Item)
  599. {
  600. if (MagentoVersionGreaterOrEqualTo('1.3.0'))
  601. {
  602. return $item->getPrice();
  603. }
  604. else
  605. {
  606. if ($item->hasCustomPrice())
  607. {
  608. return $item->getCustomPrice();
  609. }
  610. else if ($item->hasOriginalPrice())
  611. {
  612. return $item->getOriginalPrice();
  613. }
  614. }
  615. }
  616.  
  617. return 0;
  618. }
  619.  
  620. // Write XML for all products for the given order
  621. function WriteOrderItems($orderItems)
  622. {
  623. writeStartTag("Items");
  624.  
  625. $parentMap = Array();
  626.  
  627. // go through each item in the collection
  628. foreach ($orderItems as $item)
  629. {
  630. // keep track of item Id and types
  631. $parentMap[$item->getItemId()] = $item->getProductType();
  632.  
  633. // get the sku
  634. if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)
  635. {
  636. $sku = $item->getProductOptionByCode('simple_sku');
  637. }
  638. else
  639. {
  640. $sku = $item->getSku();
  641. }
  642.  
  643. // weights are handled differently if the item is a bundle or part of a bundle
  644. $weight = $item->getWeight();
  645. if ($item->getIsVirtual())
  646. {
  647. $weight = 0;
  648. }
  649.  
  650. if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE)
  651. {
  652. $name = $item->getName(). " (bundle)";
  653. $unitPrice = getCalculationPrice($item);
  654. }
  655. else
  656. {
  657. $name = $item->getName();
  658.  
  659. // if it's part of a bundle
  660. if (is_null($item->getParentItemId()))
  661. {
  662. $unitPrice = getCalculationPrice($item);
  663. }
  664. else
  665. {
  666. // need to see if the parent is a bundle or not
  667. $isBundle = ($parentMap[$item->getParentItemId()] == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE);
  668. if ($isBundle)
  669. {
  670. // it's a bundle member - price and weight come from the bundle definition itself
  671. $unitPrice = 0;
  672. $weight = 0;
  673. }
  674. else
  675. {
  676. // don't even want to include if the parent item is anything but a bundle
  677. continue;
  678. }
  679. }
  680. }
  681.  
  682. // Magento 1.4+ has Cost
  683. $unitCost = 0;
  684. if (MagentoVersionGreaterOrEqualTo('1.4.0') && $item->getBaseCost() > 0)
  685. {
  686. $unitCost = $item->getBaseCost();
  687. }
  688. else if (MagentoVersionGreaterOrEqualTo('1.3.0'))
  689. {
  690. // Magento 1.3 didn't seem to copy Cost to the item from the product
  691. // fallback to the Cost defined on the product.
  692.  
  693. $product = Mage::getModel('catalog/product');
  694. $productId = $item->getProductId();
  695. $product->load($productId);
  696.  
  697. if ($product->getCost() > 0)
  698. {
  699. $unitCost = $product->getCost();
  700. }
  701. }
  702.  
  703. writeStartTag("Item");
  704.  
  705. writeElement("ItemID", $item->getItemId());
  706. writeElement("ProductID", $item->getProductId());
  707. writeElement("Code", $sku);
  708. writeElement("SKU", $sku);
  709. writeElement("Name", $name);
  710. writeElement("Quantity", (int)$item->getQtyOrdered());
  711. writeElement("UnitPrice", $unitPrice);
  712. writeElement("UnitCost", $unitCost);
  713.  
  714. if (!$weight)
  715. {
  716. $weight = 0;
  717. }
  718. writeElement("Weight", $weight);
  719.  
  720.  
  721. writeStartTag("Attributes");
  722. $opt = $item->getProductOptions();
  723. if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)
  724. {
  725. if (is_array($opt) &&
  726. isset($opt['attributes_info']) &&
  727. is_array($opt['attributes_info']) &&
  728. is_array($opt['info_buyRequest']) &&
  729. is_array($opt['info_buyRequest']['super_attribute']))
  730. {
  731. $attr_id = $opt['info_buyRequest']['super_attribute'];
  732. reset($attr_id);
  733. foreach ($opt['attributes_info'] as $sub)
  734. {
  735. writeStartTag("Attribute");
  736. writeElement("Name", $sub['label']);
  737. writeElement("Value", $sub['value']);
  738. writeCloseTag("Attribute");
  739.  
  740. next($attr_id);
  741. }
  742. }
  743. }
  744.  
  745. if (is_array($opt) &&
  746. isset($opt['options']) &&
  747. is_array($opt['options']))
  748. {
  749. foreach ($opt['options'] as $sub)
  750. {
  751. writeStartTag("Attribute");
  752. writeElement("Name", $sub['label']);
  753. writeElement("Value", $sub['value']);
  754. writeCloseTag("Attribute");
  755. }
  756. }
  757.  
  758. // Order-item level Gift Messages are created as item attributes in ShipWorks
  759. if ($item->getGiftMessageId())
  760. {
  761. $message = Mage::helper('giftmessage/message')->getGiftMessage($item->getGiftMessageId());
  762.  
  763. // write the gift message as an attribute
  764. writeStartTag("Attribute");
  765. writeElement("Name", "Gift Message");
  766. writeelement("Value", $message['message']);
  767. writeCloseTag("Attribute");
  768.  
  769. // write the gift messgae recipient as an attribute
  770. writeStartTag("Attribute");
  771. writeElement("Name", "Gift Message, Recipient");
  772. writeelement("Value", $message['recipient']);
  773. writeCloseTag("Attribute");
  774. }
  775.  
  776.  
  777. // Uncomment the following lines to include a custom product attribute in the downloaded data.
  778. // These will appear as Order Item Attributes in ShipWorks.
  779. //$product = Mage::getModel('catalog/product');
  780. //$productId = $product->getIdBySku($sku);
  781. //$product->load($productId);
  782. //$value = $product->getAttributeText("attribute_code_here");
  783. //if ($value)
  784. //{
  785. // // write the gift message as an attribute
  786. // writeStartTag("Attribute");
  787. // writeElement("Name", "Attribute_title_here");
  788. // writeelement("Value", $value);
  789. // writeCloseTag("Attribute");
  790. //}
  791.  
  792. writeCloseTag("Attributes");
  793.  
  794. writeCloseTag("Item");
  795. }
  796.  
  797. writeCloseTag("Items");
  798. }
  799.  
  800. // Returns the status codes for the store
  801. function Action_GetStatusCodes()
  802. {
  803. writeStartTag("StatusCodes");
  804.  
  805. $statuses_node = Mage::getConfig()->getNode('global/sales/order/statuses');
  806.  
  807. foreach ($statuses_node->children() as $status)
  808. {
  809. writeStartTag("StatusCode");
  810. writeElement("Code", $status->getName());
  811. writeElement("Name", $status->label);
  812. writeCloseTag("StatusCode");
  813. }
  814.  
  815. writeCloseTag("StatusCodes");
  816. }
  817.  
  818. // Update the status of an order
  819. function Action_UpdateOrder()
  820. {
  821. // gather paramtetes
  822. if (!isset($_REQUEST['order']) ||
  823. !isset($_REQUEST['command']) || !isset($_REQUEST['comments']))
  824. {
  825. outputError(40, "Not all parameters supplied.");
  826. return;
  827. }
  828.  
  829. // newer version of ShipWorks, pull the entity id
  830. $orderID = (int)$_REQUEST['order'];
  831. $order = Mage::getModel('sales/order')->load($orderID);
  832.  
  833. $command = (string) $_REQUEST['command'];
  834. $comments = $_REQUEST['comments'];
  835. $tracking = $_REQUEST['tracking'];
  836. $carrierData = $_REQUEST['carrier'];
  837.  
  838. ExecuteOrderCommand($order, $command, $comments, $carrierData, $tracking);
  839. }
  840.  
  841. // Takes the actions necessary to get an order to Complete
  842. function CompleteOrder($order, $comments, $carrierData, $tracking)
  843. {
  844. //Check to see if the order already shipments
  845. if($order->hasShipments())
  846. {
  847. //Order already has shipments
  848. $existingShipments = $order->getShipmentsCollection();
  849.  
  850. //Grab the first shipment to add tracking to
  851. $shipment = $existingShipments->getFirstItem();
  852. }
  853. else
  854. {
  855. //Order has no shipments
  856. $shipment = $order->prepareShipment();
  857. $shipment->register();
  858. }
  859.  
  860. //Do Shipment Stuff
  861. if ($shipment)
  862. {
  863. $shipment->addComment($comments, false);
  864. $order->setIsInProcess(true);
  865.  
  866. // add tracking info if it was supplied
  867. if (strlen($tracking) > 0)
  868. {
  869. $track = Mage::getModel('sales/order_shipment_track')->setNumber($tracking);
  870.  
  871. # carrier data is of the format code|title
  872. $carrierData = preg_split("[\|]", $carrierData);
  873. $track->setCarrierCode($carrierData[0]);
  874. $track->setTitle($carrierData[1]);
  875.  
  876. $shipment->addTrack($track);
  877. }
  878.  
  879. $transactionSave = Mage::getModel('core/resource_transaction')
  880. ->addObject($shipment)
  881. ->addObject($shipment->getOrder())
  882. ->save();
  883.  
  884. // send the email if it's requested
  885. if (isset($_REQUEST['sendemail']) && $_REQUEST['sendemail'] == '1')
  886. {
  887. $shipment->sendEmail(true);
  888. }
  889. }
  890.  
  891. // invoice the order
  892. if ($order->hasInvoices())
  893. {
  894. // select the last invoice to attach the note to
  895. $invoice = $order->getInvoiceCollection()->getLastItem();
  896. }
  897. else
  898. {
  899. // prepare a brand-new invoice
  900. $invoice = $order->prepareInvoice();
  901. $invoice->register();
  902. }
  903.  
  904. // capture the invoice if possible
  905. if ($invoice->canCapture())
  906. {
  907. $invoice->Capture();
  908. }
  909.  
  910. // some magento versions prevent multiple pay() calls from have impact,
  911. // but others don't. If pay is called multiple times, Order.Total Paid is off.
  912. if ($invoice->getState() != Mage_Sales_Model_Order_Invoice::STATE_PAID)
  913. {
  914. $invoice->pay();
  915. }
  916.  
  917. // set the comment
  918. $invoice->addComment($comments);
  919.  
  920. // save the new invoice
  921. $transactionSave = Mage::getModel('core/resource_transaction')
  922. ->addObject($invoice)
  923. ->addObject($invoice->getOrder());
  924. $transactionSave->save();
  925.  
  926. // Saving will force magento to move the state/status
  927. $order->save();
  928. }
  929.  
  930.  
  931. // Changes the status of an order
  932. function ExecuteOrderCommand($order, $command, $comments, $carrierData, $tracking)
  933. {
  934. try
  935. {
  936. // to change statuses, we need to unhold if necessary
  937. if ($order->canUnhold())
  938. {
  939. $order->unhold();
  940. $order->save();
  941. }
  942.  
  943. switch (strtolower($command))
  944. {
  945. case "complete":
  946. CompleteOrder($order, $comments, $carrierData, $tracking);
  947. break;
  948. case "cancel":
  949. $order->cancel();
  950. $order->addStatusToHistory($order->getStatus(), $comments);
  951. $order->save();
  952. break;
  953. case "hold":
  954. $order->hold();
  955. $order->addStatusToHistory($order->getStatus(), $comments);
  956. $order->save();
  957. break;
  958. default:
  959. outputError(80, "Unknown order command '$command'.");
  960. break;
  961. }
  962.  
  963. writeStartTag("Debug");
  964. writeElement("OrderStatus", $order->getStatus());
  965. writeCloseTag("Debug");
  966. }
  967. catch (Exception $ex)
  968. {
  969. outputError(90, "Error Executing Command. ". $ex->getMessage());
  970. }
  971. }
  972.  
  973. // Converts a sql data string to xml date format
  974. function FormatDate($dateSql)
  975. {
  976. $pattern = "/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/i";
  977.  
  978. if (preg_match($pattern, $dateSql, $dt))
  979. {
  980. $dateUnix = mktime($dt[4], $dt[5], $dt[6], $dt[2], $dt[3], $dt[1]);
  981. return gmdate("Y-m-d\TH:i:s", $dateUnix);
  982. }
  983.  
  984. return $dateSql;
  985. }
  986.  
  987. // end output
  988. ob_end_flush();
  989. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement