-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparceltracker.class.php
385 lines (339 loc) · 15.4 KB
/
parceltracker.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php
/**
* Parcel Tracker Class
*
* A class for parsing tracking details given a carrier and tracking number,
* and returning the data as an array, RSS feed, or SOAP string.
*
* NOTE: This class should be used in conjunction with a caching mechanism
* of your choice, see rss.php included in this project for an example.
*
* @package PHP_Parcel_Tracker
* @author Brian Stanback <[email protected]>
* @author Thom Dyson <[email protected]>
* @copyright Copyright (c) 2008, Brian Stanback, Thom Dyson
* @license http://www.apache.org/licenses/LICENSE-2.0.html Apache 2.0
* @version 3.0 <27 July 2010>
* @filesource
*/
/****************************************************************************
* Copyright 2008 Brian Stanback, Thom Dyson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
include_once('abstractcarrier.class.php');
class ParcelTracker
{
/**
* An array of instantiated carriers.
*
* @var array
*/
protected $carriers;
/**
* Default configuration options.
*
* @var array
*/
protected $defaultConfig = array(
'retrMethod' => 'curl', // HTTP retrieval method, 'curl' or 'standard' for to use
// built-in PHP stream wrappers
'dateFormat' => 'us', // Setting this to 'us' formats the date/time to U.S. standards,
// Setting it to 'iso' will format using international standards
'showDayOfWeek' => true, // Set to true to include day of week in the dates, false for no day of week
'carriersDir' => 'carriers', // Path to the carrier modules
'carriers' => array( // List of carrier modules to load
'ups' => array('UPS', 'UPSCarrier', 'ups.class.php'),
'usps' => array('USPS', 'USPSCarrier', 'usps.class.php'),
'fedex' => array('FedEx', 'FedExCarrier', 'fedex.class.php'),
'smartpost' => array('SmartPost', 'SmartPostCarrier', 'smartpost.class.php'),
'dhl' => array('DHL', 'DHLCarrier', 'dhl.class.php'),
'dhl_germany' => array('DHL', 'DHLGermanyCarrier', 'dhl_germany.class.php')
)
);
/**
* Instance-specific configuration options.
*
* @var array
*/
protected $config;
/**
* Class constructor: get, configure, and store formatting and retrieval settings.
*
* @param array $config Class configuration settings.
*/
public function __construct($config = array()) {
$this->config = array_merge($this->defaultConfig, $config);
if (!isset($this->config['url'])) {
// Detect and set this script's URL
$this->config['url'] = (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['PHP_SELF'])) ? 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] : '';
}
// Setup target date and time formatting
$dayOfWeek = ($this->config['showDayOfWeek'] == 1) ? $dayOfWeek = 'l, ' : $dayOfWeek = '';
switch (strtolower($this->config['dateFormat'])) {
case 'us':
$this->config['dateFormat'] = $dayOfWeek . 'F j, Y';
$this->config['timeFormat'] = 'g:i A';
break;
case 'iso':
default:
$this->config['dateFormat'] = $dayOfWeek . 'Y-m-d';
$this->config['timeFormat'] = 'G:i';
}
// Load and verify each of the carrier modules so that they are available
// for auto-detection of tracking numbers.
$this->carriers = array();
foreach ($this->config['carriers'] as $carrierKey => $carrier) {
list($carrierName, $carrierClass, $carrierFile) = $carrier;
include_once($this->config['carriersDir'] . '/' . $carrierFile);
if (!class_exists($carrierClass)) {
die('Error: A carrier class file could not be located (' . $carrierFile . ')');
}
$this->carriers[$carrierKey] = new $carrierClass($this->config);
if (!($this->carriers[$carrierKey] instanceof AbstractCarrier)) {
die('Error: A carrier class was loaded which doesn\'t extend AbstractCarrier (' . $carrierClass . ')');
}
}
}
/**
* Parse and return parcel details for the specified carrier and tracking number.
*
* Data is returned in the following structure:
*
* array(
* 'carrier', => [string], // Carrier
* 'trackingNumber', => [string], // Tracking Number
* 'summary' => array(
* 'service' => [string], // Service class
* 'status' => [string], // Current status
* 'destination' => [string], // Destination location
* 'last_location' => [string], // Last known location
* 'next_location' => [string], // Next known location
* 'departure' => [string], // Departure date/time
* 'est_arrival' => [string], // Estimated arrival date/time
* 'arrival' => [string], // Arrival date/time
* 'details' => [string], // Miscellaneous details
* 'time' => [string] // The last updated date/time
* ),
* 'locations' => array(
* [0] => array(
* 'location' => [string], // Location name
* 'status' => [string], // Status at location
* 'time', => [string], // Date/time of package scan
* 'details' => [string] // Package progress description
* ),
* [1] => array(
* ...
* ),
* ...
* )
*
* @param string $trackingNumber The tracking number to use for collecting parcel details.
* @param string $carrier The name of the carrier to use (defined in $config['carriers']).
* If this is blank or unspecified, auto-detection of the carrier will be attempted.
* @return array|boolean An associative array with package stats in the 'summary' key and
* an array of locations in the 'locations' key, or false if the query failed.
* @todo Throw an exception if a problem is encountered, returning the specific error.
*/
public function getDetails($trackingNumber, $carrier = '') {
$parcel = false;
if (empty($carrier)) {
$carrier = $this->detectCarrier($trackingNumber);
}
if (isset($this->carriers[$carrier])) {
// Get the package data
$parcel = $this->carriers[$carrier]->fetchData($trackingNumber);
if ($parcel) {
$parcel = array_merge(array(
'carrier' => $this->config['carriers'][$carrier][0],
'trackingNumber' => $trackingNumber
), $parcel);
}
}
return $parcel;
}
/**
* Detect which carrier a particular tracking number belongs to.
*
* @param $trackingNumber string The tracking number to detect.
* @return string|boolean The array key of the carrier, as defined in the
* carriers configuration setting or false if no match was found.
*/
public function detectCarrier($trackingNumber) {
foreach ($this->carriers as $carrierKey => $instance) {
if ($instance->isTrackingNumber($trackingNumber)) {
return $carrierKey;
}
}
return false;
}
/**
* Convert result data to a formatted RSS document.
*
* @param array $parcel The tracking result from the getDetails() method.
* @return string The rendered RSS output.
* @see getDetails()
* @todo Handle errors with the parcel by outputing more explicit messages.
*/
public function toRSS($parcel, $ttl = 3600) {
if ($parcel) {
$output = $this->rssGenerateHeader($parcel['carrier'], $ttl);
$output .= $this->rssGenerateSummaryItem($parcel['details']);
foreach ($parcel['locations'] as $location) {
$output .= $this->rssGenerateLocationItem($location);
}
} else {
$output = $this->rssGenerateHeader('N/A', $ttl);
$output .= $this->rssGenerateErrorItem();
}
$output .= $this->rssGenerateFooter();
return $output;
}
/**
* Convert result data to a JavaScript Object Notation (JSON) encoded
* format for use with XHR/AJAX-based applications.
*
* @param array $parcel The tracking result from the getDetails() method.
* @return string JSON string containing the package details and locations.
* @see getDetails()
*/
public function toJSON($parcel) {
return json_encode($parcel);
}
/**
* Generate a standard RSS header.
*
* @return string The RSS header.
* @see toRSS()
*/
protected function rssGenerateHeader($carrier, $ttl = 0) {
$output = '<?xml version="1.0" encoding="utf-8"?>' . "\n" .
'<rss version="2.0">' . "\n" .
"\t" . '<channel>' . "\n" .
"\t\t" . '<title>Package Tracking Results</title>' . "\n" .
"\t\t" . '<description>Tracking details provided by ' . $carrier . '</description>' . "\n" .
"\t\t" . '<link>' . $this->config['url'] . '</link>' . "\n";
if ($ttl > 0) {
$output .= "\t\t" . '<ttl>' . $ttl . '</ttl>' . "\n";
}
return $output;
}
/**
* Generate the summary details for package tracking results.
*
* @param array $data An associative array containing the details portion from the
* getDetails() return value.
* @return string An RSS summary item.
* @see toRSS()
*/
protected function rssGenerateSummaryItem($data) {
$output = "\t\t" . '<item>' . "\n";
$output .= "\t\t\t" . '<title>Summary</title>' . "\n";
$output .= "\t\t\t" . '<description>';
if (isset($data['status']) && !empty($data['status'])) {
$output .= '<b>Status:</b> ' . $data['status'] . '<br/>';
}
$output .= '<b>As of:</b> ' . date($this->config['dateFormat'] . ' ' . $this->config['timeFormat'], isset($data['time']) ? strtotime($data['time']) : time()) . '<br/>';
if (isset($data['departure']) && !empty($data['departure'])) {
if (($departureTime = @strtotime($data['departure'])) != false) {
$output .= '<b>Departure:</b> ' . date($this->config['dateFormat'], $departureTime) . '<br/>';
} else {
$output .= '<b>Departure:</b> ' . $data['departure'] . '<br/>';
}
}
if (isset($data['destination']) && !empty($data['destination'])) {
$output .= '<b>Destination:</b> ' . $data['destination'] . '<br/>';
}
if (isset($data['service']) && !empty($data['service'])) {
$output .= '<b>Service Type:</b> ' . $data['service'] . '<br/>';
}
if (isset($data['est_arrival']) && !empty($data['est_arrival'])) {
if (($estArrivalTime = @strtotime($data['est_arrival'])) != false) {
$output .= '<b>Est. Arrival:</b> ' . date($this->config['dateFormat'], $estArrivalTime) . '<br/>';
} else {
$output .= '<b>Est. Arrival:</b> ' . $data['est_arrival'] . '<br/>';
}
} else if (isset($data['arrival']) && !empty($data['arrival'])) {
if (($arrivalTime = @strtotime($data['arrival'])) != false) {
$output .= '<b>Arrival:</b> ' . date($this->config['dateFormat'], $arrivalTime) . '<br/>';
} else {
$output .= '<b>Arrival:</b> ' . $data['arrival'] . '<br/>';
}
}
if (isset($data['last_location']) && !empty($data['last_location'])) {
$output .= '<b>Last Location:</b> ' . $data['last_location'] . '<br/>';
}
if (isset($data['next_location']) && !empty($data['next_location'])) {
$output .= '<b>Next Location:</b> ' . $data['next_location'] . '<br/>';
}
if (isset($data['details']) && !empty($data['details'])) {
$output .= '<b>Details:</b> ' . $data['details'] . '<br/>';
}
$output .= '</description>' . "\n";
$output .= "\t\t\t" . '<pubDate>' . date('D, d M Y H:i:s O') . '</pubDate>' . "\n";
$output .= "\t\t" . '</item>' . "\n";
return $output;
}
/**
* Generate the item for a tracked origin/destination point.
*
* @param array $data An associative array containing a single location from
* the locations portion of the getDetails() return value.
* @return string An RSS location item.
* @see toRSS()
*/
protected function rssGenerateLocationItem($data) {
$output = "\t\t" . '<item>' . "\n";
$output .= "\t\t\t" . '<title>' . $data['status'] . '</title>' . "\n";
$output .= "\t\t\t" . '<description>';
if (isset($data['location']) && !empty($data['location'])) {
$output .= 'Location: ' . $data['location'] . '<br/>';
}
if (isset($data['details']) && !empty($data['details'])) {
$output .= 'Details: ' . $data['details'] . '<br/>';
}
if (isset($data['time']) && ($time = @strtotime($data['time'])) != false) {
$output .= 'Local Time: ' . date($this->config['dateFormat'] . ' ' . $this->config['timeFormat'], $time) . '<br/>';
} else {
$time = time();
}
$output .= '</description>' . "\n";
$output .= "\t\t\t" . '<pubDate>' . date('D, d M Y H:i:s O', $time) . '</pubDate>' . "\n";
$output .= "\t\t" . '</item>' . "\n";
return $output;
}
/**
* Build and return an invalid tracking number error.
*
* @return string An RSS error item.
* @see toRSS()
*/
protected function rssGenerateErrorItem() {
$output = "\t\t" . '<item>' . "\n";
$output .= "\t\t\t" . '<title>Summary</title>' . "\n";
$output .= "\t\t\t" . '<description><b><font color="#777777">Error</font><br/>The tracking number is invalid, has expired, or is not yet in the system.<b></description>' . "\n";
$output .= "\t\t\t" . '<pubDate>' . date('D, d M Y H:i:s O') . '</pubDate>' . "\n";
$output .= "\t\t" . '</item>' . "\n";
$output .= $html;
return $output;
}
/**
* Generate an RSS footer.
*
* @return string The RSS footer.
* @see toRSS()
*/
protected function rssGenerateFooter() {
return "\t</channel>\n</rss>\n";
}
}