-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathannotation.php
executable file
·702 lines (619 loc) · 21.1 KB
/
annotation.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
702
<?php
/**
* @file
* Provides the Annotation PHP API.
*/
/**
* The Annotation PHP API.
*
* @package Annotation
* @author Alberto Ortiz Flores, inspired by DrupalApacheSolr and Disqus
* @version 1.0
* @access public
*
* @example
* @code
* // The user API key obtained from http://annotation.nyu.edu/api/get_my_key/.
* $service_url = 'http://127.0.0.1:8000';
*
* // Make sure to catch any errors generated by Annotation.
* try {
* $annotation = new Annotation($api_url);
*
* // Get annotations.
* $annotations = $annotation->get_annotations();
*
* // Data default to JSON
* $annons = json_decode($annotations->data);
*
* foreach ($annons as $annon) {
* echo $annon->id;
* }
* } catch(AnnotationException $exception) {
* echo $exception->getMessage();
* }
* @endcode
*/
class Annotation {
private static $instance = __CLASS__;
/**
* Service URL
*
* @var string
*/
public $service_url = 'http://127.0.0.1:8000';
/**
* User Agent
*
* @var string
*/
public $user_agent = 'NYU (+http://annotations.nyu.edu/)';
/**
* API Version
*
* @var string
*/
public $api_version = '0.1';
/**
* Parsed URL
*
* @var array
*/
protected $parsed_url;
/**
* Constructed services full path URLs
*
* @var string
*/
protected $update_url;
const ANNOTATION_API_URL = 'api/';
/**
* Creates a new interface to the Annotation API.
*
* @param $user_api_key
* (optional) The User API key to use.
* @param $server_url
* (optional) The prefix URL to use when calling the Annotation API.
*/
function __construct($service_url = 'http://127.0.0.1:8000', $client_api_key = NULL) {
$this->$service_url = $service_url;
$this->setUrl($service_url);
}
/**
* Return a valid HTTP URL given this server's host, port
*
* @param $service_url
* A string path to a Annotation request handler.
* @param $params
*
* @return string
*/
protected function _constructUrl($service_url, $params = array(), $added_query_string = NULL) {
$query_string = $this->httpBuildQuery($params);
if ($query_string) {
$query_string = '?' . $query_string;
if ($added_query_string) {
$query_string = $query_string . '&' . $added_query_string;
}
}
elseif ($added_query_string) {
$query_string = '?' . $added_query_string;
}
$url = $this->parsed_url;
if (isset($url['scheme']) && isset($url['user']) && isset($url['pass']) && isset($url['host']) && isset($url['port']) && isset($url['path'])) {
return $url['scheme'] . $url['user'] . $url['pass'] . $url['host'] . $url['port'] . $url['path'] . $service_url . $query_string;
}
}
public function check_plain($text) {
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
/**
* Get the Annotation URL
*
* @return string
*/
public function getUrl() {
return $this->_constructUrl('');
}
/**
* Set the Annotation URL
*
* @param $url
*
* @return $this
*/
public function setUrl($url) {
$parsed_url = parse_url($url);
if (!isset($parsed_url['scheme'])) {
$parsed_url['scheme'] = 'http';
}
$parsed_url['scheme'] .= '://';
if (!isset($parsed_url['user'])) {
$parsed_url['user'] = '';
}
else {
$parsed_url['host'] = '@' . $parsed_url['host'];
}
$parsed_url['pass'] = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$parsed_url['port'] = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
if (isset($parsed_url['path'])) {
// Make sure the path has a single leading/trailing slash.
$parsed_url['path'] = '/' . ltrim($parsed_url['path'], '/');
$parsed_url['path'] = rtrim($parsed_url['path'], '/') . '/';
}
else {
$parsed_url['path'] = '/';
}
// For now we ignore query and fragment.
$this->parsed_url = $parsed_url;
// Force the update url to be rebuilt.
unset($this->update_url);
return $this;
}
/**
* Check the response code and throw an exception if it's not 200.
*
* @param stdClass $response
* response object.
*
* @return
* response object
* @throw Annotation Exception
*/
protected function checkResponse($response) {
$code = (int) $response->code;
if ($code != 200) {
if ($code >= 400 && $code != 403 && $code != 404) {
$response->status_message .= $response->data;
}
throw new AnnotationException($code . " Status: " . $response->status_message);
}
return $response;
}
/**
* Central method for making a GET operation against this Annotation Server
*/
protected function _sendRawGet($url, $options = array()) {
$response = $this->_makeHttpRequest($url, $options);
return $this->checkResponse($response);
}
/**
* Central method for making a POST operation against this Annotation Server
*/
protected function _sendRawPost($url, $options = array()) {
$options['method'] = 'POST';
// Normally we use POST to send XML documents.
if (!isset($options['headers']['Content-Type'])) {
$options['headers']['Content-Type'] = 'text/xml; charset=UTF-8';
}
$response = $this->_makeHttpRequest($url, $options);
return $this->checkResponse($response);
}
protected function http_request($url, array $options = array()) {
$result = new stdClass();
// Parse the URL and make sure we can handle the schema.
$uri = @parse_url($url);
if ($uri == FALSE) {
$result->error = 'unable to parse URL';
$result->code = -1001;
return $result;
}
if (!isset($uri['scheme'])) {
$result->error = 'missing schema';
$result->code = -1002;
return $result;
}
$this->timer_start(__FUNCTION__);
// Merge the default options.
$options += array(
'headers' => array(),
'method' => 'GET',
'data' => NULL,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);
// stream_socket_client() requires timeout to be a float.
$options['timeout'] = (float) $options['timeout'];
switch ($uri['scheme']) {
case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$socket = 'tcp://' . $uri['host'] . ':' . $port;
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the standard port to prevent from breaking rewrite rules
// checking the host that do not take into account the port number.
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
break;
case 'https':
// Note: Only works when PHP is compiled with OpenSSL support.
$port = isset($uri['port']) ? $uri['port'] : 443;
$socket = 'ssl://' . $uri['host'] . ':' . $port;
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
break;
default:
$result->error = 'invalid schema ' . $uri['scheme'];
$result->code = -1003;
return $result;
}
if (empty($options['context'])) {
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
}
else {
// Create a stream with context. Allows verification of a SSL certificate.
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
}
// Make sure the socket opened properly.
if (!$fp) {
// When a network error occurs, we use a negative number so it does not
// clash with the HTTP status codes.
$result->code = -$errno;
$result->error = trim($errstr) ? trim($errstr) : 'Error opening socket @socket';
return $result;
}
// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?' . $uri['query'];
}
// Merge the default headers.
$options['headers'] += array(
'User-Agent' => $this->user_agent,
);
// Only add Content-Length if we actually have any content or if it is a POST
// or PUT request. Some non-standard servers get confused by Content-Length in
// at least HEAD/GET requests, and Squid always requires Content-Length in
// POST/PUT requests.
$content_length = strlen($options['data']);
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
$options['headers']['Content-Length'] = $content_length;
}
// If the server URL has a user then attempt to use basic authentication.
if (isset($uri['user'])) {
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ''));
}
$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
foreach ($options['headers'] as $name => $value) {
$request .= $name . ': ' . trim($value) . "\r\n";
}
$request .= "\r\n" . $options['data'];
$result->request = $request;
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - $this->timer_read(__FUNCTION__) / 1000;
if ($timeout > 0) {
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
fwrite($fp, $request);
}
// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
// instead must invoke stream_get_meta_data() each iteration.
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'];
$response = '';
while ($alive) {
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - $this->timer_read(__FUNCTION__) / 1000;
if ($timeout <= 0) {
$info['timed_out'] = TRUE;
break;
}
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
$chunk = fread($fp, 1024);
$response .= $chunk;
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
}
fclose($fp);
if ($info['timed_out']) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
return $result;
}
// Parse response headers from the response body.
// Be tolerant of malformed HTTP responses that separate header and body with
// \n\n or \r\r instead of \r\n\r\n.
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response = preg_split("/\r\n|\n|\r/", $response);
// Parse the response status line.
list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
$result->protocol = $protocol;
$result->status_message = $status_message;
$result->headers = array();
// Parse the response headers.
while ($line = trim(array_shift($response))) {
list($name, $value) = explode(':', $line, 2);
$name = strtolower($name);
if (isset($result->headers[$name]) && $name == 'set-cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$name] .= ',' . trim($value);
}
else {
$result->headers[$name] = trim($value);
}
}
$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
$result->code = $code;
switch ($code) {
case 200:
case 304:
break;
case 301:
case 302:
case 307:
$location = $result->headers['location'];
$options['timeout'] -= $this->timer_read(__FUNCTION__) / 1000;
if ($options['timeout'] <= 0) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
}
elseif ($options['max_redirects']) {
// Redirect to the new location.
$options['max_redirects']--;
$result = $this->http_request($location, $options);
$result->redirect_code = $code;
}
if (!isset($result->redirect_url)) {
$result->redirect_url = $location;
}
break;
default:
$result->error = $status_message;
}
return $result;
}
protected function timer_start($name) {
global $timers;
$timers[$name]['start'] = microtime(TRUE);
$timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
}
protected function timer_read($name) {
global $timers;
if (isset($timers[$name]['start'])) {
$stop = microtime(TRUE);
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);
if (isset($timers[$name]['time'])) {
$diff += $timers[$name]['time'];
}
return $diff;
}
return $timers[$name]['time'];
}
/**
* Central method for making the actual http request to the Annotation Server
*/
protected function _makeHttpRequest($url, $options = array()) {
if (!isset($options['method']) || $options['method'] == 'GET' || $options['method'] == 'HEAD') {
// Make sure we are not sending a request body.
$options['data'] = NULL;
}
$result = $this->http_request($url, $options);
if (!isset($result->code) || $result->code < 0) {
$result->code = 0;
$result->status_message = 'Request failed';
$result->protocol = 'HTTP/1.0';
}
// Additional information may be in the error property.
if (isset($result->error)) {
$result->status_message .= ': ' . $this->check_plain($result->error);
}
if (!isset($result->data)) {
$result->data = '';
$result->response = NULL;
}
else {
$response = json_decode($result->data);
if (is_object($response)) {
foreach ($response as $key => $value) {
$result->$key = $value;
}
}
}
return $result;
}
/**
* Get a list of annotations on a website.
*
* Both filter and exclude are multivalue arguments with coma as a divider.
* That makes is possible to use combined requests. For example, if you want
* to get all deleted spam messages, your filter argument should contain
* 'spam,killed' string.
*
* @param $forum_id
* The forum ID.
* @param $arguments
* - limit: Number of entries that should be included in the response. Default is 25.
* - start: Starting point for the query. Default is 0.
* - filter: Type of entries that should be returned.
* - exclude: Type of entries that should be excluded from the response.
* @return
* Returns posts from a forum specified by id.
*/
public function get_annotations(array $arguments = array()) {
return $this->call('annotations', $arguments);
}
public function post_annotation($user_id = NULL, array $arguments = array()) {
return $this->call('annotations/' . $user_id, $arguments, 'POST');
}
/**
* Get a list of annotations frmo a user on a website.
* @param $user_id
* @param $arguments
* - aid: Annotation id
* - limit: Number of entries that should be included in the response. Default is 25.
* - start: Starting point for the query. Default is 0.
* - filter: Type of entries that should be returned.
* - exclude: Type of entries that should be excluded from the response.
* @return
* Returns posts from a user on a forum specified by id.
*/
public function get_annotations_by_creator_id($user_id = NULL, array $arguments = array()) {
if ($user_id) {
if (isset($arguments['aid'])) {
$user_id = $user_id . '/' . $arguments['aid'];
unset($arguments['aid']);
}
return $this->call('annotations/' . $user_id, $arguments);
}
else {
throw new AnnotationException("User ID is missing.");
}
}
/**
* Get annotations thread by targetURI
*
* Finds a annotations by its targetURI. Output value is a annotations object.
*
* @param $targetURI
* the targetURI to check for an associated annotation
* @param $client_api_key
* (optional) The Partner API key.
* @return
* A thread object, otherwise NULL.
*/
public function get_annotations_by_targetURI($targetURI, $user_id = NULL) {
$arguments = array(
'targetURI' => $targetURI,
);
return $this->call('annotations/' . $user_id, $arguments);
}
public function call($query, $arguments = array(), $method ='GET') {
if (!is_array($arguments)) {
$arguments = array();
}
// Always use JSON.
$arguments['format'] = 'json';
// Default params.
$arguments += array(
'includeDeletions' => TRUE,
'withInlineContent' => TRUE,
);
if (!isset($arguments['api_version'])) {
$arguments['api_version'] = $this->api_version;
}
$queryString = $this->httpBuildQuery($arguments);
// Check string length of the query string, change method to POST
// if longer than 4000 characters (typical server handles 4096 max).
// @TODO: variable_get('annotation_post_threshold', 4000)) {
if ( strlen($queryString) > 4000 ) {
$method = 'POST';
}
if ($method == 'GET') {
$searchUrl = $this->_constructUrl(self::ANNOTATION_API_URL . $query, array(), $queryString);
return $this->_sendRawGet($searchUrl);
}
else if ($method == 'POST') {
$searchUrl = $this->_constructUrl(self::ANNOTATION_API_URL . $query);
// $options['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
$options['headers']['Content-Type'] = 'application/json; charset=UTF-8';
$options['headers']['X-Requested-With'] = 'XMLHttpRequest';
$options['data'] = json_encode( array('annotation' => $arguments['annotation'] ) );
return $this->_sendRawPost($searchUrl, $options);
}
else {
throw new AnnotationException("Unsupported method '$method' for call(), use GET or POST");
}
}
/**
* Like PHP's built in http_build_query(), but uses rawurlencode() and no [] for repeated params.
*/
public function httpBuildQuery(array $query, $parent = '') {
$params = array();
foreach ($query as $key => $value) {
$key = ($parent ? $parent : rawurlencode($key));
// Recurse into children.
if (is_array($value)) {
$params[] = $this->httpBuildQuery($value, $key);
}
// If a query parameter value is NULL, only append its key.
elseif (!isset($value)) {
$params[] = $key;
}
else {
$params[] = $key . '=' . rawurlencode($value);
}
}
return implode('&', $params);
}
}
/**
* Any unsucessful result that's created by Annotation API will generate a AnnotationException.
*/
class AnnotationException extends Exception {
/**
* The information returned from the cURL call.
*/
public $info = NULL;
/**
* The information returned from the Annotaion Service call.
*/
public $annotation = NULL;
/**
* Creates a AnnotationException.
* @param $message
* The message for the exception.
* @param $code
* (optional) The error code.
* @param $info
* (optional) The result from the cURL call.
*/
public function __construct($message, $code = 0, $info = NULL, $annotation = NULL) {
$this->info = $info;
$this->annotation = $annotation;
parent::__construct($message, $code);
}
/**
* Converts the exception to a string.
*/
public function __toString() {
$code = isset($this->annotation->code) ? $this->annotation->code : (isset($info['http_code']) ? $info['http_code'] : 0);
$message = $this->getMessage();
return __CLASS__ .": [$code]: $message\n";
}
}