diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 00000000..5d609ac7
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1 @@
+* @chriskacerguis
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 00000000..34ee3d3c
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,35 @@
+---
+name: Bug report
+about: Create a report to help us improve
+title: ''
+labels: ''
+assignees: ''
+
+---
+
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Please provide either a cleanly formatted code snippet or a link to repo / gist with code that I can use to reproduce:
+
+```php
+ public function set_response($data = null, $http_code = null)
+ {
+ $this->response($data, $http_code, true);
+ }
+```
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**Screenshots / Error Messages**
+If applicable, add screenshots and/or error messages to help explain your problem.
+
+**Environment (please complete the following information):**
+ - PHP Version: [e.g. 7.2.1]
+ - CodeIgniter Version [e.g. 4.0.1]
+ - Version [e.g. 22]
+
+**Additional context**
+Add any other context about the problem here.
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..a761a8b8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+.DS_Store
+vendor
+.idea
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
deleted file mode 100644
index a482d6ee..00000000
--- a/CHANGELOG.md
+++ /dev/null
@@ -1,49 +0,0 @@
-Changelog:
-===========
-
-### 2.7.0
-
-* Added Blacklist IP option
-* Added controller based access controls
-* Added support for OPTIONS, PATCH, and HEAD (from boh1996)
-* Added logging of the time it takes for a request (rtime column in DB)
-* Changed DB schemas to use InnoDB, not MyISAM
-* Updated Readme to reflect new developer (Chris Kacerguis)
-
-### 2.6.2
-
-* Update CodeIgniter files to 2.1.3
-* Fixed issue #165
-
-### 2.6.1
-
-* Update CodeIgniter files to 2.1.2
-* Log Table support for IPv6 & NULL parameters
-* Abstract out the processes of firing a controller method within _remap() to an separate method
-* Moved GET, POST, PUT, and DELETE parsing to separate methods, allowing them to be overridden as needed
-* Small bugfix for a PHP 5.3 strlen error
-* Fixed some PHP 5.4 warnings
-* Fix for bug in Format.php's to_html() which failed to detect if $data was really a multidimensional array.
-* Fix for empty node on XML output format, for false = 0, true = 1.
-
-### 2.6.0
-
-* Added loads of PHPDoc comments.
-* Response where method doesn't exist is now "HTTP 405 Method Not Allowed", not "HTTP 404 Not Found".
-* Compatible with PHP 5.4.
-* Added support for gzip compression.
-* Fix the apache\_request\_header function with CGI.
-* Fixed up correctly .foo extensions to work when get arguments provided.
-* Allows method emulation via X-HTTP-Method-Override
-* Support for Backbone.emulateHTTP improved.
-* Combine both URI segment and GET params instead of using one or the other
-* Separate each piece of the WWW-Authenticate header for digest requests with a comma.
-* Added IP whitelist option.
-
-### 2.5
-
-* Instead of just seeing item, item, item, the singular version of the basenode will be used if possible. [Example](http://d.pr/RS46).
-* Re-factored to use the Format library, which will soon be merged with CodeIgniter.
-* Fixed Limit bug (limit of 5 would allow 6 requests).
-* Added logging for invalid API key requests.
-* Changed serialize to serialized.
diff --git a/LICENSE.txt b/LICENSE
similarity index 94%
rename from LICENSE.txt
rename to LICENSE
index 77a4a2ef..f9121e51 100644
--- a/LICENSE.txt
+++ b/LICENSE
@@ -1,6 +1,6 @@
The MIT License
-Copyright (c) 2012 - 2014 Phil Sturgeon, Chris Kacerguis
+Copyright (c) 2012 - 2015 Phil Sturgeon, Chris Kacerguis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -19,4 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-
diff --git a/README.md b/README.md
index ebadd4aa..59776fe9 100644
--- a/README.md
+++ b/README.md
@@ -1,190 +1,164 @@
-# CodeIgniter Rest Server
+# CodeIgniter RestServer
-A fully RESTful server implementation for CodeIgniter using one library, one
-config file and one controller.
+A fully RESTful server implementation for CodeIgniter 3 using one library, one config file and one controller.
-## Requirements
+> [!IMPORTANT]
+> I have published the first "beta" of codeigniter-restserver 4. See the "development" branch. Please be sure to note the system requirments.
-1. PHP 5.4 or greater
-2. CodeIgniter 3.0+
+## Requirements
-_Note: for 1.7.x support download v2.2 from Downloads tab_
+- PHP 7.2 or greater
+- CodeIgniter 3.1.11+
## Installation
-Drag and drop the **application/libraries/Format.php** and **application/libraries/REST_Controller.php** files into your application's directories. To use `require_once` it at the top of your controllers to load it into the scope. Additionally, copy the **rest.php** file from **application/config** in your application's configuration directory.
-
-## Handling Requests
-
-When your controller extends from `REST_Controller`, the method names will be appended with the HTTP method used to access the request. If you're making an HTTP `GET` call to `/books`, for instance, it would call a `Books#index_get()` method.
-
-This allows you to implement a RESTful interface easily:
-
-```php
-class Books extends REST_Controller
-{
- public function index_get()
- {
- // Display all books
- }
-
- public function index_post()
- {
- // Create a new book
- }
-}
-```
-
-`REST_Controller` also supports `PUT` and `DELETE` methods, allowing you to support a truly RESTful interface.
-
-
-Accessing parameters is also easy. Simply use the name of the HTTP verb as a method:
-
-```php
-$this->get('blah'); // GET param
-$this->post('blah'); // POST param
-$this->put('blah'); // PUT param
+```sh
+composer require chriskacerguis/codeigniter-restserver
```
-The HTTP spec for DELETE requests precludes the use of parameters. For delete requests, you can add items to the URL
-
-```php
-public function index_delete($id)
-{
- $this->response(array(
- 'returned from delete:' => $id,
- ));
-}
-```
+## Usage
-## Content Types
+CodeIgniter Rest Server is available on [Packagist](https://packagist.org/packages/chriskacerguis/codeigniter-restserver) (using semantic versioning), and installation via composer is the recommended way to install Codeigniter Rest Server. Just add this line to your `composer.json` file:
-`REST_Controller` supports a bunch of different request/response formats, including XML, JSON and serialised PHP. By default, the class will check the URL and look for a format either as an extension or as a separate segment.
-
-This means your URLs can look like this:
-```
-http://example.com/books.json
-http://example.com/books?format=json
+```json
+"chriskacerguis/codeigniter-restserver": "^3.1"
```
-This can be flaky with URI segments, so the recommend approach is using the HTTP `Accept` header:
+or run
-```bash
-$ curl -H "Accept: application/json" http://example.com
+```sh
+composer require chriskacerguis/codeigniter-restserver
```
-Any responses you make from the class (see [responses](#responses) for more on this) will be serialised in the designated format.
-
-## Responses
+Note that you will need to copy `rest.php` to your `config` directory (e.g. `application/config`)
-The class provides a `response()` method that allows you to return data in the user's requested response format.
-
-Returning any object / array / string / whatever is easy:
+Step 1: Add this to your controller (should be before any of your code)
```php
-public function index_get()
-{
- $this->response($this->db->get('books')->result());
-}
+use chriskacerguis\RestServer\RestController;
```
-This will automatically return an `HTTP 200 OK` response. You can specify the status code in the second parameter:
+Step 2: Extend your controller
```php
-public function index_post()
- {
- // ...create new book
- $this->response($book, 201); // Send an HTTP 201 Created
- }
+class Example extends RestController
```
-If you don't specify a response code, and the data you respond with `== FALSE` (an empty array or string, for instance), the response code will automatically be set to `404 Not Found`:
+## Basic GET example
-```php
-$this->response(array()); // HTTP 404 Not Found
-```
+Here is a basic example. This controller, which should be saved as `Api.php`, can be called in two ways:
-## Multilingual Support
-
-If your application uses language files to support multiple locales, `REST_Controller` will automatically parse the HTTP `Accept-Language` header and provide the language(s) in your actions. This information can be found in the `$this->response->lang` object:
+* `http://domain/api/users/` will return the list of all users
+* `http://domain/api/users/id/1` will only return information about the user with id = 1
```php
-public function __construct()
-{
- parent::__construct();
-
- if (is_array($this->response->lang))
- {
- $this->load->language('application', $this->response->lang[0]);
- }
- else
- {
- $this->load->language('application', $this->response->lang);
- }
+ 0, 'name' => 'John', 'email' => 'john@example.com'],
+ ['id' => 1, 'name' => 'Jim', 'email' => 'jim@example.com'],
+ ];
+
+ $id = $this->get( 'id' );
+
+ if ( $id === null )
+ {
+ // Check if the users data store contains users
+ if ( $users )
+ {
+ // Set the response and exit
+ $this->response( $users, 200 );
+ }
+ else
+ {
+ // Set the response and exit
+ $this->response( [
+ 'status' => false,
+ 'message' => 'No users were found'
+ ], 404 );
+ }
+ }
+ else
+ {
+ if ( array_key_exists( $id, $users ) )
+ {
+ $this->response( $users[$id], 200 );
+ }
+ else
+ {
+ $this->response( [
+ 'status' => false,
+ 'message' => 'No such user found'
+ ], 404 );
+ }
+ }
+ }
}
```
-## Authentication
+## Extending supported formats
-This class also provides rudimentary support for HTTP basic authentication and/or the securer HTTP digest access authentication.
-
-You can enable basic authentication by setting the `$config['rest_auth']` to `'basic'`. The `$config['rest_valid_logins']` directive can then be used to set the usernames and passwords able to log in to your system. The class will automatically send all the correct headers to trigger the authentication dialogue:
+If you need to be able to support more formats for replies, you can extend the
+`Format` class to add the required `to_...` methods
+1. Extend the `RestController` class (in `libraries/MY_REST_Controller.php`)
```php
-$config['rest_valid_logins'] = array( 'username' => 'password', 'other_person' => 'secure123' );
-```
-
-Enabling digest auth is similarly easy. Configure your desired logins in the config file like above, and set `$config['rest_auth']` to `'digest'`. The class will automatically send out the headers to enable digest auth.
+format = new Format();
+ }
+}
```
-Your localhost IPs (`127.0.0.1` and `0.0.0.0`) are allowed by default.
-
-## API Keys
-
-In addition to the authentication methods above, the `REST_Controller` class also supports the use of API keys. Enabling API keys is easy. Turn it on in your **config/rest.php** file:
+2. Extend the `Format` class (can be created as a CodeIgniter library in `libraries/Format.php`).
+Following is an example to add support for PDF output
```php
-$config['rest_enable_keys'] = TRUE;
-```
-
-You'll need to create a new database table to store and access the keys. `REST_Controller` will automatically assume you have a table that looks like this:
-
-```sql
-CREATE TABLE `keys` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `key` varchar(40) NOT NULL,
- `level` int(2) NOT NULL,
- `ignore_limits` tinyint(1) NOT NULL DEFAULT '0',
- `date_created` int(11) NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-```
-
-The class will look for an HTTP header with the API key on each request. An invalid or missing API key will result in an `HTTP 403 Forbidden`.
+_data;
+ }
+
+ if (is_array($data) || substr($data, 0, 4) != '%PDF') {
+ $html = $this->to_html($data);
+
+ // Use your PDF lib of choice. For example mpdf
+ $mpdf = new \Mpdf\Mpdf();
+ $mpdf->WriteHTML($html);
+ return $mpdf->Output('', 'S');
+ }
+
+ return $data;
+ }
+}
```
-
-## Other Documentation / Tutorials
-
-* [NetTuts: Working with RESTful Services in CodeIgniter](http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/)
-
-## Contributions
-
-This project was originally written by Phil Sturgeon, however his involvment has shifted
-as he is no longer using it. As of 11/20/2013 further developement and support will be done by Chris Kacerguis.
-
-Pull Requests are the best way to fix bugs or add features. I know loads of you use this, so please
-contribute if you have improvements to be made and I'll keep releasing versions over time.
diff --git a/application/config/rest.php b/application/config/rest.php
deleted file mode 100644
index 1e70532c..00000000
--- a/application/config/rest.php
+++ /dev/null
@@ -1,462 +0,0 @@
-function($username, $password)
-| In other cases override the function _perform_library_auth in your controller
-|
-| For digest authentication the library function should return already stored md5(username:restrealm:password) for that username
-| E.g: md5('admin:REST API:1234') = '1e957ebc35631ab22d5bd6526bd14ea2'
-|
-*/
-$config['auth_library_class'] = '';
-$config['auth_library_function'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| Override auth types for specific class/method
-|--------------------------------------------------------------------------
-|
-| Set specific authentication types for methods within a class (controller)
-|
-| Set as many config entries as needed. Any methods not set will use the default 'rest_auth' config value.
-|
-| example:
-|
-| $config['auth_override_class_method']['deals']['view'] = 'none';
-| $config['auth_override_class_method']['deals']['insert'] = 'digest';
-| $config['auth_override_class_method']['accounts']['user'] = 'basic';
-| $config['auth_override_class_method']['dashboard']['*'] = 'none|digest|basic';
-|
-| Here 'deals', 'accounts' and 'dashboard' are controller names, 'view', 'insert' and 'user' are methods within. An asterisk may also be used to specify an authentication method for an entire classes methods. Ex: $config['auth_override_class_method']['dashboard']['*'] = 'basic'; (NOTE: leave off the '_get' or '_post' from the end of the method name)
-| Acceptable values are; 'none', 'digest' and 'basic'.
-|
-*/
-// $config['auth_override_class_method']['deals']['view'] = 'none';
-// $config['auth_override_class_method']['deals']['insert'] = 'digest';
-// $config['auth_override_class_method']['accounts']['user'] = 'basic';
-// $config['auth_override_class_method']['dashboard']['*'] = 'basic';
-
-
-//---Uncomment list line for the wildard unit test
-//$config['auth_override_class_method']['wildcard_test_cases']['*'] = 'basic';
-/*
-|--------------------------------------------------------------------------
-| REST Login usernames
-|--------------------------------------------------------------------------
-|
-| Array of usernames and passwords for login, if ldap is configured this is ignored
-|
-| array('admin' => '1234')
-|
-*/
-$config['rest_valid_logins'] = array('admin' => '1234');
-
-/*
-|--------------------------------------------------------------------------
-| Global IP Whitelisting
-|--------------------------------------------------------------------------
-|
-| Limit connections to your REST server to whitelisted IP addresses.
-|
-| Usage:
-| 1. Set to true *and* select an auth option for extreme security (client's IP
-| address must be in whitelist and they must also log in)
-| 2. Set to true with auth set to false to allow whitelisted IPs access with no login.
-| 3. Set to false here but set 'auth_override_class_method' to 'whitelist' to
-| restrict certain methods to IPs in your whitelist
-|
-*/
-$config['rest_ip_whitelist_enabled'] = false;
-
-/*
-|--------------------------------------------------------------------------
-| REST IP Whitelist
-|--------------------------------------------------------------------------
-|
-| Limit connections to your REST server to a comma separated
-| list of IP addresses
-|
-| Example: $config['rest_ip_whitelist'] = '123.456.789.0, 987.654.32.1';
-|
-| 127.0.0.1 and 0.0.0.0 are allowed by default.
-|
-*/
-$config['rest_ip_whitelist'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| Global IP Blacklisting
-|--------------------------------------------------------------------------
-|
-| Prevent connections to your REST server from blacklisted IP addresses.
-|
-| Usage:
-| 1. Set to true *and* add any IP address to "rest_ip_blacklist" option
-|
-*/
-$config['rest_ip_blacklist_enabled'] = false;
-
-/*
-|--------------------------------------------------------------------------
-| REST IP Blacklist
-|--------------------------------------------------------------------------
-|
-| Block connections from these IP addresses.
-|
-| Example: $config['rest_ip_blacklist'] = '123.456.789.0, 987.654.32.1';
-|
-|
-*/
-$config['rest_ip_blacklist'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| REST Database Group
-|--------------------------------------------------------------------------
-|
-| Connect to a database group for keys, logging, etc. It will only connect
-| if you have any of these features enabled.
-|
-| 'default'
-|
-*/
-$config['rest_database_group'] = 'default';
-
-/*
-|--------------------------------------------------------------------------
-| REST API Keys Table Name
-|--------------------------------------------------------------------------
-|
-| The table name in your database that stores API Keys.
-|
-| 'keys'
-|
-*/
-$config['rest_keys_table'] = 'keys';
-
-/*
-|--------------------------------------------------------------------------
-| REST Enable Keys
-|--------------------------------------------------------------------------
-|
-| When set to true REST_Controller will look for a key and match it to the DB.
-| If no key is provided, the request will return an error.
-|
-| FALSE
-
- CREATE TABLE `keys` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `key` varchar(40) NOT NULL,
- `level` int(2) NOT NULL,
- `ignore_limits` tinyint(1) NOT NULL DEFAULT '0',
- `is_private_key` tinyint(1) NOT NULL DEFAULT '0',
- `ip_addresses` TEXT NULL DEFAULT NULL,
- `date_created` int(11) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-|
-*/
-$config['rest_enable_keys'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST Table Key Column Name
-|--------------------------------------------------------------------------
-|
-| If you are not using the default table schema as shown above, what is the
-| name of the db column that holds the api key value?
-|
-*/
-$config['rest_key_column'] = 'key';
-
-/*
-|--------------------------------------------------------------------------
-| REST Key Length
-|--------------------------------------------------------------------------
-|
-| How long should created keys be? Double check this in your db schema.
-|
-| Default: 32
-| Max: 40
-|
-*/
-$config['rest_key_length'] = 40;
-
-/*
-|--------------------------------------------------------------------------
-| REST API Key Variable
-|--------------------------------------------------------------------------
-|
-| Which variable will provide us the API Key
-|
-| Default: X-API-KEY
-|
-*/
-$config['rest_key_name'] = 'X-API-KEY';
-
-/*
-|--------------------------------------------------------------------------
-| REST API Logs Table Name
-|--------------------------------------------------------------------------
-|
-| The table name in your database that stores logs.
-|
-| 'logs'
-|
-*/
-$config['rest_logs_table'] = 'logs';
-
-/*
-|--------------------------------------------------------------------------
-| REST Enable Logging
-|--------------------------------------------------------------------------
-|
-| When set to true REST_Controller will log actions based on key, date,
-| time and IP address. This is a general rule that can be overridden in the
-| $this->method array in each controller.
-|
-| FALSE
-|
- CREATE TABLE `logs` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `uri` varchar(255) NOT NULL,
- `method` varchar(6) NOT NULL,
- `params` text DEFAULT NULL,
- `api_key` varchar(40) NOT NULL,
- `ip_address` varchar(45) NOT NULL,
- `time` int(11) NOT NULL,
- `rtime` float DEFAULT NULL,
- `authorized` tinyint(1) NOT NULL,
- `response_code` smallint(3) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-|
-*/
-$config['rest_enable_logging'] = FALSE;
-
-
-/*
-|--------------------------------------------------------------------------
-| REST API Access Table Name
-|--------------------------------------------------------------------------
-|
-| The table name in your database that stores the access controls.
-|
-| 'access'
-|
-*/
-$config['rest_access_table'] = 'access';
-
-/*
-|--------------------------------------------------------------------------
-| REST Method Access Control
-|--------------------------------------------------------------------------
-|
-| When set to true REST_Controller will check the access table to see if
-| the API KEY can access that controller. rest_enable_keys *must* be enabled
-| to use this.
-|
-| FALSE
-|
-CREATE TABLE `access` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `key` varchar(40) NOT NULL DEFAULT '',
- `controller` varchar(50) NOT NULL DEFAULT '',
- `date_created` datetime DEFAULT NULL,
- `date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-|
-*/
-$config['rest_enable_access'] = FALSE;
-
-
-/*
-|--------------------------------------------------------------------------
-| REST API Param Log Format
-|--------------------------------------------------------------------------
-|
-| When set to true API log params will be stored in the database as JSON,
-| when false they will be php serialized.
-|
-*/
-$config['rest_logs_json_params'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST API Limits Table Name
-|--------------------------------------------------------------------------
-|
-| The table name in your database that stores limits.
-|
-| 'limits'
-|
-*/
-$config['rest_limits_table'] = 'limits';
-
-/*
-|--------------------------------------------------------------------------
-| REST Enable Limits
-|--------------------------------------------------------------------------
-|
-| When set to true REST_Controller will count the number of uses of each method
-| by an API key each hour. This is a general rule that can be overridden in the
-| $this->method array in each controller.
-|
-| FALSE
-|
- CREATE TABLE `limits` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `uri` varchar(255) NOT NULL,
- `count` int(10) NOT NULL,
- `hour_started` int(11) NOT NULL,
- `api_key` varchar(40) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-|
-| To specify limits, within your Controller __construct() method add per-method
-| limits with:
-
- $this->method['METHOD_NAME']['limit'] = [NUM_REQUESTS_PER_HOUR];
-
-| See application/controllers/api/example.php for examples.
-*/
-$config['rest_enable_limits'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST Ignore HTTP Accept
-|--------------------------------------------------------------------------
-|
-| Set to TRUE to ignore the HTTP Accept and speed up each request a little.
-| Only do this if you are using the $this->rest_format or /format/xml in URLs
-|
-| FALSE
-|
-*/
-$config['rest_ignore_http_accept'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST AJAX Only
-|--------------------------------------------------------------------------
-|
-| Set to TRUE to only allow AJAX requests. If TRUE and the request is not
-| coming from AJAX, a 505 response with the error message "Only AJAX
-| requests are accepted." will be returned. This is good for production
-| environments. Set to FALSE to also accept HTTP requests.
-|
-| FALSE
-|
-*/
-$config['rest_ajax_only'] = FALSE;
-
-/* End of file config.php */
-/* Location: ./system/application/config/rest.php */
diff --git a/application/controllers/api/example.php b/application/controllers/api/example.php
deleted file mode 100644
index c483ca83..00000000
--- a/application/controllers/api/example.php
+++ /dev/null
@@ -1,108 +0,0 @@
-methods['user_get']['limit'] = 500; //500 requests per hour per user/key
- $this->methods['user_post']['limit'] = 100; //100 requests per hour per user/key
- $this->methods['user_delete']['limit'] = 50; //50 requests per hour per user/key
- }
-
- function user_get()
- {
- if(!$this->get('id'))
- {
- $this->response(NULL, 400);
- }
-
- // $user = $this->some_model->getSomething( $this->get('id') );
- $users = array(
- 1 => array('id' => 1, 'name' => 'Some Guy', 'email' => 'example1@example.com', 'fact' => 'Loves swimming'),
- 2 => array('id' => 2, 'name' => 'Person Face', 'email' => 'example2@example.com', 'fact' => 'Has a huge face'),
- 3 => array('id' => 3, 'name' => 'Scotty', 'email' => 'example3@example.com', 'fact' => 'Is a Scott!', array('hobbies' => array('fartings', 'bikes'))),
- );
-
- $user = @$users[$this->get('id')];
-
- if($user)
- {
- $this->response($user, 200); // 200 being the HTTP response code
- }
-
- else
- {
- $this->response(array('error' => 'User could not be found'), 404);
- }
- }
-
- function user_post()
- {
- //$this->some_model->updateUser( $this->get('id') );
- $message = array('id' => $this->get('id'), 'name' => $this->post('name'), 'email' => $this->post('email'), 'message' => 'ADDED!');
-
- $this->response($message, 200); // 200 being the HTTP response code
- }
-
- function user_delete()
- {
- //$this->some_model->deletesomething( $this->get('id') );
- $message = array('id' => $this->get('id'), 'message' => 'DELETED!');
-
- $this->response($message, 200); // 200 being the HTTP response code
- }
-
- function users_get()
- {
- //$users = $this->some_model->getSomething( $this->get('limit') );
- $users = array(
- array('id' => 1, 'name' => 'Some Guy', 'email' => 'example1@example.com'),
- array('id' => 2, 'name' => 'Person Face', 'email' => 'example2@example.com'),
- 3 => array('id' => 3, 'name' => 'Scotty', 'email' => 'example3@example.com', 'fact' => array('hobbies' => array('fartings', 'bikes'))),
- );
-
- if($users)
- {
- $this->response($users, 200); // 200 being the HTTP response code
- }
-
- else
- {
- $this->response(array('error' => 'Couldn\'t find any users!'), 404);
- }
- }
-
-
- public function send_post()
- {
- var_dump($this->request->body);
- }
-
-
- public function send_put()
- {
- var_dump($this->put('foo'));
- }
-}
\ No newline at end of file
diff --git a/application/controllers/api/key.php b/application/controllers/api/key.php
deleted file mode 100644
index 33d8049a..00000000
--- a/application/controllers/api/key.php
+++ /dev/null
@@ -1,251 +0,0 @@
- array('level' => 10, 'limit' => 10),
- 'index_delete' => array('level' => 10),
- 'level_post' => array('level' => 10),
- 'regenerate_post' => array('level' => 10),
- );
-
- /**
- * Key Create
- *
- * Insert a key into the database.
- *
- * @access public
- * @return void
- */
- public function index_put()
- {
- // Build a new key
- $key = self::_generate_key();
-
- // If no key level provided, give them a rubbish one
- $level = $this->put('level') ? $this->put('level') : 1;
- $ignore_limits = $this->put('ignore_limits') ? $this->put('ignore_limits') : 1;
-
- // Insert the new key
- if (self::_insert_key($key, array('level' => $level, 'ignore_limits' => $ignore_limits)))
- {
- $this->response(array('status' => 1, 'key' => $key), 201); // 201 = Created
- }
-
- else
- {
- $this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error
- }
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Key Delete
- *
- * Remove a key from the database to stop it working.
- *
- * @access public
- * @return void
- */
- public function index_delete()
- {
- $key = $this->delete('key');
-
- // Does this key even exist?
- if ( ! self::_key_exists($key))
- {
- // NOOOOOOOOO!
- $this->response(array('status' => 0, 'error' => 'Invalid API Key.'), 400);
- }
-
- // Kill it
- self::_delete_key($key);
-
- // Tell em we killed it
- $this->response(array('status' => 1, 'success' => 'API Key was deleted.'), 200);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Update Key
- *
- * Change the level
- *
- * @access public
- * @return void
- */
- public function level_post()
- {
- $key = $this->post('key');
- $new_level = $this->post('level');
-
- // Does this key even exist?
- if ( ! self::_key_exists($key))
- {
- // NOOOOOOOOO!
- $this->response(array('error' => 'Invalid API Key.'), 400);
- }
-
- // Update the key level
- if (self::_update_key($key, array('level' => $new_level)))
- {
- $this->response(array('status' => 1, 'success' => 'API Key was updated.'), 200); // 200 = OK
- }
-
- else
- {
- $this->response(array('status' => 0, 'error' => 'Could not update the key level.'), 500); // 500 = Internal Server Error
- }
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Update Key
- *
- * Change the level
- *
- * @access public
- * @return void
- */
- public function suspend_post()
- {
- $key = $this->post('key');
-
- // Does this key even exist?
- if ( ! self::_key_exists($key))
- {
- // NOOOOOOOOO!
- $this->response(array('error' => 'Invalid API Key.'), 400);
- }
-
- // Update the key level
- if (self::_update_key($key, array('level' => 0)))
- {
- $this->response(array('status' => 1, 'success' => 'Key was suspended.'), 200); // 200 = OK
- }
-
- else
- {
- $this->response(array('status' => 0, 'error' => 'Could not suspend the user.'), 500); // 500 = Internal Server Error
- }
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Regenerate Key
- *
- * Remove a key from the database to stop it working.
- *
- * @access public
- * @return void
- */
- public function regenerate_post()
- {
- $old_key = $this->post('key');
- $key_details = self::_get_key($old_key);
-
- // The key wasnt found
- if ( ! $key_details)
- {
- // NOOOOOOOOO!
- $this->response(array('status' => 0, 'error' => 'Invalid API Key.'), 400);
- }
-
- // Build a new key
- $new_key = self::_generate_key();
-
- // Insert the new key
- if (self::_insert_key($new_key, array('level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits)))
- {
- // Suspend old key
- self::_update_key($old_key, array('level' => 0));
-
- $this->response(array('status' => 1, 'key' => $new_key), 201); // 201 = Created
- }
-
- else
- {
- $this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error
- }
- }
-
- // --------------------------------------------------------------------
-
- /* Helper Methods */
-
- private function _generate_key()
- {
- //$this->load->helper('security');
-
- do
- {
- $salt = do_hash(time().mt_rand());
- $new_key = substr($salt, 0, config_item('rest_key_length'));
- }
-
- // Already in the DB? Fail. Try again
- while (self::_key_exists($new_key));
-
- return $new_key;
- }
-
- // --------------------------------------------------------------------
-
- /* Private Data Methods */
-
- private function _get_key($key)
- {
- return $this->db->where(config_item('rest_key_column'), $key)->get(config_item('rest_keys_table'))->row();
- }
-
- // --------------------------------------------------------------------
-
- private function _key_exists($key)
- {
- return $this->db->where(config_item('rest_key_column'), $key)->count_all_results(config_item('rest_keys_table')) > 0;
- }
-
- // --------------------------------------------------------------------
-
- private function _insert_key($key, $data)
- {
-
- $data[config_item('rest_key_column')] = $key;
- $data['date_created'] = function_exists('now') ? now() : time();
-
- return $this->db->set($data)->insert(config_item('rest_keys_table'));
- }
-
- // --------------------------------------------------------------------
-
- private function _update_key($key, $data)
- {
- return $this->db->where(config_item('rest_key_column'), $key)->update(config_item('rest_keys_table'), $data);
- }
-
- // --------------------------------------------------------------------
-
- private function _delete_key($key)
- {
- return $this->db->where(config_item('rest_key_column'), $key)->delete(config_item('rest_keys_table'));
- }
-}
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
deleted file mode 100644
index 13df0cf0..00000000
--- a/application/libraries/Format.php
+++ /dev/null
@@ -1,380 +0,0 @@
-format->factory(array('foo' => 'bar'))->to_xml();
- *
- * @access public
- * @param $data, mixed general date to be converted
- * @param $from_type, string data format the file was provided in
- * @return Factory
- */
- public function factory($data, $from_type = NULL)
- {
- // Stupid stuff to emulate the "new static()" stuff in this libraries PHP 5.3 equivalent
- $class = __CLASS__;
- return new $class($data, $from_type);
- }
-
- /**
- * Do not use this directly, call factory()
- *
- * @access public
- * @param $data, bool
- * @param $from_type, bool
- */
- public function __construct($data = NULL, $from_type = NULL)
- {
- get_instance()->load->helper('inflector');
-
- // If the provided data is already formatted we should probably convert it to an array
- if ($from_type !== NULL)
- {
- if (method_exists($this, '_from_' . $from_type))
- {
- $data = call_user_func([$this, '_from_' . $from_type], $data);
- }
-
- else
- {
- throw new Exception('Format class does not support conversion from "' . $from_type . '".');
- }
- }
-
- $this->_data = $data;
- }
-
- // FORMATING OUTPUT ---------------------------------------------------------
-
- /**
- * to_array
- *
- * @access public
- * @param $data
- */
- public function to_array($data = NULL)
- {
- // If not just NULL, but nothing is provided
- if ($data === NULL && ! func_num_args())
- {
- $data = $this->_data;
- }
-
- $array = [];
-
- foreach ((array) $data as $key => $value)
- {
- if (is_object($value) || is_array($value))
- {
- $array[$key] = $this->to_array($value);
- }
-
- else
- {
- $array[$key] = $value;
- }
- }
-
- return $array;
- }
-
- /**
- * Format XML for output
- *
- * @access public
- * @param $data
- * @param $structure
- * @param $basenode
- */
- public function to_xml($data = NULL, $structure = NULL, $basenode = 'xml')
- {
- if ($data === NULL && ! func_num_args())
- {
- $data = $this->_data;
- }
-
- // turn off compatibility mode as simple xml throws a wobbly if you don't.
- if (ini_get('zend.ze1_compatibility_mode') == 1)
- {
- ini_set('zend.ze1_compatibility_mode', 0);
- }
-
- if ($structure === NULL)
- {
- $structure = simplexml_load_string("<$basenode />");
- }
-
- // Force it to be something useful
- if ( ! is_array($data) && ! is_object($data))
- {
- $data = (array) $data;
- }
-
- foreach ($data as $key => $value)
- {
-
- //change false/true to 0/1
- if(is_bool($value))
- {
- $value = (int) $value;
- }
-
- // no numeric keys in our xml please!
- if (is_numeric($key))
- {
- // make string key...
- $key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
- }
-
- // replace anything not alpha numeric
- $key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
-
- if ($key === '_attributes' && (is_array($value) || is_object($value)))
- {
- $attributes = $value;
- if (is_object($attributes)) $attributes = get_object_vars($attributes);
-
- foreach ($attributes as $attributeName => $attributeValue)
- {
- $structure->addAttribute($attributeName, $attributeValue);
- }
- }
- // if there is another array found recursively call this function
- elseif (is_array($value) || is_object($value))
- {
- $node = $structure->addChild($key);
-
- // recursive call.
- $this->to_xml($value, $node, $key);
- }
- else
- {
- // add single node.
- $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8");
-
- $structure->addChild($key, $value);
- }
- }
-
- return $structure->asXML();
- }
-
- /**
- * Format HTML for output
- *
- * @access public
- */
- public function to_html()
- {
- $data = (array)$this->_data;
-
- // Multi-dimensional array
- if (isset($data[0]) && is_array($data[0]))
- {
- $headings = array_keys($data[0]);
- }
-
- // Single array
- else
- {
- $headings = array_keys($data);
- $data = [$data];
- }
-
- $ci = get_instance();
- $ci->load->library('table');
-
- $ci->table->set_heading($headings);
-
- foreach ($data as &$row)
- {
- $ci->table->add_row($row);
- }
-
- return $ci->table->generate();
- }
-
- /**
- * Format CSV for output
- *
- * @access public
- */
- public function to_csv()
- {
- $data = (array)$this->_data;
-
- // Multi-dimensional array
- if (isset($data[0]) && is_array($data[0]))
- {
- $headings = array_keys($data[0]);
- }
-
- // Single array
- else
- {
- $headings = array_keys($data);
- $data = [$data];
- }
-
- $output = '"'.implode('","', $headings).'"'.PHP_EOL;
- foreach ($data as &$row)
- {
- $row = str_replace('"', '""', $row); // Escape dbl quotes per RFC 4180
- $output .= '"'.implode('","', $row).'"'.PHP_EOL;
- }
-
- return $output;
- }
-
- /**
- * Encode as JSON
- *
- * @access public
- */
- public function to_json()
- {
- $callback = isset($_GET['callback']) ? $_GET['callback'] : '';
- if ($callback === '')
- {
- return json_encode($this->_data);
-
- /* Had to take out this code, it doesn't work on Objects.
- $str = $this->_data;
- array_walk_recursive($str, function(&$item, $key)
- {
- if(!mb_detect_encoding($item, 'utf-8', true))
- {
- $item = utf8_encode($item);
- }
- });
-
- return json_encode($str);
- */
- }
-
- // we only honour jsonp callback which are valid javascript identifiers
- elseif (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback))
- {
- // this is a jsonp request, the content-type must be updated to be text/javascript
- header("Content-Type: application/javascript");
- return $callback . "(" . json_encode($this->_data) . ");";
- }
- else
- {
- // we have an invalid jsonp callback identifier, we'll return plain json with a warning field
- $this->_data['warning'] = "invalid jsonp callback provided: ".$callback;
- return json_encode($this->_data);
- }
- }
-
- /**
- * Encode as Serialized array
- *
- * @access public
- */
- public function to_serialized()
- {
- return serialize($this->_data);
- }
-
- /**
- * Output as a string representing the PHP structure
- *
- * @access public
- */
- public function to_php()
- {
- return var_export($this->_data, TRUE);
- }
-
- /**
- * Format XML for output
- *
- * @access protected
- * @param $string
- */
- protected function _from_xml($string)
- {
- return $string ? (array) simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : [];
- }
-
- /**
- * Format CSV for output
- * This function is DODGY! Not perfect CSV support but works with my REST_Controller
- *
- * @access protected
- * @param $string
- */
- protected function _from_csv($string)
- {
- $data = [];
-
- // Splits
- $rows = explode("\n", trim($string));
- $headings = explode(',', array_shift($rows));
- foreach ($rows as $row)
- {
- // The substr removes " from start and end
- $data_fields = explode('","', trim(substr($row, 1, -1)));
-
- if (count($data_fields) == count($headings))
- {
- $data[] = array_combine($headings, $data_fields);
- }
- }
-
- return $data;
- }
-
- /**
- * Encode as JSON
- *
- * @access private
- * @param string
- */
- private function _from_json($string)
- {
- return json_decode(trim($string));
- }
-
- /**
- * Encode as Serialized array
- *
- * @access private
- * @param $string
- *
- */
- private function _from_serialize($string)
- {
- return unserialize(trim($string));
- }
-
-
- /**
- * If you provide text/plain value on the Content-type header on a request
- * just return the string
- *
- * @access private
- * @param $string
- */
- private function _from_php($string)
- {
- return trim($string);
- }
-
-}
-
-/* End of file format.php */
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
deleted file mode 100644
index 9b3e945b..00000000
--- a/application/libraries/REST_Controller.php
+++ /dev/null
@@ -1,1623 +0,0 @@
- 'application/xml',
- 'json' => 'application/json',
- 'jsonp' => 'application/javascript',
- 'serialized' => 'application/vnd.php.serialized',
- 'php' => 'text/plain',
- 'html' => 'text/html',
- 'csv' => 'application/csv'
- ];
-
- /**
- * Information about the current API user
- *
- * @var object
- */
- protected $_apiuser;
-
- /**
- * Developers can extend this class and add a check in here.
- */
- protected function early_checks()
- {
-
- }
-
- /**
- * Constructor function
- * @todo Document more please.
- * @access public
- */
- public function __construct($config = 'rest')
- {
- parent::__construct();
-
- // Start the timer for how long the request takes
- $this->_start_rtime = microtime(TRUE);
-
- // Lets grab the config and get ready to party
- $this->load->config($config);
-
- // This library is bundled with REST_Controller 2.5+, but will eventually be part of CodeIgniter itself
- $this->load->library('format');
-
- // init objects
- $this->response = new stdClass();
- $this->rest = new stdClass();
-
- $this->_zlib_oc = @ini_get('zlib.output_compression');
-
- // let's learn about the request
- $this->request = new stdClass();
-
- // Check to see if this IP is Blacklisted
- if ($this->config->item('rest_ip_blacklist_enabled')) {
- $this->_check_blacklist_auth();
- }
-
- // Is it over SSL?
- $this->request->ssl = $this->_detect_ssl();
-
- // How is this request being made? POST, DELETE, GET, PUT?
- $this->request->method = $this->_detect_method();
-
- // Create argument container, if nonexistent
- if (!isset($this->{'_'.$this->request->method.'_args'})) {
- $this->{'_'.$this->request->method.'_args'} = [];
- }
-
- // Set up our 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();
-
- // Some Methods cant have a body
- $this->request->body = NULL;
-
- $this->{'_parse_' . $this->request->method}();
-
- // 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 = $this->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;
- }
-
- // 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'}
- );
-
- // Which format should the data be returned in?
- $this->response = new stdClass();
- $this->response->format = $this->_detect_output_format();
-
- // Which format should the data be returned in?
- $this->response->lang = $this->_detect_lang();
-
- // Developers can extend this class and add a check in here
- $this->early_checks();
-
- $this->rest = new StdClass();
-
- // Load DB if its enabled
- if (config_item('rest_database_group') && (config_item('rest_enable_keys') || config_item('rest_enable_logging'))) {
- $this->rest->db = $this->load->database(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 (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() && config_item('rest_ajax_only')) {
- $response = [config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'Only AJAX requests are accepted.'];
- $this->response($response, 406); // Set status to 406 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 !== TRUE && !(config_item('rest_enable_keys') && $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;
- }
- if ($this->config->item('rest_ip_whitelist_enabled')) {
- $this->_check_whitelist_auth();
- }
- }
- }
-
- /**
- * Destructor function
- * @author Chris Kacerguis
- *
- * @access public
- */
- public function __destruct()
- {
- // Record the "stop" time of the request
- $this->_end_rtime = microtime(TRUE);
- // CK: if, we are logging, log the access time here, as we are done!
- if (config_item('rest_enable_logging')) {
- $this->_log_access_time();
- }
-
- }
-
- /**
- * Remap
- *
- * 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.
- *
- * @access public
- * @param string $object_called
- * @param array $arguments The arguments passed to the controller method.
- */
- public function _remap($object_called, $arguments)
- {
- // Should we answer if not over SSL?
- if (config_item('force_https') && !$this->_detect_ssl()) {
- $this->response([config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'Unsupported protocol'], 403);
- }
-
- $pattern = '/^(.*)\.('.implode('|', array_keys($this->_supported_formats)).')$/';
- $matches = [];
- if (preg_match($pattern, $object_called, $matches)) {
- $object_called = $matches[1];
- }
-
- $controller_method = $object_called.'_'.$this->request->method;
-
- // 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 (config_item('rest_enable_keys') && $use_key && $this->_allow === FALSE) {
- if (config_item('rest_enable_logging') && $log_method) {
- $this->_log_request();
- }
-
- $this->response([config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'Invalid API Key '.$this->rest->key], 403);
- }
-
- // Check to see if this key has access to the requested controller.
- if (config_item('rest_enable_keys') && $use_key && !empty($this->rest->key) && !$this->_check_access()) {
- if (config_item('rest_enable_logging') && $log_method) {
- $this->_log_request();
- }
-
- $this->response([config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'This API key does not have access to the requested controller.'], 401);
- }
-
- // Sure it exists, but can they do anything with it?
- if ( ! method_exists($this, $controller_method)) {
- $this->response([config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'Unknown method.'], 404);
- }
-
- // Doing key related stuff? Can only do it if they have a key right?
- if (config_item('rest_enable_keys') && !empty($this->rest->key)) {
- // Check the limit
- if (config_item('rest_enable_limits') && !$this->_check_limit($controller_method)) {
- $response = [config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'This API key has reached the hourly limit for this method.'];
- $this->response($response, 401);
- }
-
- // 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 (config_item('rest_enable_logging') && $log_method) {
- $this->_log_request($authorized);
- }
-
- // They don't have good enough perms
- $response = [config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'This API key does not have enough permissions.'];
- $authorized || $this->response($response, 401);
- }
-
- // No key stuff, but record that stuff is happening
- elseif (config_item('rest_enable_logging') && $log_method) {
- $this->_log_request($authorized = TRUE);
- }
-
- // and...... GO!
- $this->_fire_method([$this, $controller_method], $arguments);
- }
-
- /**
- * Fire Method
- *
- * Fires the designated controller method with the given arguments.
- *
- * @access protected
- * @param array $method The controller method to fire
- * @param array $args The arguments to pass to the controller method
- */
- protected function _fire_method($method, $args)
- {
- call_user_func_array($method, $args);
- }
-
- /**
- * Response
- *
- * Takes pure data and optionally a status code, then creates the response.
- * Set $continue to TRUE to flush the response to the client and continue running the script.
- *
- * @access public
- * @param array $data
- * @param NULL|int $http_code
- * @param bool $continue
- */
- public function response($data = NULL, $http_code = NULL, $continue = FALSE)
- {
- // If data is NULL and not code provide, error and bail
- if ($data === NULL && $http_code === NULL) {
- $http_code = 404;
-
- // create the output variable here in the case of $this->response(array());
- $output = NULL;
- }
-
- // If data is NULL but http code provided, keep the output empty
- elseif ($data === NULL && is_numeric($http_code)) {
- $output = NULL;
- }
-
- // Otherwise (if no data but 200 provided) or some data, carry on camping!
- else {
- // Is compression requested?
- if ($this->config->item('compress_output') === TRUE && $this->_zlib_oc == FALSE) {
- if (extension_loaded('zlib')) {
- if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) {
- ob_start('ob_gzhandler');
- }
- }
- }
-
- is_numeric($http_code) || $http_code = 200;
-
- // @deprecated the following statement can be deleted.
- // If the format method exists, call and return the output in that format
- if (method_exists($this, '_format_'.$this->response->format)) {
- // Set the correct format header
- header('Content-Type: '.$this->_supported_formats[$this->response->format] . '; charset=' . strtolower($this->config->item('charset')));
-
- $output = $this->{'_format_'.$this->response->format}($data);
- }
-
- // If the format method exists, call and return the output in that format
- elseif (method_exists($this->format, 'to_'.$this->response->format)) {
- // Set the correct format header
- header('Content-Type: '.$this->_supported_formats[$this->response->format] . '; charset=' . strtolower($this->config->item('charset')));
-
- $output = $this->format->factory($data)->{'to_'.$this->response->format}();
- }
-
- // Format not supported, output directly
- else {
- $output = $data;
- }
- }
-
- set_status_header($http_code);
-
- // JC: Log response code only if rest logging enabled
- if (config_item('rest_enable_logging')) {
- $this->_log_response_code($http_code);
- }
-
- // If zlib.output_compression is enabled it will compress the output,
- // but it will not modify the content-length header to compensate for
- // the reduction, causing the browser to hang waiting for more data.
- // We'll just skip content-length in those cases.
- if ( ! $this->_zlib_oc && ! $this->config->item('compress_output')) {
- header('Content-Length: ' . strlen($output));
- }
-
- if($continue){
- echo($output);
- ob_end_flush();
- ob_flush();
- flush();
- }else{
- exit($output);
- }
- }
-
- /**
- * Detect SSL use
- *
- * Detect whether SSL is being used or not.
- *
- * @access protected
- */
- protected function _detect_ssl()
- {
- // $_SERVER['HTTPS'] (http://php.net/manual/en/reserved.variables.server.php)
- // Set to a non-empty value if the script was queried through the HTTPS protocol
- return (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']));
- }
-
-
- /**
- * Detect input format
- *
- * Detect which format the HTTP Body is provided in
- *
- * @access protected
- */
- protected function _detect_input_format()
- {
- if ($this->input->server('CONTENT_TYPE')) {
- // Check all formats against the HTTP_ACCEPT header
- foreach ($this->_supported_formats as $format => $mime) {
- if (strpos($match = $this->input->server('CONTENT_TYPE'), ';')) {
- $match = current(explode(';', $match));
- }
-
- if ($match == $mime) {
- return $format;
- }
- }
- }
-
- return NULL;
- }
-
- /**
- * Detect format
- *
- * Detect which format should be used to output the data.
- *
- * @access protected
- * @return string The output format.
- */
- protected function _detect_output_format()
- {
- $pattern = '/\.('.implode('|', array_keys($this->_supported_formats)).')$/';
-
- // Check if a file extension is used when no get arguments provided
- $matches = [];
- if (!$this->_get_args && preg_match($pattern, $this->uri->uri_string(), $matches)) {
- return $matches[1];
- }
-
- // Check if a file extension is used
- elseif ($this->_get_args && !is_array(end($this->_get_args)) && preg_match($pattern, end($this->_get_args), $matches)) {
- //elseif ($this->_get_args and !is_array(end($this->_get_args)) and preg_match($pattern, end(array_keys($this->_get_args)), $matches)) {
- // The key of the last argument
- $arg_keys = array_keys($this->_get_args);
- $last_key = end($arg_keys);
-
- // Remove the extension from arguments too
- $this->_get_args[$last_key] = preg_replace($pattern, '', $this->_get_args[$last_key]);
- $this->_args[$last_key] = preg_replace($pattern, '', $this->_args[$last_key]);
-
- return $matches[1];
- }
-
- // A format has been passed as an argument in the URL and it is supported
- if (isset($this->_get_args['format']) && array_key_exists($this->_get_args['format'], $this->_supported_formats)) {
- return $this->_get_args['format'];
- }
-
- // Otherwise, check the HTTP_ACCEPT (if it exists and we are allowed)
- if ($this->config->item('rest_ignore_http_accept') === FALSE && $this->input->server('HTTP_ACCEPT')) {
- // Check all formats against the HTTP_ACCEPT header
- foreach (array_keys($this->_supported_formats) as $format) {
- // Has this format been requested?
- if (strpos($this->input->server('HTTP_ACCEPT'), $format) !== FALSE) {
- // If not HTML or XML assume its right and send it on its way
- if ($format != 'html' && $format != 'xml') {
- return $format;
- }
-
- // HTML or XML have shown up as a match
- else {
- // If it is truly HTML, it wont want any XML
- if ($format == 'html' && strpos($this->input->server('HTTP_ACCEPT'), 'xml') === FALSE) {
- return $format;
- }
-
- // If it is truly XML, it wont want any HTML
- elseif ($format == 'xml' && strpos($this->input->server('HTTP_ACCEPT'), 'html') === FALSE) {
- return $format;
- }
- }
- }
- }
- } // End HTTP_ACCEPT checking
-
- // Well, none of that has worked! Let's see if the controller has a default
- if ( ! empty($this->rest_format)) {
- return $this->rest_format;
- }
-
- // Just use the default format
- return config_item('rest_default_format');
- }
-
- /**
- * Detect method
- *
- * Detect which HTTP method is being used
- *
- * @access protected
- * @return string
- */
- protected function _detect_method()
- {
- $method = strtolower($this->input->server('REQUEST_METHOD'));
-
- if ($this->config->item('enable_emulate_request')) {
- if ($this->input->post('_method')) {
- $method = strtolower($this->input->post('_method'));
- } elseif ($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
- $method = strtolower($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
- }
- }
-
- if (in_array($method, $this->allowed_http_methods) && method_exists($this, '_parse_' . $method)) {
- return $method;
- }
-
- return 'get';
- }
-
- /**
- * Detect API Key
- *
- * See if the user has provided an API key
- *
- * @access protected
- * @return boolean
- */
- protected function _detect_api_key()
- {
- // Get the api key name variable set in the rest config file
- $api_key_variable = 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(config_item('rest_key_column'), $key)->get(config_item('rest_keys_table'))->row())) {
- return FALSE;
- }
-
- $this->rest->key = $row->{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)) {
- // 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);
- $found_address = FALSE;
-
- foreach ($list_ip_addresses as $ip_address) {
- if ($this->input->ip_address() == trim($ip_address)) {
- // 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 $row;
- }
-
- // No key has been sent
- return FALSE;
- }
-
- /**
- * Detect language(s)
- *
- * What language do they want it in?
- *
- * @access protected
- * @return NULL|string The language code.
- */
- protected function _detect_lang()
- {
- if ( ! $lang = $this->input->server('HTTP_ACCEPT_LANGUAGE')) {
- return NULL;
- }
-
- // They might have sent a few, make it an array
- if (strpos($lang, ',') !== FALSE) {
- $langs = explode(',', $lang);
-
- $return_langs = [];
- foreach ($langs as $lang) {
- // Remove weight and strip space
- list($lang) = explode(';', $lang);
- $return_langs[] = trim($lang);
- }
-
- return $return_langs;
- }
-
- // Nope, just return the string
- return $lang;
- }
-
- /**
- * Log request
- *
- * Record the entry for awesomeness purposes
- *
- * @access protected
- * @param boolean $authorized
- * @return object
- */
- protected function _log_request($authorized = FALSE)
- {
- $status = $this->rest->db->insert(config_item('rest_logs_table'), [
- 'uri' => $this->uri->uri_string(),
- 'method' => $this->request->method,
- 'params' => $this->_args ? (config_item('rest_logs_json_params') ? json_encode($this->_args) : serialize($this->_args)) : NULL,
- 'api_key' => isset($this->rest->key) ? $this->rest->key : '',
- 'ip_address' => $this->input->ip_address(),
- 'time' => function_exists('now') ? now() : time(),
- 'authorized' => $authorized
- ]);
-
- $this->_insert_id = $this->rest->db->insert_id();
-
- return $status;
- }
-
- /**
- * Limiting requests
- *
- * Check if the requests are coming in a tad too fast.
- *
- * @access protected
- * @param string $controller_method The method being called.
- * @return boolean
- */
- protected function _check_limit($controller_method)
- {
- // They are special, or it might not even have a limit
- if ( ! empty($this->rest->ignore_limits) || !isset($this->methods[$controller_method]['limit'])) {
- // On your way sonny-jim.
- return TRUE;
- }
-
- // How many times can you get to this method an hour?
- $limit = $this->methods[$controller_method]['limit'];
-
- // Get data on a keys usage
- $result = $this->rest->db
- ->where('uri', $this->uri->uri_string())
- ->where('api_key', $this->rest->key)
- ->get(config_item('rest_limits_table'))
- ->row();
-
- // No calls yet for this key
- if ( ! $result ) {
- // Right, set one up from scratch
- $this->rest->db->insert(config_item('rest_limits_table'), [
- 'uri' => $this->uri->uri_string(),
- 'api_key' => isset($this->rest->key) ? $this->rest->key : '',
- 'count' => 1,
- 'hour_started' => time()
- ]);
- }
-
- // Been an hour since they called
- elseif ($result->hour_started < time() - (60 * 60)) {
- // Reset the started period
- $this->rest->db
- ->where('uri', $this->uri->uri_string())
- ->where('api_key', isset($this->rest->key) ? $this->rest->key : '')
- ->set('hour_started', time())
- ->set('count', 1)
- ->update(config_item('rest_limits_table'));
- }
-
- // They have called within the hour, so lets update
- else {
- // Your luck is out, you've called too many times!
- if ($result->count >= $limit) {
- return FALSE;
- }
-
- $this->rest->db
- ->where('uri', $this->uri->uri_string())
- ->where('api_key', $this->rest->key)
- ->set('count', 'count + 1', FALSE)
- ->update(config_item('rest_limits_table'));
- }
-
- return TRUE;
- }
-
- /**
- * Auth override check
- *
- * Check if there is a specific auth type set for the current class/method
- * being called.
- *
- * @access protected
- * @return boolean
- */
- protected function _auth_override_check()
- {
-
- // Assign the class/method auth type override array from the config
- $this->overrides_array = $this->config->item('auth_override_class_method');
-
- // Check to see if the override array is even populated, otherwise return FALSE
- if (empty($this->overrides_array)) {
- return FALSE;
- }
-
- // check for wildcard flag for rules for classes
- if(!empty($this->overrides_array[$this->router->class]['*'])){//check for class overides
- // None auth override found, prepare nothing but send back a TRUE override flag
- if ($this->overrides_array[$this->router->class]['*'] == 'none')
- {
- return TRUE;
- }
-
- // Basic auth override found, prepare basic
- if ($this->overrides_array[$this->router->class]['*'] == 'basic')
- {
- $this->_prepare_basic_auth();
- return TRUE;
- }
-
- // Digest auth override found, prepare digest
- if ($this->overrides_array[$this->router->class]['*'] == 'digest')
- {
- $this->_prepare_digest_auth();
- return TRUE;
- }
-
- // Whitelist auth override found, check client's ip against config whitelist
- if ($this->overrides_array[$this->router->class]['*'] == 'whitelist')
- {
- $this->_check_whitelist_auth();
- return TRUE;
- }
- }
-
- // Check to see if there's an override value set for the current class/method being called
- if (empty($this->overrides_array[$this->router->class][$this->router->method])) {
- return FALSE;
- }
-
- // None auth override found, prepare nothing but send back a TRUE override flag
- if ($this->overrides_array[$this->router->class][$this->router->method] == 'none') {
- return TRUE;
- }
-
- // Basic auth override found, prepare basic
- if ($this->overrides_array[$this->router->class][$this->router->method] == 'basic') {
- $this->_prepare_basic_auth();
-
- return TRUE;
- }
-
- // Digest auth override found, prepare digest
- if ($this->overrides_array[$this->router->class][$this->router->method] == 'digest') {
- $this->_prepare_digest_auth();
-
- return TRUE;
- }
-
- // Whitelist auth override found, check client's ip against config whitelist
- if ($this->overrides_array[$this->router->class][$this->router->method] == 'whitelist') {
- $this->_check_whitelist_auth();
-
- return TRUE;
- }
-
- // Return FALSE when there is an override value set but it does not match
- // 'basic', 'digest', or 'none'. (the value was misspelled)
- return FALSE;
- }
-
- /**
- * Parse GET
- *
- * @access protected
- */
- protected function _parse_get()
- {
- // Fix for Issue #247
- if (is_cli()) {
- $args = $_SERVER['argv'];
- unset($args[0]);
- $_SERVER['QUERY_STRING'] = $_SERVER['PATH_INFO'] = $_SERVER['REQUEST_URI'] = '/' . implode('/', $args) . '/';
- }
-
- // Grab proper GET variables
- parse_str(parse_url(http://github.com/$_SERVER['REQUEST_URI'],%20PHP_URL_QUERY), $get);
-
- // Merge both the URI segments and GET params
- $this->_get_args = array_merge($this->_get_args, $get);
- }
-
- /**
- * Parse POST
- *
- * @access protected
- */
- protected function _parse_post()
- {
- $this->_post_args = $_POST;
-
- $this->request->format && $this->request->body = file_get_contents('php://input');
- }
-
- /**
- * Parse PUT
- *
- * @access protected
- */
- protected function _parse_put()
- {
- // It might be a HTTP body
- if ($this->request->format) {
- $this->request->body = file_get_contents('php://input');
- }
-
- // If no file type is provided, this is probably just arguments
- else {
- if ($this->input->method() == 'put') {
- $this->_put_args = $this->input->input_stream();
- }
- }
-
- }
-
- /**
- * Parse HEAD
- *
- * @access protected
- */
- protected function _parse_head()
- {
- // Grab proper HEAD variables
- parse_str(parse_url(http://github.com/$_SERVER['REQUEST_URI'],%20PHP_URL_QUERY), $head);
-
- // Merge both the URI segments and HEAD params
- $this->_head_args = array_merge($this->_head_args, $head);
- }
-
- /**
- * Parse OPTIONS
- *
- * @access protected
- */
- protected function _parse_options()
- {
- // Grab proper OPTIONS variables
- parse_str(parse_url(http://github.com/$_SERVER['REQUEST_URI'],%20PHP_URL_QUERY), $options);
-
- // Merge both the URI segments and OPTIONS params
- $this->_options_args = array_merge($this->_options_args, $options);
- }
-
- /**
- * Parse PATCH
- *
- * @access protected
- */
- protected function _parse_patch()
- {
- // It might be a HTTP body
- if ($this->request->format) {
- $this->request->body = file_get_contents('php://input');
- }
-
- // If no file type is provided, this is probably just arguments
- else {
- if ($this->input->method() == 'patch') {
- $this->_patch_args = $this->input->input_stream();
- }
- }
- }
-
- /**
- * Parse DELETE
- *
- * @access protected
- */
- protected function _parse_delete()
- {
- // Set up out DELETE variables (which shouldn't really exist, but sssh!)
- if ($this->input->method() == 'delete') {
- $this->_delete_args = $this->input->input_stream();
- }
- }
-
- // INPUT FUNCTION --------------------------------------------------------------
-
- /**
- * Retrieve a value from the GET request arguments.
- *
- * @access public
- * @param string $key The key for the GET request argument to retrieve
- * @param boolean $xss_clean Whether the value should be XSS cleaned or not.
- * @return string The GET argument value.
- */
- public function get($key = NULL, $xss_clean = TRUE)
- {
- if ($key === NULL) {
- return $this->_get_args;
- }
-
- return array_key_exists($key, $this->_get_args) ? $this->_xss_clean($this->_get_args[$key], $xss_clean) : FALSE;
- }
-
- /**
- * This function retrieves a values from the OPTIONS request arguments
- *
- * @access public
- * @param string $key The OPTIONS/GET argument key
- * @param boolean $xss_clean Whether the value should be XSS cleaned or not
- * @return string The OPTIONS/GET argument value
- */
- public function options($key = NULL, $xss_clean = TRUE)
- {
- if ($key === NULL) {
- return $this->_options_args;
- }
-
- return array_key_exists($key, $this->_options_args) ? $this->_xss_clean($this->_options_args[$key], $xss_clean) : FALSE;
- }
-
- /**
- * This function retrieves a values from the HEAD request arguments
- *
- * @access public
- * @param string $key The HEAD/GET argument key
- * @param boolean $xss_clean Whether the value should be XSS cleaned or not
- * @return string The HEAD/GET argument value
- */
- public function head($key = NULL, $xss_clean = TRUE)
- {
- if ($key === NULL) {
- return $this->head_args;
- }
-
- return array_key_exists($key, $this->head_args) ? $this->_xss_clean($this->head_args[$key], $xss_clean) : FALSE;
- }
-
- /**
- * Retrieve a value from the POST request arguments.
- *
- * @access public
- * @param string $key The key for the POST request argument to retrieve
- * @param boolean $xss_clean Whether the value should be XSS cleaned or not.
- * @return string The POST argument value.
- */
- public function post($key = NULL, $xss_clean = TRUE)
- {
- if ($key === NULL) {
- return $this->_post_args;
- }
-
- return array_key_exists($key, $this->_post_args) ? $this->_xss_clean($this->_post_args[$key], $xss_clean) : FALSE;
- }
-
- /**
- * Retrieve a value from the PUT request arguments.
- *
- * @access public
- * @param string $key The key for the PUT request argument to retrieve
- * @param boolean $xss_clean Whether the value should be XSS cleaned or not.
- * @return string The PUT argument value.
- */
- public function put($key = NULL, $xss_clean = TRUE)
- {
- if ($key === NULL) {
- return $this->_put_args;
- }
-
- return array_key_exists($key, $this->_put_args) ? $this->_xss_clean($this->_put_args[$key], $xss_clean) : FALSE;
- }
-
- /**
- * Retrieve a value from the DELETE request arguments.
- *
- * @access public
- * @param string $key The key for the DELETE request argument to retrieve
- * @param boolean $xss_clean Whether the value should be XSS cleaned or not.
- * @return string The DELETE argument value.
- */
- public function delete($key = NULL, $xss_clean = TRUE)
- {
- if ($key === NULL) {
- return $this->_delete_args;
- }
-
- return array_key_exists($key, $this->_delete_args) ? $this->_xss_clean($this->_delete_args[$key], $xss_clean) : FALSE;
- }
-
- /**
- * Retrieve a value from the PATCH request arguments.
- *
- * @access public
- * @param string $key The key for the PATCH request argument to retrieve
- * @param boolean $xss_clean Whether the value should be XSS cleaned or not.
- * @return string The PATCH argument value.
- */
- public function patch($key = NULL, $xss_clean = TRUE)
- {
- if ($key === NULL) {
- return $this->_patch_args;
- }
-
- return array_key_exists($key, $this->_patch_args) ? $this->_xss_clean($this->_patch_args[$key], $xss_clean) : FALSE;
- }
-
- /**
- * Process to protect from XSS attacks.
- *
- * @access protected
- * @param string $val The input.
- * @param boolean $process Do clean or note the input.
- * @return string
- */
- protected function _xss_clean($val, $process)
- {
- if (CI_VERSION < 2) {
- return $process ? $this->input->xss_clean($val) : $val;
- }
-
- return $process ? $this->security->xss_clean($val) : $val;
- }
-
- /**
- * Retrieve the validation errors.
- *
- * @access public
- * @return array
- */
- public function validation_errors()
- {
- $string = strip_tags($this->form_validation->error_string());
-
- return explode("\n", trim($string, "\n"));
- }
-
- // SECURITY FUNCTIONS ---------------------------------------------------------
-
- /**
- * Perform LDAP Authentication
- *
- * @access protected
- * @param string $username The username to validate
- * @param string $password The password to validate
- * @return boolean
- */
- protected function _perform_ldap_auth($username = '', $password = NULL)
- {
- if (empty($username)) {
- log_message('debug', 'LDAP Auth: failure, empty username');
-
- return FALSE;
- }
-
- log_message('debug', 'LDAP Auth: Loading Config');
-
- $this->config->load('ldap.php', TRUE);
-
- $ldap = [
- 'timeout' => $this->config->item('timeout', 'ldap'),
- 'host' => $this->config->item('server', 'ldap'),
- 'port' => $this->config->item('port', 'ldap'),
- 'rdn' => $this->config->item('binduser', 'ldap'),
- 'pass' => $this->config->item('bindpw', 'ldap'),
- 'basedn' => $this->config->item('basedn', 'ldap'),
- ];
-
- log_message('debug', 'LDAP Auth: Connect to ' . $ldaphost);
-
- $ldapconfig['authrealm'] = $this->config->item('domain', 'ldap');
-
- // connect to ldap server
- $ldapconn = ldap_connect($ldap['host'], $ldap['port']);
-
- if ($ldapconn) {
-
- log_message('debug', 'Setting timeout to ' . $ldap['timeout'] . ' seconds');
-
- ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, $ldap['timeout']);
-
- log_message('debug', 'LDAP Auth: Binding to ' . $ldap['host'] . ' with dn ' . $ldap['rdn']);
-
- // binding to ldap server
- $ldapbind = ldap_bind($ldapconn, $ldap['rdn'], $ldap['pass']);
-
- // verify binding
- if ($ldapbind) {
- log_message('debug', 'LDAP Auth: bind successful');
- } else {
- log_message('error', 'LDAP Auth: bind unsuccessful');
-
- return FALSE;
- }
-
- }
-
- // search for user
- if (($res_id = ldap_search( $ldapconn, $ldap['basedn'], "uid=$username")) == FALSE) {
- log_message('error', 'LDAP Auth: User ' . $username . ' not found in search');
-
- return FALSE;
- }
-
- if (ldap_count_entries($ldapconn, $res_id) != 1) {
- log_message('error', 'LDAP Auth: failure, username ' . $username . 'found more than once');
-
- return FALSE;
- }
-
- if (( $entry_id = ldap_first_entry($ldapconn, $res_id))== FALSE) {
- log_message('error', 'LDAP Auth: failure, entry of searchresult could not be fetched');
-
- return FALSE;
- }
-
- if (( $user_dn = ldap_get_dn($ldapconn, $entry_id)) == FALSE) {
- log_message('error', 'LDAP Auth: failure, user-dn could not be fetched');
-
- return FALSE;
- }
-
- // User found, could not authenticate as user
- if (($link_id = ldap_bind($ldapconn, $user_dn, $password)) == FALSE) {
- log_message('error', 'LDAP Auth: failure, username/password did not match: ' . $user_dn);
-
- return FALSE;
- }
-
- log_message('debug', 'LDAP Auth: Success ' . $user_dn . ' authenticated successfully');
-
- $this->_user_ldap_dn = $user_dn;
- ldap_close($ldapconn);
-
- return TRUE;
- }
-
- /**
- * Perform Library Authentication - Override this function to change the way the library is called
- *
- * @access protected
- * @param string $username The username to validate
- * @param string $password The password to validate
- * @return boolean
- */
- protected function _perform_library_auth($username = '', $password = NULL)
- {
- if (empty($username)) {
- log_message('error', 'Library Auth: failure, empty username');
- return FALSE;
- }
-
- $auth_library_class = strtolower($this->config->item('auth_library_class'));
- $auth_library_function = strtolower($this->config->item('auth_library_function'));
-
- if (empty($auth_library_class)) {
- log_message('debug', 'Library Auth: failure, empty auth_library_class');
- return FALSE;
- }
-
- if (empty($auth_library_function)) {
- log_message('debug', 'Library Auth: failure, empty auth_library_function');
- return FALSE;
- }
-
- if (!is_callable([$auth_library_class, $auth_library_function])) {
- $this->load->library($auth_library_class);
- }
-
- return $this->{$auth_library_class}->$auth_library_function($username, $password);
- }
-
- /**
- * Check if the user is logged in.
- *
- * @access protected
- * @param string $username The user's name
- * @param string $password The user's password
- * @return boolean
- */
- protected function _check_login($username = '', $password = FALSE)
- {
- if (empty($username)) {
- return FALSE;
- }
-
- $auth_source = strtolower($this->config->item('auth_source'));
- $rest_auth = strtolower($this->config->item('rest_auth'));
- $valid_logins = $this->config->item('rest_valid_logins');
-
- if (!$this->config->item('auth_source') && $rest_auth == 'digest') { // for digest we do not have a password passed as argument
- return md5($username.':'.$this->config->item('rest_realm').':'.(isset($valid_logins[$username])?$valid_logins[$username]:''));
- }
-
- if ($password === FALSE) {
- return FALSE;
- }
-
- if ($auth_source == 'ldap') {
- log_message('debug', 'performing LDAP authentication for $username');
-
- return $this->_perform_ldap_auth($username, $password);
- }
-
- if ($auth_source == 'library') {
- log_message('debug', 'performing Library authentication for '.$username);
-
- return $this->_perform_library_auth($username, $password);
- }
-
- if (!array_key_exists($username, $valid_logins)) {
- return FALSE;
- }
-
- if ($valid_logins[$username] != $password) {
- return FALSE;
- }
-
- return TRUE;
- }
-
- /**
- * Check to see if the user is logged into the web app with a php session key.
- *
- * @access protected
- */
- protected function _check_php_session()
- {
- $key = $this->config->item('auth_source');
- if (!$this->session->userdata($key)) {
- $this->response(['status' => FALSE, 'error' => 'Not Authorized'], 401);
- }
- }
-
- /**
- * @todo document this.
- *
- * @access protected
- */
- protected function _prepare_basic_auth()
- {
- // If whitelist is enabled it has the first chance to kick them out
- if (config_item('rest_ip_whitelist_enabled')) {
- $this->_check_whitelist_auth();
- }
-
- $username = NULL;
- $password = NULL;
-
- // mod_php
- if ($this->input->server('PHP_AUTH_USER')) {
- $username = $this->input->server('PHP_AUTH_USER');
- $password = $this->input->server('PHP_AUTH_PW');
- }
-
- // most other servers
- elseif ($this->input->server('HTTP_AUTHENTICATION')) {
- if (strpos(strtolower($this->input->server('HTTP_AUTHENTICATION')), 'basic') === 0) {
- list($username, $password) = explode(':', base64_decode(substr($this->input->server('HTTP_AUTHORIZATION'), 6)));
- }
- }
-
- if ( ! $this->_check_login($username, $password)) {
- $this->_force_login();
- }
- }
-
- /**
- * @todo Document this.
- *
- * @access protected
- */
- protected function _prepare_digest_auth()
- {
- // If whitelist is enabled it has the first chance to kick them out
- if (config_item('rest_ip_whitelist_enabled')) {
- $this->_check_whitelist_auth();
- }
-
- $uniqid = uniqid(""); // Empty argument for backward compatibility
- // We need to test which server authentication variable to use
- // because the PHP ISAPI module in IIS acts different from CGI
- if ($this->input->server('PHP_AUTH_DIGEST')) {
- $digest_string = $this->input->server('PHP_AUTH_DIGEST');
- } elseif ($this->input->server('HTTP_AUTHORIZATION')) {
- $digest_string = $this->input->server('HTTP_AUTHORIZATION');
- } else {
- $digest_string = "";
- }
-
- // The $_SESSION['error_prompted'] variable is used to ask the password
- // again if none given or if the user enters wrong auth information.
- if (empty($digest_string)) {
- $this->_force_login($uniqid);
- }
-
- // We need to retrieve authentication informations from the $auth_data variable
- $matches = [];
- preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches);
- $digest = (empty($matches[1]) || empty($matches[2])) ? [] : array_combine($matches[1], $matches[2]);
-
- // For digest authentication the library function should return already stored md5(username:restrealm:password) for that username @see rest.php::auth_library_function config
- $A1 = $this->_check_login($digest['username'], TRUE);
- if ( ! array_key_exists('username', $digest) || ! $A1 ) {
- $this->_force_login($uniqid);
- }
-
- $A2 = md5(strtoupper($this->request->method).':'.$digest['uri']);
- $valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2);
-
- if ($digest['response'] != $valid_response) {
- $this->response([config_item('rest_status_field_name') => 0, config_item('rest_message_field_name') => 'Invalid credentials'], 401);
- exit;
- }
- }
-
- /**
- * Check if the client's ip is in the 'rest_ip_blacklist' config
- *
- * @access protected
- */
- protected function _check_blacklist_auth()
- {
- $blacklist = explode(',', config_item('rest_ip_blacklist'));
-
- foreach ($blacklist AS &$ip) {
- $ip = trim($ip);
- }
-
- if (in_array($this->input->ip_address(), $blacklist)) {
- $this->response(['status' => FALSE, 'error' => 'IP Denied'], 401);
- }
- }
-
- /**
- * Check if the client's ip is in the 'rest_ip_whitelist' config
- *
- * @access protected
- */
- protected function _check_whitelist_auth()
- {
- $whitelist = explode(',', config_item('rest_ip_whitelist'));
-
- array_push($whitelist, '127.0.0.1', '0.0.0.0');
-
- foreach ($whitelist AS &$ip) {
- $ip = trim($ip);
- }
-
- if ( ! in_array($this->input->ip_address(), $whitelist)) {
- $this->response([config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'IP not authorized'], 401);
- }
- }
-
- /**
- * @todo Document this.
- *
- * @access protected
- * @param string $nonce
- */
- protected function _force_login($nonce = '')
- {
- if (strtolower( $this->config->item('rest_auth') ) == 'basic') {
- header('WWW-Authenticate: Basic realm="'.$this->config->item('rest_realm').'"');
- } elseif (strtolower( $this->config->item('rest_auth') ) == 'digest') {
- header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm').'", qop="auth", nonce="'.$nonce.'", opaque="'.md5($this->config->item('rest_realm')).'"');
- }
-
- $this->response([config_item('rest_status_field_name') => FALSE, config_item('rest_message_field_name') => 'Not authorized'], 401);
- }
-
- /**
- * Force it into an array
- *
- * @access protected
- * @param object|array $data
- * @return array
- */
- protected function _force_loopable($data)
- {
- // Force it to be something useful
- if ( ! is_array($data) && !is_object($data)) {
- $data = (array) $data;
- }
-
- return $data;
- }
-
- /**
- * updates the log with the access time
- *
- * @access protected
- * @author Chris Kacerguis
- * @return boolean
- */
-
- protected function _log_access_time()
- {
- $payload['rtime'] = $this->_end_rtime - $this->_start_rtime;
-
- return $this->rest->db->update(config_item('rest_logs_table'), $payload, ['id' => $this->_insert_id]);
- }
-
- /**
- * updates the log with response code result
- *
- * @author Justin Chen
- * @return boolean
- */
-
- protected function _log_response_code($http_code)
- {
- $payload['response_code'] = $http_code;
- return $this->rest->db->update(config_item('rest_logs_table'), $payload, ['id' => $this->_insert_id]);
- }
-
- /**
- * Check to see if the API key has access to the controller and methods
- *
- * @access protected
- * @return boolean
- */
- protected function _check_access()
- {
- // if we don't want to check acccess, just return TRUE
- if (config_item('rest_enable_access') === FALSE) {
- return TRUE;
- }
-
- // Fetch controller based on path and controller name
- $controller = implode( '/', [$this->router->directory, $this->router->class] );
-
- // Remove any double slashes for safety
- $controller = str_replace('//', '/', $controller);
-
- // Build access table query
- $this->rest->db->select();
- $this->rest->db->where('key', $this->rest->key);
- $this->rest->db->where('controller', $controller);
-
- $query = $this->rest->db->get(config_item('rest_access_table'));
-
- if ($query->num_rows() > 0) {
- return TRUE;
- }
-
- return FALSE;
- }
-
-}
diff --git a/composer.json b/composer.json
new file mode 100644
index 00000000..329d3b46
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,17 @@
+{
+ "name": "chriskacerguis/codeigniter-restserver",
+ "description": "CI Rest Server",
+ "type": "library",
+ "license": "MIT",
+ "authors": [
+ {
+ "name": "Chris Kacerguis",
+ "email": "chriskacerguis@gmail.com"
+ }
+ ],
+ "minimum-stability": "dev",
+ "autoload": {
+ "psr-4": {"chriskacerguis\\RestServer\\": "src/"}
+ },
+ "require": {}
+}
diff --git a/documentation/404.html b/documentation/404.html
deleted file mode 100644
index 762f8381..00000000
--- a/documentation/404.html
+++ /dev/null
@@ -1,109 +0,0 @@
-
-
-
You have probably clicked on a link that is outdated and points to a page that does not exist any more or you have made an typing error in the address.
-
To continue please try to find requested page in the menu, take a look at the tree view of the whole project or use search field on the top.
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.
Takes pure data and optionally a status code, then creates the response.
-Set $continue to TRUE to flush the response to the client and continue running the script.
a",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="
+
+
+
diff --git a/language/turkish/rest_controller_lang.php b/language/turkish/rest_controller_lang.php
new file mode 100644
index 00000000..589b28cc
--- /dev/null
+++ b/language/turkish/rest_controller_lang.php
@@ -0,0 +1,18 @@
+_CI = &get_instance();
+
+ // Load the inflector helper
+ $this->_CI->load->helper('inflector');
+
+ // If the provided data is already formatted we should probably convert it to an array
+ if ($from_type !== null) {
+ if (method_exists($this, '_from_'.$from_type)) {
+ $data = call_user_func([$this, '_from_'.$from_type], $data);
+ } else {
+ throw new Exception('Format class does not support conversion from "'.$from_type.'".');
+ }
+ }
+
+ // Set the member variable to the data passed
+ $this->_data = $data;
+ }
+
+ /**
+ * Create an instance of the format class
+ * e.g: echo $this->format->factory(['foo' => 'bar'])->to_csv();.
+ *
+ * @param mixed $data Data to convert/parse
+ * @param string $from_type Type to convert from e.g. json, csv, html
+ *
+ * @return object Instance of the format class
+ */
+ public static function factory($data, $from_type = null)
+ {
+ // $class = __CLASS__;
+ // return new $class();
+
+ return new static($data, $from_type);
+ }
+
+ // FORMATTING OUTPUT ---------------------------------------------------------
+
+ /**
+ * Format data as an array.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
+ *
+ * @return array Data parsed as an array; otherwise, an empty array
+ */
+ public function to_array($data = null)
+ {
+ // If no data is passed as a parameter, then use the data passed
+ // via the constructor
+ if ($data === null && func_num_args() === 0) {
+ $data = $this->_data;
+ }
+
+ // Cast as an array if not already
+ if (is_array($data) === false) {
+ $data = (array) $data;
+ }
+
+ $array = [];
+ foreach ((array) $data as $key => $value) {
+ if (is_object($value) === true || is_array($value) === true) {
+ $array[$key] = $this->to_array($value);
+ } else {
+ $array[$key] = $value;
+ }
+ }
+
+ return $array;
+ }
+
+ /**
+ * Format data as XML.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
+ * @param null $structure
+ * @param string $basenode
+ *
+ * @return mixed
+ */
+ public function to_xml($data = null, $structure = null, $basenode = 'xml')
+ {
+ if ($data === null && func_num_args() === 0) {
+ $data = $this->_data;
+ }
+
+ if ($structure === null) {
+ $structure = simplexml_load_string("<$basenode />");
+ }
+
+ // Force it to be something useful
+ if (is_array($data) === false && is_object($data) === false) {
+ $data = (array) $data;
+ }
+
+ foreach ($data as $key => $value) {
+ //change false/true to 0/1
+ if (is_bool($value)) {
+ $value = (int) $value;
+ }
+
+ // no numeric keys in our xml please!
+ if (is_numeric($key)) {
+ // make string key...
+ $key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
+ }
+
+ // replace anything not alpha numeric
+ $key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
+
+ if ($key === '_attributes' && (is_array($value) || is_object($value))) {
+ $attributes = $value;
+ if (is_object($attributes)) {
+ $attributes = get_object_vars($attributes);
+ }
+
+ foreach ($attributes as $attribute_name => $attribute_value) {
+ $structure->addAttribute($attribute_name, $attribute_value);
+ }
+ }
+ // if there is another array found recursively call this function
+ elseif (is_array($value) || is_object($value)) {
+ $node = $structure->addChild($key);
+
+ // recursive call.
+ $this->to_xml($value, $node, $key);
+ } else {
+ // add single node.
+ $value = htmlspecialchars(html_entity_decode($value ?? '', ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
+
+ $structure->addChild($key, $value);
+ }
+ }
+
+ return $structure->asXML();
+ }
+
+ /**
+ * Format data as HTML.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
+ *
+ * @return mixed
+ */
+ public function to_html($data = null)
+ {
+ // If no data is passed as a parameter, then use the data passed
+ // via the constructor
+ if ($data === null && func_num_args() === 0) {
+ $data = $this->_data;
+ }
+
+ // Cast as an array if not already
+ if (is_array($data) === false) {
+ $data = (array) $data;
+ }
+
+ // Check if it's a multi-dimensional array
+ if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE)) {
+ // Multi-dimensional array
+ $headings = array_keys($data[0]);
+ } else {
+ // Single array
+ $headings = array_keys($data);
+ $data = [$data];
+ }
+
+ // Load the table library
+ $this->_CI->load->library('table');
+
+ $this->_CI->table->set_heading($headings);
+
+ foreach ($data as $row) {
+ // Suppressing the "array to string conversion" notice
+ // Keep the "evil" @ here
+ $row = @array_map('strval', $row);
+
+ $this->_CI->table->add_row($row);
+ }
+
+ return $this->_CI->table->generate();
+ }
+
+ /**
+ * @link http://www.metashock.de/2014/02/create-csv-file-in-memory-php/
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
+ * @param string $delimiter The optional delimiter parameter sets the field
+ * delimiter (one character only). NULL will use the default value (,)
+ * @param string $enclosure The optional enclosure parameter sets the field
+ * enclosure (one character only). NULL will use the default value (")
+ *
+ * @return string A csv string
+ */
+ public function to_csv($data = null, $delimiter = ',', $enclosure = '"')
+ {
+ // Use a threshold of 1 MB (1024 * 1024)
+ $handle = fopen('php://temp/maxmemory:1048576', 'w');
+ if ($handle === false) {
+ return;
+ }
+
+ // If no data is passed as a parameter, then use the data passed
+ // via the constructor
+ if ($data === null && func_num_args() === 0) {
+ $data = $this->_data;
+ }
+
+ // If NULL, then set as the default delimiter
+ if ($delimiter === null) {
+ $delimiter = ',';
+ }
+
+ // If NULL, then set as the default enclosure
+ if ($enclosure === null) {
+ $enclosure = '"';
+ }
+
+ // Cast as an array if not already
+ if (is_array($data) === false) {
+ $data = (array) $data;
+ }
+
+ // Check if it's a multi-dimensional array
+ if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE)) {
+ // Multi-dimensional array
+ $headings = array_keys($data[0]);
+ } else {
+ // Single array
+ $headings = array_keys($data);
+ $data = [$data];
+ }
+
+ // Apply the headings
+ fputcsv($handle, $headings, $delimiter, $enclosure);
+
+ foreach ($data as $record) {
+ // If the record is not an array, then break. This is because the 2nd param of
+ // fputcsv() should be an array
+ if (is_array($record) === false) {
+ break;
+ }
+
+ // Suppressing the "array to string conversion" notice.
+ // Keep the "evil" @ here.
+ $record = @array_map('strval', $record);
+
+ // Returns the length of the string written or FALSE
+ fputcsv($handle, $record, $delimiter, $enclosure);
+ }
+
+ // Reset the file pointer
+ rewind($handle);
+
+ // Retrieve the csv contents
+ $csv = stream_get_contents($handle);
+
+ // Close the handle
+ fclose($handle);
+
+ // Convert UTF-8 encoding to UTF-16LE which is supported by MS Excel
+ $csv = mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
+
+ return $csv;
+ }
+
+ /**
+ * Encode data as json.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
+ *
+ * @return string Json representation of a value
+ */
+ public function to_json($data = null)
+ {
+ // If no data is passed as a parameter, then use the data passed
+ // via the constructor
+ if ($data === null && func_num_args() === 0) {
+ $data = $this->_data;
+ }
+
+ // Get the callback parameter (if set)
+ $callback = $this->_CI->input->get('callback');
+
+ if (empty($callback) === true) {
+ return json_encode($data, JSON_UNESCAPED_UNICODE);
+ }
+
+ // We only honour a jsonp callback which are valid javascript identifiers
+ elseif (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback)) {
+ // Return the data as encoded json with a callback
+ return $callback.'('.json_encode($data, JSON_UNESCAPED_UNICODE).');';
+ }
+
+ // An invalid jsonp callback function provided.
+ // Though I don't believe this should be hardcoded here
+ $data['warning'] = 'INVALID JSONP CALLBACK: '.$callback;
+
+ return json_encode($data, JSON_UNESCAPED_UNICODE);
+ }
+
+ /**
+ * Encode data as a serialized array.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
+ *
+ * @return string Serialized data
+ */
+ public function to_serialized($data = null)
+ {
+ // If no data is passed as a parameter, then use the data passed
+ // via the constructor
+ if ($data === null && func_num_args() === 0) {
+ $data = $this->_data;
+ }
+
+ return serialize($data);
+ }
+
+ /**
+ * Format data using a PHP structure.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
+ *
+ * @return mixed String representation of a variable
+ */
+ public function to_php($data = null)
+ {
+ // If no data is passed as a parameter, then use the data passed
+ // via the constructor
+ if ($data === null && func_num_args() === 0) {
+ $data = $this->_data;
+ }
+
+ return var_export($data, true);
+ }
+
+ // INTERNAL FUNCTIONS
+
+ /**
+ * @param string $data XML string
+ *
+ * @return array XML element object; otherwise, empty array
+ */
+ protected function _from_xml($data)
+ {
+ return $data ? (array) simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA) : [];
+ }
+
+ /**
+ * @param string $data CSV string
+ * @param string $delimiter The optional delimiter parameter sets the field
+ * delimiter (one character only). NULL will use the default value (,)
+ * @param string $enclosure The optional enclosure parameter sets the field
+ * enclosure (one character only). NULL will use the default value (")
+ *
+ * @return array A multi-dimensional array with the outer array being the number of rows
+ * and the inner arrays the individual fields
+ */
+ protected function _from_csv($data, $delimiter = ',', $enclosure = '"')
+ {
+ // If NULL, then set as the default delimiter
+ if ($delimiter === null) {
+ $delimiter = ',';
+ }
+
+ // If NULL, then set as the default enclosure
+ if ($enclosure === null) {
+ $enclosure = '"';
+ }
+
+ return str_getcsv($data, $delimiter, $enclosure);
+ }
+
+ /**
+ * @param string $data Encoded json string
+ *
+ * @return mixed Decoded json string with leading and trailing whitespace removed
+ */
+ protected function _from_json($data)
+ {
+ return json_decode(trim($data));
+ }
+
+ /**
+ * @param string $data Data to unserialize
+ *
+ * @return mixed Unserialized data
+ */
+ protected function _from_serialize($data)
+ {
+ return unserialize(trim($data));
+ }
+
+ /**
+ * @param string $data Data to trim leading and trailing whitespace
+ *
+ * @return string Data with leading and trailing whitespace removed
+ */
+ protected function _from_php($data)
+ {
+ return trim($data);
+ }
+}
diff --git a/src/RestController.php b/src/RestController.php
new file mode 100644
index 00000000..7f292a98
--- /dev/null
+++ b/src/RestController.php
@@ -0,0 +1,2051 @@
+ '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
+ */
+ protected $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
+ $formatter = null;
+ if ($this->format && method_exists($this->format, 'to_'.$this->response->format)) {
+ $formatter = $this->format::factory($data);
+ } elseif (method_exists(Format::class, 'to_'.$this->response->format)) {
+ $formatter = Format::factory($data);
+ }
+
+ if ($formatter !== null) {
+ // CORB protection
+ // First, get the output content.
+ $output = $formatter->{'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)) {
+ $this->rest->key = $key;
+
+ if (!($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row())) {
+ return false;
+ }
+
+ if ($this->config->item('rest_keys_expire') === true && $row->{$this->config->item('rest_keys_expiry_column')} < time()) {
+ return false;
+ }
+
+ 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;
+ break;
+
+ case 'METHOD_NAME':
+ $limited_uri = 'method-name:'.$controller_method;
+ break;
+
+ case 'ROUTED_URL':
+ default:
+ $limited_uri = $this->uri->ruri_string();
+ if (strpos(strrev($limited_uri), strrev($this->response->format)) === 0) {
+ $limited_uri = substr($limited_uri, 0, -strlen($this->response->format) - 1);
+ }
+ $limited_uri = 'uri:'.$limited_uri.':'.$this->request->method; // It's good to differentiate GET from PUT
+ break;
+ }
+
+ if (isset($this->methods[$controller_method]['limit']) === false) {
+ // Everything is fine
+ return true;
+ }
+
+ // How many times can you get to this method in a defined time_limit (default: 1 hour)?
+ $limit = $this->methods[$controller_method]['limit'];
+
+ $time_limit = (isset($this->methods[$controller_method]['time']) ? $this->methods[$controller_method]['time'] : 3600); // 3600 = 60 * 60
+
+ // Get data about a keys' usage and limit to one row
+ $result = $this->rest->db
+ ->where('uri', $limited_uri)
+ ->where('api_key', $api_key)
+ ->get($this->config->item('rest_limits_table'))
+ ->row();
+
+ // No calls have been made for this key
+ if ($result === null) {
+ // Create a new row for the following key
+ $this->rest->db->insert($this->config->item('rest_limits_table'), [
+ 'uri' => $limited_uri,
+ 'api_key' => $api_key,
+ 'count' => 1,
+ 'hour_started' => time(),
+ ]);
+ }
+
+ // Been a time limit (or by default an hour) since they called
+ elseif ($result->hour_started < (time() - $time_limit)) {
+ // Reset the started period and count
+ $this->rest->db
+ ->where('uri', $limited_uri)
+ ->where('api_key', $api_key)
+ ->set('hour_started', time())
+ ->set('count', 1)
+ ->update($this->config->item('rest_limits_table'));
+ }
+
+ // They have called within the hour, so lets update
+ else {
+ // The limit has been exceeded
+ if ($result->count >= $limit) {
+ return false;
+ }
+
+ // Increase the count by one
+ $this->rest->db
+ ->where('uri', $limited_uri)
+ ->where('api_key', $api_key)
+ ->set('count', 'count + 1', false)
+ ->update($this->config->item('rest_limits_table'));
+ }
+
+ return true;
+ }
+
+ /**
+ * Check if there is a specific auth type set for the current class/method/HTTP-method being called.
+ *
+ * @return bool
+ */
+ protected function _auth_override_check()
+ {
+ // Assign the class/method auth type override array from the config
+ $auth_override_class_method = $this->config->item('auth_override_class_method');
+
+ // Check to see if the override array is even populated
+ if (!empty($auth_override_class_method)) {
+ // Check for wildcard flag for rules for classes
+ if (!empty($auth_override_class_method[$this->router->class]['*'])) { // Check for class overrides
+ // No auth override found, prepare nothing but send back a TRUE override flag
+ if ($auth_override_class_method[$this->router->class]['*'] === 'none') {
+ return true;
+ }
+
+ // Basic auth override found, prepare basic
+ if ($auth_override_class_method[$this->router->class]['*'] === 'basic') {
+ $this->_prepare_basic_auth();
+
+ return true;
+ }
+
+ // Digest auth override found, prepare digest
+ if ($auth_override_class_method[$this->router->class]['*'] === 'digest') {
+ $this->_prepare_digest_auth();
+
+ return true;
+ }
+
+ // Session auth override found, check session
+ if ($auth_override_class_method[$this->router->class]['*'] === 'session') {
+ $this->_check_php_session();
+
+ return true;
+ }
+
+ // Whitelist auth override found, check client's ip against config whitelist
+ if ($auth_override_class_method[$this->router->class]['*'] === 'whitelist') {
+ $this->_check_whitelist_auth();
+
+ return true;
+ }
+ }
+
+ // Check to see if there's an override value set for the current class/method being called
+ if (!empty($auth_override_class_method[$this->router->class][$this->router->method])) {
+ // None auth override found, prepare nothing but send back a TRUE override flag
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'none') {
+ return true;
+ }
+
+ // Basic auth override found, prepare basic
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'basic') {
+ $this->_prepare_basic_auth();
+
+ return true;
+ }
+
+ // Digest auth override found, prepare digest
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'digest') {
+ $this->_prepare_digest_auth();
+
+ return true;
+ }
+
+ // Session auth override found, check session
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'session') {
+ $this->_check_php_session();
+
+ return true;
+ }
+
+ // Whitelist auth override found, check client's ip against config whitelist
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'whitelist') {
+ $this->_check_whitelist_auth();
+
+ return true;
+ }
+ }
+ }
+
+ // Assign the class/method/HTTP-method auth type override array from the config
+ $auth_override_class_method_http = $this->config->item('auth_override_class_method_http');
+
+ // Check to see if the override array is even populated
+ if (!empty($auth_override_class_method_http)) {
+ // check for wildcard flag for rules for classes
+ if (!empty($auth_override_class_method_http[$this->router->class]['*'][$this->request->method])) {
+ // None auth override found, prepare nothing but send back a TRUE override flag
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'none') {
+ return true;
+ }
+
+ // Basic auth override found, prepare basic
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'basic') {
+ $this->_prepare_basic_auth();
+
+ return true;
+ }
+
+ // Digest auth override found, prepare digest
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'digest') {
+ $this->_prepare_digest_auth();
+
+ return true;
+ }
+
+ // Session auth override found, check session
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'session') {
+ $this->_check_php_session();
+
+ return true;
+ }
+
+ // Whitelist auth override found, check client's ip against config whitelist
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'whitelist') {
+ $this->_check_whitelist_auth();
+
+ return true;
+ }
+ }
+
+ // Check to see if there's an override value set for the current class/method/HTTP-method being called
+ if (!empty($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method])) {
+ // None auth override found, prepare nothing but send back a TRUE override flag
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'none') {
+ return true;
+ }
+
+ // Basic auth override found, prepare basic
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'basic') {
+ $this->_prepare_basic_auth();
+
+ return true;
+ }
+
+ // Digest auth override found, prepare digest
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'digest') {
+ $this->_prepare_digest_auth();
+
+ return true;
+ }
+
+ // Session auth override found, check session
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'session') {
+ $this->_check_php_session();
+
+ return true;
+ }
+
+ // Whitelist auth override found, check client's ip against config whitelist
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'whitelist') {
+ $this->_check_whitelist_auth();
+
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Parse the GET request arguments.
+ *
+ * @return void
+ */
+ protected function _parse_get()
+ {
+ // Merge both the URI segments and query parameters
+ $this->_get_args = array_merge($this->_get_args, $this->_query_args);
+ }
+
+ /**
+ * Parse the POST request arguments.
+ *
+ * @return void
+ */
+ protected function _parse_post()
+ {
+ $this->_post_args = $_POST;
+
+ if ($this->request->format) {
+ $this->request->body = $this->input->raw_input_stream;
+ }
+ }
+
+ /**
+ * Parse the PUT request arguments.
+ *
+ * @return void
+ */
+ protected function _parse_put()
+ {
+ if ($this->request->format) {
+ $this->request->body = $this->input->raw_input_stream;
+ if ($this->request->format === 'json') {
+ $this->_put_args = json_decode($this->input->raw_input_stream);
+ }
+ } elseif ($this->input->method() === 'put') {
+ // If no file type is provided, then there are probably just arguments
+ $this->_put_args = $this->input->input_stream();
+ }
+ }
+
+ /**
+ * Parse the HEAD request arguments.
+ *
+ * @return void
+ */
+ protected function _parse_head()
+ {
+ // Parse the HEAD variables
+ parse_str(parse_url(http://github.com/$this-%3Einput-%3Eserver('REQUEST_URI'), PHP_URL_QUERY), $head);
+
+ // Merge both the URI segments and HEAD params
+ $this->_head_args = array_merge($this->_head_args, $head);
+ }
+
+ /**
+ * Parse the OPTIONS request arguments.
+ *
+ * @return void
+ */
+ protected function _parse_options()
+ {
+ // Parse the OPTIONS variables
+ parse_str(parse_url(http://github.com/$this-%3Einput-%3Eserver('REQUEST_URI'), PHP_URL_QUERY), $options);
+
+ // Merge both the URI segments and OPTIONS params
+ $this->_options_args = array_merge($this->_options_args, $options);
+ }
+
+ /**
+ * Parse the PATCH request arguments.
+ *
+ * @return void
+ */
+ protected function _parse_patch()
+ {
+ // It might be a HTTP body
+ if ($this->request->format) {
+ $this->request->body = $this->input->raw_input_stream;
+ } elseif ($this->input->method() === 'patch') {
+ // If no file type is provided, then there are probably just arguments
+ $this->_patch_args = $this->input->input_stream();
+ }
+ }
+
+ /**
+ * Parse the DELETE request arguments.
+ *
+ * @return void
+ */
+ protected function _parse_delete()
+ {
+ // These should exist if a DELETE request
+ if ($this->input->method() === 'delete') {
+ $this->_delete_args = $this->input->input_stream();
+ }
+ }
+
+ /**
+ * Parse the query parameters.
+ *
+ * @return void
+ */
+ protected function _parse_query()
+ {
+ $this->_query_args = $this->input->get();
+ }
+
+ // INPUT FUNCTION --------------------------------------------------------------
+
+ /**
+ * Retrieve a value from a GET request.
+ *
+ * @param null $key Key to retrieve from the GET request
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the GET request; otherwise, NULL
+ */
+ public function get($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ return $this->_get_args;
+ }
+
+ return isset($this->_get_args[$key]) ? $this->_xss_clean($this->_get_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Retrieve a value from a OPTIONS request.
+ *
+ * @param null $key Key to retrieve from the OPTIONS request.
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the OPTIONS request; otherwise, NULL
+ */
+ public function options($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ return $this->_options_args;
+ }
+
+ return isset($this->_options_args[$key]) ? $this->_xss_clean($this->_options_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Retrieve a value from a HEAD request.
+ *
+ * @param null $key Key to retrieve from the HEAD request
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the HEAD request; otherwise, NULL
+ */
+ public function head($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ return $this->_head_args;
+ }
+
+ return isset($this->_head_args[$key]) ? $this->_xss_clean($this->_head_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Retrieve a value from a POST request.
+ *
+ * @param null $key Key to retrieve from the POST request
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the POST request; otherwise, NULL
+ */
+ public function post($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($this->_post_args), RecursiveIteratorIterator::CATCH_GET_CHILD) as $key => $value) {
+ $this->_post_args[$key] = $this->_xss_clean($this->_post_args[$key], $xss_clean);
+ }
+
+ return $this->_post_args;
+ }
+
+ return isset($this->_post_args[$key]) ? $this->_xss_clean($this->_post_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Retrieve a value from a PUT request.
+ *
+ * @param null $key Key to retrieve from the PUT request
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the PUT request; otherwise, NULL
+ */
+ public function put($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ return $this->_put_args;
+ }
+
+ return isset($this->_put_args[$key]) ? $this->_xss_clean($this->_put_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Retrieve a value from a DELETE request.
+ *
+ * @param null $key Key to retrieve from the DELETE request
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the DELETE request; otherwise, NULL
+ */
+ public function delete($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ return $this->_delete_args;
+ }
+
+ return isset($this->_delete_args[$key]) ? $this->_xss_clean($this->_delete_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Retrieve a value from a PATCH request.
+ *
+ * @param null $key Key to retrieve from the PATCH request
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the PATCH request; otherwise, NULL
+ */
+ public function patch($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ return $this->_patch_args;
+ }
+
+ return isset($this->_patch_args[$key]) ? $this->_xss_clean($this->_patch_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Retrieve a value from the query parameters.
+ *
+ * @param null $key Key to retrieve from the query parameters
+ * If NULL an array of arguments is returned
+ * @param null $xss_clean Whether to apply XSS filtering
+ *
+ * @return array|string|null Value from the query parameters; otherwise, NULL
+ */
+ public function query($key = null, $xss_clean = null)
+ {
+ if ($key === null) {
+ return $this->_query_args;
+ }
+
+ return isset($this->_query_args[$key]) ? $this->_xss_clean($this->_query_args[$key], $xss_clean) : null;
+ }
+
+ /**
+ * Sanitizes data so that Cross Site Scripting Hacks can be
+ * prevented.
+ *
+ * @param string $value Input data
+ * @param bool $xss_clean Whether to apply XSS filtering
+ *
+ * @return string
+ */
+ protected function _xss_clean($value, $xss_clean)
+ {
+ is_bool($xss_clean) || $xss_clean = $this->_enable_xss;
+
+ return $xss_clean === true ? $this->security->xss_clean($value) : $value;
+ }
+
+ /**
+ * Retrieve the validation errors.
+ *
+ * @return array
+ */
+ public function validation_errors()
+ {
+ $string = strip_tags($this->form_validation->error_string());
+
+ return explode(PHP_EOL, trim($string, PHP_EOL));
+ }
+
+ // SECURITY FUNCTIONS ---------------------------------------------------------
+
+ /**
+ * Perform LDAP Authentication.
+ *
+ * @param string $username The username to validate
+ * @param string $password The password to validate
+ *
+ * @return bool
+ */
+ protected function _perform_ldap_auth($username = '', $password = null)
+ {
+ if (empty($username)) {
+ log_message('debug', 'LDAP Auth: failure, empty username');
+
+ return false;
+ }
+
+ log_message('debug', 'LDAP Auth: Loading configuration');
+
+ $this->config->load('ldap', true);
+
+ $ldap = [
+ 'timeout' => $this->config->item('timeout', 'ldap'),
+ 'host' => $this->config->item('server', 'ldap'),
+ 'port' => $this->config->item('port', 'ldap'),
+ 'rdn' => $this->config->item('binduser', 'ldap'),
+ 'pass' => $this->config->item('bindpw', 'ldap'),
+ 'basedn' => $this->config->item('basedn', 'ldap'),
+ ];
+
+ log_message('debug', 'LDAP Auth: Connect to '.(isset($ldap['host']) ? $ldap['host'] : '[ldap not configured]'));
+
+ // Connect to the ldap server
+ $ldapconn = ldap_connect($ldap['host'], $ldap['port']);
+ if ($ldapconn) {
+ log_message('debug', 'Setting timeout to '.$ldap['timeout'].' seconds');
+
+ ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, $ldap['timeout']);
+
+ log_message('debug', 'LDAP Auth: Binding to '.$ldap['host'].' with dn '.$ldap['rdn']);
+
+ // Binding to the ldap server
+ $ldapbind = ldap_bind($ldapconn, $ldap['rdn'], $ldap['pass']);
+
+ // Verify the binding
+ if ($ldapbind === false) {
+ log_message('error', 'LDAP Auth: bind was unsuccessful');
+
+ return false;
+ }
+
+ log_message('debug', 'LDAP Auth: bind successful');
+ }
+
+ // Search for user
+ if (($res_id = ldap_search($ldapconn, $ldap['basedn'], "uid=$username")) === false) {
+ log_message('error', 'LDAP Auth: User '.$username.' not found in search');
+
+ return false;
+ }
+
+ if (ldap_count_entries($ldapconn, $res_id) !== 1) {
+ log_message('error', 'LDAP Auth: Failure, username '.$username.'found more than once');
+
+ return false;
+ }
+
+ if (($entry_id = ldap_first_entry($ldapconn, $res_id)) === false) {
+ log_message('error', 'LDAP Auth: Failure, entry of search result could not be fetched');
+
+ return false;
+ }
+
+ if (($user_dn = ldap_get_dn($ldapconn, $entry_id)) === false) {
+ log_message('error', 'LDAP Auth: Failure, user-dn could not be fetched');
+
+ return false;
+ }
+
+ // User found, could not authenticate as user
+ if (($link_id = ldap_bind($ldapconn, $user_dn, $password)) === false) {
+ log_message('error', 'LDAP Auth: Failure, username/password did not match: '.$user_dn);
+
+ return false;
+ }
+
+ log_message('debug', 'LDAP Auth: Success '.$user_dn.' authenticated successfully');
+
+ $this->_user_ldap_dn = $user_dn;
+
+ ldap_close($ldapconn);
+
+ return true;
+ }
+
+ /**
+ * Perform Library Authentication - Override this function to change the way the library is called.
+ *
+ * @param string $username The username to validate
+ * @param string $password The password to validate
+ *
+ * @return bool
+ */
+ protected function _perform_library_auth($username = '', $password = null)
+ {
+ if (empty($username)) {
+ log_message('error', 'Library Auth: Failure, empty username');
+
+ return false;
+ }
+
+ $auth_library_class = strtolower($this->config->item('auth_library_class'));
+ $auth_library_function = strtolower($this->config->item('auth_library_function'));
+
+ if (empty($auth_library_class)) {
+ log_message('debug', 'Library Auth: Failure, empty auth_library_class');
+
+ return false;
+ }
+
+ if (empty($auth_library_function)) {
+ log_message('debug', 'Library Auth: Failure, empty auth_library_function');
+
+ return false;
+ }
+
+ if (is_callable([$auth_library_class, $auth_library_function]) === false) {
+ $this->load->library($auth_library_class);
+ }
+
+ return $this->{$auth_library_class}->$auth_library_function($username, $password);
+ }
+
+ /**
+ * Check if the user is logged in.
+ *
+ * @param string $username The user's name
+ * @param bool|string $password The user's password
+ *
+ * @return bool
+ */
+ protected function _check_login($username = null, $password = false)
+ {
+ if (empty($username)) {
+ return false;
+ }
+
+ $auth_source = strtolower($this->config->item('auth_source'));
+ $rest_auth = strtolower($this->config->item('rest_auth'));
+ $valid_logins = $this->config->item('rest_valid_logins');
+
+ if (!$this->config->item('auth_source') && $rest_auth === 'digest') {
+ // For digest we do not have a password passed as argument
+ return md5($username.':'.$this->config->item('rest_realm').':'.(isset($valid_logins[$username]) ? $valid_logins[$username] : ''));
+ }
+
+ if ($password === false) {
+ return false;
+ }
+
+ if ($auth_source === 'ldap') {
+ log_message('debug', "Performing LDAP authentication for $username");
+
+ return $this->_perform_ldap_auth($username, $password);
+ }
+
+ if ($auth_source === 'library') {
+ log_message('debug', "Performing Library authentication for $username");
+
+ return $this->_perform_library_auth($username, $password);
+ }
+
+ if (array_key_exists($username, $valid_logins) === false) {
+ return false;
+ }
+
+ if ($valid_logins[$username] !== $password) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Check to see if the user is logged in with a PHP session key.
+ *
+ * @return void
+ */
+ protected function _check_php_session()
+ {
+ // If whitelist is enabled it has the first chance to kick them out
+ if ($this->config->item('rest_ip_whitelist_enabled')) {
+ $this->_check_whitelist_auth();
+ }
+
+ // Load library session of CodeIgniter
+ $this->load->library('session');
+
+ // Get the auth_source config item
+ $key = $this->config->item('auth_source');
+
+ // If false, then the user isn't logged in
+ if (!$this->session->userdata($key)) {
+ // 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_unauthorized'),
+ ], self::HTTP_UNAUTHORIZED);
+ }
+ }
+
+ /**
+ * Prepares for basic authentication.
+ *
+ * @return void
+ */
+ protected function _prepare_basic_auth()
+ {
+ // If whitelist is enabled it has the first chance to kick them out
+ if ($this->config->item('rest_ip_whitelist_enabled')) {
+ $this->_check_whitelist_auth();
+ }
+
+ // Returns NULL if the SERVER variables PHP_AUTH_USER and HTTP_AUTHENTICATION don't exist
+ $username = $this->input->server('PHP_AUTH_USER');
+ $http_auth = $this->input->server('HTTP_AUTHENTICATION') ?: $this->input->server('HTTP_AUTHORIZATION');
+
+ $password = null;
+ if ($username !== null) {
+ $password = $this->input->server('PHP_AUTH_PW');
+ } elseif ($http_auth !== null) {
+ // If the authentication header is set as basic, then extract the username and password from
+ // HTTP_AUTHORIZATION e.g. my_username:my_password. This is passed in the .htaccess file
+ if (strpos(strtolower($http_auth), 'basic') === 0) {
+ // Search online for HTTP_AUTHORIZATION workaround to explain what this is doing
+ list($username, $password) = explode(':', base64_decode(substr($this->input->server('HTTP_AUTHORIZATION'), 6)));
+ }
+ }
+
+ // Check if the user is logged into the system
+ if ($this->_check_login($username, $password) === false) {
+ $this->_force_login();
+ }
+ }
+
+ /**
+ * Prepares for digest authentication.
+ *
+ * @return void
+ */
+ protected function _prepare_digest_auth()
+ {
+ // If whitelist is enabled it has the first chance to kick them out
+ if ($this->config->item('rest_ip_whitelist_enabled')) {
+ $this->_check_whitelist_auth();
+ }
+
+ // We need to test which server authentication variable to use,
+ // because the PHP ISAPI module in IIS acts different from CGI
+ $digest_string = $this->input->server('PHP_AUTH_DIGEST');
+ if ($digest_string === null) {
+ $digest_string = $this->input->server('HTTP_AUTHORIZATION');
+ }
+
+ $unique_id = uniqid();
+
+ // The $_SESSION['error_prompted'] variable is used to ask the password
+ // again if none given or if the user enters wrong auth information
+ if (empty($digest_string)) {
+ $this->_force_login($unique_id);
+ }
+
+ // We need to retrieve authentication data from the $digest_string variable
+ $matches = [];
+ preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches);
+ $digest = (empty($matches[1]) || empty($matches[2])) ? [] : array_combine($matches[1], $matches[2]);
+
+ // For digest authentication the library function should return already stored md5(username:restrealm:password) for that username see rest.php::auth_library_function config
+ $username = $this->_check_login($digest['username'], true);
+ if (isset($digest['username']) === false || $username === false) {
+ $this->_force_login($unique_id);
+ }
+
+ $md5 = md5(strtoupper($this->request->method).':'.$digest['uri']);
+ $valid_response = md5($username.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$md5);
+
+ // Check if the string don't compare (case-insensitive)
+ if (strcasecmp($digest['response'], $valid_response) !== 0) {
+ // 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_invalid_credentials'),
+ ], self::HTTP_UNAUTHORIZED);
+ }
+ }
+
+ /**
+ * Checks if the client's ip is in the 'rest_ip_blacklist' config and generates a 401 response.
+ *
+ * @return void
+ */
+ protected function _check_blacklist_auth()
+ {
+ // Match an ip address in a blacklist e.g. 127.0.0.0, 0.0.0.0
+ $pattern = sprintf('/(?:,\s*|^)\Q%s\E(?=,\s*|$)/m', $this->input->ip_address());
+
+ // Returns 1, 0 or FALSE (on error only). Therefore implicitly convert 1 to TRUE
+ if (preg_match($pattern, $this->config->item('rest_ip_blacklist'))) {
+ // 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_ip_denied'),
+ ], self::HTTP_UNAUTHORIZED);
+ }
+ }
+
+ /**
+ * Check if the client's ip is in the 'rest_ip_whitelist' config and generates a 401 response.
+ *
+ * @return void
+ */
+ protected function _check_whitelist_auth()
+ {
+ $whitelist = explode(',', $this->config->item('rest_ip_whitelist'));
+
+ array_push($whitelist, '127.0.0.1', '0.0.0.0');
+
+ foreach ($whitelist as &$ip) {
+ // As $ip is a reference, trim leading and trailing whitespace, then store the new value
+ // using the reference
+ $ip = trim($ip);
+ }
+
+ if (in_array($this->input->ip_address(), $whitelist) === false) {
+ $this->response([
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_unauthorized'),
+ ], self::HTTP_UNAUTHORIZED);
+ }
+ }
+
+ /**
+ * Force logging in by setting the WWW-Authenticate header.
+ *
+ * @param string $nonce A server-specified data string which should be uniquely generated
+ * each time
+ *
+ * @return void
+ */
+ protected function _force_login($nonce = '')
+ {
+ $rest_auth = strtolower($this->config->item('rest_auth'));
+ $rest_realm = $this->config->item('rest_realm');
+ if ($rest_auth === 'basic') {
+ // See http://tools.ietf.org/html/rfc2617#page-5
+ header('WWW-Authenticate: Basic realm="'.$rest_realm.'"');
+ } elseif ($rest_auth === 'digest') {
+ // See http://tools.ietf.org/html/rfc2617#page-18
+ header(
+ 'WWW-Authenticate: Digest realm="'.$rest_realm
+ .'", qop="auth", nonce="'.$nonce
+ .'", opaque="'.md5($rest_realm).'"'
+ );
+ }
+
+ if ($this->config->item('strict_api_and_auth') === true) {
+ $this->is_valid_request = false;
+ }
+
+ // 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_unauthorized'),
+ ], self::HTTP_UNAUTHORIZED);
+ }
+
+ /**
+ * Updates the log table with the total access time.
+ *
+ * @author Chris Kacerguis
+ *
+ * @return bool TRUE log table updated; otherwise, FALSE
+ */
+ protected function _log_access_time()
+ {
+ if ($this->_insert_id == '') {
+ return false;
+ }
+
+ $payload['rtime'] = $this->_end_rtime - $this->_start_rtime;
+
+ return $this->rest->db->update(
+ $this->config->item('rest_logs_table'),
+ $payload,
+ [
+ 'id' => $this->_insert_id,
+ ]
+ );
+ }
+
+ /**
+ * Updates the log table with HTTP response code.
+ *
+ * @author Justin Chen
+ *
+ * @param $http_code int HTTP status code
+ *
+ * @return bool TRUE log table updated; otherwise, FALSE
+ */
+ protected function _log_response_code($http_code)
+ {
+ if ($this->_insert_id == '') {
+ return false;
+ }
+
+ $payload['response_code'] = $http_code;
+
+ return $this->rest->db->update(
+ $this->config->item('rest_logs_table'),
+ $payload,
+ [
+ 'id' => $this->_insert_id,
+ ]
+ );
+ }
+
+ /**
+ * Check to see if the API key has access to the controller and methods.
+ *
+ * @return bool TRUE the API key has access; otherwise, FALSE
+ */
+ protected function _check_access()
+ {
+ // If we don't want to check access, just return TRUE
+ if ($this->config->item('rest_enable_access') === false) {
+ return true;
+ }
+
+ // Fetch controller based on path and controller name
+ $controller = implode(
+ '/',
+ [
+ $this->router->directory,
+ $this->router->class,
+ ]
+ );
+
+ // Remove any double slashes for safety
+ $controller = str_replace('//', '/', $controller);
+
+ //check if the key has all_access
+ $accessRow = $this->rest->db
+ ->where('key', $this->rest->key)
+ ->where('controller', $controller)
+ ->get($this->config->item('rest_access_table'))->row_array();
+
+ if (!empty($accessRow) && !empty($accessRow['all_access'])) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Checks allowed domains, and adds appropriate headers for HTTP access control (CORS).
+ *
+ * @return void
+ */
+ protected function _check_cors()
+ {
+ // Convert the config items into strings
+ $allowed_headers = implode(', ', $this->config->item('allowed_cors_headers'));
+ $allowed_methods = implode(', ', $this->config->item('allowed_cors_methods'));
+
+ // If we want to allow any domain to access the API
+ if ($this->config->item('allow_any_cors_domain') === true) {
+ header('Access-Control-Allow-Origin: *');
+ header('Access-Control-Allow-Headers: '.$allowed_headers);
+ header('Access-Control-Allow-Methods: '.$allowed_methods);
+ } else {
+ // We're going to allow only certain domains access
+ // Store the HTTP Origin header
+ $origin = $this->input->server('HTTP_ORIGIN');
+ if ($origin === null) {
+ $origin = '';
+ }
+
+ // If the origin domain is in the allowed_cors_origins list, then add the Access Control headers
+ if (in_array($origin, $this->config->item('allowed_cors_origins'))) {
+ header('Access-Control-Allow-Origin: '.$origin);
+ header('Access-Control-Allow-Headers: '.$allowed_headers);
+ header('Access-Control-Allow-Methods: '.$allowed_methods);
+ }
+ }
+
+ // If there are headers that should be forced in the CORS check, add them now
+ if (is_array($this->config->item('forced_cors_headers'))) {
+ foreach ($this->config->item('forced_cors_headers') as $header => $value) {
+ header($header.': '.$value);
+ }
+ }
+
+ // If the request HTTP method is 'OPTIONS', kill the response and send it to the client
+ if ($this->input->method() === 'options') {
+ // Load DB if needed for logging
+ if (!isset($this->rest->db) && $this->config->item('rest_enable_logging')) {
+ $this->rest->db = $this->load->database($this->config->item('rest_database_group'), true);
+ }
+ exit;
+ }
+ }
+}
diff --git a/src/auth/apikey.php b/src/auth/apikey.php
new file mode 100644
index 00000000..e69de29b
diff --git a/src/auth/basic.php b/src/auth/basic.php
new file mode 100644
index 00000000..e69de29b
diff --git a/src/auth/ldap.php b/src/auth/ldap.php
new file mode 100644
index 00000000..e69de29b
diff --git a/src/index.html b/src/index.html
new file mode 100755
index 00000000..b702fbc3
--- /dev/null
+++ b/src/index.html
@@ -0,0 +1,11 @@
+
+
+
+ 403 Forbidden
+
+
+
+
Directory access is forbidden.
+
+
+
diff --git a/src/rest.php b/src/rest.php
new file mode 100644
index 00000000..7c8c4c9b
--- /dev/null
+++ b/src/rest.php
@@ -0,0 +1,703 @@
+function($username, $password)
+| In other cases override the function _perform_library_auth in your controller
+|
+| For digest authentication the library function should return already a stored
+| md5(username:restrealm:password) for that username
+|
+| e.g: md5('admin:REST API:1234') = '1e957ebc35631ab22d5bd6526bd14ea2'
+|
+*/
+$config['auth_library_class'] = '';
+$config['auth_library_function'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| Override auth types for specific class/method
+|--------------------------------------------------------------------------
+|
+| Set specific authentication types for methods within a class (controller)
+|
+| Set as many config entries as needed. Any methods not set will use the default 'rest_auth' config value.
+|
+| e.g:
+|
+| $config['auth_override_class_method']['deals']['view'] = 'none';
+| $config['auth_override_class_method']['deals']['insert'] = 'digest';
+| $config['auth_override_class_method']['accounts']['user'] = 'basic';
+| $config['auth_override_class_method']['dashboard']['*'] = 'none|digest|basic';
+|
+| Here 'deals', 'accounts' and 'dashboard' are controller names, 'view', 'insert' and 'user' are methods within. An asterisk may also be used to specify an authentication method for an entire classes methods. Ex: $config['auth_override_class_method']['dashboard']['*'] = 'basic'; (NOTE: leave off the '_get' or '_post' from the end of the method name)
+| Acceptable values are; 'none', 'digest' and 'basic'.
+|
+*/
+// $config['auth_override_class_method']['deals']['view'] = 'none';
+// $config['auth_override_class_method']['deals']['insert'] = 'digest';
+// $config['auth_override_class_method']['accounts']['user'] = 'basic';
+// $config['auth_override_class_method']['dashboard']['*'] = 'basic';
+
+// ---Uncomment list line for the wildard unit test
+// $config['auth_override_class_method']['wildcard_test_cases']['*'] = 'basic';
+
+/*
+|--------------------------------------------------------------------------
+| Override auth types for specific 'class/method/HTTP method'
+|--------------------------------------------------------------------------
+|
+| example:
+|
+| $config['auth_override_class_method_http']['deals']['view']['get'] = 'none';
+| $config['auth_override_class_method_http']['deals']['insert']['post'] = 'none';
+| $config['auth_override_class_method_http']['deals']['*']['options'] = 'none';
+*/
+
+// ---Uncomment list line for the wildard unit test
+// $config['auth_override_class_method_http']['wildcard_test_cases']['*']['options'] = 'basic';
+
+/*
+|--------------------------------------------------------------------------
+| REST Login Usernames
+|--------------------------------------------------------------------------
+|
+| Array of usernames and passwords for login, if ldap is configured this is ignored
+|
+*/
+$config['rest_valid_logins'] = ['admin' => '1234'];
+
+/*
+|--------------------------------------------------------------------------
+| Global IP White-listing
+|--------------------------------------------------------------------------
+|
+| Limit connections to your REST server to White-listed IP addresses
+|
+| Usage:
+| 1. Set to TRUE and select an auth option for extreme security (client's IP
+| address must be in white-list and they must also log in)
+| 2. Set to TRUE with auth set to FALSE to allow White-listed IPs access with no login
+| 3. Set to FALSE but set 'auth_override_class_method' to 'white-list' to
+| restrict certain methods to IPs in your white-list
+|
+*/
+$config['rest_ip_whitelist_enabled'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST Handle Exceptions
+|--------------------------------------------------------------------------
+|
+| Handle exceptions caused by the controller
+|
+*/
+$config['rest_handle_exceptions'] = true;
+
+/*
+|--------------------------------------------------------------------------
+| REST IP White-list
+|--------------------------------------------------------------------------
+|
+| Limit connections to your REST server with a comma separated
+| list of IP addresses
+|
+| e.g: '123.456.789.0, 987.654.32.1'
+|
+| 127.0.0.1 and 0.0.0.0 are allowed by default
+|
+*/
+$config['rest_ip_whitelist'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| Global IP Blacklisting
+|--------------------------------------------------------------------------
+|
+| Prevent connections to the REST server from blacklisted IP addresses
+|
+| Usage:
+| 1. Set to TRUE and add any IP address to 'rest_ip_blacklist'
+|
+*/
+$config['rest_ip_blacklist_enabled'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST IP Blacklist
+|--------------------------------------------------------------------------
+|
+| Prevent connections from the following IP addresses
+|
+| e.g: '123.456.789.0, 987.654.32.1'
+|
+*/
+$config['rest_ip_blacklist'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| REST Database Group
+|--------------------------------------------------------------------------
+|
+| Connect to a database group for keys, logging, etc. It will only connect
+| if you have any of these features enabled
+|
+*/
+$config['rest_database_group'] = 'default';
+
+/*
+|--------------------------------------------------------------------------
+| REST API Keys Table Name
+|--------------------------------------------------------------------------
+|
+| The table name in your database that stores API keys
+|
+*/
+$config['rest_keys_table'] = 'keys';
+
+/*
+|--------------------------------------------------------------------------
+| REST Enable Keys
+|--------------------------------------------------------------------------
+|
+| When set to TRUE, the REST API will look for a column name called 'key'.
+| If no key is provided, the request will result in an error. To override the
+| column name see 'rest_key_column'
+|
+| Default table schema:
+| CREATE TABLE `keys` (
+| `id` INT(11) NOT NULL AUTO_INCREMENT,
+| `user_id` INT(11) NOT NULL,
+| `key` VARCHAR(40) NOT NULL,
+| `level` INT(2) NOT NULL,
+| `ignore_limits` TINYINT(1) NOT NULL DEFAULT '0',
+| `is_private_key` TINYINT(1) NOT NULL DEFAULT '0',
+| `ip_addresses` TEXT NULL DEFAULT NULL,
+| `date_created` INT(11) NOT NULL,
+| `expires` INT(11) NOT NULL
+| PRIMARY KEY (`id`)
+| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+|
+| For PostgreSQL
+| CREATE TABLE keys (
+| id SERIAL,
+| user_id INT NOT NULL,
+| key VARCHAR(40) NOT NULL,
+| level INT NOT NULL,
+| ignore_limits SMALLINT NOT NULL DEFAULT '0',
+| is_private_key SMALLINT NOT NULL DEFAULT '0',
+| ip_addresses TEXT NULL DEFAULT NULL,
+| date_created INT NOT NULL,
+| expires INT NOT NULL,
+| PRIMARY KEY (id)
+| ) ;
+| |
+*/
+$config['rest_enable_keys'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST Table Key Column Name
+|--------------------------------------------------------------------------
+|
+| If not using the default table schema in 'rest_enable_keys', specify the
+| column name to match e.g. my_key
+|
+*/
+$config['rest_key_column'] = 'key';
+/*
+|--------------------------------------------------------------------------
+| REST Table Key Expiry Config and Column Name
+|--------------------------------------------------------------------------
+|
+| Configure wether or not api keys should expire, and the column name to
+| match e.g. expires
+| Note: the value in the column will be treated as a unix timestamp and
+| compared with php function time()
+|
+*/
+$config['rest_keys_expire'] = false;
+$config['rest_keys_expiry_column'] = 'expires';
+
+/*
+|--------------------------------------------------------------------------
+| REST API Limits method
+|--------------------------------------------------------------------------
+|
+| Specify the method used to limit the API calls
+|
+| Available methods are :
+| $config['rest_limits_method'] = 'IP_ADDRESS'; // Put a limit per ip address
+| $config['rest_limits_method'] = 'API_KEY'; // Put a limit per api key
+| $config['rest_limits_method'] = 'METHOD_NAME'; // Put a limit on method calls
+| $config['rest_limits_method'] = 'ROUTED_URL'; // Put a limit on the routed URL
+|
+*/
+$config['rest_limits_method'] = 'ROUTED_URL';
+
+/*
+|--------------------------------------------------------------------------
+| REST Key Length
+|--------------------------------------------------------------------------
+|
+| Length of the created keys. Check your default database schema on the
+| maximum length allowed
+|
+| Note: The maximum length is 40
+|
+*/
+$config['rest_key_length'] = 40;
+
+/*
+|--------------------------------------------------------------------------
+| REST API Key Variable
+|--------------------------------------------------------------------------
+|
+| Custom header to specify the API key
+
+| Note: Custom headers with the X- prefix are deprecated as of
+| 2012/06/12. See RFC 6648 specification for more details
+|
+*/
+$config['rest_key_name'] = 'X-API-KEY';
+
+/*
+|--------------------------------------------------------------------------
+| REST Enable Logging
+|--------------------------------------------------------------------------
+|
+| When set to TRUE, the REST API will log actions based on the column names 'key', 'date',
+| 'time' and 'ip_address'. This is a general rule that can be overridden in the
+| $this->method array for each controller
+|
+| Default table schema:
+| CREATE TABLE `logs` (
+| `id` INT(11) NOT NULL AUTO_INCREMENT,
+| `uri` VARCHAR(255) NOT NULL,
+| `method` VARCHAR(6) NOT NULL,
+| `params` TEXT DEFAULT NULL,
+| `api_key` VARCHAR(40) NOT NULL,
+| `ip_address` VARCHAR(45) NOT NULL,
+| `time` INT(11) NOT NULL,
+| `rtime` FLOAT DEFAULT NULL,
+| `authorized` VARCHAR(1) NOT NULL,
+| `response_code` smallint(3) DEFAULT '0',
+| PRIMARY KEY (`id`)
+| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+|
+| For PostgreSQL
+| CREATE TABLE logs (
+| id SERIAL,
+| uri VARCHAR(255) NOT NULL,
+| method VARCHAR(6) NOT NULL,
+| params TEXT DEFAULT NULL,
+| api_key VARCHAR(40) NOT NULL,
+| ip_address VARCHAR(45) NOT NULL,
+| time INT NOT NULL,
+| rtime DOUBLE PRECISION DEFAULT NULL,
+| authorized boolean NOT NULL,
+| response_code smallint DEFAULT '0',
+| PRIMARY KEY (id)
+| ) ;
+*/
+$config['rest_enable_logging'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST API Logs Table Name
+|--------------------------------------------------------------------------
+|
+| If not using the default table schema in 'rest_enable_logging', specify the
+| table name to match e.g. my_logs
+|
+*/
+$config['rest_logs_table'] = 'logs';
+
+/*
+|--------------------------------------------------------------------------
+| REST Method Access Control
+|--------------------------------------------------------------------------
+| When set to TRUE, the REST API will check the access table to see if
+| the API key can access that controller. 'rest_enable_keys' must be enabled
+| to use this
+|
+| Default table schema:
+| CREATE TABLE `access` (
+| `id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
+| `key` VARCHAR(40) NOT NULL DEFAULT '',
+| `all_access` TINYINT(1) NOT NULL DEFAULT '0',
+| `controller` VARCHAR(50) NOT NULL DEFAULT '',
+| `date_created` DATETIME DEFAULT NULL,
+| `date_modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+| PRIMARY KEY (`id`)
+| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+|
+| For PostgreSQL
+| CREATE TABLE access (
+| id SERIAL,
+| key VARCHAR(40) NOT NULL DEFAULT '',
+| all_access SMALLINT NOT NULL DEFAULT '0',
+| controller VARCHAR(50) NOT NULL DEFAULT '',
+| date_created TIMESTAMP(0) DEFAULT NULL,
+| date_modified TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+| PRIMARY KEY (id)
+| ) ;
+| CREATE OR REPLACE FUNCTION upd_timestamp() RETURNS TRIGGER
+| LANGUAGE plpgsql
+| AS
+| $$
+| BEGIN
+| NEW.modified = CURRENT_TIMESTAMP;
+| RETURN NEW;
+| END;
+| $$;
+| CREATE TRIGGER trigger_access
+| BEFORE UPDATE
+| ON access
+| FOR EACH ROW
+| EXECUTE PROCEDURE upd_timestamp();
+|
+*/
+$config['rest_enable_access'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST API Access Table Name
+|--------------------------------------------------------------------------
+|
+| If not using the default table schema in 'rest_enable_access', specify the
+| table name to match e.g. my_access
+|
+*/
+$config['rest_access_table'] = 'access';
+
+/*
+|--------------------------------------------------------------------------
+| REST API Param Log Format
+|--------------------------------------------------------------------------
+|
+| When set to TRUE, the REST API log parameters will be stored in the database as JSON
+| Set to FALSE to log as serialized PHP
+|
+*/
+$config['rest_logs_json_params'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST Enable Limits
+|--------------------------------------------------------------------------
+|
+| When set to TRUE, the REST API will count the number of uses of each method
+| by an API key each hour. This is a general rule that can be overridden in the
+| $this->method array in each controller
+|
+| Default table schema:
+| CREATE TABLE `limits` (
+| `id` INT(11) NOT NULL AUTO_INCREMENT,
+| `uri` VARCHAR(255) NOT NULL,
+| `count` INT(10) NOT NULL,
+| `hour_started` INT(11) NOT NULL,
+| `api_key` VARCHAR(40) NOT NULL,
+| PRIMARY KEY (`id`)
+| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+|
+| For PostgreSQL
+| CREATE TABLE limits (
+| id SERIAL,
+| uri VARCHAR(255) NOT NULL,
+| count INT NOT NULL,
+| hour_started INT NOT NULL,
+| api_key VARCHAR(40) NOT NULL,
+| PRIMARY KEY (id)
+| ) ;
+|
+| To specify the limits within the controller's __construct() method, add per-method
+| limits with:
+|
+| $this->methods['METHOD_NAME']['limit'] = [NUM_REQUESTS_PER_HOUR];
+|
+| See application/controllers/api/example.php for examples
+*/
+$config['rest_enable_limits'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST API Limits Table Name
+|--------------------------------------------------------------------------
+|
+| If not using the default table schema in 'rest_enable_limits', specify the
+| table name to match e.g. my_limits
+|
+*/
+$config['rest_limits_table'] = 'limits';
+
+/*
+|--------------------------------------------------------------------------
+| REST Ignore HTTP Accept
+|--------------------------------------------------------------------------
+|
+| Set to TRUE to ignore the HTTP Accept and speed up each request a little.
+| Only do this if you are using the $this->rest_format or /format/xml in URLs
+|
+*/
+$config['rest_ignore_http_accept'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST AJAX Only
+|--------------------------------------------------------------------------
+|
+| Set to TRUE to allow AJAX requests only. Set to FALSE to accept HTTP requests
+|
+| Note: If set to TRUE and the request is not AJAX, a 505 response with the
+| error message 'Only AJAX requests are accepted.' will be returned.
+|
+| Hint: This is good for production environments
+|
+*/
+$config['rest_ajax_only'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| REST Language File
+|--------------------------------------------------------------------------
+|
+| Language file to load from the language directory
+|
+*/
+$config['rest_language'] = 'english';
+
+/*
+|--------------------------------------------------------------------------
+| CORS Check
+|--------------------------------------------------------------------------
+|
+| Set to TRUE to enable Cross-Origin Resource Sharing (CORS). Useful if you
+| are hosting your API on a different domain from the application that
+| will access it through a browser
+|
+*/
+$config['check_cors'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| CORS Allowable Headers
+|--------------------------------------------------------------------------
+|
+| If using CORS checks, set the allowable headers here
+|
+*/
+$config['allowed_cors_headers'] = [
+ 'Origin',
+ 'X-Requested-With',
+ 'Content-Type',
+ 'Accept',
+ 'Access-Control-Request-Method',
+];
+
+/*
+|--------------------------------------------------------------------------
+| CORS Allowable Methods
+|--------------------------------------------------------------------------
+|
+| If using CORS checks, you can set the methods you want to be allowed
+|
+*/
+$config['allowed_cors_methods'] = [
+ 'GET',
+ 'POST',
+ 'OPTIONS',
+ 'PUT',
+ 'PATCH',
+ 'DELETE',
+];
+
+/*
+|--------------------------------------------------------------------------
+| CORS Allow Any Domain
+|--------------------------------------------------------------------------
+|
+| Set to TRUE to enable Cross-Origin Resource Sharing (CORS) from any
+| source domain
+|
+*/
+$config['allow_any_cors_domain'] = false;
+
+/*
+|--------------------------------------------------------------------------
+| CORS Allowable Domains
+|--------------------------------------------------------------------------
+|
+| Used if $config['check_cors'] is set to TRUE and $config['allow_any_cors_domain']
+| is set to FALSE. Set all the allowable domains within the array
+|
+| e.g. $config['allowed_origins'] = ['http://www.example.com/', 'https://spa.example.com/']
+|
+*/
+$config['allowed_cors_origins'] = [];
+
+/*
+|--------------------------------------------------------------------------
+| CORS Forced Headers
+|--------------------------------------------------------------------------
+|
+| If using CORS checks, always include the headers and values specified here
+| in the OPTIONS client preflight.
+| Example:
+| $config['forced_cors_headers'] = [
+| 'Access-Control-Allow-Credentials' => 'true'
+| ];
+|
+| Added because of how Sencha Ext JS framework requires the header
+| Access-Control-Allow-Credentials to be set to true to allow the use of
+| credentials in the REST Proxy.
+| See documentation here:
+| http://docs.sencha.com/extjs/6.5.2/classic/Ext.data.proxy.Rest.html#cfg-withCredentials
+|
+*/
+$config['forced_cors_headers'] = [];