forked from chriskacerguis/codeigniter-restserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestController.php
2040 lines (1718 loc) · 71.5 KB
/
RestController.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 chriskacerguis\RestServer;
use Exception;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use stdClass;
defined('BASEPATH') or exit('No direct script access allowed');
/**
* CodeIgniter Rest Controller
* A fully RESTful server implementation for CodeIgniter using one library, one config file and one controller.
*
* @link https://github.com/chriskacerguis/codeigniter-restserver
*
* @version 4.0.0
*/
class RestController extends \CI_Controller
{
/**
* This defines the rest format
* Must be overridden it in a controller so that it is set.
*
* @var string|null
*/
protected $rest_format = null;
/**
* Defines the list of method properties such as limit, log and level.
*
* @var array
*/
protected $methods = [];
/**
* Defines https status.
*/
protected $http_status = [];
/**
* List of allowed HTTP methods.
*
* @var array
*/
protected $allowed_http_methods = ['get', 'delete', 'post', 'put', 'options', 'patch', 'head'];
/**
* Contains details about the request
* Fields: body, format, method, ssl
* Note: This is a dynamic object (stdClass).
*
* @var object
*/
protected $request = null;
/**
* Contains details about the response
* Fields: format, lang
* Note: This is a dynamic object (stdClass).
*
* @var object
*/
protected $response = null;
/**
* Contains details about the REST API
* Fields: db, ignore_limits, key, level, user_id
* Note: This is a dynamic object (stdClass).
*
* @var object
*/
protected $rest = null;
/**
* The arguments for the GET request method.
*
* @var array
*/
protected $_get_args = [];
/**
* The arguments for the POST request method.
*
* @var array
*/
protected $_post_args = [];
/**
* The arguments for the PUT request method.
*
* @var array
*/
protected $_put_args = [];
/**
* The arguments for the DELETE request method.
*
* @var array
*/
protected $_delete_args = [];
/**
* The arguments for the PATCH request method.
*
* @var array
*/
protected $_patch_args = [];
/**
* The arguments for the HEAD request method.
*
* @var array
*/
protected $_head_args = [];
/**
* The arguments for the OPTIONS request method.
*
* @var array
*/
protected $_options_args = [];
/**
* The arguments for the query parameters.
*
* @var array
*/
protected $_query_args = [];
/**
* The arguments from GET, POST, PUT, DELETE, PATCH, HEAD and OPTIONS request methods combined.
*
* @var array
*/
protected $_args = [];
/**
* The insert_id of the log entry (if we have one).
*
* @var string
*/
protected $_insert_id = '';
/**
* If the request is allowed based on the API key provided.
*
* @var bool
*/
protected $_allow = true;
/**
* The LDAP Distinguished Name of the User post authentication.
*
* @var string
*/
protected $_user_ldap_dn = '';
/**
* The start of the response time from the server.
*
* @var number
*/
protected $_start_rtime;
/**
* The end of the response time from the server.
*
* @var number
*/
protected $_end_rtime;
/**
* List all supported methods, the first will be the default format.
*
* @var array
*/
protected $_supported_formats = [
'json' => 'application/json',
'array' => 'application/json',
'csv' => 'application/csv',
'html' => 'text/html',
'jsonp' => 'application/javascript',
'php' => 'text/plain',
'serialized' => 'application/vnd.php.serialized',
'xml' => 'application/xml',
];
/**
* Information about the current API user.
*
* @var object
*/
protected $_apiuser;
/**
* Whether or not to perform a CORS check and apply CORS headers to the request.
*
* @var bool
*/
protected $check_cors = null;
/**
* Enable XSS flag
* Determines whether the XSS filter is always active when
* GET, OPTIONS, HEAD, POST, PUT, DELETE and PATCH data is encountered
* Set automatically based on config setting.
*
* @var bool
*/
protected $_enable_xss = false;
private $is_valid_request = true;
/**
* Common HTTP status codes and their respective description.
*
* @link http://www.restapitutorial.com/httpstatuscodes.html
*/
const HTTP_OK = 200;
const HTTP_CREATED = 201;
const HTTP_NOT_MODIFIED = 304;
const HTTP_BAD_REQUEST = 400;
const HTTP_UNAUTHORIZED = 401;
const HTTP_FORBIDDEN = 403;
const HTTP_NOT_FOUND = 404;
const HTTP_METHOD_NOT_ALLOWED = 405;
const HTTP_NOT_ACCEPTABLE = 406;
const HTTP_INTERNAL_ERROR = 500;
/**
* @var Format
*/
private $format;
/**
* @var bool
*/
protected $auth_override;
/**
* Extend this function to apply additional checking early on in the process.
*
* @return void
*/
protected function early_checks()
{
}
/**
* Constructor for the REST API.
*
* @param string $config Configuration filename minus the file extension
* e.g: my_rest.php is passed as 'my_rest'
*/
public function __construct($config = 'rest')
{
parent::__construct();
// Set the default value of global xss filtering. Same approach as CodeIgniter 3
$this->_enable_xss = ($this->config->item('global_xss_filtering') === true);
// Don't try to parse template variables like {elapsed_time} and {memory_usage}
// when output is displayed for not damaging data accidentally
$this->output->parse_exec_vars = false;
// Load the rest.php configuration file
$this->get_local_config($config);
// Log the loading time to the log table
if ($this->config->item('rest_enable_logging') === true) {
// Start the timer for how long the request takes
$this->_start_rtime = microtime(true);
}
// Determine supported output formats from configuration
$supported_formats = $this->config->item('rest_supported_formats');
// Validate the configuration setting output formats
if (empty($supported_formats)) {
$supported_formats = [];
}
if (!is_array($supported_formats)) {
$supported_formats = [$supported_formats];
}
// Add silently the default output format if it is missing
$default_format = $this->_get_default_output_format();
if (!in_array($default_format, $supported_formats)) {
$supported_formats[] = $default_format;
}
// Now update $this->_supported_formats
$this->_supported_formats = array_intersect_key($this->_supported_formats, array_flip($supported_formats));
// Get the language
$language = $this->config->item('rest_language');
if ($language === null) {
$language = 'english';
}
// Load the language file
$this->lang->load('rest_controller', $language, false, true, __DIR__.'/../');
// Initialise the response, request and rest objects
$this->request = new stdClass();
$this->response = new stdClass();
$this->rest = new stdClass();
// Check to see if the current IP address is blacklisted
if ($this->config->item('rest_ip_blacklist_enabled') === true) {
$this->_check_blacklist_auth();
}
// Determine whether the connection is HTTPS
$this->request->ssl = is_https();
// How is this request being made? GET, POST, PATCH, DELETE, INSERT, PUT, HEAD or OPTIONS
$this->request->method = $this->_detect_method();
// Check for CORS access request
$check_cors = $this->config->item('check_cors');
if ($check_cors === true) {
$this->_check_cors();
}
// Create an argument container if it doesn't exist e.g. _get_args
if (isset($this->{'_'.$this->request->method.'_args'}) === false) {
$this->{'_'.$this->request->method.'_args'} = [];
}
// Set up the query parameters
$this->_parse_query();
// Set up the GET variables
$this->_get_args = array_merge($this->_get_args, $this->uri->ruri_to_assoc());
// Try to find a format for the request (means we have a request body)
$this->request->format = $this->_detect_input_format();
// Not all methods have a body attached with them
$this->request->body = null;
$this->{'_parse_'.$this->request->method}();
// Fix parse method return arguments null
if ($this->{'_'.$this->request->method.'_args'} === null) {
$this->{'_'.$this->request->method.'_args'} = [];
}
// Which format should the data be returned in?
$this->response->format = $this->_detect_output_format();
// Which language should the data be returned in?
$this->response->lang = $this->_detect_lang();
// Now we know all about our request, let's try and parse the body if it exists
if ($this->request->format && $this->request->body) {
$this->request->body = Format::factory($this->request->body, $this->request->format)->to_array();
// Assign payload arguments to proper method container
$this->{'_'.$this->request->method.'_args'} = $this->request->body;
}
//get header vars
$this->_head_args = $this->input->request_headers();
// Merge both for one mega-args variable
$this->_args = array_merge(
$this->_get_args,
$this->_options_args,
$this->_patch_args,
$this->_head_args,
$this->_put_args,
$this->_post_args,
$this->_delete_args,
$this->{'_'.$this->request->method.'_args'}
);
// Extend this function to apply additional checking early on in the process
$this->early_checks();
// Load DB if its enabled
if ($this->config->item('rest_database_group') && ($this->config->item('rest_enable_keys') || $this->config->item('rest_enable_logging'))) {
$this->rest->db = $this->load->database($this->config->item('rest_database_group'), true);
}
// Use whatever database is in use (isset returns FALSE)
elseif (property_exists($this, 'db')) {
$this->rest->db = $this->db;
}
// Check if there is a specific auth type for the current class/method
// _auth_override_check could exit so we need $this->rest->db initialized before
$this->auth_override = $this->_auth_override_check();
// Checking for keys? GET TO WorK!
// Skip keys test for $config['auth_override_class_method']['class'['method'] = 'none'
if ($this->config->item('rest_enable_keys') && $this->auth_override !== true) {
$this->_allow = $this->_detect_api_key();
}
// Only allow ajax requests
if ($this->input->is_ajax_request() === false && $this->config->item('rest_ajax_only')) {
// Display an error response
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ajax_only'),
], self::HTTP_NOT_ACCEPTABLE);
}
// When there is no specific override for the current class/method, use the default auth value set in the config
if ($this->auth_override === false &&
(!($this->config->item('rest_enable_keys') && $this->_allow === true) ||
($this->config->item('allow_auth_and_keys') === true && $this->_allow === true))) {
$rest_auth = strtolower($this->config->item('rest_auth'));
switch ($rest_auth) {
case 'basic':
$this->_prepare_basic_auth();
break;
case 'digest':
$this->_prepare_digest_auth();
break;
case 'session':
$this->_check_php_session();
break;
}
}
}
/**
* Does the auth stuff.
*/
private function do_auth($method = false)
{
// If we don't want to do auth, then just return true
if ($method === false) {
return true;
}
if (file_exists(__DIR__.'/auth/'.$method.'.php')) {
include __DIR__.'/auth/'.$method.'.php';
}
}
/**
* @param $config_file
*/
private function get_local_config($config_file)
{
if (file_exists(APPPATH.'config/'.$config_file.'.php')) {
$this->load->config($config_file, false);
} else {
if (file_exists(__DIR__.'/'.$config_file.'.php')) {
$config = [];
include __DIR__.'/'.$config_file.'.php';
foreach ($config as $key => $value) {
$this->config->set_item($key, $value);
}
}
}
}
/**
* De-constructor.
*
* @author Chris Kacerguis
*
* @return void
*/
public function __destruct()
{
// Log the loading time to the log table
if ($this->config->item('rest_enable_logging') === true) {
// Get the current timestamp
$this->_end_rtime = microtime(true);
$this->_log_access_time();
}
}
/**
* Requests are not made to methods directly, the request will be for
* an "object". This simply maps the object and method to the correct
* Controller method.
*
* @param string $object_called
* @param array $arguments The arguments passed to the controller method
*
* @throws Exception
*/
public function _remap($object_called, $arguments = [])
{
// Should we answer if not over SSL?
if ($this->config->item('force_https') && $this->request->ssl === false) {
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported'),
], self::HTTP_FORBIDDEN);
}
// Remove the supported format from the function name e.g. index.json => index
$object_called = preg_replace('/^(.*)\.(?:'.implode('|', array_keys($this->_supported_formats)).')$/', '$1', $object_called);
$controller_method = $object_called.'_'.$this->request->method;
// Does this method exist? If not, try executing an index method
if (!method_exists($this, $controller_method)) {
$controller_method = 'index_'.$this->request->method;
array_unshift($arguments, $object_called);
}
// Do we want to log this method (if allowed by config)?
$log_method = !(isset($this->methods[$controller_method]['log']) && $this->methods[$controller_method]['log'] === false);
// Use keys for this method?
$use_key = !(isset($this->methods[$controller_method]['key']) && $this->methods[$controller_method]['key'] === false);
// They provided a key, but it wasn't valid, so get them out of here
if ($this->config->item('rest_enable_keys') && $use_key && $this->_allow === false) {
if ($this->config->item('rest_enable_logging') && $log_method) {
$this->_log_request();
}
// fix cross site to option request error
if ($this->request->method == 'options') {
exit;
}
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => sprintf($this->lang->line('text_rest_invalid_api_key'), $this->rest->key),
], self::HTTP_FORBIDDEN);
}
// Check to see if this key has access to the requested controller
if ($this->config->item('rest_enable_keys') && $use_key && empty($this->rest->key) === false && $this->_check_access() === false) {
if ($this->config->item('rest_enable_logging') && $log_method) {
$this->_log_request();
}
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_unauthorized'),
], self::HTTP_UNAUTHORIZED);
}
// Sure it exists, but can they do anything with it?
if (!method_exists($this, $controller_method)) {
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unknown_method'),
], self::HTTP_METHOD_NOT_ALLOWED);
}
// Doing key related stuff? Can only do it if they have a key right?
if ($this->config->item('rest_enable_keys') && empty($this->rest->key) === false) {
// Check the limit
if ($this->config->item('rest_enable_limits') && $this->_check_limit($controller_method) === false) {
$response = [$this->config->item('rest_status_field_name') => false, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_time_limit')];
$this->response($response, self::HTTP_UNAUTHORIZED);
}
// If no level is set use 0, they probably aren't using permissions
$level = isset($this->methods[$controller_method]['level']) ? $this->methods[$controller_method]['level'] : 0;
// If no level is set, or it is lower than/equal to the key's level
$authorized = $level <= $this->rest->level;
// IM TELLIN!
if ($this->config->item('rest_enable_logging') && $log_method) {
$this->_log_request($authorized);
}
if ($authorized === false) {
// They don't have good enough perms
$response = [$this->config->item('rest_status_field_name') => false, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_permissions')];
$this->response($response, self::HTTP_UNAUTHORIZED);
}
}
//check request limit by ip without login
elseif ($this->config->item('rest_limits_method') == 'IP_ADDRESS' && $this->config->item('rest_enable_limits') && $this->_check_limit($controller_method) === false) {
$response = [$this->config->item('rest_status_field_name') => false, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_address_time_limit')];
$this->response($response, self::HTTP_UNAUTHORIZED);
}
// No key stuff, but record that stuff is happening
elseif ($this->config->item('rest_enable_logging') && $log_method) {
$this->_log_request($authorized = true);
}
// Call the controller method and passed arguments
try {
if ($this->is_valid_request) {
call_user_func_array([$this, $controller_method], $arguments);
}
} catch (Exception $ex) {
if ($this->config->item('rest_handle_exceptions') === false) {
throw $ex;
}
// If the method doesn't exist, then the error will be caught and an error response shown
$_error = &load_class('Exceptions', 'core');
$_error->show_exception($ex);
}
}
/**
* Takes mixed data and optionally a status code, then creates the response.
*
* @param array|null $data Data to output to the user
* @param int|null $http_code HTTP status code
* @param bool $continue TRUE to flush the response to the client and continue
* running the script; otherwise, exit
*/
public function response($data = null, $http_code = null, $continue = false)
{
//if profiling enabled then print profiling data
$isProfilingEnabled = $this->config->item('enable_profiling');
if (!$isProfilingEnabled) {
ob_start();
// If the HTTP status is not NULL, then cast as an integer
if ($http_code !== null) {
// So as to be safe later on in the process
$http_code = (int) $http_code;
}
// Set the output as NULL by default
$output = null;
// If data is NULL and no HTTP status code provided, then display, error and exit
if ($data === null && $http_code === null) {
$http_code = self::HTTP_NOT_FOUND;
}
// If data is not NULL and a HTTP status code provided, then continue
elseif ($data !== null) {
// If the format method exists, call and return the output in that format
if (method_exists(Format::class, 'to_'.$this->response->format)) {
// CORB protection
// First, get the output content.
$output = Format::factory($data)->{'to_'.$this->response->format}();
// Set the format header
// Then, check if the client asked for a callback, and if the output contains this callback :
if (isset($this->_get_args['callback']) && $this->response->format == 'json' && preg_match('/^'.$this->_get_args['callback'].'/', $output)) {
$this->output->set_content_type($this->_supported_formats['jsonp'], strtolower($this->config->item('charset')));
} else {
$this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
}
// An array must be parsed as a string, so as not to cause an array to string error
// Json is the most appropriate form for such a data type
if ($this->response->format === 'array') {
$output = Format::factory($output)->{'to_json'}();
}
} else {
// If an array or object, then parse as a json, so as to be a 'string'
if (is_array($data) || is_object($data)) {
$data = Format::factory($data)->{'to_json'}();
}
// Format is not supported, so output the raw data as a string
$output = $data;
}
}
// If not greater than zero, then set the HTTP status code as 200 by default
// Though perhaps 500 should be set instead, for the developer not passing a
// correct HTTP status code
$http_code > 0 || $http_code = self::HTTP_OK;
$this->output->set_status_header($http_code);
// JC: Log response code only if rest logging enabled
if ($this->config->item('rest_enable_logging') === true) {
$this->_log_response_code($http_code);
}
// Output the data
$this->output->set_output($output);
if ($continue === false) {
// Display the data and exit execution
$this->output->_display();
exit;
} else {
if (is_callable('fastcgi_finish_request')) {
// Terminates connection and returns response to client on PHP-FPM.
$this->output->_display();
ob_end_flush();
fastcgi_finish_request();
ignore_user_abort(true);
} else {
// Legacy compatibility.
ob_end_flush();
}
}
ob_end_flush();
// Otherwise dump the output automatically
} else {
echo json_encode($data);
}
}
/**
* Takes mixed data and optionally a status code, then creates the response
* within the buffers of the Output class. The response is sent to the client
* lately by the framework, after the current controller's method termination.
* All the hooks after the controller's method termination are executable.
*
* @param array|null $data Data to output to the user
* @param int|null $http_code HTTP status code
*/
public function set_response($data = null, $http_code = null)
{
$this->response($data, $http_code, true);
}
/**
* Get the input format e.g. json or xml.
*
* @return string|null Supported input format; otherwise, NULL
*/
protected function _detect_input_format()
{
// Get the CONTENT-TYPE value from the SERVER variable
$content_type = $this->input->server('CONTENT_TYPE');
if (empty($content_type) === false) {
// If a semi-colon exists in the string, then explode by ; and get the value of where
// the current array pointer resides. This will generally be the first element of the array
$content_type = (strpos($content_type, ';') !== false ? current(explode(';', $content_type)) : $content_type);
// Check all formats against the CONTENT-TYPE header
foreach ($this->_supported_formats as $type => $mime) {
// $type = format e.g. csv
// $mime = mime type e.g. application/csv
// If both the mime types match, then return the format
if ($content_type === $mime) {
return $type;
}
}
}
}
/**
* Gets the default format from the configuration. Fallbacks to 'json'
* if the corresponding configuration option $config['rest_default_format']
* is missing or is empty.
*
* @return string The default supported input format
*/
protected function _get_default_output_format()
{
$default_format = (string) $this->config->item('rest_default_format');
return $default_format === '' ? 'json' : $default_format;
}
/**
* Detect which format should be used to output the data.
*
* @return mixed|null|string Output format
*/
protected function _detect_output_format()
{
// Concatenate formats to a regex pattern e.g. \.(csv|json|xml)
$pattern = '/\.('.implode('|', array_keys($this->_supported_formats)).')($|\/)/';
$matches = [];
// Check if a file extension is used e.g. http://example.com/api/index.json?param1=param2
if (preg_match($pattern, $this->uri->uri_string(), $matches)) {
return $matches[1];
}
// Get the format parameter named as 'format'
if (isset($this->_get_args['format'])) {
$format = strtolower($this->_get_args['format']);
if (isset($this->_supported_formats[$format]) === true) {
return $format;
}
}
// Get the HTTP_ACCEPT server variable
$http_accept = $this->input->server('HTTP_ACCEPT');
// Otherwise, check the HTTP_ACCEPT server variable
if ($this->config->item('rest_ignore_http_accept') === false && $http_accept !== null) {
// Check all formats against the HTTP_ACCEPT header
foreach (array_keys($this->_supported_formats) as $format) {
// Has this format been requested?
if (strpos($http_accept, $format) !== false) {
if ($format !== 'html' && $format !== 'xml') {
// If not HTML or XML assume it's correct
return $format;
} elseif ($format === 'html' && strpos($http_accept, 'xml') === false) {
// HTML or XML have shown up as a match
// If it is truly HTML, it wont want any XML
return $format;
} elseif ($format === 'xml' && strpos($http_accept, 'html') === false) {
// If it is truly XML, it wont want any HTML
return $format;
}
}
}
}
// Check if the controller has a default format
if (empty($this->rest_format) === false) {
return $this->rest_format;
}
// Obtain the default format from the configuration
return $this->_get_default_output_format();
}
/**
* Get the HTTP request string e.g. get or post.
*
* @return string|null Supported request method as a lowercase string; otherwise, NULL if not supported
*/
protected function _detect_method()
{
// Declare a variable to store the method
$method = null;
// Determine whether the 'enable_emulate_request' setting is enabled
if ($this->config->item('enable_emulate_request') === true) {
$method = $this->input->post('_method');
if ($method === null) {
$method = $this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE');
}
if ($method !== null) {
$method = strtolower($method);
}
}
if (empty($method)) {
// Get the request method as a lowercase string
$method = $this->input->method();
}
return in_array($method, $this->allowed_http_methods) && method_exists($this, '_parse_'.$method) ? $method : 'get';
}
/**
* See if the user has provided an API key.
*
* @return bool
*/
protected function _detect_api_key()
{
// Get the api key name variable set in the rest config file
$api_key_variable = $this->config->item('rest_key_name');
// Work out the name of the SERVER entry based on config
$key_name = 'HTTP_'.strtoupper(str_replace('-', '_', $api_key_variable));
$this->rest->key = null;
$this->rest->level = null;
$this->rest->user_id = null;
$this->rest->ignore_limits = false;
// Find the key from server or arguments
if (($key = isset($this->_args[$api_key_variable]) ? $this->_args[$api_key_variable] : $this->input->server($key_name))) {
if (!($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row())) {
return false;
}
$this->rest->key = $row->{$this->config->item('rest_key_column')};
isset($row->user_id) && $this->rest->user_id = $row->user_id;
isset($row->level) && $this->rest->level = $row->level;
isset($row->ignore_limits) && $this->rest->ignore_limits = $row->ignore_limits;
$this->_apiuser = $row;
/*
* If "is private key" is enabled, compare the ip address with the list
* of valid ip addresses stored in the database
*/
if (empty($row->is_private_key) === false) {
// Check for a list of valid ip addresses
if (isset($row->ip_addresses)) {
// multiple ip addresses must be separated using a comma, explode and loop
$list_ip_addresses = explode(',', $row->ip_addresses);
$ip_address = $this->input->ip_address();
$found_address = false;
foreach ($list_ip_addresses as $list_ip) {
if ($ip_address === trim($list_ip)) {
// there is a match, set the the value to TRUE and break out of the loop
$found_address = true;
break;
}
}
return $found_address;
} else {
// There should be at least one IP address for this private key
return false;
}
}
return true;
}
// No key has been sent
return false;
}
/**
* Preferred return language.
*
* @return string|null|array The language code
*/
protected function _detect_lang()
{
$lang = $this->input->server('HTTP_ACCEPT_LANGUAGE');
if ($lang === null) {
return;
}
// It appears more than one language has been sent using a comma delimiter
if (strpos($lang, ',') !== false) {
$langs = explode(',', $lang);
$return_langs = [];
foreach ($langs as $lang) {
// Remove weight and trim leading and trailing whitespace
list($lang) = explode(';', $lang);
$return_langs[] = trim($lang);
}
return $return_langs;
}
// Otherwise simply return as a string
return $lang;
}
/**
* Add the request to the log table.
*
* @param bool $authorized TRUE the user is authorized; otherwise, FALSE
*
* @return bool TRUE the data was inserted; otherwise, FALSE
*/
protected function _log_request($authorized = false)
{
// Insert the request into the log table
$is_inserted = $this->rest->db
->insert(
$this->config->item('rest_logs_table'),
[
'uri' => $this->uri->uri_string(),
'method' => $this->request->method,
'params' => $this->_args ? ($this->config->item('rest_logs_json_params') === true ? json_encode($this->_args) : serialize($this->_args)) : null,
'api_key' => isset($this->rest->key) ? $this->rest->key : '',
'ip_address' => $this->input->ip_address(),
'time' => time(),
'authorized' => $authorized,
]
);
// Get the last insert id to update at a later stage of the request
$this->_insert_id = $this->rest->db->insert_id();
return $is_inserted;
}
/**
* Check if the requests to a controller method exceed a limit.
*
* @param string $controller_method The method being called
*
* @return bool TRUE the call limit is below the threshold; otherwise, FALSE
*/
protected function _check_limit($controller_method)
{
// They are special, or it might not even have a limit
if (empty($this->rest->ignore_limits) === false) {
// Everything is fine
return true;
}
$api_key = isset($this->rest->key) ? $this->rest->key : '';
switch ($this->config->item('rest_limits_method')) {
case 'IP_ADDRESS':
$api_key = $this->input->ip_address();
$limited_uri = 'ip-address:'.$api_key;
break;
case 'API_KEY':
$limited_uri = 'api-key:'.$api_key;