-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCkan_client.php
701 lines (640 loc) · 16.3 KB
/
Ckan_client.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
<?php
/**
* Ckan_client class
*
* A PHP client for the CKAN (Comprehensive Knowledge Archive Network) API.
*
* For details and documentation, please see http://github.com/jeffreybarke/Ckan_client-PHP
*
* @author Jeffrey Barke
* @copyright Copyright 2010 Jeffrey Barke
* @license http://github.com/jeffreybarke/Ckan_client-PHP/blob/master/LICENSE
* @link http://github.com/jeffreybarke/Ckan_client-PHP
*
*/
class Ckan_client
{
// Properties ---------------------------------------------------------
/**
* Client's API key. Required for any PUT or POST methods.
*
* @link http://knowledgeforge.net/ckan/doc/ckan/api.html#ckan-api-keys
* @since Version 0.1.0
*/
private $api_key = FALSE;
/**
* Version of the CKAN API we're using.
*
* @var string
* @link http://knowledgeforge.net/ckan/doc/ckan/api.html#api-versions
* @since Version 0.1.0
*/
private $api_version = '2';
/**
* URI to the CKAN web service.
*
* @var string
* @since Version 0.1.0
*/
private $base_url = 'http://api.data.gov.ph/api/%d';
/**
* Internal cURL object.
*
* @since Version 0.1.0
*/
private $ch = FALSE;
/**
* cURL headers.
*
* @since Version 0.1.0
*/
private $ch_headers;
/**
* Standard HTTP status codes.
*
* @var array
* @since Version 0.1.0
*/
private $http_status_codes = array(
'200' => 'OK',
'301' => 'Moved Permanently',
'400' => 'Bad Request',
'403' => 'Not Authorized',
'404' => 'Not Found',
'409' => 'Conflict (e.g. name already exists)',
'500' => 'Service Error'
);
/**
* Array of CKAN resources and their URI fragment.
*
* @var array
* @link http://knowledgeforge.net/ckan/doc/ckan/api.html#ckan-model-api
* @since Version 0.1.0
*/
private $resources = array(
'package_register' => 'rest/package',
'package_entity' => 'rest/package',
'group_register' => 'rest/group',
'group_entity' => 'rest/group',
'tag_register' => 'rest/tag',
'tag_entity' => 'rest/tag',
'rating_register' => 'rest/rating',
'rating_entity' => 'rest/rating',
'revision_register' => 'rest/revision',
'revision_entity' => 'rest/revision',
'license_list' => 'rest/licenses',
'package_search' => 'search/package'
);
/**
* Ckan_client user agent string.
*
* @var string
* @since Version 0.1.0
*/
private $user_agent = 'Ckan_client-PHP/%s';
/**
* Ckan_client version number.
*
* @var string
* @since Version 0.1.0
*/
private $version = '0.1.0';
// Magic methods ------------------------------------------------------
/**
* Constructor
*
* Calls the API key, base URI and user agent setters.
* Initializes the internal cURL object.
*
* @param string CKAN API key.
*/
public function __construct($api_key = FALSE)
{
// If provided, set the API key.
if ($api_key)
{
$this->set_api_key($api_key);
}
// Set base URI and Ckan_client user agent string.
$this->set_base_url();
$this->set_user_agent();
// Create cURL object.
$this->ch = curl_init();
// Follow any Location: headers that the server sends.
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE);
// However, don't follow more than five Location: headers.
curl_setopt($this->ch, CURLOPT_MAXREDIRS, 5);
// Automatically set the Referer: field in requests
// following a Location: redirect.
curl_setopt($this->ch, CURLOPT_AUTOREFERER, TRUE);
// Return the transfer as a string instead of dumping to screen.
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
// If it takes more than 45 seconds, fail
curl_setopt($this->ch, CURLOPT_TIMEOUT, 45);
// We don't want the header (use curl_getinfo())
curl_setopt($this->ch, CURLOPT_HEADER, FALSE);
// Set user agent to Ckan_client
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->user_agent);
// Track the handle's request string
curl_setopt($this->ch, CURLINFO_HEADER_OUT, TRUE);
// Attempt to retrieve the modification date of the remote document.
curl_setopt($this->ch, CURLOPT_FILETIME, TRUE);
// Initialize cURL headers
$this->set_headers();
// Include PHP Markdown library
require_once('lib/php_markdown/markdown.php');
}
/**
* Destructor
*
* Since it's possible to leave cURL open, this is the last chance to
* close it.
*/
public function __destruct()
{
// Cleanup
if ($this->ch)
{
curl_close($this->ch);
unset($this->ch);
}
}
// Setters ------------------------------------------------------------
/**
* Sets the CKAN API key.
*
* @access public
* @param string CKAN API key.
* @return void
* @since Version 0.1.0
*/
public function set_api_key($api_key)
{
$this->api_key = $api_key;
}
/**
* Sets the CKAN API base URI.
*
* @access private
* @return void
* @since Version 0.1.0
*/
private function set_base_url()
{
// Append the CKAN API version to the base URI.
$this->base_url = sprintf($this->base_url, $this->api_version);
}
/**
* Sets the custom cURL headers.
*
* @access private
* @return void
* @since Version 0.1.0
*/
private function set_headers()
{
$date = new DateTime(NULL, new DateTimeZone('UTC'));
$this->ch_headers = array(
'Date: ' . $date->format('D, d M Y H:i:s') . ' GMT', // RFC 1123
'Accept: application/json;q=1.0, application/xml;q=0.5, */*;q=0.0',
'Accept-Charset: utf-8',
'Accept-Encoding: gzip'
);
}
/**
* Sets the Ckan_client user agent string.
*
* @access private
* @return void
* @since Version 0.1.0
*/
private function set_user_agent()
{
if ('80' === @$_SERVER['SERVER_PORT'])
{
$server_name = 'http://' . $_SERVER['SERVER_NAME'];
}
else
{
$server_name = '';
}
$this->user_agent = sprintf($this->user_agent, $this->version) .
' (' . $server_name . $_SERVER['PHP_SELF'] . ')';
}
// Public (API) methods -----------------------------------------------
// Package register resource
/**
* @access public
* @return array An array of all package IDs.
* @since Version 0.1.0
*/
public function get_package_register()
{
return $this->make_request('GET', $this->resources['package_register']);
}
/**
* @access public
* @param string Package
* @return bool
* @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
* @since Version 0.1.0
*/
public function post_package_register($data)
{
return $this->make_request('POST',
$this->resources['package_register'],
$data);
}
// Package entity resouce
/**
* @access public
* @param string Package ID
* @return object Package
* @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
* @since Version 0.1.0
*/
public function get_package_entity($package)
{
return $this->make_request('GET',
$this->resources['package_entity'] . '/' . urlencode($package));
}
/**
* @access public
* @param string Package ID
* @param string Packing
* @return bool
* @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
* @since Version 0.1.0
*/
public function put_package_entity($package, $data)
{
return $this->make_request('PUT',
$this->resources['package_entity'] . '/' . urlencode($package),
$data);
}
// Package utility alias
/**
* CKAN package GET utility alias.
*
* @see get_package_register(), get_package_entity()
* @access public
* @since Version 0.1.0
*/
public function get_package($package = FALSE)
{
if ($package)
{
return $this->get_package_entity($package);
}
else
{
return $this->get_package_register();
}
}
// Group register resource
/**
* @access public
* @return array An array of all group IDs.
* @since Version 0.1.0
*/
public function get_group_register()
{
return $this->make_request('GET', $this->resources['group_register']);
}
// Group entity resource
/**
* @access public
* @param string Group ID
* @return object Group
* @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
* @since Version 0.1.0
*/
public function get_group_entity($group)
{
return $this->make_request('GET',
$this->resources['group_entity'] . '/' . urlencode($group));
}
// Group utility alias
/**
* CKAN group GET utility alias.
*
* @see get_group_register(), get_group_entity()
* @access public
* @since Version 0.1.0
*/
public function get_group($group = FALSE)
{
if ($group)
{
return $this->get_group_entity($group);
}
else
{
return $this->get_group_register();
}
}
// Tag register resource
/**
* @access public
* @since Version 0.1.0
*/
public function get_tag_register()
{
return $this->make_request('GET', $this->resources['tag_register']);
}
// Tag entity resource
/**
* @access public
* @since Version 0.1.0
*/
public function get_tag_entity($tag)
{
return $this->make_request('GET', $this->resources['tag_entity'] .
'/' . urlencode($tag));
}
// Tag utility alias
/**
* @access public
* @since Version 0.1.0
*/
public function get_tag($tag = FALSE)
{
if ($tag)
{
return $this->get_tag_entity($tag);
}
else
{
return $this->get_tag_register();
}
}
// Revision register resource
/**
* @access public
* @since Version 0.1.0
*/
public function get_revision_register()
{
return $this->make_request('GET',
$this->resources['revision_register']);
}
// Revision entity resource
/**
* @access public
* @since Version 0.1.0
*/
public function get_revision_entity($revision)
{
return $this->make_request('GET',
$this->resources['revision_entity'] . '/' . urlencode($revision));
}
// Revision utility alias
/**
* @access public
* @since Version 0.1.0
*/
public function get_revision($revision = FALSE)
{
if ($revision)
{
return $this->get_revision_entity($revision);
}
else
{
return $this->get_revision_register();
}
}
// License list resource
/**
* @access public
* @since Version 0.1.0
*/
public function get_license_list()
{
return $this->make_request('GET', $this->resources['license_list']);
}
// License utility alias
public function get_license()
{
return $this->get_license_list();
}
// Search API
/**
* Searches CKAN packages.
*
* @access public
* @param string Keywords to search for
* @param array Optional. Search options.
* @return mixed If success, search object. On fail, false.
* @since Version 0.1.0
*/
public function search_package($keywords, $opts = array())
{
// Gots to have keywords or there's nothing to search for.
// Also, $opts better be an array
if (0 === strlen(trim($keywords)) || FALSE === is_array($opts))
{
throw new Exception('We need keywords, yo!');
}
$q = '';
// Set querystring based on $opts param.
$q .= '&order_by=' . ((isset($opts['order_by']))
? urlencode($opts['order_by']) : 'rank');
$q .= '&offset=' . ((isset($opts['offset']))
? urlencode($opts['offset']) : '0');
$q .= '&limit=' . ((isset($opts['limit']))
? urlencode($opts['limit']) : '20');
$q .= '&filter_by_openness=' . ((isset($opts['openness']))
? urlencode($opts['openness']) : '0');
$q .= '&filter_by_downloadable=' . ((isset($opts['downloadable']))
? urlencode($opts['downloadable']) : '0');
return $data = $this->make_request('GET',
$this->resources['package_search'] . '?q=' .
urlencode($keywords) . $q);
}
/**
* CKAN package search utility alias, since it's most likely ppl just
* want to search the packages.
*
* @see search_package()
* @access public
* @since Version 0.1.0
*/
public function search($keywords, $opts = array())
{
return $this->search_package($keywords, $opts);
}
// Public methods -----------------------------------------------------
/**
* Helper function to ease the display of search results.
* Outputs directly to screen.
*
* @access public
* @param object Result from search() or search_package()
* @param array Optional. An array of formatting options.
* @return void
* @since Version 0.1.0
*/
public function search_display($data, $opts = array())
{
if ($data)
{
// Set vars based on $opts param.
$search_term = (isset($opts['search_term'])) ?
$opts['search_term'] : '';
$title_tag = '<' .
((isset($opts['title_tag'])) ? $opts['title_tag'] : 'h2') . '>';
$title_close_tag = str_replace('<', '</', $title_tag);
$result_list_tag = (isset($opts['result_list_tag']))
? $opts['result_list_tag'] : 'ul';
if (strlen(trim($result_list_tag)))
{
$result_list_close_tag = '</' . $result_list_tag . '>';
$result_list_tag = '<' . $result_list_tag . '>';
}
else
{
$result_list_close_tag = '';
}
$show_notes = (isset($opts['show_notes']))
? $opts['show_notes'] : FALSE;
$format_notes = (isset($opts['format_notes']))
? $opts['format_notes'] : FALSE;
// Set search title string
// is|are, count, ''|s, ''|search_term, .|:
printf($title_tag . 'There %s %d result%s%s%s' . $title_close_tag,
(($data->count === 1) ? 'is' : 'are'),
$data->count,
(($data->count === 1) ? '' : 's'),
(strlen(trim($search_term))
? ' for “' . $search_term . '”' : ''),
(($data->count === 0) ? '.' : ':'));
if ($data->count > 0)
{
print $result_list_tag;
foreach ($data->results as $val)
{
$package = $this->get_package_entity($val);
printf('<li><a href="%s">%s</a>',
$package->ckan_url,
$package->title);
if (isset($package->notes) && $package->notes &&
$show_notes)
{
print ': ';
if (TRUE === $format_notes)
{
print Markdown($package->notes);
}
elseif (FALSE === $format_notes)
{
print $package->notes;
}
else
{
print strip_tags(Markdown($package->notes),
$format_notes);
}
}
print '</li>';
}
print $result_list_close_tag;
}
}
}
// Private methods ----------------------------------------------------
/**
* Make a request to the CKAN API.
*
* @access private
* @param string HTTP method (GET, PUT, POST).
* @param string URI fragment to CKAN resource.
* @param string Optional. String in JSON-format that will be in request body.
* @return mixed If success, either an array or object. Otherwise FALSE.
* @since Version 0.1.0
*/
private function make_request($method, $url, $data = FALSE)
{
// Set cURL method.
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
// Set cURL URI.
curl_setopt($this->ch, CURLOPT_URL, $this->base_url . $url);
// If POST or PUT, add Authorization: header and request body
if ($method === 'POST' || $method === 'PUT')
{
// We needs a key and some data, yo!
if ( ! ($this->api_key && $data))
{
// throw exception
throw new Exception('Missing either an API key or POST data.');
}
else
{
// Add Authorization: header.
$this->ch_headers[] = 'Authorization: ' . $this->api_key;
// Add data to request body.
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
}
}
else
{
// Since we can't use HTTPS,
// if it's in there, remove Authorization: header
$key = array_search('Authorization: ' . $this->api_key,
$this->ch_headers);
if ($key !== FALSE)
{
unset($this->ch_headers[$key]);
}
curl_setopt($this->ch, CURLOPT_POSTFIELDS, NULL);
}
// Set headers.
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->ch_headers);
// Execute request and get response headers.
$response = curl_exec($this->ch);
$info = curl_getinfo($this->ch);
// Check HTTP response code
if ($info['http_code'] !== 200)
{
throw new Exception($info['http_code'] . ': ' .
$this->http_status_codes[$info['http_code']]);
}
// Determine how to parse
if (isset($info['content_type']) && $info['content_type'])
{
$content_type = str_replace('application/', '',
substr($info['content_type'], 0,
strpos($info['content_type'], ';')));
return $this->parse_response($response, $content_type);
}
else
{
throw new Exception('Unknown content type.');
}
}
/**
* Parse the response from the CKAN API.
*
* @access private
* @param string Data returned from the CKAN API.
* @param string Format of data returned from the CKAN API.
* @return mixed If success, either an array or object. Otherwise FALSE.
* @since Version 0.1.0
*/
private function parse_response($data = FALSE, $format = FALSE)
{
if ($data)
{
if ('json' === $format)
{
return json_decode($data);
}
else
{
throw new Exception('Unable to parse this data format.');
}
}
return FALSE;
}
}
$ckan = new Ckan_client();