forked from trueheart78/mailgun.php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActiveResource.php
590 lines (535 loc) · 15 KB
/
ActiveResource.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
<?php
/**
* Basic implementation of the Ruby on Rails ActiveResource REST client.
* Intended to work with RoR-based REST servers, which all share similar
* API patterns.
*
* MailGun uses patched version. Modifications:
* 1) Throw error in case when server returns not 2xx response.
* 2) Check content-type and parse only text/xml response
* 3) Use proxy to get and set data to avoid conflicts
*
* Usage:
*
* <?php
*
* require_once ('ActiveResource.php');
*
* class Song extends ActiveResource {
* var $site = 'http://localhost:3000/';
* var $element_name = 'songs';
* }
*
* // create new item
* $song = new Song (array ('artist' => 'Joe Cocker', 'title' => 'A Little Help From My Friends'));
* $song->save ();
*
* // fetch and update an item
* $song->find (44)->set ('title', 'The River')->save ();
*
* // line by line
* $song->find (44);
* $song->title = 'The River';
* $song->save ();
*
* // get all songs
* $songs = $song->find ('all');
*
* // delete a song
* $song->find (44);
* $song->destroy ();
*
* // custom method
* $songs = $song->get ('by_year', array ('year' => 1999));
*
* ?>
*
* @author John Luxford <[email protected]>
* @version 0.13 beta
* @license http://opensource.org/licenses/lgpl-2.1.php
*/
class __Proxy {
var $resource;
function __construct(&$resource) {
$this->resource = $resource;
}
/**
* Getter for internal object data.
*/
function __get ($k) {
if (isset ($this->resource->_data[$k])) {
return $this->resource->_data[$k];
}
return $this->resource->{$k};
}
/**
* Setter for internal object data.
*/
function __set ($k, $v) {
if (isset ($this->resource->_data[$k])) {
$this->resource->_data[$k] = $v;
return;
}
$this->resource->{$k} = $v;
return $this->resource;
}
}
class ActiveResource {
/**
* The REST site address, e.g., http://user:pass@domain:port/
*/
var $site = false;
/**
* HTTP Basic Authentication user
*/
var $user = null;
/**
* HTTP Basic Authentication password
*/
var $password = null;
/**
* The remote collection, e.g., person or things
*/
var $element_name = false;
/**
* The data of the current object, accessed via the anonymous get/set methods.
*/
var $_data = array ();
/**
* An error message if an error occurred.
*/
var $error = false;
/**
* The error number if an error occurred.
*/
var $errno = false;
/**
* The request that was sent to the server.
*/
var $request_body = '';
/**
* The complete URL that the request was sent to.
*/
var $request_uri = '';
/**
* The request method sent to the server.
*/
var $request_method = '';
/**
* The response code returned from the server.
*/
var $response_code = false;
/**
* The raw response headers sent from the server.
*/
var $response_headers = '';
/**
* The response body sent from the server.
*/
var $response_body = '';
/**
* The format requests should use to send data (url or xml).
*/
var $request_format = 'url';
/**
* Proxy to safely get and set data
*/
var $p = null;
/**
* Corrections to improper pleuralizations.
*/
var $pleural_corrections = array (
'persons' => 'people',
'peoples' => 'people',
'mans' => 'men',
'mens' => 'men',
'womans' => 'women',
'womens' => 'women',
'childs' => 'children',
'childrens' => 'children',
'sheeps' => 'sheep',
'octopuses' => 'octopi',
'quizs' => 'quizzes',
'axises' => 'axes',
'buffalos' => 'buffaloes',
'tomatos' => 'tomatoes',
'potatos' => 'potatoes',
'oxes' => 'oxen',
'mouses' => 'mice',
'matrixes' => 'matrices',
'vertexes' => 'vertices',
'indexes' => 'indices',
);
/**
* Constructor method.
*/
function __construct ($data = array ()) {
$this->_data = $data;
// Allow class-defined element name or use class name if not defined
$this->element_name = ($this->element_name ? $this->pleuralize ($this->element_name) : $this->pleuralize (strtolower (get_class ($this))));
// if configuration file (config.ini.php) exists use it (overwrite class properties/attribute values).
$config_file_path = dirname (__FILE__) . '/' . 'config.ini.php';
if (file_exists ($config_file_path)) {
$properties = parse_ini_file ($config_file_path);
foreach ($properties as $property => $value )
$this->{$property} = $value;
}
$this->p = new __Proxy($this);
}
/**
* Pleuralize the element name.
*/
function pleuralize ($word) {
$word .= 's';
$word = preg_replace ('/(x|ch|sh|ss])s$/', '\1es', $word);
$word = preg_replace ('/ss$/', 'ses', $word);
$word = preg_replace ('/([ti])ums$/', '\1a', $word);
$word = preg_replace ('/sises$/', 'ses', $word);
$word = preg_replace ('/([^aeiouy]|qu)ys$/', '\1ies', $word);
$word = preg_replace ('/(?:([^f])fe|([lr])f)s$/', '\1\2ves', $word);
if (isset ($this->pleural_corrections[$word])) {
return $this->pleural_corrections[$word];
}
return $word;
}
/**
* Saves a new record or updates an existing one via:
*
* POST /collection.xml
* PUT /collection/id.xml
*/
function save () {
if (isset ($this->_data['id'])) {
return $this->_send_and_receive ($this->site . $this->element_name . '/' . $this->_data['id'] . '.xml', 'PUT', $this->_data); // update
}
return $this->_send_and_receive ($this->site . $this->element_name . '.xml', 'POST', $this->_data); // create
}
/**
* Deletes a record via:
*
* DELETE /collection/id.xml
*/
function destroy () {
return $this->_send_and_receive ($this->site . $this->element_name . '/' . $this->_data['id'] . '.xml', 'DELETE');
}
/**
* Finds a record or records via:
*
* GET /collection/id.xml
* GET /collection.xml
*/
function find ($id = false, $options = array ()) {
if (! $id) {
$id = $this->_data['id'];
}
if ($id == 'all') {
$url = $this->site . $this->element_name . '.xml';
if (count ($options) > 0) {
$url .= '?' . http_build_query ($options);
}
return $this->_send_and_receive ($url, 'GET');
}
return $this->_send_and_receive ($this->site . $this->element_name . '/' . $id . '.xml', 'GET');
}
/**
* Gets a specified custom method on the current object via:
*
* GET /collection/id/method.xml
* GET /collection/id/method.xml?attr=value
*/
function get ($method, $options = array ()) {
$req = $this->site . $this->element_name;
if ($this->_data['id']) {
$req .= '/' . $this->_data['id'];
}
$req .= '/' . $method . '.xml';
if (count ($options) > 0) {
$req .= '?' . http_build_query ($options);
}
return $this->_send_and_receive ($req, 'GET');
}
/**
* Posts to a specified custom method on the current object via:
*
* POST /collection/id/method.xml
*/
function post ($method, $options = array ()) {
$req = $this->site . $this->element_name;
if (isset($this->_data['id'])) {
$req .= '/' . $this->_data['id'];
}
$req .= '/' . $method . '.xml';
return $this->_send_and_receive ($req, 'POST', $options);
}
/**
* Puts to a specified custom method on the current object via:
*
* PUT /collection/id/method.xml
*/
function put ($method, $options = array ()) {
$req = $this->site . $this->element_name;
if ($this->_data['id']) {
$req .= '/' . $this->_data['id'];
}
$req .= '/' . $method . '.xml';
if (count ($options) > 0) {
$req .= '?' . http_build_query ($options);
}
return $this->_send_and_receive ($req, 'PUT');
}
/**
* Simple recursive function to build an XML response.
*/
function _build_xml ($k, $v) {
if (is_object ($v) && strtolower (get_class ($v)) == 'simplexmlelement') {
return preg_replace ('/<\?xml(.*?)\?>/', '', $v->asXML ());
}
$res = '';
$attrs = '';
if (! is_numeric ($k)) {
$res = '<' . $k . '{{attributes}}>';
}
if (is_array ($v)) {
foreach ($v as $key => $value) {
if (strpos ($key, '@') === 0) {
$attrs .= ' ' . substr ($key, 1) . '="' . $this->_xml_entities ($value) . '"';
continue;
}
$res .= $this->_build_xml ($key, $value);
$keys = array_keys ($v);
if (is_numeric ($key) && $key != array_pop ($keys)) {
$res .= '</' . $k . ">\n<" . $k . '>';
}
}
} else {
$res .= $this->_xml_entities ($v);
}
if (! is_numeric ($k)) {
$res .= '</' . $k . ">\n";
}
$res = str_replace ('<' . $k . '{{attributes}}>', '<' . $k . $attrs . '>', $res);
return $res;
}
/**
* Converts entities to unicode entities (ie. < becomes <).
* From php.net/htmlentities comments, user "webwurst at web dot de"
*/
function _xml_entities ($string) {
$trans = get_html_translation_table (HTML_ENTITIES);
foreach ($trans as $key => $value) {
$trans[$key] = '&#' . ord ($key) . ';';
}
return strtr ($string, $trans);
}
/**
* Build the request, call _fetch() and parse the results.
*/
function _send_and_receive ($url, $method, $data = array ()) {
$params = '';
$el = substr ($this->element_name, 0, -1);
if ($this->request_format == 'url') {
foreach ($data as $k => $v) {
if ($k != 'id' && $k != 'created-at' && $k != 'updated-at') {
$params .= '&' . $el . '[' . str_replace ('-', '_', $k) . ']=' . rawurlencode ($v);
}
}
$params = substr ($params, 1);
} elseif ($this->request_format == 'xml') {
$params = '<?xml version="1.0" encoding="UTF-8"?><' . $el . ">\n";
foreach ($data as $k => $v) {
if ($k != 'id' && $k != 'created-at' && $k != 'updated-at') {
$params .= $this->_build_xml ($k, $v);
}
}
$params .= '</' . $el . '>';
}
$this->request_body = $params;
$this->request_uri = $url;
$this->request_method = $method;
$res = $this->_fetch ($url, $method, $params);
### echo "RESULT $res\n";
list ($headers, $res) = explode ("\r\n\r\n", $res, 2);
$this->response_headers = $headers;
$this->response_body = $res;
if (preg_match ('/HTTP\/[0-9]\.[0-9] ([0-9]+)/', $headers, $regs)) {
$this->response_code = $regs[1];
} else {
$this->response_code = false;
}
if (! $res) {
return $this;
} elseif ($res == ' ') {
$this->error = 'Empty reply';
return $this;
}
if (! preg_match('/content-type:\stext\/xml/mi', $this->response_headers )) {
return $this;
}
// parse XML response
$xml = new SimpleXMLElement ($res);
if ($xml->getName () == $this->element_name) {
// multiple
$res = array ();
$cls = get_class ($this);
foreach ($xml->children () as $child) {
$obj = new $cls;
foreach ((array) $child as $k => $v) {
$k = str_replace ('-', '_', $k);
if (isset ($v['nil']) && $v['nil'] == 'true') {
continue;
} else {
$obj->_data[$k] = $v;
}
}
$res[] = $obj;
}
return $res;
} elseif ($xml->getName () == 'errors') {
// parse error message
$this->error = $xml->error;
$this->errno = $this->response_code;
return false;
}
foreach ((array) $xml as $k => $v) {
$k = str_replace ('-', '_', $k);
if (isset ($v['nil']) && $v['nil'] == 'true') {
continue;
} else {
$this->_data[$k] = $v;
}
}
return $this;
}
/**
* Fetch the specified request via cURL.
*/
function _fetch ($url, $method, $params) {
if (! extension_loaded ('curl')) {
$this->error = 'cURL extension not loaded.';
return false;
}
$ch = curl_init ();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_VERBOSE, 0);
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
/* HTTP Basic Authentication */
if ($this->user && $this->password) {
curl_setopt ($ch, CURLOPT_USERPWD, $this->user . ":" . $this->password);
}
if ($this->request_format == 'xml') {
curl_setopt ($ch, CURLOPT_HTTPHEADER, array ("Content-Type: text/xml", "Length: " . strlen ($params)));
}
switch ($method) {
case 'POST':
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $params);
//curl_setopt ($ch, CURLOPT_HTTPHEADER, array ("Content-Type: application/x-www-form-urlencoded\n"));
break;
case 'DELETE':
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case 'PUT':
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt ($ch, CURLOPT_POSTFIELDS, $params);
//curl_setopt ($ch, CURLOPT_HTTPHEADER, array ("Content-Type: application/x-www-form-urlencoded\n"));
break;
case 'GET':
default:
break;
}
$res = curl_exec ($ch);
// Check HTTP status code
$http_code = curl_getinfo ($ch, CURLINFO_HTTP_CODE);
if ($http_code < 200 || 299 < $http_code) {
list ($headers, $body) = explode ("\r\n\r\n", $res, 2);
$this->errno = $http_code;
$this->error = "Server error";
curl_close ($ch);
throw new Exception('Active Resource Error HTTP code:'.$this->errno.". Server says: ".strip_tags($body));
}
if (! $res) {
$this->errno = curl_errno ($ch);
$this->error = curl_error ($ch);
curl_close ($ch);
throw new Exception('Active Resource I/O Error '.$this->errno.". ".$this->error);
}
curl_close ($ch);
return $res;
}
/**
* Getter for internal object data.
*/
function __get ($k) {
if (isset ($this->_data[$k])) {
return $this->_data[$k];
}
return $this->{$k};
}
/**
* Setter for internal object data.
*/
function __set ($k, $v) {
if (isset ($this->_data[$k])) {
$this->_data[$k] = $v;
return;
}
$this->{$k} = $v;
}
/**
* Quick setter for chaining methods.
*/
function set ($k, $v = false) {
if (! $v && is_array ($k)) {
foreach ($k as $key => $value) {
$this->_data[$key] = $value;
}
} else {
$this->_data[$k] = $v;
}
return $this;
}
}
/** TODO: Replace with a proper set of tests.
class Test extends ActiveResource {}
$t = new Test;
echo $t->pleuralize ('person') . "\n";
echo $t->pleuralize ('people') . "\n";
echo $t->pleuralize ('man') . "\n";
echo $t->pleuralize ('woman') . "\n";
echo $t->pleuralize ('women') . "\n";
echo $t->pleuralize ('child') . "\n";
echo $t->pleuralize ('sheep') . "\n";
echo $t->pleuralize ('octopus') . "\n";
echo $t->pleuralize ('virus') . "\n";
echo $t->pleuralize ('quiz') . "\n";
echo $t->pleuralize ('axis') . "\n";
echo $t->pleuralize ('axe') . "\n";
echo $t->pleuralize ('buffalo') . "\n";
echo $t->pleuralize ('tomato') . "\n";
echo $t->pleuralize ('potato') . "\n";
echo $t->pleuralize ('ox') . "\n";
echo $t->pleuralize ('mouse') . "\n";
echo $t->pleuralize ('matrix') . "\n";
echo $t->pleuralize ('vertex') . "\n";
echo $t->pleuralize ('vortex') . "\n";
echo $t->pleuralize ('index') . "\n";
echo $t->pleuralize ('sandwich') . "\n";
echo $t->pleuralize ('mass') . "\n";
echo $t->pleuralize ('fax') . "\n";
echo $t->pleuralize ('pin') . "\n";
echo $t->pleuralize ('touch') . "\n";
echo $t->pleuralize ('sash') . "\n";
echo $t->pleuralize ('bromium') . "\n";
echo $t->pleuralize ('prophecy') . "\n";
echo $t->pleuralize ('crisis') . "\n";
echo $t->pleuralize ('life') . "\n";
echo $t->pleuralize ('wife') . "\n";
echo $t->pleuralize ('song') . "\n";
*/
?>