-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcoreylib.php
More file actions
3342 lines (2841 loc) · 96.3 KB
/
Copy pathcoreylib.php
File metadata and controls
3342 lines (2841 loc) · 96.3 KB
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Plugin Name: coreylib
Plugin URI: http://github.com/collegeman/coreylib
Description: A small PHP library for downloading, caching, and extracting data formatted as XML or JSON
Version: 2.0
Author: Aaron Collegeman
Author URI: http://github.com/collegeman
License: GPL2
*/
/**
* coreylib
* Parse and cache XML and JSON.
* @author Aaron Collegeman aaron@collegeman.net
* @version 2.0
*
* Copyright (C)2008-2010 Fat Panda LLC.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// src/core.php
/**
* Generic Exception wrapper
*/
class clException extends Exception {}
/**
* Configuration defaults.
*/
// enable debugging output
@define('COREYLIB_DEBUG', false);
// maximum number of times to retry downloading content before failure
@define('COREYLIB_MAX_DOWNLOAD_ATTEMPTS', 3);
// the number of seconds to wait before timing out on CURL requests
@define('COREYLIB_DEFAULT_TIMEOUT', 30);
// the default HTTP method for requesting data from the URL
@define('COREYLIB_DEFAULT_METHOD', 'get');
// set this to true to disable all caching activity
@define('COREYLIB_NOCACHE', false);
// default cache strategy is clFileCache
@define('COREYLIB_DEFAULT_CACHE_STRATEGY', 'clFileCache');
// the name of the folder to create for clFileCache files - this folder is created inside the path clFileCache is told to use
@define('COREYLIB_FILECACHE_DIR', '.coreylib');
// auto-detect WordPress environment?
@define('COREYLIB_DETECT_WORDPRESS', true);
/**
* Coreylib core.
*/
class clApi {
// request method
const METHOD_GET = 'get';
const METHOD_POST = 'post';
private $method;
// the URL provided in the constructor
private $url;
// default HTTP headers
private $headers = array(
);
// default curlopts
private $curlopts = array(
CURLOPT_USERAGENT => 'coreylib/2.0',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
);
// the parameters being passed in the request
private $params = array();
// basic authentication
private $user;
private $pass;
// the cURL handle used to get the content
private $ch;
// reference to caching strategy
private $cache;
// the download
private $download;
// the cache key
private $cache_key;
/**
* @param String $url The URL to connect to, with or without query string
* @param clCache $cache An instance of an implementation of clCache, or null (the default)
* to trigger the use of the global caching impl, or false, to indicate that no caching
* should be performed.
*/
function __construct($url, $cache = null) {
// parse the URL and extract things like user, pass, and query string
if (( $parts = @parse_url($url) ) && strtolower($parts['scheme']) != 'file') {
$this->user = @$parts['user'];
$this->pass = @$parts['pass'];
@parse_str($parts['query'], $this->params);
// rebuild $url
$url = sprintf('%s://%s%s',
$parts['scheme'],
$parts['host'] . ( @$parts['port'] ? ':'.$parts['port'] : '' ),
$parts['path'] . ( @$parts['fragment'] ? ':'.$parts['fragment'] : '')
);
}
// stash the processed $url
$this->url = $url;
// setup the default request method
$this->method = ($method = strtolower(COREYLIB_DEFAULT_METHOD)) ? $method : self::METHOD_GET;
$this->curlopt(CURLOPT_CONNECTTIMEOUT, COREYLIB_DEFAULT_TIMEOUT);
$this->cache = is_null($cache) ? coreylib_get_cache() : $cache;
}
function getUrl() {
return $this->url;
}
/**
* Download and parse the data from the specified endpoint using an HTTP GET.
* @param mixed $cache_for An expression of time (e.g., 10 minutes), or 0 to cache forever, or FALSE to flush the cache, or -1 to skip over all caching (the default)
* @param string One of clApi::METHOD_GET or clApi::METHOD_POST, or null
* @param string (optional) Force the node type, ignoring content type signals and auto-detection
* @return clNode if parsing succeeds; otherwise FALSE.
* @see http://php.net/manual/en/function.strtotime.php
*/
function &parse($cache_for = -1, $override_method = null, $node_type = null) {
$node = false;
if (is_null($this->download)) {
$this->download = $this->download(false, $cache_for, $override_method);
}
// if the download succeeded
if ($this->download->is2__()) {
if ($node_type) {
$node = clNode::getNodeFor($this->download->getContent(), $node_type);
} else if ($this->download->isXml()) {
$node = clNode::getNodeFor($this->download->getContent(), 'xml');
} else if ($this->download->isJson()) {
$node = clNode::getNodeFor($this->download->getContent(), 'json');
} else {
throw new clException("Unable to determine content type. You can force a particular type by passing a third argument to clApi->parse(\$cache_for = -1, \$override_method = null, \$node_type = null).");
}
}
return $node;
}
/**
* Download and parse the data from the specified endpoint using an HTTP POST.
* @param mixed $cache_for An expression of time (e.g., 10 minutes), or 0 to cache forever, or FALSE to flush the cache, or -1 to skip over all caching (the default)
* @return bool TRUE if parsing succeeds; otherwise FALSE.
* @see http://php.net/manual/en/function.strtotime.php
* @deprecated Use clApi->parse($cache_for, clApi::METHOD_POST) instead.
*/
function post($cache_for = -1) {
return $this->parse($cache_for, self::METHOD_POST);
}
/**
* Retrieve the content of the parsed document.
*/
function getContent() {
return $this->download ? $this->download->getContent() : '';
}
/**
* Print the content of the parsed document.
*/
function __toString() {
return $this->getContent();
}
/**
* Set or get a coreylib configuration setting.
* @param mixed $option Can be either a string or an array of key/value configuration settings
* @param mixed $value The value to assign
* @return mixed If $value is null, then return the value stored by $option; otherwise, null.
*/
static function setting($option, $value = null) {
if (!is_null($value) || is_array($option)) {
if (is_array($option)) {
self::$options = array_merge(self::$options, $option);
} else {
self::$options[$option] = $value;
}
} else {
return @self::$options[$option];
}
}
/**
* Set or get an HTTP header configuration
* @param mixed $name Can be either a string or an array of key/value pairs
* @param mixed $value The value to assign
* @return mixed If $value is null, then return the value stored by $name; otherwise, null.
*/
function header($name, $value = null) {
if (!is_null($value) || is_array($name)) {
if (is_array($name)) {
$this->headers = array_merge($this->headers, $name);
} else {
$this->headers[$name] = $value;
}
} else {
return @$this->headers[$name];
}
}
/**
* Set or get a request parameter
* @param mixed $name Can be either a string or an array of key/value pairs
* @param mixed $value The value to assign
* @return mixed If $value is null, then return the value stored by $name; otherwise, null.
*/
function param($name, $value = null) {
if (!is_null($value) || is_array($name)) {
if (is_array($name)) {
$this->params = array_merge($this->params, $name);
} else {
$this->params[$name] = $value;
}
} else {
return @$this->params[$name];
}
}
/**
* Set or get a CURLOPT configuration
* @param mixed $opt One of the CURL option constants, or an array of option/value pairs
* @param mixed $value The value to assign
* @return mixed If $value is null, then return the value stored by $opt; otherwise, null.
*/
function curlopt($opt, $value = null) {
if (!is_null($value) || is_array($opt)) {
if (is_array($opt)) {
$this->curlopts = array_merge($this->curlopts, $opt);
} else {
$this->curlopts[$opt] = $value;
}
} else {
return @$this->curlopts[$opt];
}
}
/**
* Download the content according to the settings on this object, or load from the cache.
* @param bool $queue If true, setup a CURL connection and return the handle; otherwise, execute the handle and return the content
* @param mixed $cache_for One of:
* An expression of how long to cache the data (e.g., "10 minutes")
* 0, indicating cache duration should be indefinite
* FALSE to regenerate the cache
* or -1 to skip over all caching (the default)
* @param string $override_method one of clApi::METHOD_GET or clApi::METHOD_POST; optional, defaults to null.
* @return clDownload
* @see http://php.net/manual/en/function.strtotime.php
*/
function &download($queue = false, $cache_for = -1, $override_method = null) {
$method = is_null($override_method) ? $this->method : $override_method;
$qs = http_build_query($this->params);
$url = ($method == self::METHOD_GET ? $this->url.($qs ? '?'.$qs : '') : $this->url);
// use the URL to generate a cache key unique to request and any authentication data present
$this->cache_key = $cache_key = md5($method.$this->user.$this->pass.$url.$qs);
if (($download = $this->cacheGet($cache_key, $cache_for)) !== false) {
return $download;
}
// TODO: implement file:// protocol here
$this->ch = curl_init($url);
// authenticate?
if ($this->user) {
curl_setopt($this->ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($this->ch, CURLOPT_USERPWD, "$this->user:$this->pass");
}
// set headers
$headers = array();
foreach($this->headers as $name => $value) {
$headers[] = "{$name}: {$value}";
}
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
// apply pre-set curl opts, allowing some (above) to be overwritten
foreach($this->curlopts as $opt => $val) {
curl_setopt($this->ch, $opt, $val);
}
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
if ($this->method != self::METHOD_POST) {
curl_setopt($this->ch, CURLOPT_HTTPGET, true);
} else {
curl_setopt($this->ch, CURLOPT_POST, true);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->params);
}
if ($queue) {
$download = new clDownload($this->ch, false);
} else {
$content = curl_exec($this->ch);
$download = new clDownload($this->ch, $content);
// cache?
if ($download->is2__()) {
$this->cacheSet($cache_key, $download, $cache_for);
}
}
return $download;
}
function setDownload(&$download) {
if (!($download instanceof clDownload)) {
throw new Exception('$download must be of type clDownload');
}
$this->download = $download;
}
function cacheWith($clCache) {
$this->cache = $clCache;
}
function cacheGet($cache_key, $cache_for = -1) {
if (!$this->cache || COREYLIB_NOCACHE || $cache_for === -1 || $cache_for === false) {
return false;
}
return $this->cache->get($cache_key);
}
function cacheSet($cache_key, $download, $cache_for = -1) {
if (!$this->cache || COREYLIB_NOCACHE || $cache_for === -1) {
return false;
} else {
return $this->cache->set($cache_key, $download, $cache_for);
}
}
/**
* Delete cache entry for this API.
* Note that the cache key is generated from several components of the request,
* including: the request method, the URL, the query string (parameters), and
* any username or password used. Changing any one of these before executing
* this function will modify the cache key used to store/retrieve the cached
* response. So, make sure to fully configure your clApi instance before running
* this method.
* @param string $override_method For feature parity with clApi->parse, allows
* for overriding the HTTP method used in cache key generation.
* @return A reference to this clApi instance (to support method chaining)
*/
function &flush($override_method = null) {
$method = is_null($override_method) ? $this->method : $override_method;
$qs = http_build_query($this->params);
$url = ($method == self::METHOD_GET ? $this->url.($qs ? '?'.$qs : '') : $this->url);
// use the URL to generate a cache key unique to request and any authentication data present
$cache_key = md5($method.$this->user.$this->pass.$url.$qs);
$this->cacheDel($cache_key);
return $this;
}
function cacheDel($cache_key = null) {
if (!$this->cache || COREYLIB_NOCACHE) {
return false;
} else {
return $this->cache->del($cache_key);
}
}
function getCacheKey() {
return $this->cache_key;
}
function &getDownload() {
return $this->download;
}
static $sort_by = null;
/**
* Given a collection of clNode objects, use $selector to query a set of nodes
* from each, then (optionally) sort those nodes by one or more sorting filters.
* Sorting filters should be specified <type>:<selector>, where <type> is one of
* str, num, date, bool, or fx and <selector> is a valid node selector expression.
* The value at <selector> in each node will be converted to <type>, and the
* collection will then be sorted by those converted values. In the special case
* of fx, <selector> should instead be a callable function. The function (a custom)
* sorting rule, should be implemented as prescribed by the usort documentation,
* and should handle node value selection internally.
* @param mixed $apis array(clNode), an array of stdClass objects (the return value of clApi::exec), a single clNode instance, or a URL to query
* @param string $selector
* @param string $sort_by
* @return array(clNode) A (sometimes) sorted collection of clNode objects
* @see http://www.php.net/manual/en/function.usort.php
*/
static function &grep($nodes, $selector, $sort_by = null /* dynamic args */) {
$args = func_get_args();
$nodes = @array_shift($args);
if (!$nodes) {
return false;
} else if (!is_array($nodes)) {
if ($nodes instanceof clNode) {
$nodes = array($nodes);
} else {
$api = new clApi((string) $nodes);
if ($node = $api->parse()) {
clApi::log("The URL [$nodes] did not parse, so clApi::grep fails.", E_USER_ERROR);
return false;
}
$nodes = array($node);
}
}
$selector = @array_shift($args);
if (!$selector) {
clApi::log('clApi::grep requires $selector argument (arg #2)', E_USER_WARNING);
return false;
}
$sort_by = array();
foreach($args as $s) {
if (preg_match('/(.*?)\:(.*)/', $s, $matches)) {
@list($type, $order) = preg_split('/,\s*/', $matches[1]);
if (!$order) {
$order = 'asc';
}
$sort_by[] = (object) array(
'type' => $type,
'order' => strtolower($order),
'selector' => $matches[2]
);
} else {
clApi::log("clApi::grep $sort_by arguments must be formatted <type>:<selector>: [{$s}] is invalid.", E_USER_WARNING);
}
}
// build the node collection
$grepd = array();
foreach($nodes as $node) {
// automatically detect clApi::exec results...
if ($node instanceof stdClass) {
if ($node->parsed) {
$grepd = array_merge( $grepd, $node->parsed->get($selector)->toArray() );
} else {
clApi::log(sprintf("clApi::grep can't sort failed parse on [%s]", $node->api->getUrl()), E_USER_WARNING);
}
} else {
$grepd = array_merge( $grepd, $node->get($selector)->toArray() );
}
}
// sort the collection
foreach($sort_by as $s) {
self::$sort_by = $s;
usort($grepd, array('clApi', 'grep_sort'));
if ($order == 'desc') {
$grepd = array_reverse($grepd);
}
}
return $grepd;
}
static function grep_sort($node1, $node2) {
$sort_by = self::$sort_by;
$v1 = $node1->get($sort_by->selector);
$v2 = $node2->get($sort_by->selector);
if ($sort_by->type == 'string') {
$v1 = (string) $v1;
$v2 = (string) $v2;
return strcasecmp($v1, $v2);
} else if ($sort_by->type == 'bool') {
$v1 = (bool) (string) $v1;
$v2 = (bool) (string) $v2;
return ($v1 === $v2) ? 0 : ( $v1 === true ? -1 : 1 );
} else if ($sort_by->type == 'num') {
$v1 = (float) (string) $v1;
$v2 = (float) (string) $v2;
return ($v1 === $v2) ? 0 : ( $v1 < $v2 ? -1 : 1 );
} else if ($sort_by->type == 'date') {
$v1 = strtotime((string) $v1);
$v2 = strtotime((string) $v2);
return ($v1 === $v2) ? 0 : ( $v1 < $v2 ? -1 : 1 );
}
}
/**
* Use curl_multi to execute a collection of clApi objects.
*/
static function exec($apis, $cache_for = -1, $override_method = null, $node_type = null) {
$mh = curl_multi_init();
$handles = array();
foreach($apis as $a => $api) {
if (is_string($api)) {
$api = new clApi($api);
$apis[$a] = $api;
} else if (!($api instanceof clApi)) {
throw new Exception("clApi::exec expects an Array of clApi objects.");
}
$download = $api->download(true, $cache_for, $override_method);
$ch = $download->getCurl();
if ($download->getContent() === false) {
curl_multi_add_handle($mh, $ch);
} else {
$api->setDownload($download);
}
$handles[(int) $ch] = array($api, $download, $ch);
}
do {
$status = curl_multi_exec($mh, $active);
} while($status == CURLM_CALL_MULTI_PERFORM || $active);
foreach($handles as $ch => $ref) {
list($api, $download, $ch) = $ref;
// update the download object with content and CH info
$download->update(curl_multi_getcontent($ch), curl_getinfo($ch));
// if the download was a success
if ($download->is2__()) {
// cache the download
$api->cacheSet($api->getCacheKey(), $download, $cache_for);
}
$api->setDownload($download);
}
$results = array();
foreach($apis as $api) {
$results[] = (object) array(
'api' => $api,
'parsed' => $api->parse($cache_for = -1, $override_method = null, $node_type = null)
);
}
curl_multi_close($mh);
return $results;
}
/**
* Print $msg to the error log.
* @param mixed $msg Can be a string, or an Exception, or any other object
* @param int $level One of the E_USER_* error level constants.
* @return string The value of $msg, post-processing
* @see http://www.php.net/manual/en/errorfunc.constants.php
*/
static function log($msg, $level = E_USER_NOTICE) {
if ($msg instanceof Exception) {
$msg = $msg->getMessage();
} else if (!is_string($msg)) {
$msg = print_r($msg, true);
}
if ($level == E_USER_NOTICE && !COREYLIB_DEBUG) {
// SHHH...
return $msg;
}
trigger_error($msg, $level);
return $msg;
}
}
if (!function_exists('coreylib')):
function coreylib($url, $cache_for = -1, $params = array(), $method = clApi::METHOD_GET) {
$api = new clApi($url);
$api->param($params);
if ($node = $api->parse($cache_for, $method)) {
return $node;
} else {
return false;
}
}
endif;
class clDownload {
private $content = '';
private $ch;
private $info;
function __construct(&$ch = null, $content = false) {
$this->ch = $ch;
$this->info = curl_getinfo($this->ch);
$this->content = $content;
}
function __sleep() {
return array('info', 'content');
}
function getContent() {
return $this->content;
}
function update($content, $info) {
$this->content = $content;
$this->info = $info;
}
function hasContent() {
return (bool) strlen(trim($this->content));
}
function &getCurl() {
return $this->ch;
}
function getInfo() {
return $this->info;
}
private static $xmlContentTypes = array(
'text/xml',
'application/rss\+xml',
'xml'
);
function isXml() {
if (preg_match(sprintf('#(%s)#i', implode('|', self::$xmlContentTypes)), $this->info['content_type'])) {
return true;
} else if (stripos('<?xml', trim($this->content)) === 0) {
return true;
} else {
return false;
}
}
private static $jsonContentTypes = array(
'text/javascript',
'application/x-javascript',
'application/json',
'text/x-javascript',
'text/x-json',
'.*json.*'
);
function isJson() {
if (preg_match(sprintf('#(%s)#i', implode('|', self::$jsonContentTypes)), $this->info['content_type'])) {
return true;
} else if (substr(trim($this->content), 0) === '{' && substr(trim($this->content), -1) === '}') {
return true;
} else if (substr(trim($this->content), 0) === '[' && substr(trim($this->content), -1) === ']') {
return true;
} else {
return false;
}
}
function __call($name, $args) {
if (preg_match('/^is(\d+)(_)?(_)?$/', $name, $matches)) {
$status = $this->info['http_code'];
if (!$status) {
return false;
}
$http_status_code = $matches[1];
$any_ten = @$matches[2];
$any_one = @$matches[3];
if ($any_ten || $any_one) {
for($ten = 0; $ten <= ($any_ten ? 0 : 90); $ten+=10) {
for($one = 0; $one <= (($any_ten || $any_one) ? 0 : 9); $one++) {
$code = $http_status_code . ($ten == 0 ? '0' : '') . ($ten + $one);
if ($code == $status) {
return true;
}
}
}
} else if ($status == $http_status_code) {
return true;
} else {
return false;
}
} else {
throw new clException("Call to unknown function: $name");
}
}
}
// src/cache.php
/**
* Core caching pattern.
*/
abstract class clCache {
/**
* Get the value stored in this cache, uniquely identified by $cache_key.
* @param string $cache_key The cache key
* @param bool $return_raw Instead of returning the cached value, return a packet
* of type stdClass, with two properties: expires (the timestamp
* indicating when this cached data should no longer be valid), and value
* (the unserialized value that was cached there)
*/
abstract function get($cache_key, $return_raw = false);
/**
* Update the cache at $cache_key with $value, setting the expiration
* of $value to a moment in the future, indicated by $timeout.
* @param string $cache_key Uniquely identifies this cache entry
* @param mixed $value Some arbitrary value; can be any serializable type
* @param mixed $timeout An expression of time or a positive integer indicating the number of seconds;
* a $timeout of 0 indicates "cache indefinitely."
* @return a stdClass instance with two properties: expires (the timestamp
* indicating when this cached data should no longer be valid), and value
* (the unserialized value that was cached there)
* @see http://php.net/manual/en/function.strtotime.php
*/
abstract function set($cache_key, $value, $timeout = 0);
/**
* Remove from the cache the value uniquely identified by $cache_key
* @param string $cache_key
* @return true when the cache key existed; otherwise, false
*/
abstract function del($cache_key);
/**
* Remove all cache entries.
*/
abstract function flush();
/**
* Store or retrieve the global cache object.
*/
static $cache;
static function cache($cache = null) {
if (!is_null($cache)) {
if (!($cache instanceof clCache)) {
throw new Exception('Object %s does not inherit from clCache', get_class($object));
}
self::$cache = new clStash($cache);
}
if (!self::$cache) {
try {
// default is FileCache
$class = COREYLIB_DEFAULT_CACHE_STRATEGY;
$cache = new $class();
self::$cache = new clStash($cache);
} catch (Exception $e) {
clApi::log($e, E_USER_WARNING);
return false;
}
}
return self::$cache;
}
private static $buffers = array();
/**
* Attempt to find some cached content. If it's found, echo
* the content, and return true. If it's not found, invoke ob_start(),
* and return false. In the latter case, the calling script should
* next proceed to generate the content to be cached, then, the
* script should call clCache::save(), thus caching the content and
* printing it at the same time.
* @param string $cache_key
* @param mixed $cache_for An expression of how long the content
* should be cached
* @param clCache $cache Optionally, a clCache implementation other
* than the global default
* @return mixed - see codedoc above
*/
static function cached($cache_key, $cache_for = -1, $cache = null) {
$cache = self::cache($cache);
if ($cached = $cache->get($cache_key, true)) {
if ($cached->expires != 0 && $cached->expires <= self::time()) {
self::$buffers[] = (object) array(
'cache' => $cache,
'cache_key' => $cache_key,
'cache_for' => $cache_for
);
ob_start();
return false;
} else {
echo $cached->value;
return true;
}
} else {
self::$buffers[] = (object) array(
'cache' => $cache,
'cache_key' => $cache_key,
'cache_for' => $cache_for
);
ob_start();
return false;
}
}
/**
* Save the current cache buffer.
* @see clCache::cached
*/
static function save($cache_for = null) {
if ($buffer = array_pop(self::$buffers)) {
$buffer->cache->set($buffer->cache_key, ob_get_flush(), $cache_for ? $cache_for : $buffer->cache_for);
} else {
clApi::log("clCache::save called, but no buffer was open", E_USER_WARNING);
}
}
/**
* Cancel the current cache buffer.
* @see clCache::cached
*/
static function cancel() {
if (!array_pop(self::$buffers)) {
clApi::log("clCache::cancel called, but no buffer was open");
}
}
/**
* Read data from the global clCache instance.
*/
static function read($cache_key) {
$cache = self::cache();
return $cache->get($cache_key);
}
/**
* Delete content cached in the global default clCache instance.
*/
static function delete($cache_key) {
$cache = self::cache();
$cache->del($cache_key);
}
/**
* Write content to the global clCache instance.
*/
static function write($cache_key, $value, $timeout = -1) {
$cache = self::cache();
return $cache->set($cache_key, $value, $timeout);
}
/**
* Convert timeout expression to timestamp marking the moment in the future
* at which point the timeout (or expiration) would occur.
* @param mixed $timeout An expression of time or a positive integer indicating the number of seconds
* @see http://php.net/manual/en/function.strtotime.php
* @return a *nix timestamp in the future, or the current time if $timeout is 0, always in GMT.
*/
static function time($timeout = 0) {
if ($timeout === -1) {
return false;
}
if (!is_numeric($timeout)) {
$original = trim($timeout);
// normalize the expression: should be future
$firstChar = substr($timeout, 0, 1);
if ($firstChar == "-") {
$timeout = substr($timeout, 1);
} else if ($firstChar != "-") {
if (stripos($timeout, 'last') === false) {
$timeout = str_replace('last', 'next', $timeout);
}
}
if (($timeout = strtotime(gmdate('c', strtotime($timeout)))) === false) {
clApi::log("'$original' is an invalid expression of time.", E_USER_WARNING);
return false;
}
return $timeout;
} else {
return strtotime(gmdate('c'))+$timeout;
}
}
/**
* Produce a standard cache packet.
* @param $value to be wrapped
* @return stdClass
*/
static function raw(&$value, $expires) {
return (object) array(
'created' => self::time(),
'expires' => $expires,
'value' => $value
);
}
}
/**
* A proxy for another caching system -- stashes the cached
* data in memory, for fastest possible access.
*/
class clStash extends clCache {
private $proxied;
private $mem = array();
function __construct($cache) {
if (is_null($cache)) {
throw new clException("Cache object to proxy cannot be null.");
} else if (!($cache instanceOf clCache)) {
throw new clException("Cache object must inherit from clCache");
}
$this->proxied = $cache;
}
function get($cache_key, $return_raw = false) {
if ($stashed = @$this->mem[$cache_key]) {
// is the stash too old?
if ($stashed->expires != 0 && $stashed->expires <= self::time()) {
// yes, stash is too old. try to resource, just in case
if ($raw = $this->proxied->get($cache_key, true)) {
// there was something fresher in the proxied cache, to stash it
$this->mem[$cache_key] = $raw;
// then return the requested data
return $return_raw ? $raw : $raw->value;
// nope... we got nothing
} else {
return false;
}
// no, the stash was not too old
} else {
clApi::log("Cached data loaded from memory [{$cache_key}]");
return $return_raw ? $stashed : $stashed->value;
}
// there was nothing in the stash:
} else {
// try to retrieve from the proxied cache:
if ($raw = $this->proxied->get($cache_key, true)) {
// there was a value in the proxied cache:
$this->mem[$cache_key] = $raw;
return $return_raw ? $raw : $raw->value;
// nothing in the proxied cache:
} else {
return false;
}
}
}
function set($cache_key, $value, $timeout = 0) {
return $this->mem[$cache_key] = $this->proxied->set($cache_key, $value, $timeout);
}
function del($cache_key) {
unset($this->mem[$cache_key]);
return $this->proxied->del($cache_key);
}
function flush() {
$this->mem[] = array();
$this->proxied->flush();
}
}
/**
* Caches data to the file system.
*/