-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathRestler.php
1690 lines (1595 loc) · 59.3 KB
/
Restler.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
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
namespace Luracast\Restler;
use Exception;
use InvalidArgumentException;
use Luracast\Restler\Data\ApiMethodInfo;
use Luracast\Restler\Data\ValidationInfo;
use Luracast\Restler\Data\Validator;
use Luracast\Restler\Format\iFormat;
use Luracast\Restler\Format\iDecodeStream;
use Luracast\Restler\Format\UrlEncodedFormat;
/**
* REST API Server. It is the server part of the Restler framework.
* inspired by the RestServer code from
* <http://jacwright.com/blog/resources/RestServer.txt>
*
*
* @category Framework
* @package Restler
* @author R.Arul Kumaran <[email protected]>
* @copyright 2010 Luracast
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link http://luracast.com/products/restler/
*
*
* @method static void onGet() onGet(Callable $function) fired before reading the request details
* @method static void onRoute() onRoute(Callable $function) fired before finding the api method
* @method static void onNegotiate() onNegotiate(Callable $function) fired before content negotiation
* @method static void onPreAuthFilter() onPreAuthFilter(Callable $function) fired before pre auth filtering
* @method static void onAuthenticate() onAuthenticate(Callable $function) fired before auth
* @method static void onPostAuthFilter() onPostAuthFilter(Callable $function) fired before post auth filtering
* @method static void onValidate() onValidate(Callable $function) fired before validation
* @method static void onCall() onCall(Callable $function) fired before api method call
* @method static void onCompose() onCompose(Callable $function) fired before composing response
* @method static void onRespond() onRespond(Callable $function) fired before sending response
* @method static void onComplete() onComplete(Callable $function) fired after sending response
* @method static void onMessage() onMessage(Callable $function) fired before composing error response
*
* @method void onGet() onGet(Callable $function) fired before reading the request details
* @method void onRoute() onRoute(Callable $function) fired before finding the api method
* @method void onNegotiate() onNegotiate(Callable $function) fired before content negotiation
* @method void onPreAuthFilter() onPreAuthFilter(Callable $function) fired before pre auth filtering
* @method void onAuthenticate() onAuthenticate(Callable $function) fired before auth
* @method void onPostAuthFilter() onPostAuthFilter(Callable $function) fired before post auth filtering
* @method void onValidate() onValidate(Callable $function) fired before validation
* @method void onCall() onCall(Callable $function) fired before api method call
* @method void onCompose() onCompose(Callable $function) fired before composing response
* @method void onRespond() onRespond(Callable $function) fired before sending response
* @method void onComplete() onComplete(Callable $function) fired after sending response
* @method void onMessage() onMessage(Callable $function) fired before composing error response
*
* @property bool|null _authenticated
* @property bool _authVerified
*/
class Restler extends EventDispatcher
{
const VERSION = '5';
// ==================================================================
//
// Public variables
//
// ------------------------------------------------------------------
/**
* Reference to the last exception thrown
* @var RestException
*/
public $exception = null;
/**
* Used in production mode to store the routes and more
*
* @var iCache
*/
public $cache;
/**
* URL of the currently mapped service
*
* @var string
*/
public $url;
/**
* Http request method of the current request.
* Any value between [GET, PUT, POST, DELETE]
*
* @var string
*/
public $requestMethod;
/**
* Requested data format.
* Instance of the current format class
* which implements the iFormat interface
*
* @var iFormat
* @example jsonFormat, xmlFormat, yamlFormat etc
*/
public $requestFormat;
/**
* Response data format.
*
* Instance of the current format class
* which implements the iFormat interface
*
* @var iFormat
* @example jsonFormat, xmlFormat, yamlFormat etc
*/
public $responseFormat;
/**
* Http status code
*
* @var int|null when specified it will override @status comment
*/
public $responseCode=null;
/**
* @var string base url of the api service
*/
protected $baseUrl;
/**
* @var bool Used for waiting till verifying @format
* before throwing content negotiation failed
*/
protected $requestFormatDiffered = false;
/**
* method information including metadata
*
* @var ApiMethodInfo
*/
public $apiMethodInfo;
/**
* @var int for calculating execution time
*/
protected $startTime;
/**
* When set to false, it will run in debug mode and parse the
* class files every time to map it to the URL
*
* @var boolean
*/
protected $productionMode = false;
public $refreshCache = false;
/**
* Caching of url map is enabled or not
*
* @var boolean
*/
protected $cached;
/**
* @var int
*/
protected $apiVersion = 1;
/**
* @var int
*/
protected $requestedApiVersion = 1;
/**
* @var int
*/
protected $apiMinimumVersion = 1;
/**
* @var array
*/
protected $apiVersionMap = array();
/**
* Associated array that maps formats to their respective format class name
*
* @var array
*/
protected $formatMap = array();
/**
* List of the Mime Types that can be produced as a response by this API
*
* @var array
*/
protected $writableMimeTypes = array();
/**
* List of the Mime Types that are supported for incoming requests by this API
*
* @var array
*/
protected $readableMimeTypes = array();
/**
* Associated array that maps formats to their respective format class name
*
* @var array
*/
protected $formatOverridesMap = array('extensions' => array());
/**
* list of filter classes
*
* @var array
*/
protected $filterClasses = array();
/**
* instances of filter classes that are executed after authentication
*
* @var array
*/
protected $postAuthFilterClasses = array();
// ==================================================================
//
// Protected variables
//
// ------------------------------------------------------------------
/**
* Data sent to the service
*
* @var array
*/
protected $requestData = array();
/**
* list of authentication classes
*
* @var array
*/
protected $authClasses = array();
/**
* list of error handling classes
*
* @var array
*/
protected $errorClasses = array();
protected $authenticated = false;
protected $authVerified = false;
/**
* @var mixed
*/
protected $responseData;
/**
* Constructor
*
* @param boolean $productionMode When set to false, it will run in
* debug mode and parse the class files
* every time to map it to the URL
*
* @param bool $refreshCache will update the cache when set to true
*/
public function __construct($productionMode = false, $refreshCache = false)
{
parent::__construct();
$this->startTime = time();
Util::$restler = $this;
Scope::set('Restler', $this);
$this->productionMode = $productionMode;
if (is_null(Defaults::$cacheDirectory)) {
Defaults::$cacheDirectory = dirname($_SERVER['SCRIPT_FILENAME']) .
DIRECTORY_SEPARATOR . 'cache';
}
$this->cache = new Defaults::$cacheClass();
$this->refreshCache = $refreshCache;
// use this to rebuild cache every time in production mode
if ($productionMode && $refreshCache) {
$this->cached = false;
}
}
/**
* Main function for processing the api request
* and return the response
*
* @throws Exception when the api service class is missing
* @throws RestException to send error response
*/
public function handle()
{
try {
try {
try {
$this->get();
} catch (Exception $e) {
$this->requestData
= array(Defaults::$fullRequestDataName => array());
if (!$e instanceof RestException) {
$e = new RestException(
500,
$this->productionMode ? null : $e->getMessage(),
array(),
$e
);
}
$this->route();
throw $e;
}
if (Defaults::$useVendorMIMEVersioning)
$this->responseFormat = $this->negotiateResponseFormat();
$this->route();
} catch (Exception $e) {
$this->negotiate();
if (!$e instanceof RestException) {
$e = new RestException(
500,
$this->productionMode ? null : $e->getMessage(),
array(),
$e
);
}
throw $e;
}
$this->negotiate();
$this->preAuthFilter();
$this->authenticate();
$this->postAuthFilter();
$this->validate();
$this->preCall();
$this->call();
$this->compose();
$this->postCall();
if (Defaults::$returnResponse) {
return $this->respond();
}
$this->respond();
} catch (Exception $e) {
try{
if (Defaults::$returnResponse) {
return $this->message($e);
}
$this->message($e);
} catch (Exception $e2) {
if (Defaults::$returnResponse) {
return $this->message($e2);
}
$this->message($e2);
}
}
}
/**
* read the request details
*
* Find out the following
* - baseUrl
* - url requested
* - version requested (if url based versioning)
* - http verb/method
* - negotiate content type
* - request data
* - set defaults
*/
protected function get()
{
$this->dispatch('get');
if (empty($this->formatMap)) {
$this->setSupportedFormats('JsonFormat');
}
$this->url = $this->getPath();
$this->requestMethod = Util::getRequestMethod();
$this->requestFormat = $this->getRequestFormat();
$this->requestData = $this->getRequestData(false);
//parse defaults
foreach ($_GET as $key => $value) {
if (isset(Defaults::$aliases[$key])) {
$_GET[Defaults::$aliases[$key]] = $value;
unset($_GET[$key]);
$key = Defaults::$aliases[$key];
}
if (in_array($key, Defaults::$overridables)) {
Defaults::setProperty($key, $value);
}
}
}
/**
* Returns a list of the mime types (e.g. ["application/json","application/xml"]) that the API can respond with
* @return array
*/
public function getWritableMimeTypes()
{
return $this->writableMimeTypes;
}
/**
* Returns the list of Mime Types for the request that the API can understand
* @return array
*/
public function getReadableMimeTypes()
{
return $this->readableMimeTypes;
}
/**
* Call this method and pass all the formats that should be supported by
* the API Server. Accepts multiple parameters
*
* @param string ,... $formatName class name of the format class that
* implements iFormat
*
* @example $restler->setSupportedFormats('JsonFormat', 'XmlFormat'...);
* @throws Exception
*/
public function setSupportedFormats($format = null /*[, $format2...$farmatN]*/)
{
$args = func_get_args();
$extensions = array();
$throwException = $this->requestFormatDiffered;
$this->writableMimeTypes = $this->readableMimeTypes = array();
foreach ($args as $className) {
$obj = Scope::get($className);
if (!$obj instanceof iFormat)
throw new Exception('Invalid format class; must implement ' .
'iFormat interface');
if ($throwException && get_class($obj) === get_class($this->requestFormat)) {
$throwException = false;
}
foreach ($obj->getMIMEMap() as $mime => $extension) {
if($obj->isWritable()){
$this->writableMimeTypes[]=$mime;
$extensions[".$extension"] = true;
}
if($obj->isReadable())
$this->readableMimeTypes[]=$mime;
if (!isset($this->formatMap[$extension]))
$this->formatMap[$extension] = $className;
if (!isset($this->formatMap[$mime]))
$this->formatMap[$mime] = $className;
}
}
if ($throwException) {
throw new RestException(
403,
'Content type `' . $this->requestFormat->getMIME() . '` is not supported.'
);
}
$this->formatMap['default'] = $args[0];
$this->formatMap['extensions'] = array_keys($extensions);
}
/**
* Call this method and pass all the formats that can be used to override
* the supported formats using `@format` comment. Accepts multiple parameters
*
* @param string ,... $formatName class name of the format class that
* implements iFormat
*
* @example $restler->setOverridingFormats('JsonFormat', 'XmlFormat'...);
* @throws Exception
*/
public function setOverridingFormats($format = null /*[, $format2...$farmatN]*/)
{
$args = func_get_args();
$extensions = array();
foreach ($args as $className) {
$obj = Scope::get($className);
if (!$obj instanceof iFormat)
throw new Exception('Invalid format class; must implement ' .
'iFormat interface');
foreach ($obj->getMIMEMap() as $mime => $extension) {
if (!isset($this->formatOverridesMap[$extension]))
$this->formatOverridesMap[$extension] = $className;
if (!isset($this->formatOverridesMap[$mime]))
$this->formatOverridesMap[$mime] = $className;
if($obj->isWritable())
$extensions[".$extension"] = true;
}
}
$this->formatOverridesMap['extensions'] = array_keys($extensions);
}
/**
* Set one or more string to be considered as the base url
*
* When more than one base url is provided, restler will make
* use of $_SERVER['HTTP_HOST'] to find the right one
*
* @param string ,... $url
*/
public function setBaseUrls($url /*[, $url2...$urlN]*/)
{
if (func_num_args() > 1) {
$urls = func_get_args();
usort($urls, function ($a, $b) {
return strlen($a) - strlen($b);
});
foreach ($urls as $u) {
if (0 === strpos($_SERVER['HTTP_HOST'], parse_url($u, PHP_URL_HOST))) {
$this->baseUrl = $u;
return;
}
}
}
$this->baseUrl = $url;
}
/**
* Parses the request url and get the api path
*
* @return string api path
*/
protected function getPath()
{
// fix SCRIPT_NAME for PHP 5.4 built-in web server
if (false === strpos($_SERVER['SCRIPT_NAME'], '.php'))
$_SERVER['SCRIPT_NAME']
= '/' . substr($_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT']) + 1);
list($base, $path) = Util::splitCommonPath(
strtok(urldecode($_SERVER['REQUEST_URI']), '?'), //remove query string
$_SERVER['SCRIPT_NAME']
);
if (!$this->baseUrl) {
// Fix port number retrieval if port is specified in HOST header.
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$portPos = strpos($host,":");
if ($portPos){
$port = substr($host,$portPos+1);
} else {
$port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : '80';
$port = isset($_SERVER['HTTP_X_FORWARDED_PORT']) ? $_SERVER['HTTP_X_FORWARDED_PORT'] : $port; // Amazon ELB
}
$https = $port === '443' ||
(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') || // Amazon ELB
(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on');
$baseUrl = ($https ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'];
if ($port != '80' && $port != '443')
$baseUrl .= ':' . $port;
$this->baseUrl = $baseUrl . $base;
} elseif (!empty($base) && false === strpos($this->baseUrl, $base)) {
$this->baseUrl .= $base;
}
$path = str_replace(
array_merge(
$this->formatMap['extensions'],
$this->formatOverridesMap['extensions']
),
'',
rtrim($path, '/') //remove trailing slash if found
);
if (Defaults::$useUrlBasedVersioning && strlen($path) && $path[0] === 'v') {
$version = intval(substr($path, 1));
if ($version && $version <= $this->apiVersion) {
$this->requestedApiVersion = $version;
$path = explode('/', $path, 2);
$path = count($path) === 2 ? $path[1] : '';
}
} else {
$this->requestedApiVersion = $this->apiMinimumVersion;
}
return $path;
}
/**
* Parses the request to figure out format of the request data
*
* @throws RestException
* @return iFormat any class that implements iFormat
* @example JsonFormat
*/
protected function getRequestFormat()
{
$format = null ;
// check if client has sent any information on request format
if (
!empty($_SERVER['CONTENT_TYPE']) ||
(
!empty($_SERVER['HTTP_CONTENT_TYPE']) &&
$_SERVER['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE']
)
) {
$mime = $_SERVER['CONTENT_TYPE'];
if (false !== $pos = strpos($mime, ';')) {
$mime = substr($mime, 0, $pos);
}
if ($mime === UrlEncodedFormat::MIME)
$format = Scope::get('UrlEncodedFormat');
elseif (isset($this->formatMap[$mime])) {
$format = Scope::get($this->formatMap[$mime]);
$format->setMIME($mime);
} elseif (!$this->requestFormatDiffered && isset($this->formatOverridesMap[$mime])) {
//if our api method is not using an @format comment
//to point to this $mime, we need to throw 403 as in below
//but since we don't know that yet, we need to defer that here
$format = Scope::get($this->formatOverridesMap[$mime]);
$format->setMIME($mime);
$this->requestFormatDiffered = true;
} else {
throw new RestException(
403,
"Content type `$mime` is not supported."
);
}
}
if(!$format){
$format = Scope::get($this->formatMap['default']);
}
return $format;
}
public function getRequestStream()
{
static $tempStream = false;
if (!$tempStream) {
$tempStream = fopen('php://temp', 'r+');
$rawInput = fopen('php://input', 'r');
stream_copy_to_stream($rawInput, $tempStream);
}
rewind($tempStream);
return $tempStream;
}
/**
* Parses the request data and returns it
*
* @param bool $includeQueryParameters
*
* @return array php data
*/
public function getRequestData($includeQueryParameters = true)
{
$get = UrlEncodedFormat::decoderTypeFix($_GET);
if ($this->requestMethod === 'PUT'
|| $this->requestMethod === 'PATCH'
|| $this->requestMethod === 'POST'
) {
if (!empty($this->requestData)) {
return $includeQueryParameters
? $this->requestData + $get
: $this->requestData;
}
$stream = $this->getRequestStream();
if($stream === FALSE)
return array();
$r = $this->requestFormat instanceof iDecodeStream
? $this->requestFormat->decodeStream($stream)
: $this->requestFormat->decode(stream_get_contents($stream));
$r = is_array($r)
? array_merge($r, array(Defaults::$fullRequestDataName => $r))
: array(Defaults::$fullRequestDataName => $r);
return $includeQueryParameters
? $r + $get
: $r;
}
return $includeQueryParameters ? $get : array(); //no body
}
/**
* Find the api method to execute for the requested Url
*/
protected function route()
{
$this->dispatch('route');
$params = $this->getRequestData();
//backward compatibility for restler 2 and below
if (!Defaults::$smartParameterParsing) {
$params = $params + array(Defaults::$fullRequestDataName => $params);
}
$this->apiMethodInfo = $o = Routes::find(
$this->url, $this->requestMethod,
$this->requestedApiVersion, $params
);
//set defaults based on api method comments
if (isset($o->metadata)) {
foreach (Defaults::$fromComments as $key => $defaultsKey) {
if (array_key_exists($key, $o->metadata)) {
$value = $o->metadata[$key];
Defaults::setProperty($defaultsKey, $value);
}
}
}
if (!isset($o->className))
throw new RestException(404);
if(isset($this->apiVersionMap[$o->className])){
Scope::$classAliases[Util::getShortName($o->className)]
= $this->apiVersionMap[$o->className][$this->requestedApiVersion];
}
foreach ($this->authClasses as $auth) {
if (isset($this->apiVersionMap[$auth])) {
Scope::$classAliases[$auth] = $this->apiVersionMap[$auth][$this->requestedApiVersion];
} elseif (isset($this->apiVersionMap[Scope::$classAliases[$auth]])) {
Scope::$classAliases[$auth]
= $this->apiVersionMap[Scope::$classAliases[$auth]][$this->requestedApiVersion];
}
}
}
/**
* Negotiate the response details such as
* - cross origin resource sharing
* - media type
* - charset
* - language
*
* @throws RestException
*/
protected function negotiate()
{
$this->dispatch('negotiate');
$this->negotiateCORS();
$this->responseFormat = $this->negotiateResponseFormat();
$this->negotiateCharset();
$this->negotiateLanguage();
}
protected function negotiateCORS()
{
if (
$this->requestMethod === 'OPTIONS'
&& Defaults::$crossOriginResourceSharing
) {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header('Access-Control-Allow-Methods: '
. Defaults::$accessControlAllowMethods);
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header('Access-Control-Allow-Headers: '
. $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
header('Access-Control-Allow-Origin: ' .
((Defaults::$accessControlAllowOrigin === '*' && isset($_SERVER['HTTP_ORIGIN']))
? $_SERVER['HTTP_ORIGIN'] : Defaults::$accessControlAllowOrigin));
header('Access-Control-Allow-Credentials: true');
exit(0);
}
}
// ==================================================================
//
// Protected functions
//
// ------------------------------------------------------------------
/**
* Parses the request to figure out the best format for response.
* Extension, if present, overrides the Accept header
*
* @throws RestException
* @return iFormat
* @example JsonFormat
*/
protected function negotiateResponseFormat()
{
$metadata = Util::nestedValue($this, 'apiMethodInfo', 'metadata');
//check if the api method insists on response format using @format comment
if ($metadata && isset($metadata['format'])) {
$formats = explode(',', (string)$metadata['format']);
foreach ($formats as $i => $f) {
$f = trim($f);
if (!in_array($f, $this->formatOverridesMap))
throw new RestException(
500,
"Given @format is not present in overriding formats. Please call `\$r->setOverridingFormats('$f');` first."
);
$formats[$i] = $f;
}
call_user_func_array(array($this, 'setSupportedFormats'), $formats);
}
// check if client has specified an extension
/** @var $format iFormat*/
$format = null;
$extensions = explode(
'.',
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
while ($extensions) {
$extension = array_pop($extensions);
$extension = explode('/', $extension);
$extension = array_shift($extension);
if ($extension && isset($this->formatMap[$extension])) {
$format = Scope::get($this->formatMap[$extension]);
$format->setExtension($extension);
// echo "Extension $extension";
return $format;
}
}
// check if client has sent list of accepted data formats
if (isset($_SERVER['HTTP_ACCEPT'])) {
$acceptList = Util::sortByPriority($_SERVER['HTTP_ACCEPT']);
foreach ($acceptList as $accept => $quality) {
if (isset($this->formatMap[$accept])) {
$format = Scope::get($this->formatMap[$accept]);
$format->setMIME($accept);
//echo "MIME $accept";
// Tell cache content is based on Accept header
@header('Vary: Accept');
return $format;
} elseif (false !== ($index = strrpos($accept, '+'))) {
$mime = substr($accept, 0, $index);
if (is_string(Defaults::$apiVendor)
&& 0 === stripos($mime,
'application/vnd.'
. Defaults::$apiVendor . '-v')
) {
$extension = substr($accept, $index + 1);
if (isset($this->formatMap[$extension])) {
//check the MIME and extract version
$version = intval(substr($mime,
18 + strlen(Defaults::$apiVendor)));
if ($version > 0 && $version <= $this->apiVersion) {
$this->requestedApiVersion = $version;
$format = Scope::get($this->formatMap[$extension]);
$format->setExtension($extension);
// echo "Extension $extension";
Defaults::$useVendorMIMEVersioning = true;
@header('Vary: Accept');
return $format;
}
}
}
}
}
} else {
// RFC 2616: If no Accept header field is
// present, then it is assumed that the
// client accepts all media types.
$_SERVER['HTTP_ACCEPT'] = '*/*';
}
if (strpos($_SERVER['HTTP_ACCEPT'], '*') !== false) {
if (false !== strpos($_SERVER['HTTP_ACCEPT'], 'application/*')) {
$format = Scope::get('JsonFormat');
} elseif (false !== strpos($_SERVER['HTTP_ACCEPT'], 'text/*')) {
$format = Scope::get('XmlFormat');
} elseif (false !== strpos($_SERVER['HTTP_ACCEPT'], '*/*')) {
$format = Scope::get($this->formatMap['default']);
}
}
if (empty($format)) {
// RFC 2616: If an Accept header field is present, and if the
// server cannot send a response which is acceptable according to
// the combined Accept field value, then the server SHOULD send
// a 406 (not acceptable) response.
$format = Scope::get($this->formatMap['default']);
$this->responseFormat = $format;
throw new RestException(
406,
'Content negotiation failed. ' .
'Try `' . $format->getMIME() . '` instead.'
);
} else {
// Tell cache content is based at Accept header
@header("Vary: Accept");
return $format;
}
}
protected function negotiateCharset()
{
if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
$found = false;
$charList = Util::sortByPriority($_SERVER['HTTP_ACCEPT_CHARSET']);
foreach ($charList as $charset => $quality) {
if (in_array($charset, Defaults::$supportedCharsets)) {
$found = true;
Defaults::$charset = $charset;
break;
}
}
if (!$found) {
if (strpos($_SERVER['HTTP_ACCEPT_CHARSET'], '*') !== false) {
//use default charset
} else {
throw new RestException(
406,
'Content negotiation failed. ' .
'Requested charset is not supported'
);
}
}
}
}
protected function negotiateLanguage()
{
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$found = false;
$langList = Util::sortByPriority($_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langList as $lang => $quality) {
foreach (Defaults::$supportedLanguages as $supported) {
if (strcasecmp($supported, $lang) === 0) {
$found = true;
Defaults::$language = $supported;
break 2;
}
}
}
if (!$found) {
if (strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], '*') !== false) {
//use default language
} else {
//ignore
}
}
}
}
/**
* Filer api calls before authentication
*/
protected function preAuthFilter()
{
if (empty($this->filterClasses)) {
return;
}
$this->dispatch('preAuthFilter');
foreach ($this->filterClasses as $filterClass) {
/**
* @var iFilter
*/
$filterObj = Scope::get($filterClass);
if (!$filterObj instanceof iFilter) {
throw new RestException (
500, 'Filter Class ' .
'should implement iFilter');
} else if (!($ok = $filterObj->__isAllowed())) {
if (is_null($ok)
&& $filterObj instanceof iUseAuthentication
) {
//handle at authentication stage
$this->postAuthFilterClasses[] = $filterClass;
continue;
}
throw new RestException(403); //Forbidden
}
}
}
protected function authenticate()
{
$o = &$this->apiMethodInfo;
$accessLevel = max(Defaults::$apiAccessLevel, $o->accessLevel);
if ($accessLevel || count($this->postAuthFilterClasses)) {
$this->dispatch('authenticate');
if (!count($this->authClasses) && $accessLevel > 1) {
throw new RestException(
403,
'at least one Authentication Class is required'
);
}
$unauthorized = false;
foreach ($this->authClasses as $authClass) {
try {
$authObj = Scope::get($authClass);
if (!method_exists($authObj, Defaults::$authenticationMethod)) {
throw new RestException (
500, 'Authentication Class ' .
'should implement iAuthenticate');
} elseif (
!$authObj->{Defaults::$authenticationMethod}()
) {
throw new RestException(401);
}
$unauthorized = false;
break;
} catch (InvalidAuthCredentials $e) {
$this->authenticated = false;
throw $e;
} catch (RestException $e) {
if (!$unauthorized) {
$unauthorized = $e;
}
}
}
$this->authVerified = true;
if ($unauthorized) {
if ($accessLevel > 1) { //when it is not a hybrid api
throw $unauthorized;
} else {
$this->authenticated = false;
}
} else {
$this->authenticated = true;
}
}
}
/**
* Filer api calls after authentication
*/
protected function postAuthFilter()
{
if(empty($this->postAuthFilterClasses)) {
return;
}
$this->dispatch('postAuthFilter');
foreach ($this->postAuthFilterClasses as $filterClass) {
Scope::get($filterClass);