Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 601 lines (422 sloc) 20.785 kB
93c4d4c @pdweinstein Initial Commit
authored
1 <?php
2
3 /*
4 * This CTA class file is an API wrapper for interfacing with the Chicago Transit Authority's three web-based Application Programming
a2f03a5 @pdweinstein Added more info to README on how to use the class. Minor changes to c…
authored
5 * Interfaces for Bus, Train ('El') and Alerts related information.
93c4d4c @pdweinstein Initial Commit
authored
6 *
a2f03a5 @pdweinstein Added more info to README on how to use the class. Minor changes to c…
authored
7 * Due to the evolution of the CTA's API interfaces, there are three distinct APIs, one for Bus, Train and Customer Alerts information. As a
93c4d4c @pdweinstein Initial Commit
authored
8 * result there are three distinct URI endpoints and two distinct API keys.
9 *
a2f03a5 @pdweinstein Added more info to README on how to use the class. Minor changes to c…
authored
10 * This class brings all three APIs together into one object with related methods for accessing Bus, Train and Customer Alert information.
93c4d4c @pdweinstein Initial Commit
authored
11 *
12 * However, there is no requirement that both an Bus and Train API key are needed to use this class file. That is while this class
13 * file helps to unify the three distinct APIs together for a PHP developer, this class can also be used to interface with just the
a2f03a5 @pdweinstein Added more info to README on how to use the class. Minor changes to c…
authored
14 * Bus, Train or Customer Alert API and nothing else.
93c4d4c @pdweinstein Initial Commit
authored
15 *
16 * Thus the initiation of the object is done by simply providing a Bus and/or Train API Key.
17 *
18 * More information about the CTA's APIs, including terms of use and including how to request API Keys, can be found at:
19 * http://www.transitchicago.com/developers/default.aspx
20 *
a2f03a5 @pdweinstein Added more info to README on how to use the class. Minor changes to c…
authored
21 * @package CTA
22 * @author Paul Weinstein, <pdw@weinstein.org>
23 * @version 1.0
24 * @copyright Copyright (c) 2011 Paul Weinstein, <pdw@weinstein.org>
25 * @license MIT License, <https://github.com/pdweinstein/PHP-Wrapper-for-CTA-APIs/blob/master/LICENSE>
93c4d4c @pdweinstein Initial Commit
authored
26 *
27 * Copyright (c) 2011 Paul Weinstein, <pdw@weinstein.org>
28 *
29 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
30 * (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
31 * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
32 * so, subject to the following conditions:
33 *
34 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
35 *
36 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
37 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
38 * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
39 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40 *
41 */
42
43 // Class is in session
44 class CTA {
45
46 var $trainAPIURL = 'lapi.transitchicago.com/api/1.0/';
47 var $busAPIURL = 'www.ctabustracker.com/bustime/api/v1/';
48 var $statusAPIURL = 'www.transitchicago.com/api/1.0/';
49 var $trainAPIKey = '';
50 var $busAPIKey = '';
51 var $timeout = '300';
52 var $debug = false;
53
54 /**
55 * __construct function, the initiation of the object where developer's API key(s) are collected and stored for use
56 *
57 * @access public
58 * @param string $trainKey, A CTA Train API Key. Optional. (default: '')
59 * @param string $busKey, A CTA Bus API Key. Optional. (default: '')
60 * @param bool $debug, Enable/Disable debugging information. Optional. (default: false)
61 * @return void
62 *
63 */
64 public function __construct( $trainKey = '', $busKey = '', $debug = false ) {
65
66 $this->trainAPIKey = urlencode( $trainKey );
67 $this->busAPIKey = urlencode( $busKey );
68 $this->debug = $debug;
69
70 }
71
72 /**
73 * statusRoutes function, uses the routes method of the customer alerts API to get status information about various CTA services
74 *
75 * @access public
76 * @param array $types, An array listing what types of service to request status information for. Required
77 * bus, rail, station and systemwide are valid service types. Status of one or more service types can be requested
78 * @param array $routeIDs, An array listing what routes to return status information for. Optional. (default: '')
79 * Note for the unique identifier for routes for this method are defined by General Transit Feed Specification (GTFS)
80 * See http://www.transitchicago.com/developers/gtfs.aspx for more information
81 * @param array $stationIDs, An array provding a list of station ids to request status information about. Optional. (default: '')
82 * Note for the unique identifier for routes for this method are defined by General Transit Feed Specification (GTFS)
83 * See http://www.transitchicago.com/developers/gtfs.aspx for more information
84 * @return array Returns an array of results from the XML result of the API call or false if an error is detected.
85 */
86 public function statusRoutes( $types, $routeIDs = array(), $stationIDs = array() ) {
87
88 $t = '';
89 $r = '';
90 $s = '';
91
92 // $types, routeIDs and $stationIDs are csv in GET arguments so
93 // validate, format and pass on
94 if ( is_array( $types ) AND is_array( $routeIDs ) AND is_array( $stationIDs )){
95
96 foreach( $types as $type ){
97
98 $t .= urlencode( $type ). ',';
99
100 }
101
102 foreach( $routeIDs as $route ){
103
104 $r .= urlencode( $route ). ',';
105
106 }
107
108 foreach( $stationIDs as $station ){
109
110 $s .= urlencode( $station ). ',';
111
112 }
113
114 } else {
115
116 // An error occured are we in debugging mode?
117 if ( $this->debug ) {
118
119 echo 'Unknown parameter. Lists of Service Type, Route IDs and station IDs need to be provided in an array.';
120
121 }
122
123 return false;
124
125 }
126
127 $args = 'type=' .$t. '&routeid=' .$r. '&stationid=' .$s;
128 $response = $this->httpRequest( $this->statusAPIURL. 'routes.aspx?', '', $args );
129 return simplexml_load_string( $response );
130
131 }
132
133 /**
134 * statusAlerts function, uses the alerts method of the customer alerts API to get alerts about various CTA services
135 *
136 * @access public
137 * @param string $active, true/false string denotes if the request is for only active service alerts. Optional. (default: 'false')
138 * @param string $accessibility, true/false string dentoes if the request is for service alerts regarding accessibility. Optional.
139 * (default: 'true')
140 * @param string $planned, true/false string denotes if the request is to include common, planned alerts. Optional. (default: 'true')
141 * @param array $routeIDs, An array listing what routes to return status information for. Optional. (default: '')
142 * Note for the unique identifier for routes for this method are defined by General Transit Feed Specification (GTFS)
143 * See http://www.transitchicago.com/developers/gtfs.aspx for more information
144 * @param array $stationIDs, An array provding a list of station ids to request status information about. Optional. (default: '')
145 * Note for the unique identifier for routes for this method are defined by General Transit Feed Specification (GTFS)
146 * See http://www.transitchicago.com/developers/gtfs.aspx for more information
147 * @param string $byStartDate, An date formatted string that provides alerts starting prior to the date given. Optional.
148 * Date Format is yyyyMMdd
149 * @param int $recentDays, An interger denoting the number of days before current date. Optional.
150 * @return array Returns an array of results from the XML result of the API call or false if an error is detected.
151 *
152 */
153 public function statusAlerts( $active = 'false', $accessibility = 'true', $planned = 'true', $routeIDs = array(), $stationIDs = array(), $byStartDate = '', $recentDays = '' ){
154
155 $r = '';
156 $s = '';
157
158 // RouteIDs and $stationIDs become csv strings for GET
159 // validate, format and pass on
160
161 if ( is_array( $routeIDs ) AND is_array( $stationIDs )){
162
163 foreach( $routeIDs as $route ){
164
165 $r .= urlencode( $route ). ',';
166
167 }
168
169 foreach( $stationIDs as $station ){
170
171 $s .= urlencode( $station ). ',';
172
173 }
174
175 } else {
176
177 // An error occured are we in debugging mode?
178 if ( $this->debug ) {
179
180 echo 'Unknown parameter. Lists of Route IDs and station IDs need to be provided in an array.';
181
182 }
183
184 return false;
185
186 }
187
188 $args = 'activeonly=' .urlencode( $active ). '&accessibility=' . urlencode( $accessibility ). '&planned=' .urlencode( $planned ). '&routeid=' .$r. '&stationid=' .$s. '&bystartdate=' . urlencode( $byStartDate ). '&recentdays=' . urlencode( $recentdays );
189 $response = $this->httpRequest( $this->statusAPIURL. 'alerts.aspx?', '', $args );
190 return simplexml_load_string( $response );
191
192 }
193
194 /**
195 * train function, Using the Train API and Key, provides a list of predictions of train arrivles based on provided arguments
196 *
197 * @access public
198 * @param string $mapID, An identifier denoting what station to provide predictions for. Required if no $stopID is provided
199 * Note for the unique identifier for stations are defined by General Transit Feed Specification (GTFS)
200 * See http://www.transitchicago.com/developers/gtfs.aspx for more information
201 * @param string $stopID, An identifier denoting what platform or platform side to provide predictions for.
202 * Required id no $mapID is provided
203 * Note for the unique identifier for stations are defined by General Transit Feed Specification (GTFS)
204 * See http://www.transitchicago.com/developers/gtfs.aspx for more information
205 * @param string $maxResults, The maximum number of results desired. Optional. (default: '')
206 * @param string $routeCode, Allows for the specification of a single route (default: '')
207 * @return array Returns an array of results from the XML result of the API call.
208 *
209 */
210 public function train( $mapID = '', $stopID = '', $maxResults = '', $routeCode = '' ) {
211
212 // Validate our arguments and prep for GET Request
213 $args = '&mapid=' . urlencode( $mapID ). '&stpid=' .urlencode( $stopID ). '&max=' .urlencode( $maxResults ). '&rt=' . urlencode( $routeCode );
214
215 $response = $this->httpRequest( $this->trainAPIURL. 'ttarrivals.aspx?key=' .$this->trainAPIKey, $args );
216
217 // Parse our XML into array and return
218 return simplexml_load_string( $response );
219
220 }
221
222 /**
223 * bustime function, get the local date and time as defined by the CTA Bus Tracker system/API
224 *
225 * @access public
226 * @return array Returns an array of results from the XML result of the API call.
227 *
228 */
229 public function bustime(){
230
231 $response = $this->httpRequest( $this->busAPIURL. 'gettime?key=' .$this->busAPIKey );
232 return simplexml_load_string( $response );
233
234 }
235
236 /**
237 * busGetVehicles function, that provides vehicle information via bus API
238 *
239 * @access public
240 * @param array $vehicleID, An array of vehicle ids. A maximum of 10 ids can be provided. Required if routeNo(s) are not provide
241 * (default: array())
242 * @param array $routeNo, An array of bus route number(s). A maimum of 10 routes can be provided. Required if vechicle id(s)
243 * are not provided. (default: array())
244 * @return array Returns an array of results from the XML result of the API call or false if an error is detected.
245 *
246 */
247 public function busGetVehicles( $vehicleIDs = array(), $routeNos = array() ) {
248
249 // Note arguemtns are either or, either vehicle id or route number
250 if ((( !$vehicleIDs ) AND ( !$routeNos )) OR (( $vehicleIDs ) AND ( $routeNos ))) {
251
252 // An error occured are we in debugging mode?
253 if ( $this->debug ) {
254
255 echo 'Too many or too few arguments. Need to provide vehicle IDs or route number.';
256
257 }
258
259 return false;
260
261 } else if ( is_array( $vehicleIDs ) AND sizeof( $vehicleIDs ) > 0 ) {
262 echo 'here';
263 $v = '';
264
265 foreach( $vehicleIDs as $vehicle ){
266
267 $v .= urlencode( $vehicle ). ',';
268
269 }
270
271 $args = '&vid=' .$v;
272 $reponse = $this->httpRequest( $this->busAPIURL. 'getvehicles?key=' .$this->busAPIKey, $args );
273 return simplexml_load_string( $reponse );
274
275 } else if ( is_array( $routeNos ) AND sizeof( $routeNos ) > 0 ) {
276
277 $r = '';
278
279 foreach( $routeNos as $route ){
280
281 $r .= urlencode( $route ). ',';
282
283 }
284
285 $args = '&rt=' .$r;
286 $reponse = $this->httpRequest( $this->busAPIURL. 'getvehicles?key=' .$this->busAPIKey, $args );
287 return simplexml_load_string( $reponse );
288
289 } else {
290
291 // An error occured are we in debugging mode?
292 if ( $this->debug ) {
293
294 echo 'An unknown error occurred.';
295
296 }
297
298 return false;
299
300 }
301
302 }
303
304 /**
305 * busGetRoutes function, provides a list of routes currently in service
306 *
307 * @access public
308 * @return array Returns an array of results from the XML result of the API call.
309 *
310 */
311 public function busGetRoutes(){
312
313 $response = $this->httpRequest( $this->busAPIURL. 'getroutes?key=' .$this->busAPIKey );
314 return simplexml_load_string( $response );
315
316 }
317
318 /**
319 * busGetDirections function provides the bi-directional nature of the route. i.e, is the bus route East - West or North - South
320 *
321 * @access public
322 * @param string $routeNo is the route number to check. Required.
323 * @return array Returns an array of results from the XML result of the API call.
324 *
325 */
326 public function busGetDirections( $routeNo ){
327
328 $args = '&rt=' .urlencode( $routeNo );
329
330 $response = $this->httpRequest( $this->busAPIURL. 'getdirections?key=' .$this->busAPIKey, $args );
331 return simplexml_load_string( $response );
332
333 }
334
335 /**
336 * busGetStops function provides a list of stops for a specific route traveling in a single, specific direction.
337 *
338 * @access public
339 * @param string $routeNo, is the route number be checked. Required
340 * @param string $direction is the direction of the route. Required.
341 * @return array Returns an array of results from the XML result of the API call.
342 *
343 */
344 public function busGetStops( $routeNo, $direction ){
345
346 $args = '&rt=' .urlencode( $routeNo ). '&dir=' .urlencode( $direction );
347
348 $response = $this->httpRequest( $this->busAPIURL. 'getstops?key=' .$this->busAPIKey, $args );
349 return simplexml_load_string( $response );
350
351 }
352
353 // Note: patternIDs is csv string
354 /**
355 * busGetPatterns function provides a set of geo-locations that can be connected to create a layout
356 *
357 * @access public
358 * @param array $patternIDs is an array containing no more than 10 pattern ids. Required if route number is not provided.
359 * (default: array())
360 * @param string $routeNo a string of a single route number. Required if pattern id(s) are not provided. (default: '')
361 * @return array Returns an array of results from the XML result of the API call or false if an error is detected.
362 *
363 */
364 public function busGetPatterns( $patternIDs = array(), $routeNo = '' ){
365
366 // Note arguemtns are either or, either vehicle id or route number
367 if ((( !$patternIDs ) AND ( !$routeNo )) OR (( $patternIDs ) AND ( $routeNo ))) {
368
369 // An error occured are we in debugging mode?
370 if ( $this->debug ) {
371
372 echo 'Too many or too few arguments. Need to provide pattern IDs or a route number.';
373
374 }
375
376 return false;
377
378 } else if ( is_array( $patternIDs ) AND sizeof( $patternIDs ) > 0 ) {
379
380 $p = '';
381
382 foreach( $patternIDs as $pattern ){
383
384 $p .= urlencode( $pattern ). ',';
385
386 }
387
388 $args = '&pid=' .$p;
389
390 $reponse = $this->httpRequest( $this->busAPIURL. 'getpatterns?key=' .$this->busAPIKey, $args );
391 return simplexml_load_string( $reponse );
392
393 } else if ( $routeNo != '' ) {
394
395 $args = '&rt=' .urlencode( $routeNo );
396 $reponse = $this->httpRequest( $this->busAPIURL. 'getpatterns?key=' .$this->busAPIKey, $args );
397 return simplexml_load_string( $reponse );
398
399 } else {
400
401 // An error occured are we in debugging mode?
402 if ( $this->debug ) {
403
404 echo 'An unknown error occurred.';
405
406 }
407
408 return false;
409
410 }
411
412 }
413
414 /**
415 * busGetPredictions function for getting predictions of arrivals for one or more stops or one or more vehicles.
416 *
417 * @access public
418 * @param array $stopIDs, Up to 10 stop IDs to get predictions for. Required if no vehicle id is provided. (default: array())
419 * @param array $routeNos, Up to 10 route numbers for matching with stop id(s). Optional with $stopIDs. (default: array())
420 * @param array $vehicleIDs, Up to 10 vechicle IDs. Required if no stop id(s) are provided. (default: array())
421 * @param string $limit of prodictions to return. Optional (default: '')
422 * @return array Returns an array of results from the XML result of the API call or false if an error is detected.
423 *
424 */
425 public function busGetPredictions( $stopIDs = array(), $routeNos = array(), $vehicleIDs = array(), $limit = '' ){
426
427 // routeNos and $vehicleIDs can be comebined together, but not with vehicleIDs
428 if ( sizeof( $stopIDs ) > 0 AND sizeof( $vehicleIDs ) > 0 ) {
429
430 // An error occured are we in debugging mode?
431 if ( $this->debug ) {
432
433 echo 'Conflicting arguments. Cannot provide both stop id(s) and vehicle id(s).';
434
435 }
436
437 return false;
438
439 }
440
441 if ( is_array( $stopIDs ) AND sizeof( $stopIDs ) > 0 AND is_array( $routeNos ) AND sizeof( $routeNos ) > 0 ) {
442
443 $s = '';
444
445 foreach( $stopIDs as $stop ){
446
447 $s .= urlencode( $stop ). ',';
448
449 }
450
451 $r = '';
452
453 foreach( $routeNos as $route ){
454
455 $r .= urlencode( $route ). ',';
456
457 }
458
459 $args = '&stpid=' .$s. '&rt=' .$r. '$top=' . urlencode( $limit );
460 $response = $this->httpRequest( $this->busAPIURL. 'getpredictions?key=' .$this->busAPIKey, $args );
461
462 } else if ( $vehicleIDs ) {
463
464 $v = '';
465
466 foreach( $vehicleIDs as $vehicle ){
467
468 $r .= urlencode( $vehicle ). ',';
469
470 }
471
472 $args = '&vid=' .$v. '&top=' .urlencode( $limit );
473 $response = $this->httpRequest( $this->busAPIURL, 'getprediections?key=' .$this->busAPIKey, $args );
474
475 } else {
476
477 // An error occured are we in debugging mode?
478 if ( $this->debug ) {
479
480 echo 'An unknown error occurred.';
481
482 }
483
484 return false;
485
486 }
487
488 return simplexml_load_string( $response );
489
490 }
491
492 /**
493 * busGetServiceBulletins function, provides bus related service information on for a list of routes or stops
494 *
495 * @access public
496 * @param array $routeNos, an array of route numbers. Required if no stop id(s) are provided. (default: array())
497 * @param array $stopIDs, an array of stop id(s). Required id no route numbers are provided. (default: array())
498 * @param string $direction, is simplly a single route direction and is required with route number. (default: '')
499 * @return array Returns an array of results from the XML result of the API call or false if an error is detected.
500 *
501 */
502 public function busGetServiceBulletins( $routeNos = array(), $stopIDs = array(), $direction = '' ){
503
504 if ( is_array( $stopIDs ) AND sizeof( $stopIDs ) > 0 OR is_array( $routeNos ) AND sizeof( $routeNos ) > 0 ) {
505
506 $s = '';
507
508 foreach( $stopIDs as $stop ){
509
510 $s .= urlencode( $stop ). ',';
511
512 }
513
514 $r = '';
515
516 foreach( $routeNos as $route ){
517
518 $r .= urlencode( $route ). ',';
519
520 }
521
522 $args = '&rt=' .$r. '&rtdir=' .urlencode( $direction ). '&stpid=' .$s;
523 echo 'Here is: ' .$args;
524 $response = $this->httpRequest( $this->busAPIURL. 'getservicebulletins?key=' .$this->busAPIKey, $args );
525 return simplexml_load_string( $response );
526
527 } else {
528
529 // An error occured are we in debugging mode?
530 if ( $this->debug ) {
531
532 echo 'Too few arguments. Need to provide at least one stop id or one route id.';
533
534 }
535
536 return false;
537
538 }
539
540 }
541
542 /**
543 * httpRequest function, our function for using the cURL libraries and sending the HTTP request.
544 *
545 * @access private
546 * @param string $reqURL, The URI endpoing and API Key, if required, of API. Required.
547 * @param string $args, The GET arguments, after the API Key, required for a sucessful request. Optional. (default: '')
548 * @return string The results of the HTTP request
549 *
550 */
551 private function httpRequest( $reqURL, $args = '' ) {
552
553
554 // Configure cURL for our request
555 $curl_handle = curl_init();
556
557 // Set for GET
558 curl_setopt( $curl_handle, CURLOPT_HTTPGET, 1 );
559
560 $reqURL .= $args;
561 $reqURL = 'http://' .$reqURL;
562 //$reqURL = 'http://' .urlencode( $reqURL );
563
564 // Provide our URL
565 curl_setopt ( $curl_handle, CURLOPT_URL, $reqURL );
566
567 // Set add'l cURL headers
568 curl_setopt( $curl_handle, CURLOPT_HEADER, 0 );
569 curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, 1 );
570 curl_setopt( $curl_handle, CURLOPT_TIMEOUT, $this->timeout );
571 curl_setopt( $curl_handle, CURLOPT_CONNECTTIMEOUT, 1 );
572
573 // Debug?
574 if ( $this->debug ) {
575
576 echo 'This is request URL ' .$reqURL;
577
578 }
579
580 // And execute
581 $response = curl_exec( $curl_handle );
582 $code = curl_getinfo( $curl_handle, CURLINFO_HTTP_CODE );
583
584 // Close up shop
585 curl_close( $curl_handle );
586
587 if (( $code != '200' ) OR ( $this->debug )) {
588
589
590
591 }
592
593 return $response;
594
595 }
596
597 }
598 // Class Dismissed
599
600 ?>
Something went wrong with that request. Please try again.