PageRenderTime 35ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wp-e-commerce/wpsc-shipping/ups_20.php

https://github.com/AaronFernandes/aquestionof
PHP | 899 lines | 697 code | 90 blank | 112 comment | 112 complexity | 8723222851c86b45ef42ff5b8916fe7d MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  1. <?php
  2. /* Author : Greg Gullett and Instinct.co.uk
  3. * SVN : UPS Trunk :
  4. * Version : 1.1.0 : December 21, 2010
  5. */
  6. class ash_ups {
  7. var $internal_name, $name;
  8. var $service_url = "";
  9. var $Services = "";
  10. var $singular_shipping = FALSE;
  11. var $shipment;
  12. function ash_ups() {
  13. global $wpec_ash;
  14. $this->internal_name = "ups";
  15. $this->name="UPS";
  16. $this->is_external=true;
  17. $this->requires_curl=true;
  18. $this->requires_weight=true;
  19. $this->needs_zipcode=true;
  20. $this->_setServiceURL();
  21. $this->_includeUPSData();
  22. $this->shipment = $wpec_ash->get_shipment();
  23. return true;
  24. }
  25. function __autoload($name){
  26. include("../wpsc-includes/shipping.helper.php");
  27. }
  28. function getId() {
  29. // return $this->usps_id;
  30. }
  31. function setId($id) {
  32. // $usps_id = $id;
  33. // return true;
  34. }
  35. private function _setServiceURL(){
  36. global $wpdb;
  37. $wpsc_ups_settings = get_option("wpsc_ups_settings");
  38. $wpsc_ups_environment = (array_key_exists("upsenvironment",(array)$wpsc_ups_settings)) ? $wpsc_ups_settings["upsenvironment"] : "1";
  39. if ($wpsc_ups_environment == "1"){
  40. $this->service_url = "https://wwwcie.ups.com/ups.app/xml/Rate";
  41. }else{
  42. $this->service_url = "https://www.ups.com/ups.app/xml/Rate";
  43. }
  44. }
  45. function getName() {
  46. return $this->name;
  47. }
  48. function getInternalName() {
  49. return $this->internal_name;
  50. }
  51. private function _includeUPSData(){
  52. $this->drop_types = array(
  53. "01"=>"Daily Pickup",
  54. "03"=>"Customer Counter",
  55. "06"=>"One Time Pickup",
  56. "07"=>"On Call Air",
  57. "19"=>"Letter Center",
  58. "20"=>"Air Service Center",
  59. "11"=>"Suggested Retail Rates (Advanced Config)"
  60. );
  61. $this->cust_types = array(
  62. "01" => "Daily Pickup, with UPS Account",
  63. "03" => "No Daily Pickup, with No or Other Account",
  64. "04" => "Retail Outlet (Only US origin shipments)"
  65. );
  66. $this->Services = array(
  67. "14" => "Next Day Air Early AM",
  68. "01" => "Next Day Air",
  69. "13" => "Next Day Air Saver",
  70. "59" => "2nd Day Air AM",
  71. "02" => "2nd Day Air",
  72. "12" => "3 Day Select",
  73. "03" => "Ground",
  74. "11" => "Standard",
  75. "07" => "Worldwide Express",
  76. "54" => "Worldwide Express Plus",
  77. "08" => "Worldwide Expedited",
  78. "65" => "Saver",
  79. "82" => "UPS Today Standard",
  80. "83" => "UPS Today Dedicated Courier",
  81. "84" => "UPS Today Intercity",
  82. "85" => "UPS Today Express",
  83. "86" => "UPS Today Express Saver"
  84. );
  85. }
  86. function getForm(){
  87. if (!isset($this->Services)){
  88. $this->_includeUPSData();
  89. }
  90. //__('Your Packaging', 'wpsc'); <-- use to translate
  91. $wpsc_ups_settings = get_option("wpsc_ups_settings");
  92. $wpsc_ups_services = get_option("wpsc_ups_services");
  93. // Defined on page 41 in UPS API documentation RSS_Tool_06_10_09.pdf
  94. /*$packaging_options['00'] = __('**UNKNOWN**', 'wpsc');*/
  95. $packaging_options['01'] = __('UPS Letter', 'wpsc');
  96. $packaging_options['02'] = __('Your Packaging', 'wpsc');
  97. $packaging_options['03'] = __('UPS Tube', 'wpsc');
  98. $packaging_options['04'] = __('UPS Pak', 'wpsc');
  99. $packaging_options['21'] = __('UPS Express Box', 'wpsc');
  100. $packaging_options['2a'] = __('UPS Express Box - Small', 'wpsc');
  101. $packaging_options['2b'] = __('UPS Express Box - Medium', 'wpsc');
  102. $packaging_options['2c'] = __('UPS Express Box - Large', 'wpsc');
  103. $output = "<tr>\n\r";
  104. $output .= " <td>".__('Destination Type', 'wpsc')."</td>\n\r";
  105. $output .= " <td>\n\r";
  106. // Default is Residential
  107. $checked[0] = "checked='checked'";
  108. $checked[1] = "";
  109. if ($wpsc_ups_settings['49_residential'] == "2"){
  110. $checked[0] = "";
  111. $checked[1] = "checked='checked'";
  112. }
  113. $output .= " <label><input type='radio' {$checked[0]} value='1' name='wpsc_ups_settings[49_residential]'/>".__('Residential Address', 'wpsc')."</label><br />\n\r";
  114. $output .= " <label><input type='radio' {$checked[1]} value='2' name='wpsc_ups_settings[49_residential]'/>".__('Commercial Address', 'wpsc')."</label>\n\r";
  115. $output .= " </td>\n\r";
  116. $output .= "</tr>\n\r";
  117. $output .= "<tr>\n\r";
  118. // Dropoff Type
  119. $output .= " <td>".__('Dropoff Type', 'wpsc')."</td>\n\r";
  120. $output .= " <td>\n\r";
  121. $output .= ("<script type=\"text/javascript\">
  122. function checkDropValue(){
  123. var val = jQuery(\"#drop_type option:selected\").val();
  124. if (val == \"11\"){
  125. jQuery(\"#cust_type\").removeAttr(\"disabled\");
  126. }else{
  127. jQuery(\"#cust_type\").attr(\"disabled\", true);
  128. }
  129. }
  130. </script>");
  131. $output .= " <select id='drop_type' name='wpsc_ups_settings[DropoffType]' onChange='checkDropValue()' >\n\r";
  132. $sel2_drop = "";
  133. if (empty($wpsc_ups_settings['DropoffType'])){
  134. $sel2_drop = "01";
  135. }else{ $sel2_drop = $wpsc_ups_settings['DropoffType']; }
  136. foreach(array_keys((array)$this->drop_types) as $dkey){
  137. $sel = "";
  138. if ($sel2_drop == $dkey){
  139. $sel = 'selected="selected"';
  140. }
  141. $output .= " <option value=\"".$dkey."\" ".$sel." >".$this->drop_types[$dkey]."</option>\n\r";
  142. }
  143. $output .= " </select>\n\r";
  144. $output .= " </td>\n\r";
  145. $output .= "</tr>\n\r";
  146. $cust = "disabled='true'";
  147. if ($wpsc_ups_settings['DropoffType'] == "11"){
  148. $cust = "";
  149. }
  150. // Customer Type
  151. $output .= " <td>".__('Customer Type', 'wpsc')."</td>\n\r";
  152. $output .= " <td>\n\r";
  153. $output .= " <select id='cust_type' name='wpsc_ups_settings[CustomerType]' ".$cust." >\n\r";
  154. $sel3_drop = "";
  155. if (empty($wpsc_ups_settings['CustomerType'])){
  156. $sel3_drop = "01";
  157. }else{ $sel3_drop = $wpsc_ups_settings['CustomerType']; }
  158. foreach(array_keys($this->cust_types) as $dkey){
  159. $sel = "";
  160. if ($sel3_drop == $dkey){
  161. $sel = 'selected="selected"';
  162. }
  163. $output .= " <option value=\"".$dkey."\" ".$sel." >".$this->cust_types[$dkey]."</option>\n\r";
  164. }
  165. $output .= " </select>\n\r";
  166. $output .= " </td>\n\r";
  167. $output .= "</tr>\n\r";
  168. // Packaging Config
  169. $output .= "<tr>\n\r";
  170. $output .= " <td>".__('Packaging', 'wpsc')."</td>\n\r";
  171. $output .= " <td>\n\r";
  172. $output .= " <select name='wpsc_ups_settings[48_container]'>\n\r";
  173. foreach($packaging_options as $key => $name) {
  174. $selected = '';
  175. if($key == $wpsc_ups_settings['48_container']) {
  176. $selected = "selected='true' ";
  177. }
  178. $output .= " <option value='{$key}' {$selected}>{$name}</option>\n\r";
  179. }
  180. $output .= " </select>\n\r";
  181. $output .= " </td>\n\r";
  182. $output .= "</tr>\n\r";
  183. $selected_env = $wpsc_ups_settings['upsenvironment'];
  184. if ($selected_env == "1"){
  185. $env_test = "checked=\"checked\"";
  186. }
  187. $output .= ("
  188. <tr>
  189. <td><label for=\"ups_env_test\" >".__('Use Testing Environment', 'wpsc')."</label></td>
  190. <td>
  191. <input type=\"checkbox\" id=\"ups_env_test\" name=\"wpsc_ups_settings[upsenvironment]\" value=\"1\" ".$env_test." /><br />
  192. </td>
  193. </tr>
  194. ");
  195. $selected_negotiated_rate = $wpsc_ups_settings['ups_negotiated_rates'];
  196. $negotiated_rates = "";
  197. if ($selected_negotiated_rate == "1"){
  198. $negotiated_rates = "checked=\"checked\"";
  199. }
  200. $output .= ("
  201. <tr>
  202. <td><label for=\"ups_negotiated_rates\" >".__('Show UPS negotiated rates', 'wpsc')." *</label></td>
  203. <td>
  204. <input type=\"checkbox\" id=\"ups_negotiated_rates\" name=\"wpsc_ups_settings[ups_negotiated_rates]\" value=\"1\" ".$negotiated_rates." /><br />
  205. </td>
  206. </tr>
  207. ");
  208. $insured_shipment = "";
  209. if ($wpsc_ups_settings['insured_shipment'] == "1"){
  210. $insured_shipment = "checked=\"checked\"";
  211. }
  212. $output .= ("
  213. <tr>
  214. <td><label for=\"ups_insured_shipment\" >".__('Insure shipment against cart total', 'wpsc')." *</label></td>
  215. <td>
  216. <input type=\"checkbox\" id=\"ups_insured_shipment\" name=\"wpsc_ups_settings[insured_shipment]\" value=\"1\" ".$insured_shipment." /><br />
  217. </td>
  218. </tr>
  219. ");
  220. $singular_shipping = "";
  221. if ($wpsc_ups_settings['singular_shipping'] == "1"){
  222. $singular_shipping = "checked=\"checked\"";
  223. }
  224. $output .= ("
  225. <tr>
  226. <td><label for=\"ups_singular_shipping\" >".__('Singular Shipping', 'wpsc')." *</label></td>
  227. <td>
  228. <input type=\"checkbox\" id=\"ups_singular_shipping\" name=\"wpsc_ups_settings[singular_shipping]\" value=\"1\" ".$singular_shipping." /><br />
  229. ".__('Rate each quantity of items in a cart as its own package using dimensions on product')."
  230. </td>
  231. </tr>
  232. ");
  233. $output .= ("
  234. <tr>
  235. <td>
  236. ".__('UPS Preferred Services', 'wpsc')."
  237. </td>
  238. <td>
  239. <div id=\"resizeable\" class=\"ui-widget-content multiple-select\">");
  240. ksort($this->Services);
  241. $first=false;
  242. foreach(array_keys($this->Services) as $service){
  243. $checked = "";
  244. if(is_array($wpsc_ups_services)){
  245. if ((array_search($service,$wpsc_ups_services) !== false)){
  246. $checked = "checked=\"checked\"";
  247. }
  248. }
  249. $output .= ("<input type=\"checkbox\" id=\"wps_ups_srv_$service\" name=\"wpsc_ups_services[]\" value=\"$service\" $checked />
  250. <label for=\"wps_ups_srv_$service\">".$this->Services[$service]."</label>
  251. <br />");
  252. }
  253. $output .= (" </div>
  254. <br />
  255. -Note: ".__('All services used if no services selected','wpsc')."
  256. </td>
  257. </tr>");
  258. $output .= ("<tr>
  259. <td>".__('UPS Account #', 'wpsc')." *:</td>
  260. <td>
  261. <input type=\"text\" name='wpsc_ups_settings[upsaccount]' value=\"".$wpsc_ups_settings['upsaccount']."\" />
  262. </td>
  263. </tr>");
  264. $output .= ("<tr>
  265. <td>".__('UPS Username', 'wpsc')." :</td>
  266. <td>
  267. <input type=\"text\" name='wpsc_ups_settings[upsusername]' value=\"".base64_decode($wpsc_ups_settings['upsusername'])."\" />
  268. </td>
  269. </tr>");
  270. $output .= ("<tr>
  271. <td>".__('UPS Password', 'wpsc')." :</td>
  272. <td>
  273. <input type=\"password\" name='wpsc_ups_settings[upspassword]' value=\"".base64_decode($wpsc_ups_settings['upspassword'])."\" />
  274. </td>
  275. </tr>");
  276. $output .= ("<tr>
  277. <td>".__('UPS XML API Key', 'wpsc')." :</td>
  278. <td>
  279. <input type=\"text\" name='wpsc_ups_settings[upsid]' value=\"".base64_decode($wpsc_ups_settings['upsid'])."\" />
  280. <br />
  281. ".__('Don\'t have an API login/ID ?', 'wpsc')."
  282. <a href=\"https://www.ups.com/upsdeveloperkit?loc=en_US\" target=\"_blank\">".__('Click Here','wpsc')."</a>.
  283. <br />
  284. ".__('* For Negotiated rates, you must enter a UPS account number and select "Show UPS negotiated rates" ', 'wpsc')."
  285. </td>
  286. </tr>");
  287. // End new Code
  288. return $output;
  289. }
  290. function submit_form() {
  291. /* This function is called when the user hit "submit" in the
  292. * UPS settings area under Shipping to update the setttings.
  293. */
  294. if (isset( $_POST['wpsc_ups_settings'] ) && !empty( $_POST['wpsc_ups_settings'] ) ) {
  295. $wpsc_ups_services = $_POST['wpsc_ups_services'];
  296. update_option('wpsc_ups_services',$wpsc_ups_services);
  297. $temp = $_POST['wpsc_ups_settings'];
  298. // base64_encode the information so it isnt stored as plaintext.
  299. // base64 is by no means secure but without knowing if the server
  300. // has mcrypt installed what can you do really?
  301. $temp['upsusername'] = base64_encode($temp['upsusername']);
  302. $temp['upspassword'] = base64_encode($temp['upspassword']);
  303. $temp['upsid'] = base64_encode($temp['upsid']);
  304. update_option('wpsc_ups_settings', $temp);
  305. }
  306. return true;
  307. }
  308. function array2xml($data){
  309. $xml = "";
  310. if (is_array($data)){
  311. foreach($data as $key=>$value){
  312. //if(empty($value)){
  313. // $xml .= "<".trim($key)." />\n";
  314. //}else{
  315. $xml .= "<".trim($key).">\n";
  316. $xml .= $this->array2xml($value);
  317. $xml .= "</".trim($key).">\n";
  318. // }
  319. }
  320. }else if(is_bool($data)){
  321. if($data){$xml = "true\n";}
  322. else { $xml = "false\n"; }
  323. }else{
  324. $xml = trim($data)."\n";
  325. }
  326. return $xml;
  327. }
  328. private function _is_large(&$pack ,$package){
  329. $maximum = 165; // in inches
  330. $large_floor = 130; // in inches
  331. $calc_total = ((2 * $package->width)+(2 * $package->height));
  332. if ($calc_total >= $maximum){
  333. throw new Exception("Package dimensions exceed non-freight limits");
  334. }elseif($calc_total > $large_floor){
  335. $pack["LargePackageIndicator"] = "";
  336. }
  337. }
  338. private function _insured_value(&$pack, $package, $args){
  339. $monetary_value = $package->value;
  340. if ($package->insurance === TRUE){
  341. if ($package->insured_amount){
  342. $monetary_value = $package->insured_amount;
  343. }
  344. $pack["PackageServiceOptions"]["InsuredValue"] = array(
  345. "CurrencyCode" => $args["currency"],
  346. "MonetaryValue" => $package->insured_amount
  347. );
  348. }
  349. }
  350. private function _declared_value(&$pack, $package, $args){
  351. $pack["PackageServiceOptions"]["DeclaredValue"] = array(
  352. "CurrencyCode" => $args["currency"],
  353. "MonetaryValue" => $args["cart_total"]
  354. );
  355. }
  356. private function _build_shipment(&$Shipment, $args){
  357. $cart_shipment = $this->shipment;
  358. foreach($cart_shipment->packages as $package){
  359. $pack = array(
  360. "PackagingType" => array(
  361. "Code"=>"02"
  362. ),
  363. "Dimensions" => array(
  364. "UnitOfMeasurement" => array(
  365. "Code" => "IN"
  366. ),
  367. "Length" => $package->length,
  368. "Width" => $package->width,
  369. "Height" => $package->height
  370. ),
  371. "PackageWeight"=>array(
  372. "UnitOfMeasurement"=>array(
  373. "Code" => "LBS"
  374. ),
  375. "Weight" => $package->weight
  376. )
  377. ); // End Package
  378. // handle if the package is "large" or not (UPS standard)
  379. $this->_is_large($pack, $package);
  380. $this->_insured_value($pack, $package, $args);
  381. $this->_declared_value($pack, $package, $args);
  382. $Shipment .= $this->array2xml(array("Package"=>$pack));
  383. } // End for each package in shipment
  384. }
  385. private function _buildRateRequest($args){
  386. // Vars is an array
  387. // $RateRequest, $RatePackage, $RateCustomPackage, $RateRequestEnd
  388. // Are defined in ups_data.php that is included below if not
  389. // done so by instantiating class ... shouldnt ever need to
  390. // Always start of with this, it includes the auth block
  391. $REQUEST = "<?xml version=\"1.0\"?>\n
  392. <AccessRequest xml:lang=\"en-US\">\n";
  393. $access = array(
  394. "AccessLicenseNumber"=>base64_decode($args['api_id']), // UPS API ID#
  395. "UserId" =>base64_decode($args['username']), // UPS API Username
  396. "Password" =>base64_decode($args['password']) // UPS API Password
  397. );
  398. $REQUEST .= $this->array2xml($access);
  399. $REQUEST .= "</AccessRequest>\n";
  400. $REQUEST .= "<RatingServiceSelectionRequest xml:lang=\"en-US\">\n";
  401. // By Default we will shop. Shop when you do not have a service type
  402. // and you want to get a set of services and rates back!
  403. $RequestType = "Shop";
  404. // If service type is set we cannot shop so instead we Rate!
  405. if (isset($args["service"])){
  406. $RequestType = "Rate";
  407. }
  408. $RatingServiceRequest = array(
  409. "Request"=>array(
  410. "TransactionReference"=>array(
  411. "CustomerContext"=>"Rate Request",
  412. "XpciVersion"=>"1.0001"
  413. ),
  414. "RequestAction"=>"Rate",
  415. "RequestOption"=>$RequestType
  416. )
  417. );
  418. // Set the dropoff code
  419. $dropCode = (array_key_exists('DropoffType',$args)) ? $args['DropoffType'] : '01';
  420. $PickupType = array("PickupType"=>array(
  421. "Code"=>$dropCode
  422. ));
  423. $REQUEST .= $this->array2xml($PickupType);
  424. if ($dropCode == "11" && $args['shipr_ccode'] == "US"){
  425. // Set the request code
  426. $CustCode = (array_key_exists('CustomerType',$args)) ? $args['CustomerType'] : '01';
  427. $CustomerType = array("CustomerClassification"=>array(
  428. "Code"=>$CustCode
  429. ));
  430. $REQUEST .= $this->array2xml($CustomerType);
  431. }
  432. // Set up Shipment Node
  433. $Shipment = "";
  434. // Shipper Address (billing)
  435. $Shipper = array(
  436. "Address"=>array(
  437. "StateProvinceCode"=>$args['shipr_state'],
  438. "PostalCode"=>$args['shipr_pcode'], // The shipper Postal Code
  439. "CountryCode"=>$args['shipr_ccode']
  440. ));
  441. // Negotiated Rates
  442. if (array_key_exists('negotiated_rates', $args) ){
  443. if ($args['negotiated_rates'] == '1' && !empty($args['account_number'])){
  444. $Shipper["ShipperNumber"] = $args['account_number'];
  445. }
  446. }
  447. // If the city is configured use it
  448. if (array_key_exists('shipr_city', $args)){
  449. if (!empty($args['shipr_city'])){
  450. $Shipper["Address"]["City"] = $args["shipr_city"];
  451. }
  452. }
  453. $Shipment .= $this->array2xml(array("Shipper"=>$Shipper));
  454. // The physical address the shipment is from (normally the same as billing)
  455. $ShipFrom=array(
  456. "Address"=>array(
  457. "StateProvinceCode"=>$args['shipf_state'],
  458. "PostalCode"=>$args['shipf_pcode'], // The shipper Postal Code
  459. "CountryCode"=>$args['shipf_ccode']
  460. ));
  461. // If the city is configured use it
  462. if (array_key_exists('shipf_city', $args)){
  463. if (!empty($args['shipf_city'])){
  464. $ShipFrom["Address"]["City"] = $args["shipf_city"];
  465. }
  466. }
  467. $Shipment .= $this->array2xml(array("ShipFrom"=>$ShipFrom));
  468. $ShipTo= array(
  469. "Address"=>array(
  470. "StateProvinceCode"=>$args['dest_state'], // The Destination State
  471. "PostalCode"=>$args['dest_pcode'], // The Destination Postal Code
  472. "CountryCode"=>$args['dest_ccode'], // The Destination Country
  473. //"ResidentialAddress"=>"1"
  474. ));
  475. if ($args['residential'] == '1'){ //ResidentialAddressIndicator orig - Indicator
  476. $ShipTo["Address"]["ResidentialAddressIndicator"] = "1";
  477. }
  478. $Shipment .= $this->array2xml(array("ShipTo"=>$ShipTo));
  479. // If there is a specific service being requested then
  480. // we want to pass the service into the XML
  481. if (isset($args["service"])){
  482. $Shipment .= array("Service"=>array("Code" =>$args['service']));
  483. }
  484. // Include this only if you want negotiated rates
  485. if (array_key_exists('negotiated_rates', $args) ){
  486. if ($args['negotiated_rates'] == "1"){
  487. $Shipment .=array("RateInformation"=>array("NegotiatedRatesIndicator" => ""));
  488. }
  489. }
  490. if ((boolean)$args["singular_shipping"]){
  491. $this->_build_shipment($Shipment,$args);
  492. }else{
  493. $package = array("Package"=> array(
  494. "PackagingType"=>array("Code"=>$args['packaging']),
  495. "PackageWeight"=>array(
  496. "UnitOfMeasurement"=>array("Code"=>$args['units']),
  497. "Weight" => $args["weight"]
  498. )
  499. ));
  500. if ((boolean)$args["insured_shipment"]){
  501. $package["PackageServiceOptions"] = array(
  502. "InsuredValue"=> array(
  503. "CurrencyCode"=>$args["currency"],
  504. "MonetaryValue"=>$args["cart_total"]
  505. )
  506. );
  507. }
  508. $Shipment .= $this->array2xml($package);
  509. }
  510. // Set the structure for the Shipment Node
  511. $RatingServiceRequest["Shipment"] = $Shipment;
  512. $REQUEST .= $this->array2xml($RatingServiceRequest);
  513. $REQUEST .= "</RatingServiceSelectionRequest>";
  514. // Return the final XML document as a string to be used by _makeRateRequest
  515. return $REQUEST;
  516. }
  517. private function _makeRateRequest($message){
  518. // Make the XML request to the server and retrieve the response
  519. $ch = curl_init();
  520. curl_setopt($ch, CURLOPT_URL,$this->service_url);
  521. curl_setopt($ch, CURLOPT_POST, 1);
  522. curl_setopt($ch, CURLOPT_POSTFIELDS,
  523. $message);
  524. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  525. $data = curl_exec($ch);
  526. curl_close($ch);
  527. return $data;
  528. }
  529. public function futureDate($interval){
  530. //Wed Apr 7
  531. date_default_timezone_set('America/Los_Angeles');
  532. $timestamp = date('c');
  533. $hour = date("G");
  534. if ((int)$hour >= 3){
  535. $interval += 1;
  536. }
  537. $date = date("Y-m-d");
  538. $interval = " +$interval day";
  539. $final = date("D M j",strtotime(date("Y-m-d", strtotime($date)).$interval));
  540. $test = explode(" ",$final);
  541. if ($test[0] == "Sat"){
  542. return $this->futureDate($interval+2);
  543. }else if($test[0] == "Sun"){
  544. return $this->futureDate($interval+1);
  545. }
  546. return $final;
  547. }
  548. private function _parseQuote($raw){
  549. global $wpdb;
  550. $config = get_option('wpsc_ups_settings');
  551. $debug = (array_key_exists('upsenvironment', $config)) ? $config['upsenvironment'] : "";
  552. $rate_table = array();
  553. $wpsc_ups_services = get_option("wpsc_ups_services");
  554. // Initialize a DOM using the XML passed in!
  555. $objDOM = new DOMDocument();
  556. if($raw != '') {
  557. $objDOM->loadXML($raw);
  558. // Get the <ResponseStatusCode> from the UPS XML
  559. $getStatusNode = $objDOM->getElementsByTagName("ResponseStatusCode");
  560. // Get the value of the error code, 1 == No Error, 0 == Error !!!
  561. $statusCode = $getStatusNode->item(0)->nodeValue;
  562. if ($statusCode == "0"){
  563. // Usually I dont leave debug stuff in but this is handy stuff!!
  564. // it will print out the error message returned by UPS!
  565. if ($debug == "1"){
  566. $getErrorDescNode = $objDOM->getElementsByTagName("ErrorDescription");
  567. $ErrorDesc = $getErrorDescNode->item(0)->nodeValue;
  568. echo "<br />Error : ".$ErrorDesc."<br />";
  569. }
  570. return false;
  571. }else{
  572. $RateBlocks = $objDOM->getElementsByTagName("RatedShipment");
  573. foreach($RateBlocks as $rate_block){
  574. // Get the <Service> Node from the XML chunk
  575. $getServiceNode = $rate_block->getElementsByTagName("Service");
  576. $serviceNode = $getServiceNode->item(0);
  577. // Get the <Code> Node from the <Service> chunk
  578. $getServiceCodeNode = $serviceNode->getElementsByTagName("Code");
  579. // Get the value from <Code>
  580. $serviceCode = $getServiceCodeNode->item(0)->nodeValue;
  581. $go = true;
  582. $price = "";
  583. $time = "";
  584. //if (array_key_exists('ups_negotiated_rates', $config)){
  585. $getNegotiatedRateNode = $rate_block->getElementsByTagName("NegotiatedRates");
  586. if ($getNegotiatedRateNode){
  587. $negotiatedRateNode = $getNegotiatedRateNode->item(0);
  588. if ($negotiatedRateNode){
  589. $getNetSummaryNode = $negotiatedRateNode->getElementsByTagName("NetSummaryCharges");
  590. $netSummaryNode = $getNetSummaryNode->item(0);
  591. $getGrandTotalNode = $netSummaryNode->getElementsByTagName("GrandTotal");
  592. $grandTotalNode = $getGrandTotalNode->item(0);
  593. $getMonetaryNode = $grandTotalNode->getElementsByTagName("MonetaryValue");
  594. $monetaryNode = $getMonetaryNode->item(0)->nodeValue;
  595. if (!empty($monetaryNode)){
  596. $go = false;
  597. $price = $monetaryNode;
  598. }
  599. }
  600. }
  601. // Get the <TotalCharges> Node from the XML chunk
  602. $getChargeNodes = $rate_block->getElementsByTagName("TotalCharges");
  603. $chargeNode = $getChargeNodes->item(0);
  604. /*
  605. $getDeliveryNode = $rate_block->getElementsByTagName("GuaranteedDaysToDelivery");
  606. $deliveryDays = $getDeliveryNode->item(0)->nodeValue;
  607. if ($deliveryDays){
  608. $time = $this->futureDate($deliveryDays);
  609. }else{
  610. $time = $this->futureDate(6);
  611. }
  612. */
  613. // Get the <CurrencyCode> from the <TotalCharge> chunk
  614. $getCurrNode= $chargeNode->getElementsByTagName("CurrencyCode");
  615. // Get the value of <CurrencyCode>
  616. $currCode = $getCurrNode->item(0)->nodeValue;
  617. if ($go == true){
  618. // Get the <MonetaryValue> from the <TotalCharge> chunk
  619. $getMonetaryNode= $chargeNode->getElementsByTagName("MonetaryValue");
  620. // Get the value of <MonetaryValue>
  621. $price = $getMonetaryNode->item(0)->nodeValue;
  622. }
  623. // If there are any services specified in the admin area
  624. // this will check that list and pass on adding any services that
  625. // are not explicitly defined.
  626. if (!empty($wpsc_ups_services)){
  627. if (is_array($wpsc_ups_services)){
  628. if (array_search($serviceCode, (array)$wpsc_ups_services) === false){
  629. continue;
  630. }
  631. }else if ($wpsc_ups_services != $serviceCode){
  632. continue;
  633. }
  634. }
  635. if(array_key_exists($serviceCode,(array)$this->Services)){
  636. $rate_table[$this->Services[$serviceCode]] = array($currCode,$price);
  637. }
  638. } // End foreach rated shipment block
  639. }
  640. }
  641. // Revers sort the rate selection so it is cheapest First!
  642. asort($rate_table);
  643. return $rate_table;
  644. }
  645. private function _formatTable($services, $currency=false){
  646. /* The checkout template expects the array to be in a certain
  647. * format. This function will iterate through the provided
  648. * services array and format it for use. During the loop
  649. * we take advantage of the loop and translate the currency
  650. * if necessary based off of what UPS tells us they are giving us
  651. * for currency and what is set for the main currency in the settings
  652. * area
  653. */
  654. $converter = null;
  655. if ($currency){
  656. $converter = new CURRENCYCONVERTER();
  657. }
  658. $finalTable = array();
  659. foreach(array_keys($services) as $service){
  660. if ($currency != false && $currency != $services[$service][0]){
  661. $temp =$services[$service][1];
  662. $services[$service][1] = $converter->convert($services[$service][1],
  663. $currency,
  664. $services[$service][0]);
  665. }
  666. $finalTable[$service] = $services[$service][1];
  667. }
  668. return $finalTable;
  669. }
  670. function getQuote(){
  671. global $wpdb, $wpec_ash;
  672. if (!is_object($wpec_ash)){
  673. $wpec_ash = new ASH();
  674. }
  675. // Arguments array for various functions to use
  676. $args = array();
  677. // Final rate table
  678. $rate_table = array();
  679. // Get the ups settings from the ups account info page (Shipping tab)
  680. $wpsc_ups_settings = get_option("wpsc_ups_settings", array());
  681. // Get the wordpress shopping cart options
  682. $wpsc_options = get_option("wpsc_options");
  683. // API Auth settings //
  684. $args['username'] = (array_key_exists('upsaccount',$wpsc_ups_settings)) ? $wpsc_ups_settings['upsusername'] : "";
  685. $args['password'] = (array_key_exists('upspassword',$wpsc_ups_settings)) ? $wpsc_ups_settings['upspassword'] : "";
  686. $args['api_id'] = (array_key_exists('upsid',$wpsc_ups_settings)) ? $wpsc_ups_settings['upsid'] : "";
  687. $args['account_number'] = (array_key_exists('upsaccount',$wpsc_ups_settings)) ? $wpsc_ups_settings['upsaccount'] : "";
  688. $args['negotiated_rates'] = (array_key_exists('ups_negotiated_rates',$wpsc_ups_settings)) ?
  689. $wpsc_ups_settings['ups_negotiated_rates'] : "";
  690. $args['residential'] = $wpsc_ups_settings['49_residential'];
  691. $args["singular_shipping"] = (array_key_exists("singular_shipping", $wpsc_ups_settings)) ? $wpsc_ups_settings["singular_shipping"] : "0";
  692. $args['insured_shipment'] = (array_key_exists("insured_shipment", $wpsc_ups_settings)) ? $wpsc_ups_settings["insured_shipment"] : "0";
  693. // What kind of pickup service do you use ?
  694. $args['DropoffType'] = $wpsc_ups_settings['DropoffType'];
  695. $args['packaging'] = $wpsc_ups_settings['48_container'];
  696. // Preferred Currency to display
  697. $currency_data = $wpdb->get_row("SELECT `code`
  698. FROM `".WPSC_TABLE_CURRENCY_LIST."`
  699. WHERE `isocode`='".get_option("currency_type")."'
  700. LIMIT 1", ARRAY_A) ;
  701. if ($currency_data){
  702. $args['currency'] = $currency_data['code'];
  703. }else{
  704. $args['currency'] = "USD";
  705. }
  706. // Shipping billing / account address
  707. $origin_region_data = $wpdb->get_results("SELECT `".WPSC_TABLE_REGION_TAX."`.* FROM `".WPSC_TABLE_REGION_TAX."`
  708. WHERE `".WPSC_TABLE_REGION_TAX."`.`id` = '".get_option('base_region')."' ",ARRAY_A);
  709. $args['shipr_state']= (is_array($origin_region_data)) ? $origin_region_data[0]['code'] : "";
  710. $args['shipr_city'] = get_option('base_city');
  711. $args['shipr_ccode'] = get_option('base_country');
  712. $args['shipr_pcode'] = get_option('base_zipcode');
  713. // Physical Shipping address being shipped from
  714. $args['shipf_state'] = $args['shipr_state'];
  715. $args['shipf_city'] = $args['shipr_city'];
  716. $args['shipf_ccode'] = $args['shipr_ccode'];
  717. $args['shipf_pcode'] = $args['shipr_pcode'];
  718. // Get the total weight from the shopping cart
  719. $args['units'] = "LBS";
  720. $args['weight'] = wpsc_cart_weight_total();
  721. // Destination zip code
  722. $args['dest_ccode'] = $_SESSION['wpsc_delivery_country'];
  723. if ($args['dest_ccode'] == "UK"){
  724. // So, UPS is a little off the times
  725. $args['dest_ccode'] = "GB";
  726. }
  727. // If ths zip code is provided via a form post use it!
  728. if(isset($_POST['zipcode']) && ($_POST['zipcode'] != "Your Zipcode" && $_POST['zipcode'] != "YOURZIPCODE")) {
  729. $args['dest_pcode'] = $_POST['zipcode'];
  730. $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
  731. } else if(isset($_SESSION['wpsc_zipcode']) && ($_POST['zipcode'] != "Your Zipcode" && $_POST['zipcode'] != "YOURZIPCODE")) {
  732. // Well, we have a zip code in the session and no new one provided
  733. $args['dest_pcode'] = $_SESSION['wpsc_zipcode'];
  734. }else{
  735. // We cannot get a quote without a zip code so might as well return!
  736. return array();
  737. }
  738. // If the region code is provided via a form post use it!
  739. if(isset($_POST['region']) && !empty($_POST['region'])) {
  740. $query ="SELECT `".WPSC_TABLE_REGION_TAX."`.* FROM `".WPSC_TABLE_REGION_TAX."`
  741. WHERE `".WPSC_TABLE_REGION_TAX."`.`id` = '".$_POST['region']."'";
  742. $dest_region_data = $wpdb->get_results($query, ARRAY_A);
  743. $args['dest_state'] = (is_array($dest_region_data)) ? $dest_region_data[0]['code'] : "";
  744. $_SESSION['wpsc_state'] = $args['dest_state'];
  745. } else if(isset($_SESSION['wpsc_state'])) {
  746. // Well, we have a zip code in the session and no new one provided
  747. $args['dest_state'] = $_SESSION['wpsc_state'];
  748. } else{
  749. $args['dest_state'] = "";
  750. }
  751. $shipping_cache_check['state'] = $args['dest_state'];
  752. $shipping_cache_check['zipcode'] = $args['dest_pcode'];
  753. $shipping_cache_check['weight'] = $args['weight'];
  754. if (!(boolean)$args["singular_shipping"]){
  755. // This is where shipping breaks out of UPS if weight is higher than 150 LBS
  756. if($weight > 150){
  757. unset($_SESSION['quote_shipping_method']);
  758. $shipping_quotes[TXT_WPSC_OVER_UPS_WEIGHT] = 0;
  759. $_SESSION['wpsc_shipping_cache_check']['weight'] = $args['weight'];
  760. $_SESSION['wpsc_shipping_cache'][$this->internal_name] = $shipping_quotes;
  761. $_SESSION['quote_shipping_method'] = $this->internal_name;
  762. return array($shipping_quotes);
  763. }
  764. }
  765. // We do not want to spam UPS (and slow down our process) if we already
  766. // have a shipping quote!
  767. if(($_SESSION['wpsc_shipping_cache_check'] === $shipping_cache_check)
  768. && ($_SESSION['wpsc_shipping_cache'][$this->internal_name] != null)) {
  769. $rate_table = $_SESSION['wpsc_shipping_cache'][$this->internal_name];
  770. return $rate_table;
  771. }else{
  772. global $wpsc_cart;
  773. $args["cart_total"] = $wpsc_cart->calculate_subtotal(true);
  774. // Build the XML request
  775. $request = $this->_buildRateRequest($args);
  776. // Now that we have the message to send ... Send it!
  777. $raw_quote = $this->_makeRateRequest($request);
  778. // Now we have the UPS response .. unfortunately its not ready
  779. // to be viewed by normal humans ...
  780. $quotes = $this->_parseQuote($raw_quote);
  781. // If we actually have rates back from UPS we can use em!
  782. if ($quotes != false){
  783. $rate_table = $this->_formatTable($quotes,$args['currency']);
  784. }else{
  785. if ($wpsc_ups_settings['upsenvironment'] == '1'){
  786. echo "<strong>:: GetQuote ::DEBUG OUTPUT::</strong><br />";
  787. echo "Arguments sent to UPS";
  788. print_r($args);
  789. echo "<hr />";
  790. print $request;
  791. echo "<hr />";
  792. echo "Response from UPS";
  793. echo $raw_quote;
  794. echo "</strong>:: GetQuote ::End DEBUG OUTPUT::";
  795. }
  796. }
  797. }
  798. $wpec_ash->cache_results($this->internal_name,
  799. $args["dest_ccode"], $args["dest_state"],
  800. $args["dest_pcode"], $rate_table, $this->shipment);
  801. // return the final formatted array !
  802. return $rate_table;
  803. }
  804. // Empty Function, this exists just b/c it is prototyped elsewhere
  805. function get_item_shipping(){
  806. }
  807. }
  808. $ash_ups = new ash_ups();
  809. $wpsc_shipping_modules[$ash_ups->getInternalName()] = $ash_ups;