00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035 class Mage_Usa_Model_Shipping_Carrier_Ups
00036 extends Mage_Usa_Model_Shipping_Carrier_Abstract
00037 implements Mage_Shipping_Model_Carrier_Interface
00038 {
00039
00040 protected $_code = 'ups';
00041
00042 protected $_request = null;
00043
00044 protected $_result = null;
00045
00046 protected $_xmlAccessRequest = null;
00047
00048 protected $_defaultCgiGatewayUrl = 'http://www.ups.com:80/using/services/rave/qcostcgi.cgi';
00049
00050 public function collectRates(Mage_Shipping_Model_Rate_Request $request)
00051 {
00052 if (!$this->getConfigFlag('active')) {
00053 return false;
00054 }
00055
00056 $this->setRequest($request);
00057
00058 $this->_result = $this->_getQuotes();
00059 $this->_updateFreeMethodQuote($request);
00060
00061 return $this->getResult();
00062 }
00063
00064 public function setRequest(Mage_Shipping_Model_Rate_Request $request)
00065 {
00066 $this->_request = $request;
00067
00068 $r = new Varien_Object();
00069
00070 if ($request->getLimitMethod()) {
00071 $r->setAction($this->getCode('action', 'single'));
00072 $r->setProduct($request->getLimitMethod());
00073 } else {
00074 $r->setAction($this->getCode('action', 'all'));
00075 $r->setProduct('GND'.$this->getConfigData('dest_type'));
00076 }
00077
00078 if ($request->getUpsPickup()) {
00079 $pickup = $request->getUpsPickup();
00080 } else {
00081 $pickup = $this->getConfigData('pickup');
00082 }
00083 $r->setPickup($this->getCode('pickup', $pickup));
00084
00085 if ($request->getUpsContainer()) {
00086 $container = $request->getUpsContainer();
00087 } else {
00088 $container = $this->getConfigData('container');
00089 }
00090 $r->setContainer($this->getCode('container', $container));
00091
00092 if ($request->getUpsDestType()) {
00093 $destType = $request->getUpsDestType();
00094 } else {
00095 $destType = $this->getConfigData('dest_type');
00096 }
00097 $r->setDestType($this->getCode('dest_type', $destType));
00098
00099 if ($request->getOrigCountry()) {
00100 $origCountry = $request->getOrigCountry();
00101 } else {
00102 $origCountry = Mage::getStoreConfig('shipping/origin/country_id', $this->getStore());
00103 }
00104
00105 $r->setOrigCountry(Mage::getModel('directory/country')->load($origCountry)->getIso2Code());
00106
00107 if ($request->getOrigRegionCode()) {
00108 $origRegionCode = $request->getOrigRegionCode();
00109 } else {
00110 $origRegionCode = Mage::getStoreConfig('shipping/origin/region_id', $this->getStore());
00111 if (is_numeric($origRegionCode)) {
00112 $origRegionCode = Mage::getModel('directory/region')->load($origRegionCode)->getCode();
00113 }
00114 }
00115 $r->setOrigRegionCode($origRegionCode);
00116
00117 if ($request->getOrigPostcode()) {
00118 $r->setOrigPostal($request->getOrigPostcode());
00119 } else {
00120 $r->setOrigPostal(Mage::getStoreConfig('shipping/origin/postcode', $this->getStore()));
00121 }
00122
00123 if ($request->getOrigCity()) {
00124 $r->setOrigCity($request->getOrigCity());
00125 } else {
00126 $r->setOrigCity(Mage::getStoreConfig('shipping/origin/city', $this->getStore()));
00127 }
00128
00129
00130 if ($request->getDestCountryId()) {
00131 $destCountry = $request->getDestCountryId();
00132 } else {
00133 $destCountry = self::USA_COUNTRY_ID;
00134 }
00135
00136
00137 if ($destCountry==self::USA_COUNTRY_ID && ($request->getDestPostcode()=='00912' || $request->getDestRegionCode()==self::PUERTORICO_COUNTRY_ID)) {
00138 $destCountry = self::PUERTORICO_COUNTRY_ID;
00139 }
00140
00141 $r->setDestCountry(Mage::getModel('directory/country')->load($destCountry)->getIso2Code());
00142
00143 $r->setDestRegionCode($request->getDestRegionCode());
00144
00145 if ($request->getDestPostcode()) {
00146 $r->setDestPostal($request->getDestPostcode());
00147 } else {
00148
00149 }
00150
00151 $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
00152 $r->setWeight($weight);
00153 if ($request->getFreeMethodWeight()!=$request->getPackageWeight()) {
00154 $r->setFreeMethodWeight($request->getFreeMethodWeight());
00155 }
00156
00157 $r->setValue($request->getPackageValue());
00158 $r->setValueWithDiscount($request->getPackageValueWithDiscount());
00159
00160 if ($request->getUpsUnitMeasure()) {
00161 $unit = $request->getUpsUnitMeasure();
00162 } else {
00163 $unit = $this->getConfigData('unit_of_measure');
00164 }
00165 $r->setUnitMeasure($unit);
00166
00167 $this->_rawRequest = $r;
00168
00169 return $this;
00170 }
00171
00172 public function getResult()
00173 {
00174 return $this->_result;
00175 }
00176
00177 protected function _getQuotes()
00178 {
00179 switch ($this->getConfigData('type')) {
00180 case 'UPS':
00181 return $this->_getCgiQuotes();
00182
00183 case 'UPS_XML':
00184 return $this->_getXmlQuotes();
00185 }
00186 return null;
00187 }
00188
00189 protected function _setFreeMethodRequest($freeMethod)
00190 {
00191 $r = $this->_rawRequest;
00192
00193 $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
00194 $r->setWeight($weight);
00195 $r->setAction($this->getCode('action', 'single'));
00196 $r->setProduct($freeMethod);
00197 }
00198
00199 protected function _getCgiQuotes()
00200 {
00201 $r = $this->_rawRequest;
00202
00203 $params = array(
00204 'accept_UPS_license_agreement' => 'yes',
00205 '10_action' => $r->getAction(),
00206 '13_product' => $r->getProduct(),
00207 '14_origCountry' => $r->getOrigCountry(),
00208 '15_origPostal' => $r->getOrigPostal(),
00209 'origCity' => $r->getOrigCity(),
00210 '19_destPostal' => substr($r->getDestPostal(), 0, 5),
00211 '22_destCountry' => $r->getDestCountry(),
00212 '23_weight' => $r->getWeight(),
00213 '47_rate_chart' => $r->getPickup(),
00214 '48_container' => $r->getContainer(),
00215 '49_residential' => $r->getDestType(),
00216 'weight_std' => strtolower($r->getUnitMeasure()),
00217 );
00218 $params['47_rate_chart'] = $params['47_rate_chart']['label'];
00219
00220 try {
00221 $url = $this->getConfigData('gateway_url');
00222 if (!$url) {
00223 $url = $this->_defaultCgiGatewayUrl;
00224 }
00225 $client = new Zend_Http_Client();
00226 $client->setUri($url);
00227 $client->setConfig(array('maxredirects'=>0, 'timeout'=>30));
00228 $client->setParameterGet($params);
00229 $response = $client->request();
00230 $responseBody = $response->getBody();
00231 } catch (Exception $e) {
00232 $responseBody = '';
00233 }
00234
00235 return $this->_parseCgiResponse($responseBody);
00236 }
00237
00238 public function getShipmentByCode($code,$origin = null){
00239 if($origin===null){
00240 $origin = $this->getConfigData('origin_shipment');
00241 }
00242 $arr = $this->getCode('originShipment',$origin);
00243 if(isset($arr[$code]))
00244 return $arr[$code];
00245 else
00246 return false;
00247 }
00248
00249
00250 protected function _parseCgiResponse($response)
00251 {
00252 $costArr = array();
00253 $priceArr = array();
00254 $errorTitle = Mage::helper('usa')->__('Unknown error');
00255 if (strlen(trim($response))>0) {
00256 $rRows = explode("\n", $response);
00257 $allowedMethods = explode(",", $this->getConfigData('allowed_methods'));
00258 foreach ($rRows as $rRow) {
00259 $r = explode('%', $rRow);
00260 switch (substr($r[0],-1)) {
00261 case 3: case 4:
00262 if (in_array($r[1], $allowedMethods)) {
00263 $responsePrice = Mage::app()->getLocale()->getNumber($r[8]);
00264 $costArr[$r[1]] = $responsePrice;
00265 $priceArr[$r[1]] = $this->getMethodPrice($responsePrice, $r[1]);
00266 }
00267 break;
00268 case 5:
00269 $errorTitle = $r[1];
00270 break;
00271 case 6:
00272 if (in_array($r[3], $allowedMethods)) {
00273 $responsePrice = Mage::app()->getLocale()->getNumber($r[10]);
00274 $costArr[$r[3]] = $responsePrice;
00275 $priceArr[$r[3]] = $this->getMethodPrice($responsePrice, $r[3]);
00276 }
00277 break;
00278 }
00279 }
00280 asort($priceArr);
00281 }
00282
00283 $result = Mage::getModel('shipping/rate_result');
00284 $defaults = $this->getDefaults();
00285 if (empty($priceArr)) {
00286 $error = Mage::getModel('shipping/rate_result_error');
00287 $error->setCarrier('ups');
00288 $error->setCarrierTitle($this->getConfigData('title'));
00289
00290 $error->setErrorMessage($this->getConfigData('specificerrmsg'));
00291 $result->append($error);
00292 } else {
00293 foreach ($priceArr as $method=>$price) {
00294 $rate = Mage::getModel('shipping/rate_result_method');
00295 $rate->setCarrier('ups');
00296 $rate->setCarrierTitle($this->getConfigData('title'));
00297 $rate->setMethod($method);
00298 $method_arr = $this->getCode('method', $method);
00299 $rate->setMethodTitle(Mage::helper('usa')->__($method_arr));
00300 $rate->setCost($costArr[$method]);
00301 $rate->setPrice($price);
00302 $result->append($rate);
00303 }
00304 }
00305 #echo "<pre>".print_r($result,1)."</pre>";
00306 return $result;
00307 }
00308
00309
00310
00311
00312
00313
00314
00315
00316 public function getCode($type, $code='')
00317 {
00318 $codes = array(
00319 'action'=>array(
00320 'single'=>'3',
00321 'all'=>'4',
00322 ),
00323
00324 'originShipment'=>array(
00325
00326 'United States Domestic Shipments' => array(
00327 '01' => Mage::helper('usa')->__('UPS Next Day Air'),
00328 '02' => Mage::helper('usa')->__('UPS Second Day Air'),
00329 '03' => Mage::helper('usa')->__('UPS Ground'),
00330 '07' => Mage::helper('usa')->__('UPS Worldwide Express'),
00331 '08' => Mage::helper('usa')->__('UPS Worldwide Expedited'),
00332 '11' => Mage::helper('usa')->__('UPS Standard'),
00333 '12' => Mage::helper('usa')->__('UPS Three-Day Select'),
00334 '13' => Mage::helper('usa')->__('UPS Next Day Air Saver'),
00335 '14' => Mage::helper('usa')->__('UPS Next Day Air Early A.M.'),
00336 '54' => Mage::helper('usa')->__('UPS Worldwide Express Plus'),
00337 '59' => Mage::helper('usa')->__('UPS Second Day Air A.M.'),
00338 '65' => Mage::helper('usa')->__('UPS Saver'),
00339 ),
00340
00341 'Shipments Originating in United States' => array(
00342 '01' => Mage::helper('usa')->__('UPS Next Day Air'),
00343 '02' => Mage::helper('usa')->__('UPS Second Day Air'),
00344 '03' => Mage::helper('usa')->__('UPS Ground'),
00345 '07' => Mage::helper('usa')->__('UPS Worldwide Express'),
00346 '08' => Mage::helper('usa')->__('UPS Worldwide Expedited'),
00347 '11' => Mage::helper('usa')->__('UPS Standard'),
00348 '12' => Mage::helper('usa')->__('UPS Three-Day Select'),
00349 '14' => Mage::helper('usa')->__('UPS Next Day Air Early A.M.'),
00350 '54' => Mage::helper('usa')->__('UPS Worldwide Express Plus'),
00351 '59' => Mage::helper('usa')->__('UPS Second Day Air A.M.'),
00352 '65' => Mage::helper('usa')->__('UPS Saver'),
00353 ),
00354
00355 'Shipments Originating in Canada' => array(
00356 '01' => Mage::helper('usa')->__('UPS Express'),
00357 '02' => Mage::helper('usa')->__('UPS Expedited'),
00358 '07' => Mage::helper('usa')->__('UPS Worldwide Express'),
00359 '08' => Mage::helper('usa')->__('UPS Worldwide Expedited'),
00360 '11' => Mage::helper('usa')->__('UPS Standard'),
00361 '12' => Mage::helper('usa')->__('UPS Three-Day Select'),
00362 '14' => Mage::helper('usa')->__('UPS Express Early A.M.'),
00363 '65' => Mage::helper('usa')->__('UPS Saver'),
00364 ),
00365
00366 'Shipments Originating in the European Union' => array(
00367 '07' => Mage::helper('usa')->__('UPS Express'),
00368 '08' => Mage::helper('usa')->__('UPS Expedited'),
00369 '11' => Mage::helper('usa')->__('UPS Standard'),
00370 '54' => Mage::helper('usa')->__('UPS Worldwide Express PlusSM'),
00371 '65' => Mage::helper('usa')->__('UPS Saver'),
00372 ),
00373
00374 'Polish Domestic Shipments' => array(
00375 '07' => Mage::helper('usa')->__('UPS Express'),
00376 '08' => Mage::helper('usa')->__('UPS Expedited'),
00377 '11' => Mage::helper('usa')->__('UPS Standard'),
00378 '54' => Mage::helper('usa')->__('UPS Worldwide Express Plus'),
00379 '65' => Mage::helper('usa')->__('UPS Saver'),
00380 '82' => Mage::helper('usa')->__('UPS Today Standard'),
00381 '83' => Mage::helper('usa')->__('UPS Today Dedicated Courrier'),
00382 '84' => Mage::helper('usa')->__('UPS Today Intercity'),
00383 '85' => Mage::helper('usa')->__('UPS Today Express'),
00384 '86' => Mage::helper('usa')->__('UPS Today Express Saver'),
00385 ),
00386
00387 'Puerto Rico Origin' => array(
00388 '01' => Mage::helper('usa')->__('UPS Next Day Air'),
00389 '02' => Mage::helper('usa')->__('UPS Second Day Air'),
00390 '03' => Mage::helper('usa')->__('UPS Ground'),
00391 '07' => Mage::helper('usa')->__('UPS Worldwide Express'),
00392 '08' => Mage::helper('usa')->__('UPS Worldwide Expedited'),
00393 '14' => Mage::helper('usa')->__('UPS Next Day Air Early A.M.'),
00394 '54' => Mage::helper('usa')->__('UPS Worldwide Express Plus'),
00395 '65' => Mage::helper('usa')->__('UPS Saver'),
00396 ),
00397
00398 'Shipments Originating in Mexico' => array(
00399 '07' => Mage::helper('usa')->__('UPS Express'),
00400 '08' => Mage::helper('usa')->__('UPS Expedited'),
00401 '54' => Mage::helper('usa')->__('UPS Express Plus'),
00402 '65' => Mage::helper('usa')->__('UPS Saver'),
00403 ),
00404
00405 'Shipments Originating in Other Countries' => array(
00406 '07' => Mage::helper('usa')->__('UPS Express'),
00407 '08' => Mage::helper('usa')->__('UPS Worldwide Expedited'),
00408 '11' => Mage::helper('usa')->__('UPS Standard'),
00409 '54' => Mage::helper('usa')->__('UPS Worldwide Express Plus'),
00410 '65' => Mage::helper('usa')->__('UPS Saver')
00411 )
00412 ),
00413
00414 'method'=>array(
00415 '1DM' => Mage::helper('usa')->__('Next Day Air Early AM'),
00416 '1DML' => Mage::helper('usa')->__('Next Day Air Early AM Letter'),
00417 '1DA' => Mage::helper('usa')->__('Next Day Air'),
00418 '1DAL' => Mage::helper('usa')->__('Next Day Air Letter'),
00419 '1DAPI' => Mage::helper('usa')->__('Next Day Air Intra (Puerto Rico)'),
00420 '1DP' => Mage::helper('usa')->__('Next Day Air Saver'),
00421 '1DPL' => Mage::helper('usa')->__('Next Day Air Saver Letter'),
00422 '2DM' => Mage::helper('usa')->__('2nd Day Air AM'),
00423 '2DML' => Mage::helper('usa')->__('2nd Day Air AM Letter'),
00424 '2DA' => Mage::helper('usa')->__('2nd Day Air'),
00425 '2DAL' => Mage::helper('usa')->__('2nd Day Air Letter'),
00426 '3DS' => Mage::helper('usa')->__('3 Day Select'),
00427 'GND' => Mage::helper('usa')->__('Ground'),
00428 'GNDCOM' => Mage::helper('usa')->__('Ground Commercial'),
00429 'GNDRES' => Mage::helper('usa')->__('Ground Residential'),
00430 'STD' => Mage::helper('usa')->__('Canada Standard'),
00431 'XPR' => Mage::helper('usa')->__('Worldwide Express'),
00432 'WXS' => Mage::helper('usa')->__('Worldwide Express Saver'),
00433 'XPRL' => Mage::helper('usa')->__('Worldwide Express Letter'),
00434 'XDM' => Mage::helper('usa')->__('Worldwide Express Plus'),
00435 'XDML' => Mage::helper('usa')->__('Worldwide Express Plus Letter'),
00436 'XPD' => Mage::helper('usa')->__('Worldwide Expedited'),
00437 ),
00438
00439 'pickup'=>array(
00440 'RDP' => array("label"=>'Regular Daily Pickup',"code"=>"01"),
00441 'OCA' => array("label"=>'On Call Air',"code"=>"07"),
00442 'OTP' => array("label"=>'One Time Pickup',"code"=>"06"),
00443 'LC' => array("label"=>'Letter Center',"code"=>"19"),
00444 'CC' => array("label"=>'Customer Counter',"code"=>"03"),
00445 ),
00446
00447 'container'=>array(
00448 'CP' => '00',
00449 'ULE' => '01',
00450 'UT' => '03',
00451 'UEB' => '21',
00452 'UW25' => '24',
00453 'UW10' => '25',
00454 ),
00455
00456 'container_description'=>array(
00457 'CP' => Mage::helper('usa')->__('Customer Packaging'),
00458 'ULE' => Mage::helper('usa')->__('UPS Letter Envelope'),
00459 'UT' => Mage::helper('usa')->__('UPS Tube'),
00460 'UEB' => Mage::helper('usa')->__('UPS Express Box'),
00461 'UW25' => Mage::helper('usa')->__('UPS Worldwide 25 kilo'),
00462 'UW10' => Mage::helper('usa')->__('UPS Worldwide 10 kilo'),
00463 ),
00464
00465 'dest_type'=>array(
00466 'RES' => '01',
00467 'COM' => '02',
00468 ),
00469
00470 'dest_type_description'=>array(
00471 'RES' => Mage::helper('usa')->__('Residential'),
00472 'COM' => Mage::helper('usa')->__('Commercial'),
00473 ),
00474
00475 'unit_of_measure'=>array(
00476 'LBS' => Mage::helper('usa')->__('Pounds'),
00477 'KGS' => Mage::helper('usa')->__('Kilograms'),
00478 ),
00479
00480 );
00481
00482 if (!isset($codes[$type])) {
00483
00484 return false;
00485 } elseif (''===$code) {
00486 return $codes[$type];
00487 }
00488
00489 if (!isset($codes[$type][$code])) {
00490
00491 return false;
00492 } else {
00493 return $codes[$type][$code];
00494 }
00495 }
00496
00497 protected function _getXmlQuotes()
00498 {
00499 $url = $this->getConfigData('gateway_xml_url');
00500
00501 $this->setXMLAccessRequest();
00502 $xmlRequest=$this->_xmlAccessRequest;
00503
00504 $r = $this->_rawRequest;
00505 $params = array(
00506 'accept_UPS_license_agreement' => 'yes',
00507 '10_action' => $r->getAction(),
00508 '13_product' => $r->getProduct(),
00509 '14_origCountry' => $r->getOrigCountry(),
00510 '15_origPostal' => $r->getOrigPostal(),
00511 'origCity' => $r->getOrigCity(),
00512 'origRegionCode' => $r->getOrigRegionCode(),
00513 '19_destPostal' => substr($r->getDestPostal(), 0, 5),
00514 '22_destCountry' => $r->getDestCountry(),
00515 'destRegionCode' => $r->getDestRegionCode(),
00516 '23_weight' => $r->getWeight(),
00517 '47_rate_chart' => $r->getPickup(),
00518 '48_container' => $r->getContainer(),
00519 '49_residential' => $r->getDestType(),
00520 );
00521 $params['10_action'] = $params['10_action']=='4'? 'Shop' : 'Rate';
00522 $serviceCode = $r->getProduct() ? $r->getProduct() : '';
00523 $serviceDescription = $serviceCode ? $this->getShipmentByCode($serviceCode) : '';
00524
00525 $xmlRequest .= <<< XMLRequest
00526 <?xml version="1.0"?>
00527 <RatingServiceSelectionRequest xml:lang="en-US">
00528 <Request>
00529 <TransactionReference>
00530 <CustomerContext>Rating and Service</CustomerContext>
00531 <XpciVersion>1.0</XpciVersion>
00532 </TransactionReference>
00533 <RequestAction>Rate</RequestAction>
00534 <RequestOption>{$params['10_action']}</RequestOption>
00535 </Request>
00536 <PickupType>
00537 <Code>{$params['47_rate_chart']['code']}</Code>
00538 <Description>{$params['47_rate_chart']['label']}</Description>
00539 </PickupType>
00540
00541 <Shipment>
00542
00543 <Service>
00544 <Code>{$serviceCode}</Code>
00545 <Description>{$serviceDescription}</Description>
00546 </Service>
00547 <Shipper>
00548 XMLRequest;
00549
00550 if ($this->getConfigFlag('negotiated_active') && ($shipper = $this->getConfigData('shipper_number')) ) {
00551 $xmlRequest .= "<ShipperNumber>{$shipper}</ShipperNumber>";
00552 }
00553
00554 $xmlRequest .= <<< XMLRequest
00555 <Address>
00556 <City>{$params['origCity']}</City>
00557 <PostalCode>{$params['15_origPostal']}</PostalCode>
00558 <CountryCode>{$params['14_origCountry']}</CountryCode>
00559 <StateProvinceCode>{$params['origRegionCode']}</StateProvinceCode>
00560 </Address>
00561 </Shipper>
00562 <ShipTo>
00563 <Address>
00564 <PostalCode>{$params['19_destPostal']}</PostalCode>
00565 <CountryCode>{$params['22_destCountry']}</CountryCode>
00566 <ResidentialAddress>{$params['49_residential']}</ResidentialAddress>
00567 <StateProvinceCode>{$params['destRegionCode']}</StateProvinceCode>
00568 XMLRequest;
00569
00570 $xmlRequest .= ($params['49_residential']==='01' ? "<ResidentialAddressIndicator>{$params['49_residential']}</ResidentialAddressIndicator>" : '');
00571
00572 $xmlRequest .= <<< XMLRequest
00573 </Address>
00574 </ShipTo>
00575
00576
00577 <ShipFrom>
00578 <Address>
00579 <PostalCode>{$params['15_origPostal']}</PostalCode>
00580 <CountryCode>{$params['14_origCountry']}</CountryCode>
00581 <StateProvinceCode>{$params['origRegionCode']}</StateProvinceCode>
00582 </Address>
00583 </ShipFrom>
00584
00585 <Package>
00586 <PackagingType><Code>{$params['48_container']}</Code></PackagingType>
00587 <PackageWeight>
00588 <UnitOfMeasurement><Code>{$r->getUnitMeasure()}</Code></UnitOfMeasurement>
00589 <Weight>{$params['23_weight']}</Weight>
00590 </PackageWeight>
00591 </Package>
00592 XMLRequest;
00593 if ($this->getConfigFlag('negotiated_active')) {
00594 $xmlRequest .= "<RateInformation><NegotiatedRatesIndicator/></RateInformation>";
00595 }
00596
00597 $xmlRequest .= <<< XMLRequest
00598 </Shipment>
00599 </RatingServiceSelectionRequest>
00600 XMLRequest;
00601
00602 try {
00603 $ch = curl_init();
00604 curl_setopt($ch, CURLOPT_URL, $url);
00605 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
00606 curl_setopt($ch, CURLOPT_HEADER, 0);
00607 curl_setopt($ch, CURLOPT_POST, 1);
00608 curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest);
00609 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
00610 $xmlResponse = curl_exec ($ch);
00611 } catch (Exception $e) {
00612 $xmlResponse = '';
00613 }
00614 return $this->_parseXmlResponse($xmlResponse);
00615 }
00616
00617 protected function _parseXmlResponse($xmlResponse)
00618 {
00619 $costArr = array();
00620 $priceArr = array();
00621 if (strlen(trim($xmlResponse))>0) {
00622 $xml = new Varien_Simplexml_Config();
00623 $xml->loadString($xmlResponse);
00624 $arr = $xml->getXpath("//RatingServiceSelectionResponse/Response/ResponseStatusCode/text()");
00625 $success = (int)$arr[0][0];
00626 if($success===1){
00627 $arr = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment");
00628 $allowedMethods = explode(",", $this->getConfigData('allowed_methods'));
00629
00630
00631 $negotiatedArr = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment/NegotiatedRates");
00632 $negotiatedActive = $this->getConfigFlag('negotiated_active')
00633 && $this->getConfigData('shipper_number')
00634 && !empty($negotiatedArr);
00635
00636 foreach ($arr as $shipElement){
00637 $code = (string)$shipElement->Service->Code;
00638 #$shipment = $this->getShipmentByCode($code);
00639 if (in_array($code, $allowedMethods)) {
00640
00641 if ($negotiatedActive) {
00642 $cost = $shipElement->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue;
00643 } else {
00644 $cost = $shipElement->TotalCharges->MonetaryValue;
00645 }
00646
00647 $costArr[$code] = $cost;
00648 $priceArr[$code] = $this->getMethodPrice(floatval($cost),$code);
00649 }
00650 }
00651 } else {
00652 $arr = $xml->getXpath("//RatingServiceSelectionResponse/Response/Error/ErrorDescription/text()");
00653 $errorTitle = (string)$arr[0][0];
00654 $error = Mage::getModel('shipping/rate_result_error');
00655 $error->setCarrier('ups');
00656 $error->setCarrierTitle($this->getConfigData('title'));
00657
00658 $error->setErrorMessage($this->getConfigData('specificerrmsg'));
00659 }
00660 }
00661
00662 $result = Mage::getModel('shipping/rate_result');
00663 $defaults = $this->getDefaults();
00664 if (empty($priceArr)) {
00665 $error = Mage::getModel('shipping/rate_result_error');
00666 $error->setCarrier('ups');
00667 $error->setCarrierTitle($this->getConfigData('title'));
00668 if(!isset($errorTitle)){
00669 $errorTitle = Mage::helper('usa')->__('Cannot retrieve shipping rates');
00670 }
00671
00672 $error->setErrorMessage($this->getConfigData('specificerrmsg'));
00673 $result->append($error);
00674 } else {
00675 foreach ($priceArr as $method=>$price) {
00676 $rate = Mage::getModel('shipping/rate_result_method');
00677 $rate->setCarrier('ups');
00678 $rate->setCarrierTitle($this->getConfigData('title'));
00679 $rate->setMethod($method);
00680 $method_arr = $this->getShipmentByCode($method);
00681 $rate->setMethodTitle($method_arr);
00682 $rate->setCost($costArr[$method]);
00683 $rate->setPrice($price);
00684 $result->append($rate);
00685 }
00686 }
00687 return $result;
00688 }
00689
00690 public function getTracking($trackings)
00691 {
00692 $return = array();
00693
00694 if (!is_array($trackings)) {
00695 $trackings = array($trackings);
00696 }
00697
00698 if ($this->getConfigData('type')=='UPS') {
00699 $this->_getCgiTracking($trackings);
00700 } elseif ($this->getConfigData('type')=='UPS_XML'){
00701 $this->setXMLAccessRequest();
00702 $this->_getXmlTracking($trackings);
00703 }
00704
00705 return $this->_result;
00706 }
00707
00708 protected function setXMLAccessRequest()
00709 {
00710 $userid = $this->getConfigData('username');
00711 $userid_pass = $this->getConfigData('password');
00712 $access_key = $this->getConfigData('access_license_number');
00713
00714 $this->_xmlAccessRequest = <<<XMLAuth
00715 <?xml version="1.0"?>
00716 <AccessRequest xml:lang="en-US">
00717 <AccessLicenseNumber>$access_key</AccessLicenseNumber>
00718 <UserId>$userid</UserId>
00719 <Password>$userid_pass</Password>
00720 </AccessRequest>
00721 XMLAuth;
00722 }
00723
00724 protected function _getCgiTracking($trackings)
00725 {
00726
00727
00728 $result = Mage::getModel('shipping/tracking_result');
00729 $defaults = $this->getDefaults();
00730 foreach($trackings as $tracking){
00731 $status = Mage::getModel('shipping/tracking_result_status');
00732 $status->setCarrier('ups');
00733 $status->setCarrierTitle($this->getConfigData('title'));
00734 $status->setTracking($tracking);
00735 $status->setPopup(1);
00736 $status->setUrl("http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0&error_carried=true&tracknums_displayed=5&TypeOfInquiryNumber=T&loc=en_US&InquiryNumber1=$tracking&AgreeToTermsAndConditions=yes");
00737 $result->append($status);
00738 }
00739
00740 $this->_result = $result;
00741 return $result;
00742 }
00743
00744 protected function _getXmlTracking($trackings)
00745 {
00746 $url = $this->getConfigData('tracking_xml_url');
00747
00748 foreach($trackings as $tracking){
00749 $xmlRequest=$this->_xmlAccessRequest;
00750
00751
00752
00753
00754 $xmlRequest .= <<<XMLAuth
00755 <?xml version="1.0" ?>
00756 <TrackRequest xml:lang="en-US">
00757 <Request>
00758 <RequestAction>Track</RequestAction>
00759 <RequestOption>activity</RequestOption>
00760 </Request>
00761 <TrackingNumber>$tracking</TrackingNumber>
00762 <IncludeFreight>01</IncludeFreight>
00763 </TrackRequest>
00764 XMLAuth;
00765 try {
00766 $ch = curl_init();
00767 curl_setopt($ch, CURLOPT_URL, $url);
00768 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
00769 curl_setopt($ch, CURLOPT_HEADER, 0);
00770 curl_setopt($ch, CURLOPT_POST, 1);
00771 curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest);
00772 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
00773 $xmlResponse = curl_exec ($ch);
00774 curl_close ($ch);
00775 }catch (Exception $e) {
00776 $xmlResponse = '';
00777 }
00778
00779 $this->_parseXmlTrackingResponse($tracking, $xmlResponse);
00780 }
00781
00782 return $this->_result;
00783 }
00784
00785 protected function _parseXmlTrackingResponse($trackingvalue, $xmlResponse)
00786 {
00787 $errorTitle = 'Unable to retrieve tracking';
00788 $resultArr = array();
00789 $packageProgress = array();
00790
00791 if ($xmlResponse) {
00792 $xml = new Varien_Simplexml_Config();
00793 $xml->loadString($xmlResponse);
00794 $arr = $xml->getXpath("//TrackResponse/Response/ResponseStatusCode/text()");
00795 $success = (int)$arr[0][0];
00796
00797 if($success===1){
00798 $arr = $xml->getXpath("//TrackResponse/Shipment/Service/Description/text()");
00799 $resultArr['service'] = (string)$arr[0];
00800
00801 $arr = $xml->getXpath("//TrackResponse/Shipment/PickupDate/text()");
00802 $resultArr['shippeddate'] = (string)$arr[0];
00803
00804 $arr = $xml->getXpath("//TrackResponse/Shipment/Package/PackageWeight/Weight/text()");
00805 $weight = (string)$arr[0];
00806
00807 $arr = $xml->getXpath("//TrackResponse/Shipment/Package/PackageWeight/UnitOfMeasurement/Code/text()");
00808 $unit = (string)$arr[0];
00809
00810 $resultArr['weight'] = "{$weight} {$unit}";
00811
00812 $activityTags = $xml->getXpath("//TrackResponse/Shipment/Package/Activity");
00813 if ($activityTags) {
00814 $i=1;
00815 foreach ($activityTags as $activityTag) {
00816 $addArr=array();
00817 if (isset($activityTag->ActivityLocation->Address->City)) {
00818 $addArr[] = (string)$activityTag->ActivityLocation->Address->City;
00819 }
00820 if (isset($activityTag->ActivityLocation->Address->StateProvinceCode)) {
00821 $addArr[] = (string)$activityTag->ActivityLocation->Address->StateProvinceCode;
00822 }
00823 if (isset($activityTag->ActivityLocation->Address->CountryCode)) {
00824 $addArr[] = (string)$activityTag->ActivityLocation->Address->CountryCode;
00825 }
00826 $dateArr = array();
00827 $date = (string)$activityTag->Date;
00828 $dateArr[] = substr($date,0,4);
00829 $dateArr[] = substr($date,4,2);
00830 $dateArr[] = substr($date,-2,2);
00831
00832 $timeArr = array();
00833 $time = (string)$activityTag->Time;
00834 $timeArr[] = substr($time,0,2);
00835 $timeArr[] = substr($time,2,2);
00836 $timeArr[] = substr($time,-2,2);
00837
00838 if($i==1){
00839 $resultArr['status'] = (string)$activityTag->Status->StatusType->Description;
00840 $resultArr['deliverydate'] = implode('-',$dateArr);
00841 $resultArr['deliverytime'] = implode(':',$timeArr);
00842 $resultArr['deliverylocation'] = (string)$activityTag->ActivityLocation->Description;
00843 $resultArr['signedby'] = (string)$activityTag->ActivityLocation->SignedForByName;
00844 if ($addArr) {
00845 $resultArr['deliveryto']=implode(', ',$addArr);
00846 }
00847 }else{
00848 $tempArr=array();
00849 $tempArr['activity'] = (string)$activityTag->Status->StatusType->Description;
00850 $tempArr['deliverydate'] = implode('-',$dateArr);
00851 $tempArr['deliverytime'] = implode(':',$timeArr);
00852 if ($addArr) {
00853 $tempArr['deliverylocation']=implode(', ',$addArr);
00854 }
00855 $packageProgress[] = $tempArr;
00856 }
00857 $i++;
00858 }
00859 $resultArr['progressdetail'] = $packageProgress;
00860 }
00861 } else {
00862 $arr = $xml->getXpath("//TrackResponse/Response/Error/ErrorDescription/text()");
00863 $errorTitle = (string)$arr[0][0];
00864 }
00865 }
00866
00867 if (!$this->_result) {
00868 $this->_result = Mage::getModel('shipping/tracking_result');
00869 }
00870
00871 $defaults = $this->getDefaults();
00872
00873 if ($resultArr) {
00874 $tracking = Mage::getModel('shipping/tracking_result_status');
00875 $tracking->setCarrier('ups');
00876 $tracking->setCarrierTitle($this->getConfigData('title'));
00877 $tracking->setTracking($trackingvalue);
00878 $tracking->addData($resultArr);
00879 $this->_result->append($tracking);
00880 } else {
00881 $error = Mage::getModel('shipping/tracking_result_error');
00882 $error->setCarrier('ups');
00883 $error->setCarrierTitle($this->getConfigData('title'));
00884 $error->setTracking($trackingvalue);
00885 $error->setErrorMessage($errorTitle);
00886 $this->_result->append($error);
00887 }
00888 return $this->_result;
00889 }
00890
00891 public function getResponse()
00892 {
00893 $statuses = '';
00894 if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result){
00895 if ($trackings = $this->_result->getAllTrackings()) {
00896 foreach ($trackings as $tracking){
00897 if($data = $tracking->getAllData()){
00898 if (isset($data['status'])) {
00899 $statuses .= Mage::helper('usa')->__($data['status']);
00900 } else {
00901 $statuses .= Mage::helper('usa')->__($data['error_message']);
00902 }
00903 }
00904 }
00905 }
00906 }
00907 if (empty($statuses)) {
00908 $statuses = Mage::helper('usa')->__('Empty response');
00909 }
00910 return $statuses;
00911 }
00912
00913
00914
00915
00916
00917
00918 public function getAllowedMethods()
00919 {
00920 $allowed = explode(',', $this->getConfigData('allowed_methods'));
00921 $arr = array();
00922 foreach ($allowed as $k) {
00923 $arr[$k] = $this->getCode('method', $k);
00924 }
00925 return $arr;
00926 }
00927
00928 }