From 5b06fd97c29ee8d6a61dc5ebfd6c8429a7cef61b Mon Sep 17 00:00:00 2001
From: Philip Berndroth
Date: Mon, 27 Jun 2016 20:36:14 +0200
Subject: [PATCH 001/129] fix json_encode for integer values
without the parameter JSON_NUMERIC_CHECK the json_encode function is ignoring the integer values from a array or database and then the integer values are serialized into a string.
---
application/libraries/Format.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index 0b6a496d..2132b649 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -403,14 +403,14 @@ public function to_json($data = NULL)
if (empty($callback) === TRUE)
{
- return json_encode($data);
+ return json_encode($data, JSON_NUMERIC_CHECK);
}
// 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).');';
+ return $callback.'('.json_encode($data, JSON_NUMERIC_CHECK).');';
}
// An invalid jsonp callback function provided.
From 74a280a4401a80f3ca4f64595e98995d8aca58d2 Mon Sep 17 00:00:00 2001
From: softwarespot
Date: Sun, 10 Jul 2016 07:30:20 +0300
Subject: [PATCH 002/129] Minor style guide fixes
---
application/libraries/Format.php | 1 -
application/libraries/REST_Controller.php | 30 +++++++++++------------
2 files changed, 14 insertions(+), 17 deletions(-)
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index 2132b649..00129b28 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -521,5 +521,4 @@ protected function _from_php($data)
{
return trim($data);
}
-
}
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 299b9e69..d0b354c0 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -589,7 +589,6 @@ public function __destruct()
/**
* Checks to see if we have everything we need to run this library.
*
- * @author Chris Kacerguis
* @access protected
* @return Exception
*/
@@ -615,8 +614,8 @@ protected function preflight_checks()
* Controller method
*
* @access public
- * @param string $object_called
- * @param array $arguments The arguments passed to the controller method
+ * @param string $object_called
+ * @param array $arguments The arguments passed to the controller method
*/
public function _remap($object_called, $arguments = [])
{
@@ -669,7 +668,7 @@ public function _remap($object_called, $arguments = [])
}
// Sure it exists, but can they do anything with it?
- if (!method_exists($this, $controller_method))
+ if (! method_exists($this, $controller_method))
{
$this->response([
$this->config->item('rest_status_field_name') => FALSE,
@@ -1118,7 +1117,7 @@ protected function _log_request($authorized = FALSE)
* Check if the requests to a controller method exceed a limit
*
* @access protected
- * @param string $controller_method The method being called
+ * @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)
@@ -1694,8 +1693,8 @@ public function query($key = NULL, $xss_clean = NULL)
* prevented
*
* @access protected
- * @param string $value Input data
- * @param bool $xss_clean Whether to apply XSS filtering
+ * @param string $value Input data
+ * @param bool $xss_clean Whether to apply XSS filtering
* @return string
*/
protected function _xss_clean($value, $xss_clean)
@@ -1724,8 +1723,8 @@ public function validation_errors()
* Perform LDAP Authentication
*
* @access protected
- * @param string $username The username to validate
- * @param string $password The password to validate
+ * @param string $username The username to validate
+ * @param string $password The password to validate
* @return bool
*/
protected function _perform_ldap_auth($username = '', $password = NULL)
@@ -1819,8 +1818,8 @@ protected function _perform_ldap_auth($username = '', $password = NULL)
* 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
+ * @param string $username The username to validate
+ * @param string $password The password to validate
* @return bool
*/
protected function _perform_library_auth($username = '', $password = NULL)
@@ -1858,8 +1857,8 @@ protected function _perform_library_auth($username = '', $password = NULL)
* Check if the user is logged in
*
* @access protected
- * @param string $username The user's name
- * @param bool|string $password The user's password
+ * @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)
@@ -2162,12 +2161,12 @@ protected function _check_access()
{
return TRUE;
}
-
+
//check if the key has all_access
$accessRow = $this->rest->db
->where('key', $this->rest->key)
->get($this->config->item('rest_access_table'))->row_array();
-
+
if (!empty($accessRow) && !empty($accessRow['all_access']))
{
return TRUE;
@@ -2235,5 +2234,4 @@ protected function _check_cors()
exit;
}
}
-
}
From 091849652295e44e9a969835d716d983f4b3a45e Mon Sep 17 00:00:00 2001
From: teabrg
Date: Mon, 18 Jul 2016 09:11:36 +0200
Subject: [PATCH 003/129] Check if API KEY submitted is activated
Quickly deactivate API KEY's from accessing your API in case you do not wish to always go to database, change keys, etc
---
application/libraries/REST_Controller.php | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 299b9e69..d6174f8e 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1000,7 +1000,13 @@ protected function _detect_api_key()
// Find the key from server or arguments
if (($key = isset($this->_args[$api_key_variable]) ? $this->_args[$api_key_variable] : $this->input->server($key_name)))
{
- if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row()))
+ //if you have a field to check if the API KEY provided by the user is activated or not
+ //(in case you quickly want to deactivate specific users)
+ // you can also perform an extra check for this
+
+ $existsactive = $this->db->query("SELECT api_key_activated FROM api_keys WHERE api_key = '".$key."' ");
+ $isactive = $existsactive->result();
+ if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row() ) || $isactive[0]->activated == 'no' )
{
return FALSE;
}
From e911a7b5112f815fae14a8f3128a9091ffa57713 Mon Sep 17 00:00:00 2001
From: teabrg
Date: Mon, 18 Jul 2016 09:23:07 +0200
Subject: [PATCH 004/129] Update REST_Controller.php
---
application/libraries/REST_Controller.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index d6174f8e..ed1d283f 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1006,7 +1006,7 @@ protected function _detect_api_key()
$existsactive = $this->db->query("SELECT api_key_activated FROM api_keys WHERE api_key = '".$key."' ");
$isactive = $existsactive->result();
- if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row() ) || $isactive[0]->activated == 'no' )
+ if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row() ) || $isactive[0]->api_key_activated == 'no' )
{
return FALSE;
}
From 3677830638f74e2e42554b9e5d9addd4b69d6848 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 30 Jul 2016 12:51:04 -0500
Subject: [PATCH 005/129] added inital composer file
---
composer.json | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
create mode 100644 composer.json
diff --git a/composer.json b/composer.json
new file mode 100644
index 00000000..a4d014d7
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,16 @@
+{
+ "description": "REST Server for the CodeIgniter framework",
+ "name": "chriskacerguis/codeigniter-restserver",
+ "type": "project",
+ "homepage": "https://github.com/chriskacerguis/codeigniter-restserver",
+ "authors": [
+ {
+ "name": "Chris Kacerguis",
+ "role": "Developer"
+ }
+ ],
+ "license": "MIT",
+ "support": {
+ "source": "https://github.com/chriskacerguis/codeigniter-restserver"
+ }
+}
\ No newline at end of file
From 32c46b6dffc7fb09fc928f4d13732f7a93abba80 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 30 Jul 2016 15:35:27 -0500
Subject: [PATCH 006/129] added .gitignore
---
.gitignore | 1 +
1 file changed, 1 insertion(+)
create mode 100644 .gitignore
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..496ee2ca
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.DS_Store
\ No newline at end of file
From 60242fd1e877c2e98f2ca9ed2c1fe850f1cb1c51 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 30 Jul 2016 15:38:49 -0500
Subject: [PATCH 007/129] added important note about 4.0.0
---
README.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/README.md b/README.md
index 59214003..b33b448a 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,12 @@ config file and one controller.
_Note: for 1.7.x support download v2.2 from Downloads tab_
+## Important Update on 4.0.0
+
+Please note that version 4.0.0 is in the works, and is considered a breaking change (per SemVer). As CI 3.1.0 now has native support for Composer, this library will be moving to be composer based.
+
+Take a look at the "development" branch to see what's up.
+
## 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.
From dc290963aaeb14d31f0617b934e5d8a1e396d220 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Thu, 18 Aug 2016 10:23:17 -0500
Subject: [PATCH 008/129] added vendor to .gitignore
---
.gitignore | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/.gitignore b/.gitignore
index 496ee2ca..47f36f65 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
-.DS_Store
\ No newline at end of file
+.DS_Store
+vendor
\ No newline at end of file
From 5aaef2cbd0bb2ddc82bcb961be4b435dbb077cf2 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Thu, 18 Aug 2016 10:26:04 -0500
Subject: [PATCH 009/129] remove JSON_NUMERIC_CHECK
---
application/libraries/Format.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index 00129b28..d078298c 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -403,14 +403,14 @@ public function to_json($data = NULL)
if (empty($callback) === TRUE)
{
- return json_encode($data, JSON_NUMERIC_CHECK);
+ return json_encode($data);
}
// 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_NUMERIC_CHECK).');';
+ return $callback.'('.json_encode($data).');';
}
// An invalid jsonp callback function provided.
From 3f3c0fec16d515c4211b4a0a62fb121bfeab0e9f Mon Sep 17 00:00:00 2001
From: teabrg
Date: Tue, 23 Aug 2016 09:29:11 +0200
Subject: [PATCH 010/129] Redo using Query Builder
---
application/libraries/REST_Controller.php | 3 +++
1 file changed, 3 insertions(+)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index ed1d283f..be693779 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1005,6 +1005,9 @@ protected function _detect_api_key()
// you can also perform an extra check for this
$existsactive = $this->db->query("SELECT api_key_activated FROM api_keys WHERE api_key = '".$key."' ");
+ // Using the Query builder method. This will only work if you have a column named activated in the api_key table.
+ //If you also want to add this as a config item replace the get('activated') with $this->config->item('rest_key_activated_column').
+ $existsactive = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get('activated')->result();
$isactive = $existsactive->result();
if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row() ) || $isactive[0]->api_key_activated == 'no' )
{
From 59110a62ecb550c852926757ec81e45ea26fb217 Mon Sep 17 00:00:00 2001
From: Jay Paul Torres Bandas
Date: Sun, 4 Sep 2016 08:31:29 -0500
Subject: [PATCH 011/129] Spanish Lang - Fix (#692)
---
application/language/spanish/rest_controller_lang.php | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/application/language/spanish/rest_controller_lang.php b/application/language/spanish/rest_controller_lang.php
index 962376c7..b6dea8fb 100644
--- a/application/language/spanish/rest_controller_lang.php
+++ b/application/language/spanish/rest_controller_lang.php
@@ -10,8 +10,8 @@
$lang['text_rest_ip_unauthorized'] = 'IP no autorizada';
$lang['text_rest_unauthorized'] = 'Acceso no autorizado';
$lang['text_rest_ajax_only'] = 'Solo peticiones ajax permitidas';
-$lang['text_rest_api_key_unauthorized'] = 'This API key does not have access to the requested controller';
-$lang['text_rest_api_key_permissions'] = 'This API key does not have enough permissions';
-$lang['text_rest_api_key_time_limit'] = 'This API key has reached the time limit for this method';
-$lang['text_rest_unknown_method'] = 'metodo desconocido';
+$lang['text_rest_api_key_unauthorized'] = 'Esta clave de API no tiene acceso al controlador solicitado';
+$lang['text_rest_api_key_permissions'] = 'Esta clave de API no tiene suficientes permisos';
+$lang['text_rest_api_key_time_limit'] = 'Esta clave de API ha alcanzado el límite de tiempo para este método';
+$lang['text_rest_unknown_method'] = 'método desconocido';
$lang['text_rest_unsupported'] = 'Protocolo no soportado';
From 565ab5332c118be2f743fc71f009570419e533bc Mon Sep 17 00:00:00 2001
From: Eray Akartuna
Date: Thu, 8 Sep 2016 02:41:46 +0300
Subject: [PATCH 012/129] Turkish Language (#695)
---
application/language/turkish/index.html | 11 +++++++++++
.../language/turkish/rest_controller_lang.php | 17 +++++++++++++++++
2 files changed, 28 insertions(+)
create mode 100644 application/language/turkish/index.html
create mode 100644 application/language/turkish/rest_controller_lang.php
diff --git a/application/language/turkish/index.html b/application/language/turkish/index.html
new file mode 100644
index 00000000..b702fbc3
--- /dev/null
+++ b/application/language/turkish/index.html
@@ -0,0 +1,11 @@
+
+
+
+ 403 Forbidden
+
+
+
+
Directory access is forbidden.
+
+
+
diff --git a/application/language/turkish/rest_controller_lang.php b/application/language/turkish/rest_controller_lang.php
new file mode 100644
index 00000000..2efcd2c8
--- /dev/null
+++ b/application/language/turkish/rest_controller_lang.php
@@ -0,0 +1,17 @@
+
Date: Thu, 8 Sep 2016 08:07:34 -0500
Subject: [PATCH 013/129] removed code that was causing issues due to hard
codes and non-config options.
---
application/libraries/REST_Controller.php | 11 +----------
1 file changed, 1 insertion(+), 10 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 0fb76fec..d0b354c0 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -999,16 +999,7 @@ protected function _detect_api_key()
// 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 you have a field to check if the API KEY provided by the user is activated or not
- //(in case you quickly want to deactivate specific users)
- // you can also perform an extra check for this
-
- $existsactive = $this->db->query("SELECT api_key_activated FROM api_keys WHERE api_key = '".$key."' ");
- // Using the Query builder method. This will only work if you have a column named activated in the api_key table.
- //If you also want to add this as a config item replace the get('activated') with $this->config->item('rest_key_activated_column').
- $existsactive = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get('activated')->result();
- $isactive = $existsactive->result();
- if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row() ) || $isactive[0]->api_key_activated == 'no' )
+ if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row()))
{
return FALSE;
}
From 079ea94915e558a868879f29e71f51c5e2f6dd84 Mon Sep 17 00:00:00 2001
From: teabrg
Date: Thu, 8 Sep 2016 15:08:34 +0200
Subject: [PATCH 014/129] Greek Language Translation (#696)
---
.../language/greek/rest_controller_lang.php | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
create mode 100644 application/language/greek/rest_controller_lang.php
diff --git a/application/language/greek/rest_controller_lang.php b/application/language/greek/rest_controller_lang.php
new file mode 100644
index 00000000..319333b2
--- /dev/null
+++ b/application/language/greek/rest_controller_lang.php
@@ -0,0 +1,17 @@
+
Date: Sat, 10 Sep 2016 21:34:49 +0100
Subject: [PATCH 015/129] fix rate limiting (#702)
---
application/libraries/REST_Controller.php | 9 +++------
1 file changed, 3 insertions(+), 6 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index d0b354c0..81be0a22 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1133,12 +1133,10 @@ protected function _check_limit($controller_method)
{
case 'API_KEY':
$limited_uri = 'api-key:' . (isset($this->rest->key) ? $this->rest->key : '');
- $limited_method_name = isset($this->rest->key) ? $this->rest->key : '';
break;
case 'METHOD_NAME':
$limited_uri = 'method-name:' . $controller_method;
- $limited_method_name = $controller_method;
break;
case 'ROUTED_URL':
@@ -1149,20 +1147,19 @@ protected function _check_limit($controller_method)
$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
- $limited_method_name = $controller_method;
break;
}
- if (isset($this->methods[$limited_method_name]['limit']) === FALSE )
+ 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[$limited_method_name]['limit'];
+ $limit = $this->methods[$controller_method]['limit'];
- $time_limit = (isset($this->methods[$limited_method_name]['time']) ? $this->methods[$limited_method_name]['time'] : 3600); // 3600 = 60 * 60
+ $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
From 4b45c72cb751222eed601f3385209c050c41a0e8 Mon Sep 17 00:00:00 2001
From: TGoC
Date: Sat, 10 Sep 2016 21:35:04 +0100
Subject: [PATCH 016/129] typo - example rate limit (#703)
---
application/controllers/api/Example.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
index 2cfecaaf..2f8f9e7a 100644
--- a/application/controllers/api/Example.php
+++ b/application/controllers/api/Example.php
@@ -25,9 +25,9 @@ function __construct()
// Configure limits on our controller methods
// Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
- $this->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
+ $this->methods['users_get']['limit'] = 500; // 500 requests per hour per user/key
+ $this->methods['users_post']['limit'] = 100; // 100 requests per hour per user/key
+ $this->methods['users_delete']['limit'] = 50; // 50 requests per hour per user/key
}
public function users_get()
From 706f3b8375a0f6d1c65224dc112429f02037a572 Mon Sep 17 00:00:00 2001
From: Eray Akartuna
Date: Thu, 29 Sep 2016 05:39:04 +0300
Subject: [PATCH 017/129] Limit request by ip address - without rest key (#711)
---
application/config/rest.php | 1 +
.../bulgarian/rest_controller_lang.php | 1 +
.../language/english/rest_controller_lang.php | 1 +
.../language/french/rest_controller_lang.php | 1 +
.../language/german/rest_controller_lang.php | 1 +
.../language/greek/rest_controller_lang.php | 1 +
.../rest_controller_lang.php | 1 +
.../romanian/rest_controller_lang.php | 1 +
.../serbian_cyr/rest_controller_lang.php | 1 +
.../serbian_lat/rest_controller_lang.php | 1 +
.../rest_controller_lang.php | 1 +
.../language/spanish/rest_controller_lang.php | 1 +
.../rest_controller_lang.php | 1 +
.../language/turkish/rest_controller_lang.php | 1 +
application/libraries/REST_Controller.php | 24 +++++++++++++++----
15 files changed, 33 insertions(+), 5 deletions(-)
diff --git a/application/config/rest.php b/application/config/rest.php
index a159144e..95ddc5cf 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -334,6 +334,7 @@
| 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
diff --git a/application/language/bulgarian/rest_controller_lang.php b/application/language/bulgarian/rest_controller_lang.php
index 6145307d..1dec8515 100644
--- a/application/language/bulgarian/rest_controller_lang.php
+++ b/application/language/bulgarian/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'API ключът не е оторизиран зо достъп до заявения контролер';
$lang['text_rest_api_key_permissions'] = 'API ключът няма достатъчно права';
$lang['text_rest_api_key_time_limit'] = 'API ключът е изполван с превишаване на времевия лимит за този метод';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Неизвестен метод';
$lang['text_rest_unsupported'] = 'Неподдържан протокол';
diff --git a/application/language/english/rest_controller_lang.php b/application/language/english/rest_controller_lang.php
index 1c665bdc..06bf4b96 100644
--- a/application/language/english/rest_controller_lang.php
+++ b/application/language/english/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'This API key does not have access to the requested controller';
$lang['text_rest_api_key_permissions'] = 'This API key does not have enough permissions';
$lang['text_rest_api_key_time_limit'] = 'This API key has reached the time limit for this method';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';
$lang['text_rest_unknown_method'] = 'Unknown method';
$lang['text_rest_unsupported'] = 'Unsupported protocol';
diff --git a/application/language/french/rest_controller_lang.php b/application/language/french/rest_controller_lang.php
index fb5727f5..f8c0d13f 100644
--- a/application/language/french/rest_controller_lang.php
+++ b/application/language/french/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Cette clef d\'API n\'a pas accès au contrôleur demandé';
$lang['text_rest_api_key_permissions'] = 'Cette clef d\'API n\'a pas les permissions requises';
$lang['text_rest_api_key_time_limit'] = 'Cette clef d\'API a atteint sa limite de temps pour cette méthode';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Méthode inconnue';
$lang['text_rest_unsupported'] = 'Protocole non-supporté';
diff --git a/application/language/german/rest_controller_lang.php b/application/language/german/rest_controller_lang.php
index 012d0363..4230c3cd 100644
--- a/application/language/german/rest_controller_lang.php
+++ b/application/language/german/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Dieser API Schlüssel hat keinen Zugriff auf den angeforderten Controller';
$lang['text_rest_api_key_permissions'] = 'Dieser API Schlüssel besitzt die erforderlichen Rechte nicht';
$lang['text_rest_api_key_time_limit'] = 'Dieser API Schlüssel ist abgelaufen';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Unbekannte Methode';
$lang['text_rest_unsupported'] = 'Protokoll nicht unterstützt';
diff --git a/application/language/greek/rest_controller_lang.php b/application/language/greek/rest_controller_lang.php
index 319333b2..f85b0673 100644
--- a/application/language/greek/rest_controller_lang.php
+++ b/application/language/greek/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Αυτό το API key δεν έχει πρόσβαση στον συγκεκριμένο controller';
$lang['text_rest_api_key_permissions'] = 'Αυτό το API key δεν έχει αρκετά δικαιώματα';
$lang['text_rest_api_key_time_limit'] = 'Αυτό το API key έχει φτάσει στο μέγιστο όριο requests για την συγκεκριμένη μέθοδο';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Άγνωστη μέθοδος';
$lang['text_rest_unsupported'] = 'Το συγκεκριμένο πρωτόκολλο δεν υποστηρίζεται';
diff --git a/application/language/portuguese-brazilian/rest_controller_lang.php b/application/language/portuguese-brazilian/rest_controller_lang.php
index 04bbf6e3..84dc9e0e 100644
--- a/application/language/portuguese-brazilian/rest_controller_lang.php
+++ b/application/language/portuguese-brazilian/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Esta chave da API não tem acesso ao controller solicitado';
$lang['text_rest_api_key_permissions'] = 'Esta chave da API não tem permissões suficientes';
$lang['text_rest_api_key_time_limit'] = 'Esta chave da API já atingiu o tempo limite para este método';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Método desconhecido';
$lang['text_rest_unsupported'] = 'Sem suporte para este protocolo';
diff --git a/application/language/romanian/rest_controller_lang.php b/application/language/romanian/rest_controller_lang.php
index c7b94478..f151d527 100644
--- a/application/language/romanian/rest_controller_lang.php
+++ b/application/language/romanian/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Această cheie API nu are acees la controller-ul solicitat';
$lang['text_rest_api_key_permissions'] = 'Această cheie API nu are suficiente permisiuni';
$lang['text_rest_api_key_time_limit'] = 'Această cheie API a atins limita de timp pentru această metodă';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Metodă necunoscută';
$lang['text_rest_unsupported'] = 'Protocol neacceptat';
diff --git a/application/language/serbian_cyr/rest_controller_lang.php b/application/language/serbian_cyr/rest_controller_lang.php
index e2164214..4d249c49 100644
--- a/application/language/serbian_cyr/rest_controller_lang.php
+++ b/application/language/serbian_cyr/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Овај *API* кључ нема овлашћења за захтевани контролер';
$lang['text_rest_api_key_permissions'] = 'Овај *API* кључ нема дозвољен степен овлашћења';
$lang['text_rest_api_key_time_limit'] = 'Овај *API* кључ је прекорачио временски лимит за дати метод';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Непознат метод';
$lang['text_rest_unsupported'] = 'Неподржан протокол';
diff --git a/application/language/serbian_lat/rest_controller_lang.php b/application/language/serbian_lat/rest_controller_lang.php
index 4b6b749f..057ab930 100644
--- a/application/language/serbian_lat/rest_controller_lang.php
+++ b/application/language/serbian_lat/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Ovaj API ključ nema ovlašćenje za zahtevani kontroler';
$lang['text_rest_api_key_permissions'] = 'Ovaj API ključ nema dozvoljen stepen ovlašćenja';
$lang['text_rest_api_key_time_limit'] = 'Ovaj API ključ je prekoračio vremenski limit za dati metod';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'Nepoznat metod';
$lang['text_rest_unsupported'] = 'Nepodržan protokol';
diff --git a/application/language/simplified-chinese/rest_controller_lang.php b/application/language/simplified-chinese/rest_controller_lang.php
index f7f19fb1..f32e9e7d 100644
--- a/application/language/simplified-chinese/rest_controller_lang.php
+++ b/application/language/simplified-chinese/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = '此 API key无法存取指定的 controller';
$lang['text_rest_api_key_permissions'] = '此 API key没有足够的权限';
$lang['text_rest_api_key_time_limit'] = '此 API key已经超过有效期限';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = '未知的方法';
$lang['text_rest_unsupported'] = '不支持的请求方法';
diff --git a/application/language/spanish/rest_controller_lang.php b/application/language/spanish/rest_controller_lang.php
index b6dea8fb..2ca81056 100644
--- a/application/language/spanish/rest_controller_lang.php
+++ b/application/language/spanish/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Esta clave de API no tiene acceso al controlador solicitado';
$lang['text_rest_api_key_permissions'] = 'Esta clave de API no tiene suficientes permisos';
$lang['text_rest_api_key_time_limit'] = 'Esta clave de API ha alcanzado el límite de tiempo para este método';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = 'método desconocido';
$lang['text_rest_unsupported'] = 'Protocolo no soportado';
diff --git a/application/language/traditional-chinese/rest_controller_lang.php b/application/language/traditional-chinese/rest_controller_lang.php
index f388c446..b1f80caf 100644
--- a/application/language/traditional-chinese/rest_controller_lang.php
+++ b/application/language/traditional-chinese/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = '這個 API 金鑰沒有辦法存取指定的 controller';
$lang['text_rest_api_key_permissions'] = '這個 API 金鑰沒有具備足夠權限';
$lang['text_rest_api_key_time_limit'] = '這個 API 金鑰已經超過有效期限';
+$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = '未知的方法';
$lang['text_rest_unsupported'] = '不支援的通訊協定';
diff --git a/application/language/turkish/rest_controller_lang.php b/application/language/turkish/rest_controller_lang.php
index 2efcd2c8..589b28cc 100644
--- a/application/language/turkish/rest_controller_lang.php
+++ b/application/language/turkish/rest_controller_lang.php
@@ -13,5 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Ulaşılmak istenilen controllera API anahtarının erişim yetkisi bulunmamaktadır';
$lang['text_rest_api_key_permissions'] = 'Bu API anahtarının yeterli yetkisi bulunmamaktadır';
$lang['text_rest_api_key_time_limit'] = 'API anahtarı bu metod için zaman sınırına ulaştı.';
+$lang['text_rest_ip_address_time_limit'] = 'IP adresi bu metod için zaman sınırına ulaştı.';
$lang['text_rest_unknown_method'] = 'Bilinmeyen metod';
$lang['text_rest_unsupported'] = 'Desteklenmeyen protokol';
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 81be0a22..45ceb5ed 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -704,6 +704,13 @@ public function _remap($object_called, $arguments = [])
}
}
+ //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)
{
@@ -1129,10 +1136,17 @@ protected function _check_limit($controller_method)
return TRUE;
}
+ $api_key = isset($this->rest->key) ? $this->rest->key : '';
+
switch ($this->config->item('rest_limits_method'))
{
+ case 'IP_ADDRESS':
+ $limited_uri = 'ip-address:' .$this->input->ip_address();
+ $api_key = $this->input->ip_address();
+ break;
+
case 'API_KEY':
- $limited_uri = 'api-key:' . (isset($this->rest->key) ? $this->rest->key : '');
+ $limited_uri = 'api-key:' . $api_key;
break;
case 'METHOD_NAME':
@@ -1164,7 +1178,7 @@ protected function _check_limit($controller_method)
// Get data about a keys' usage and limit to one row
$result = $this->rest->db
->where('uri', $limited_uri)
- ->where('api_key', $this->rest->key)
+ ->where('api_key', $api_key)
->get($this->config->item('rest_limits_table'))
->row();
@@ -1174,7 +1188,7 @@ protected function _check_limit($controller_method)
// Create a new row for the following key
$this->rest->db->insert($this->config->item('rest_limits_table'), [
'uri' => $limited_uri,
- 'api_key' => isset($this->rest->key) ? $this->rest->key : '',
+ 'api_key' =>$api_key,
'count' => 1,
'hour_started' => time()
]);
@@ -1186,7 +1200,7 @@ protected function _check_limit($controller_method)
// Reset the started period and count
$this->rest->db
->where('uri', $limited_uri)
- ->where('api_key', isset($this->rest->key) ? $this->rest->key : '')
+ ->where('api_key', $api_key)
->set('hour_started', time())
->set('count', 1)
->update($this->config->item('rest_limits_table'));
@@ -1204,7 +1218,7 @@ protected function _check_limit($controller_method)
// Increase the count by one
$this->rest->db
->where('uri', $limited_uri)
- ->where('api_key', $this->rest->key)
+ ->where('api_key', $api_key)
->set('count', 'count + 1', FALSE)
->update($this->config->item('rest_limits_table'));
}
From 929b0f5ef68a52e4bc639da662af24c629aae74a Mon Sep 17 00:00:00 2001
From: Ties Kuypers
Date: Wed, 26 Oct 2016 15:51:57 +0200
Subject: [PATCH 018/129] added dutch translation (#721)
* Added dutch language
* Create index.html
---
application/language/dutch/index.html | 11 +++++++++++
.../language/dutch/rest_controller_lang.php | 16 ++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 application/language/dutch/index.html
create mode 100644 application/language/dutch/rest_controller_lang.php
diff --git a/application/language/dutch/index.html b/application/language/dutch/index.html
new file mode 100644
index 00000000..b702fbc3
--- /dev/null
+++ b/application/language/dutch/index.html
@@ -0,0 +1,11 @@
+
+
+
+ 403 Forbidden
+
+
+
+
Directory access is forbidden.
+
+
+
diff --git a/application/language/dutch/rest_controller_lang.php b/application/language/dutch/rest_controller_lang.php
new file mode 100644
index 00000000..182ca61c
--- /dev/null
+++ b/application/language/dutch/rest_controller_lang.php
@@ -0,0 +1,16 @@
+
Date: Wed, 26 Oct 2016 16:52:42 +0300
Subject: [PATCH 019/129] Bulgarian language update. (#719)
Signed-off-by:Ivan Tcholakov
---
application/language/bulgarian/rest_controller_lang.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/language/bulgarian/rest_controller_lang.php b/application/language/bulgarian/rest_controller_lang.php
index 1dec8515..4ba134d8 100644
--- a/application/language/bulgarian/rest_controller_lang.php
+++ b/application/language/bulgarian/rest_controller_lang.php
@@ -13,6 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'API ключът не е оторизиран зо достъп до заявения контролер';
$lang['text_rest_api_key_permissions'] = 'API ключът няма достатъчно права';
$lang['text_rest_api_key_time_limit'] = 'API ключът е изполван с превишаване на времевия лимит за този метод';
-$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
+$lang['text_rest_ip_address_time_limit'] = 'За текущия IP адрес е превишен времевия лимит за изпълнение на метода';
$lang['text_rest_unknown_method'] = 'Неизвестен метод';
$lang['text_rest_unsupported'] = 'Неподдържан протокол';
From 73eaa18822473acadcc65ca8ffb10c7b60f54de9 Mon Sep 17 00:00:00 2001
From: Barayuda Gautama
Date: Wed, 23 Nov 2016 00:08:54 +0800
Subject: [PATCH 020/129] Add Indonesian language (#723)
---
application/language/indonesia/index.html | 11 +++++++++++
.../indonesia/rest_controller_lang.php | 18 ++++++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 application/language/indonesia/index.html
create mode 100644 application/language/indonesia/rest_controller_lang.php
diff --git a/application/language/indonesia/index.html b/application/language/indonesia/index.html
new file mode 100644
index 00000000..b702fbc3
--- /dev/null
+++ b/application/language/indonesia/index.html
@@ -0,0 +1,11 @@
+
+
+
+ 403 Forbidden
+
+
+
+
Directory access is forbidden.
+
+
+
diff --git a/application/language/indonesia/rest_controller_lang.php b/application/language/indonesia/rest_controller_lang.php
new file mode 100644
index 00000000..771c6835
--- /dev/null
+++ b/application/language/indonesia/rest_controller_lang.php
@@ -0,0 +1,18 @@
+
Date: Tue, 22 Nov 2016 18:09:56 +0200
Subject: [PATCH 021/129] Code smell, PHP Doc problems, Index methods, and
global exception handler (#726)
* Fixed throws statement
* Removed unnecessary return doc
* Fixed wrong return value
* Fixed parameter types in PHP DOC
* Removed paths inspection in the project
* Added index methods support! Finally
* Handle all exceptions showings in one place. not 2
* Added changes to the change log
---
.gitignore | 3 ++-
CHANGELOG.md | 4 ++++
application/controllers/api/Example.php | 1 +
application/controllers/api/Key.php | 1 +
application/libraries/Format.php | 10 +++++-----
application/libraries/REST_Controller.php | 17 ++++++++---------
6 files changed, 21 insertions(+), 15 deletions(-)
diff --git a/.gitignore b/.gitignore
index 47f36f65..a761a8b8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
.DS_Store
-vendor
\ No newline at end of file
+vendor
+.idea
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dfdadc58..e22c03ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,10 @@
Changelog:
===========
+### UNRELEASED
+* Added support for CodeIgniter controller's index methods (index_GET, index_POST...)
+* Added exceptions handling when the method could not be found
+
### 2.7.2
* Added $this->query() in which query parameters can now be obtained regardless of whether a GET request is sent or not
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
index 2f8f9e7a..b571e74d 100644
--- a/application/controllers/api/Example.php
+++ b/application/controllers/api/Example.php
@@ -3,6 +3,7 @@
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
+/** @noinspection PhpIncludeInspection */
require APPPATH . '/libraries/REST_Controller.php';
/**
diff --git a/application/controllers/api/Key.php b/application/controllers/api/Key.php
index 0fa67172..35d7c0f7 100644
--- a/application/controllers/api/Key.php
+++ b/application/controllers/api/Key.php
@@ -3,6 +3,7 @@
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
+/** @noinspection PhpIncludeInspection */
require APPPATH . '/libraries/REST_Controller.php';
/**
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index d078298c..a6e2cf98 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -461,8 +461,8 @@ public function to_php($data = NULL)
// INTERNAL FUNCTIONS
/**
- * @param $data XML string
- * @return SimpleXMLElement XML element object; otherwise, empty array
+ * @param string $data XML string
+ * @return array XML element object; otherwise, empty array
*/
protected function _from_xml($data)
{
@@ -496,7 +496,7 @@ protected function _from_csv($data, $delimiter = ',', $enclosure = '"')
}
/**
- * @param $data Encoded json string
+ * @param string $data Encoded json string
* @return mixed Decoded json string with leading and trailing whitespace removed
*/
protected function _from_json($data)
@@ -505,7 +505,7 @@ protected function _from_json($data)
}
/**
- * @param string Data to unserialized
+ * @param string $data Data to unserialize
* @return mixed Unserialized data
*/
protected function _from_serialize($data)
@@ -514,7 +514,7 @@ protected function _from_serialize($data)
}
/**
- * @param $data Data to trim leading and trailing whitespace
+ * @param string $data Data to trim leading and trailing whitespace
* @return string Data with leading and trailing whitespace removed
*/
protected function _from_php($data)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 45ceb5ed..17f81375 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -375,7 +375,6 @@ protected function early_checks()
* @access public
* @param string $config Configuration filename minus the file extension
* e.g: my_rest.php is passed as 'my_rest'
- * @return void
*/
public function __construct($config = 'rest')
{
@@ -590,7 +589,7 @@ public function __destruct()
* Checks to see if we have everything we need to run this library.
*
* @access protected
- * @return Exception
+ * @@throws Exception
*/
protected function preflight_checks()
{
@@ -632,6 +631,11 @@ public function _remap($object_called, $arguments = [])
$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);
@@ -725,13 +729,8 @@ public function _remap($object_called, $arguments = [])
catch (Exception $ex)
{
// If the method doesn't exist, then the error will be caught and an error response shown
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => [
- 'classname' => get_class($ex),
- 'message' => $ex->getMessage()
- ]
- ], self::HTTP_INTERNAL_SERVER_ERROR);
+ $_error = &load_class('Exceptions', 'core');
+ $_error->show_exception($ex);
}
}
From dfb0a4f5802cbc8bc4e55f09a6cfca877fa125a3 Mon Sep 17 00:00:00 2001
From: SC
Date: Tue, 22 Nov 2016 17:10:56 +0100
Subject: [PATCH 022/129] Add italian language (#733)
* added italian translation
* Create index.html
---
application/language/italian/index.html | 11 +++++++++++
.../language/italian/rest_controller_lang.php | 16 ++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 application/language/italian/index.html
create mode 100644 application/language/italian/rest_controller_lang.php
diff --git a/application/language/italian/index.html b/application/language/italian/index.html
new file mode 100644
index 00000000..b702fbc3
--- /dev/null
+++ b/application/language/italian/index.html
@@ -0,0 +1,11 @@
+
+
+
+ 403 Forbidden
+
+
+
+
Directory access is forbidden.
+
+
+
diff --git a/application/language/italian/rest_controller_lang.php b/application/language/italian/rest_controller_lang.php
new file mode 100644
index 00000000..783f16ab
--- /dev/null
+++ b/application/language/italian/rest_controller_lang.php
@@ -0,0 +1,16 @@
+
Date: Tue, 22 Nov 2016 17:11:15 +0100
Subject: [PATCH 023/129] response continue fix (#722)
---
application/libraries/REST_Controller.php | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 17f81375..d7a691da 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -745,6 +745,7 @@ public function _remap($object_called, $arguments = [])
*/
public function response($data = NULL, $http_code = NULL, $continue = FALSE)
{
+ ob_start();
// If the HTTP status is not NULL, then cast as an integer
if ($http_code !== NULL)
{
@@ -813,6 +814,10 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
$this->output->_display();
exit;
}
+ else
+ {
+ ob_end_flush();
+ }
// Otherwise dump the output automatically
}
From d19dc77f03521c7a725a4555407e1e4e7a85f6e1 Mon Sep 17 00:00:00 2001
From: Ian Lin
Date: Wed, 23 Nov 2016 00:11:35 +0800
Subject: [PATCH 024/129] fix cross site to option request error (#720)
cross site request first can use option http method.
but use `keys` authentication, authentication can fail
---
application/libraries/REST_Controller.php | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index d7a691da..1f0374a0 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -650,6 +650,11 @@ public function _remap($object_called, $arguments = [])
{
$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,
From d8a6cbb1d8991859f89dc57222afaacb1de7e082 Mon Sep 17 00:00:00 2001
From: Amit Moryossef
Date: Wed, 21 Dec 2016 16:26:17 +0200
Subject: [PATCH 025/129] All around cleaning (#734)
* Fixed throws statement
* Removed unnecessary return doc
* Fixed wrong return value
* Fixed parameter types in PHP DOC
* Removed paths inspection in the project
* Added index methods support! Finally
* Handle all exceptions showings in one place. not 2
* Added changes to the change log
* Fixed properties PHPDoc
* English spelling fixes
---
CHANGELOG.md | 6 +++---
README.md | 6 +++---
application/config/rest.php | 20 ++++++++++----------
application/controllers/api/Example.php | 2 +-
application/libraries/REST_Controller.php | 18 +++++++++---------
5 files changed, 26 insertions(+), 26 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e22c03ed..ce83aeda 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,7 +38,7 @@ Changelog:
* 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
+* Small bug-fix 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.
@@ -55,11 +55,11 @@ Changelog:
* 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.
+* Added IP white-list 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).
+* Instead of just seeing item, item, item, the singular version of the base-node 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.
diff --git a/README.md b/README.md
index b33b448a..4b212f4e 100644
--- a/README.md
+++ b/README.md
@@ -150,9 +150,9 @@ Enabling digest auth is similarly easy. Configure your desired logins in the con
If you're tying this library into an AJAX endpoint where clients authenticate using PHP sessions then you may not like either of the digest nor basic authentication methods. In that case, you can tell the REST Library what PHP session variable to check for. If the variable exists, then the user is authorized. It will be up to your application to set that variable. You can define the variable in ``$config['auth_source']``. Then tell the library to use a php session variable by setting ``$config['rest_auth']`` to ``session``.
-All three methods of authentication can be secured further by using an IP whitelist. If you enable `$config['rest_ip_whitelist_enabled']` in your config file, you can then set a list of allowed IPs.
+All three methods of authentication can be secured further by using an IP white-list. If you enable `$config['rest_ip_whitelist_enabled']` in your config file, you can then set a list of allowed IPs.
-Any client connecting to your API will be checked against the whitelisted IP array. If they're on the list, they'll be allowed access. If not, sorry, no can do hombre. The whitelist is a comma-separated string:
+Any client connecting to your API will be checked against the white-listed IP array. If they're on the list, they'll be allowed access. If not, sorry, no can do hombre. The whitelist is a comma-separated string:
```php
$config['rest_ip_whitelist'] = '123.456.789.0, 987.654.32.1';
@@ -196,7 +196,7 @@ $ curl -X POST -H "X-API-KEY: some_key_here" http://example.com/books
## Contributions
This project was originally written by Phil Sturgeon, however his involvement has shifted
-as he is no longer using it. As of 2013/11/20 further developement and support will be done by Chris Kacerguis.
+as he is no longer using it. As of 2013/11/20 further development 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
index 95ddc5cf..f49b751d 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -104,8 +104,8 @@
| Set to specify the REST API requires to be logged in
|
| FALSE No login required
-| 'basic' Unsecure login
-| 'digest' More secure login
+| 'basic' Unsecured login
+| 'digest' More secured login
| 'session' Check for a PHP session variable. See 'auth_source' to set the
| authorization key
|
@@ -189,7 +189,7 @@
/*
|--------------------------------------------------------------------------
-| Override auth types for specfic 'class/method/HTTP method'
+| Override auth types for specific 'class/method/HTTP method'
|--------------------------------------------------------------------------
|
| example:
@@ -214,24 +214,24 @@
/*
|--------------------------------------------------------------------------
-| Global IP Whitelisting
+| Global IP White-listing
|--------------------------------------------------------------------------
|
-| Limit connections to your REST server to whitelisted IP addresses
+| 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 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 but set 'auth_override_class_method' to 'whitelist' to
-| restrict certain methods to IPs in your whitelist
+| 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 IP Whitelist
+| REST IP White-list
|--------------------------------------------------------------------------
|
| Limit connections to your REST server with a comma separated
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
index b571e74d..7aef773a 100644
--- a/application/controllers/api/Example.php
+++ b/application/controllers/api/Example.php
@@ -73,7 +73,7 @@ public function users_get()
$this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
- // Get the user from the array, using the id as key for retreival.
+ // Get the user from the array, using the id as key for retrieval.
// Usually a model is to be used for this.
$user = NULL;
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 1f0374a0..1c0fb179 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -285,16 +285,16 @@ abstract class REST_Controller extends CI_Controller {
/**
* The start of the response time from the server
*
- * @var string
+ * @var number
*/
- protected $_start_rtime = '';
+ protected $_start_rtime;
/**
* The end of the response time from the server
*
- * @var string
+ * @var number
*/
- protected $_end_rtime = '';
+ protected $_end_rtime;
/**
* List all supported methods, the first will be the default format
@@ -567,7 +567,7 @@ public function __construct($config = 'rest')
}
/**
- * Deconstructor
+ * De-constructor
*
* @author Chris Kacerguis
* @access public
@@ -778,7 +778,7 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
$output = $this->format->factory($data)->{'to_' . $this->response->format}();
// 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 datatype
+ // Json is the most appropriate form for such a data type
if ($this->response->format === 'array')
{
$output = $this->format->factory($output)->{'to_json'}();
@@ -1473,7 +1473,7 @@ protected function _parse_put()
}
else if ($this->input->method() === 'put')
{
- // If no filetype is provided, then there are probably just arguments
+ // If no file type is provided, then there are probably just arguments
$this->_put_args = $this->input->input_stream();
}
}
@@ -1523,7 +1523,7 @@ protected function _parse_patch()
}
else if ($this->input->method() === 'patch')
{
- // If no filetype is provided, then there are probably just arguments
+ // If no file type is provided, then there are probably just arguments
$this->_patch_args = $this->input->input_stream();
}
}
@@ -1941,7 +1941,7 @@ protected function _check_php_session()
// Get the auth_source config item
$key = $this->config->item('auth_source');
- // If falsy, then the user isn't logged in
+ // If false, then the user isn't logged in
if ( ! $this->session->userdata($key))
{
// Display an error response
From e1cbdc1848b07b66a1328fdba2e4b39c5df80426 Mon Sep 17 00:00:00 2001
From: kiss7001
Date: Wed, 21 Dec 2016 23:26:55 +0900
Subject: [PATCH 026/129] bug fix (#735)
---
application/controllers/api/Key.php | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/application/controllers/api/Key.php b/application/controllers/api/Key.php
index 35d7c0f7..547334b6 100644
--- a/application/controllers/api/Key.php
+++ b/application/controllers/api/Key.php
@@ -233,7 +233,7 @@ private function _generate_key()
private function _get_key($key)
{
- return $this->db
+ return $this->rest->db
->where(config_item('rest_key_column'), $key)
->get(config_item('rest_keys_table'))
->row();
@@ -241,7 +241,7 @@ private function _get_key($key)
private function _key_exists($key)
{
- return $this->db
+ return $this->rest->db
->where(config_item('rest_key_column'), $key)
->count_all_results(config_item('rest_keys_table')) > 0;
}
@@ -251,21 +251,21 @@ private function _insert_key($key, $data)
$data[config_item('rest_key_column')] = $key;
$data['date_created'] = function_exists('now') ? now() : time();
- return $this->db
+ return $this->rest->db
->set($data)
->insert(config_item('rest_keys_table'));
}
private function _update_key($key, $data)
{
- return $this->db
+ return $this->rest->db
->where(config_item('rest_key_column'), $key)
->update(config_item('rest_keys_table'), $data);
}
private function _delete_key($key)
{
- return $this->db
+ return $this->rest->db
->where(config_item('rest_key_column'), $key)
->delete(config_item('rest_keys_table'));
}
From 7e1c22c3b2601ca03a885dd34365ef8b7e7fb1b3 Mon Sep 17 00:00:00 2001
From: Ian Lin
Date: Wed, 21 Dec 2016 22:29:44 +0800
Subject: [PATCH 027/129] Fix parse method return arguments null (#744)
* fix cross site to option request error
cross site request first can use option http method.
but use `keys` authentication, authentication can fail
* Fix Parse error
Fix parse method return arguments null
---
application/libraries/REST_Controller.php | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 1c0fb179..bc9e750f 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -475,6 +475,12 @@ public function __construct($config = 'rest')
$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'} = [];
+ }
// Now we know all about our request, let's try and parse the body if it exists
if ($this->request->format && $this->request->body)
From a36e4728114a53d4639dc8a5da27da11b3c43249 Mon Sep 17 00:00:00 2001
From: lweb20
Date: Mon, 26 Dec 2016 20:35:16 -0500
Subject: [PATCH 028/129] Add config to handle or not exceptions (#739)
---
application/config/rest.php | 10 ++++++++++
application/libraries/REST_Controller.php | 6 +++++-
2 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/application/config/rest.php b/application/config/rest.php
index f49b751d..deafeeb7 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -229,6 +229,16 @@
*/
$config['rest_ip_whitelist_enabled'] = FALSE;
+/*
+|--------------------------------------------------------------------------
+| REST Handle Exceptions
+|--------------------------------------------------------------------------
+|
+| Handle exceptions caused by the controller
+|
+*/
+$config['rest_handle_exceptions'] = TRUE;
+
/*
|--------------------------------------------------------------------------
| REST IP White-list
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index bc9e750f..442046a1 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -595,7 +595,7 @@ public function __destruct()
* Checks to see if we have everything we need to run this library.
*
* @access protected
- * @@throws Exception
+ * @throws Exception
*/
protected function preflight_checks()
{
@@ -739,6 +739,10 @@ public function _remap($object_called, $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);
From 5aef7b41bb08de33bcd892cc2d6e1276a5338722 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Mon, 26 Dec 2016 19:40:44 -0600
Subject: [PATCH 029/129] added gitter badge
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 4b212f4e..8943a5ce 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,7 @@
# CodeIgniter Rest Server
+[](https://gitter.im/codeigniter-restserver/Lobby)
+
A fully RESTful server implementation for CodeIgniter using one library, one
config file and one controller.
From 859eb0156ca92ca55adf3baf09968b34bb8016cd Mon Sep 17 00:00:00 2001
From: Himphen Hui
Date: Sat, 24 Jun 2017 07:51:13 +0800
Subject: [PATCH 030/129] Update rest_controller_lang.php (#799)
---
.../language/traditional-chinese/rest_controller_lang.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/language/traditional-chinese/rest_controller_lang.php b/application/language/traditional-chinese/rest_controller_lang.php
index b1f80caf..a8450f2b 100644
--- a/application/language/traditional-chinese/rest_controller_lang.php
+++ b/application/language/traditional-chinese/rest_controller_lang.php
@@ -13,6 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = '這個 API 金鑰沒有辦法存取指定的 controller';
$lang['text_rest_api_key_permissions'] = '這個 API 金鑰沒有具備足夠權限';
$lang['text_rest_api_key_time_limit'] = '這個 API 金鑰已經超過有效期限';
-$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
+$lang['text_rest_ip_address_time_limit'] = '這個 IP 位置的流量已經超過上限';
$lang['text_rest_unknown_method'] = '未知的方法';
$lang['text_rest_unsupported'] = '不支援的通訊協定';
From a5eda57900ac5fc37a2691e42d4b6147af95fa1c Mon Sep 17 00:00:00 2001
From: Reinhard
Date: Sat, 24 Jun 2017 01:51:38 +0200
Subject: [PATCH 031/129] Insert comma's and then a space. (#800)
Inserting a space first and then a comma seems wrong to me. Was this intended?
---
application/libraries/REST_Controller.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 442046a1..d5c2b4f0 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2229,8 +2229,8 @@ protected function _check_access()
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'));
+ $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)
From 4443857630df2dc1c284e5d3c8e0967d9a004061 Mon Sep 17 00:00:00 2001
From: Goran Grbic
Date: Sat, 24 Jun 2017 01:52:04 +0200
Subject: [PATCH 032/129] Additional translation set (#808)
* Additional translation set
* APPPATH const variable already finishes with trailing slash
---
application/controllers/api/Example.php | 2 +-
application/language/serbian_cyr/rest_controller_lang.php | 2 +-
application/language/serbian_lat/rest_controller_lang.php | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
index 7aef773a..eb2f9069 100644
--- a/application/controllers/api/Example.php
+++ b/application/controllers/api/Example.php
@@ -4,7 +4,7 @@
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
-require APPPATH . '/libraries/REST_Controller.php';
+require APPPATH . 'libraries/REST_Controller.php';
/**
* This is an example of a few basic user interaction methods you could use
diff --git a/application/language/serbian_cyr/rest_controller_lang.php b/application/language/serbian_cyr/rest_controller_lang.php
index 4d249c49..e83ff4db 100644
--- a/application/language/serbian_cyr/rest_controller_lang.php
+++ b/application/language/serbian_cyr/rest_controller_lang.php
@@ -13,6 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Овај *API* кључ нема овлашћења за захтевани контролер';
$lang['text_rest_api_key_permissions'] = 'Овај *API* кључ нема дозвољен степен овлашћења';
$lang['text_rest_api_key_time_limit'] = 'Овај *API* кључ је прекорачио временски лимит за дати метод';
-$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
+$lang['text_rest_ip_address_time_limit'] = 'Ова *IP* адреса је прекорачила временски лимит за дати метод';//todo translate
$lang['text_rest_unknown_method'] = 'Непознат метод';
$lang['text_rest_unsupported'] = 'Неподржан протокол';
diff --git a/application/language/serbian_lat/rest_controller_lang.php b/application/language/serbian_lat/rest_controller_lang.php
index 057ab930..6046788d 100644
--- a/application/language/serbian_lat/rest_controller_lang.php
+++ b/application/language/serbian_lat/rest_controller_lang.php
@@ -13,6 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Ovaj API ključ nema ovlašćenje za zahtevani kontroler';
$lang['text_rest_api_key_permissions'] = 'Ovaj API ključ nema dozvoljen stepen ovlašćenja';
$lang['text_rest_api_key_time_limit'] = 'Ovaj API ključ je prekoračio vremenski limit za dati metod';
-$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
+$lang['text_rest_ip_address_time_limit'] = 'Ova IP adresa je prekoračila vremenski limit za dati metod';
$lang['text_rest_unknown_method'] = 'Nepoznat metod';
$lang['text_rest_unsupported'] = 'Nepodržan protokol';
From b0229a15c5caabcf485c10304fa99dde6c3e0055 Mon Sep 17 00:00:00 2001
From: Jonghwi
Date: Sat, 24 Jun 2017 08:53:11 +0900
Subject: [PATCH 033/129] Korean language support (#812)
* Added Korean language translation
* Create default index.html
---
application/language/korean/index.html | 11 +++++++++++
.../language/korean/rest_controller_lang.php | 16 ++++++++++++++++
2 files changed, 27 insertions(+)
create mode 100644 application/language/korean/index.html
create mode 100644 application/language/korean/rest_controller_lang.php
diff --git a/application/language/korean/index.html b/application/language/korean/index.html
new file mode 100644
index 00000000..b702fbc3
--- /dev/null
+++ b/application/language/korean/index.html
@@ -0,0 +1,11 @@
+
+
+
+ 403 Forbidden
+
+
+
+
Directory access is forbidden.
+
+
+
diff --git a/application/language/korean/rest_controller_lang.php b/application/language/korean/rest_controller_lang.php
new file mode 100644
index 00000000..df6f9b46
--- /dev/null
+++ b/application/language/korean/rest_controller_lang.php
@@ -0,0 +1,16 @@
+
Date: Sun, 23 Jul 2017 17:56:35 +0300
Subject: [PATCH 034/129] Added encode conversion to to_csv-function so that
special characters are shown correctly in MS Excel. (#818)
---
application/libraries/Format.php | 3 +++
1 file changed, 3 insertions(+)
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index a6e2cf98..b1405302 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -378,6 +378,9 @@ public function to_csv($data = NULL, $delimiter = ',', $enclosure = '"')
// 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;
}
From db3eef81fb36a1457bcce79e7a57c6b37c5403be Mon Sep 17 00:00:00 2001
From: Natan Felles
Date: Thu, 6 Jul 2017 18:42:20 -0300
Subject: [PATCH 035/129] Translated text_rest_ip_address_time_limit
---
.../language/portuguese-brazilian/rest_controller_lang.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/language/portuguese-brazilian/rest_controller_lang.php b/application/language/portuguese-brazilian/rest_controller_lang.php
index 84dc9e0e..10c164c6 100644
--- a/application/language/portuguese-brazilian/rest_controller_lang.php
+++ b/application/language/portuguese-brazilian/rest_controller_lang.php
@@ -13,6 +13,6 @@
$lang['text_rest_api_key_unauthorized'] = 'Esta chave da API não tem acesso ao controller solicitado';
$lang['text_rest_api_key_permissions'] = 'Esta chave da API não tem permissões suficientes';
$lang['text_rest_api_key_time_limit'] = 'Esta chave da API já atingiu o tempo limite para este método';
-$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
+$lang['text_rest_ip_address_time_limit'] = 'Este Endereço IP atingiu o limite de tempo para este método';
$lang['text_rest_unknown_method'] = 'Método desconhecido';
$lang['text_rest_unsupported'] = 'Sem suporte para este protocolo';
From a2a9868a35bfec272144fd78bebe783180372603 Mon Sep 17 00:00:00 2001
From: Natan Felles
Date: Sun, 23 Jul 2017 11:58:03 -0300
Subject: [PATCH 036/129] Migrations (#820)
* Translated text_rest_ip_address_time_limit
* Add startup Migrations and DB Helper
* Revert "Translated text_rest_ip_address_time_limit"
This reverts commit fa1617def0d3b918fb23d2a60c748754aa4ab863.
* Add startup Migrations and DB Helper
* Update users table migration
---
application/helpers/db_helper.php | 69 +++++++++++++++++
application/helpers/index.html | 11 +++
.../20170706025420_create_table_users.php | 69 +++++++++++++++++
.../20170706030520_create_table_api_keys.php | 69 +++++++++++++++++
.../20170706031435_create_table_api_logs.php | 75 +++++++++++++++++++
...20170706032133_create_table_api_access.php | 62 +++++++++++++++
...20170706032825_create_table_api_limits.php | 57 ++++++++++++++
application/migrations/index.html | 11 +++
8 files changed, 423 insertions(+)
create mode 100755 application/helpers/db_helper.php
create mode 100644 application/helpers/index.html
create mode 100644 application/migrations/20170706025420_create_table_users.php
create mode 100644 application/migrations/20170706030520_create_table_api_keys.php
create mode 100644 application/migrations/20170706031435_create_table_api_logs.php
create mode 100644 application/migrations/20170706032133_create_table_api_access.php
create mode 100644 application/migrations/20170706032825_create_table_api_limits.php
create mode 100644 application/migrations/index.html
diff --git a/application/helpers/db_helper.php b/application/helpers/db_helper.php
new file mode 100755
index 00000000..9a007a46
--- /dev/null
+++ b/application/helpers/db_helper.php
@@ -0,0 +1,69 @@
+
+ */
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+if ( ! function_exists('add_foreign_key'))
+{
+ /**
+ * @param string $table Table name
+ * @param string $foreign_key Collumn name having the Foreign Key
+ * @param string $references Table and column reference. Ex: users(id)
+ * @param string $on_delete RESTRICT, NO ACTION, CASCADE, SET NULL, SET DEFAULT
+ * @param string $on_update RESTRICT, NO ACTION, CASCADE, SET NULL, SET DEFAULT
+ *
+ * @return string SQL command
+ */
+ function add_foreign_key($table, $foreign_key, $references, $on_delete = 'RESTRICT', $on_update = 'RESTRICT')
+ {
+ $references = explode('(', str_replace(')', '', str_replace('`', '', $references)));
+
+ return "ALTER TABLE `{$table}` ADD CONSTRAINT `{$table}_{$foreign_key}_fk` FOREIGN KEY (`{$foreign_key}`) REFERENCES `{$references[0]}`(`{$references[1]}`) ON DELETE {$on_delete} ON UPDATE {$on_update}";
+ }
+}
+
+if ( ! function_exists('drop_foreign_key'))
+{
+ /**
+ * @param string $table Table name
+ * @param string $foreign_key Collumn name having the Foreign Key
+ *
+ * @return string SQL command
+ */
+ function drop_foreign_key($table, $foreign_key)
+ {
+ return "ALTER TABLE `{$table}` DROP FOREIGN KEY `{$table}_{$foreign_key}_fk`";
+ }
+}
+
+if ( ! function_exists('add_trigger'))
+{
+ /**
+ * @param string $trigger_name Trigger name
+ * @param string $table Table name
+ * @param string $statement Command to run
+ * @param string $time BEFORE or AFTER
+ * @param string $event INSERT, UPDATE or DELETE
+ * @param string $type FOR EACH ROW [FOLLOWS|PRECEDES]
+ *
+ * @return string SQL Command
+ */
+ function add_trigger($trigger_name, $table, $statement, $time = 'BEFORE', $event = 'INSERT', $type = 'FOR EACH ROW')
+ {
+ return 'DELIMITER ;;' . PHP_EOL . "CREATE TRIGGER `{$trigger_name}` {$time} {$event} ON `{$table}` {$type}" . PHP_EOL . 'BEGIN' . PHP_EOL . $statement . PHP_EOL . 'END;' . PHP_EOL . 'DELIMITER ;;';
+ }
+}
+
+if ( ! function_exists('drop_trigger'))
+{
+ /**
+ * @param string $trigger_name Trigger name
+ *
+ * @return string SQL Command
+ */
+ function drop_trigger($trigger_name)
+ {
+ return "DROP TRIGGER {$trigger_name};";
+ }
+}
diff --git a/application/helpers/index.html b/application/helpers/index.html
new file mode 100644
index 00000000..b702fbc3
--- /dev/null
+++ b/application/helpers/index.html
@@ -0,0 +1,11 @@
+
+
+
+ 403 Forbidden
+
+
+
+
+
+
+
From 944c1f3c9065cab08bb385b0d4b91daa4e789079 Mon Sep 17 00:00:00 2001
From: Adrian Bean
Date: Wed, 9 Aug 2017 17:01:41 +0100
Subject: [PATCH 037/129] Force validation (#809)
* Update rest.php
* Update REST_Controller.php
Update to force the use of both the api key and the basic authentication when the config value is set in rest.php
This resolves the issue of the basic auth always being valid on every request.
---
application/config/rest.php | 1 +
application/libraries/REST_Controller.php | 42 +++++++++++++++++------
2 files changed, 33 insertions(+), 10 deletions(-)
diff --git a/application/config/rest.php b/application/config/rest.php
index deafeeb7..cdb92bf4 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -138,6 +138,7 @@
|
*/
$config['allow_auth_and_keys'] = TRUE;
+$config['strict_api_and_auth'] = TRUE; // force the use of both api and auth before a valid api request is made
/*
|--------------------------------------------------------------------------
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index d5c2b4f0..449bb747 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -335,6 +335,8 @@ abstract class REST_Controller extends CI_Controller {
* @var bool
*/
protected $_enable_xss = FALSE;
+
+ private $is_valid_request = TRUE;
/**
* HTTP status codes and their respective description
@@ -631,17 +633,19 @@ public function _remap($object_called, $arguments = [])
$this->config->item('rest_status_field_name') => FALSE,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported')
], self::HTTP_FORBIDDEN);
+
+ $this->is_valid_request = false;
}
// 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);
- }
+ // 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);
@@ -656,8 +660,8 @@ public function _remap($object_called, $arguments = [])
{
$this->_log_request();
}
-
- // fix cross site to option request error
+
+ // fix cross site to option request error
if($this->request->method == 'options') {
exit;
}
@@ -666,6 +670,8 @@ public function _remap($object_called, $arguments = [])
$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);
+
+ $this->is_valid_request = false;
}
// Check to see if this key has access to the requested controller
@@ -680,6 +686,8 @@ public function _remap($object_called, $arguments = [])
$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);
+
+ $this->is_valid_request = false;
}
// Sure it exists, but can they do anything with it?
@@ -689,6 +697,8 @@ public function _remap($object_called, $arguments = [])
$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);
+
+ $this->is_valid_request = false;
}
// Doing key related stuff? Can only do it if they have a key right?
@@ -699,6 +709,8 @@ public function _remap($object_called, $arguments = [])
{
$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);
+
+ $this->is_valid_request = false;
}
// If no level is set use 0, they probably aren't using permissions
@@ -716,6 +728,8 @@ public function _remap($object_called, $arguments = [])
// 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);
+
+ $this->is_valid_request = false;
}
}
@@ -724,6 +738,8 @@ public function _remap($object_called, $arguments = [])
{
$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);
+
+ $this->is_valid_request = false;
}
// No key stuff, but record that stuff is happening
@@ -735,7 +751,9 @@ public function _remap($object_called, $arguments = [])
// Call the controller method and passed arguments
try
{
- call_user_func_array([$this, $controller_method], $arguments);
+ if ($this->is_valid_request) {
+ call_user_func_array([$this, $controller_method], $arguments);
+ }
}
catch (Exception $ex)
{
@@ -744,8 +762,8 @@ public function _remap($object_called, $arguments = [])
}
// 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);
+ $_error = &load_class('Exceptions', 'core');
+ $_error->show_exception($ex);
}
}
@@ -2136,6 +2154,10 @@ protected function _force_login($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,
From cf49abe06096d46c971266ef5c7f3626c39400b6 Mon Sep 17 00:00:00 2001
From: Hanisch-IT
Date: Fri, 15 Sep 2017 17:38:02 +0200
Subject: [PATCH 038/129] Codeigniter Composer Ready (#832)
* First steps for composer ready. Try to load Config/Language from this library if not existing in CI project
* Add backward compatibility for Format
* Add backward compatibility for Format
* Add backward compatibility for Format
* Update Readme
Remove namespace for backward capability
* Update Readme
* Update readme
- add language / config section
---
README.md | 24 ++-
application/libraries/Format.php | 2 +-
application/libraries/REST_Controller.php | 211 +++++++++++++---------
composer.json | 14 +-
4 files changed, 159 insertions(+), 92 deletions(-)
diff --git a/README.md b/README.md
index 8943a5ce..5a9423d2 100644
--- a/README.md
+++ b/README.md
@@ -18,9 +18,19 @@ Please note that version 4.0.0 is in the works, and is considered a breaking cha
Take a look at the "development" branch to see what's up.
-## Installation
+## Installation & loading
-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.
+CodeIgniter Rest Server is available on [Packagist](https://packagist.org/packages/hanischit/kraken-api) (using semantic versioning), and installation via composer is the recommended way to install Kraken-api. Just add this line to your `composer.json` file:
+
+```json
+"chriskacerguis/codeigniter-restserver": "^3.0"
+```
+
+or run
+
+```sh
+composer require chriskacerguis/codeigniter-restserver
+```
## Handling Requests
@@ -118,6 +128,16 @@ If you don't specify a response code, and the data you respond with `== FALSE` (
$this->response([]); // HTTP 404 Not Found
```
+## Configuration
+
+You can overwrite all default configurations by creating a rest.php file in your config folder with your configs.
+All given configurations will overwrite the default ones.
+
+## Language
+
+You can overwrite all default language files. Just add a rest_controller_lang.php to your language and overwrite the what you want.
+
+
## 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:
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index b1405302..4b5ad3e6 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -378,7 +378,7 @@ public function to_csv($data = NULL, $delimiter = ',', $enclosure = '"')
// 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');
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 449bb747..7a1566aa 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -302,15 +302,15 @@ abstract class REST_Controller extends CI_Controller {
* @var array
*/
protected $_supported_formats = [
- 'json' => 'application/json',
- 'array' => 'application/json',
- 'csv' => 'application/csv',
- 'html' => 'text/html',
- 'jsonp' => 'application/javascript',
- 'php' => 'text/plain',
- 'serialized' => 'application/vnd.php.serialized',
- 'xml' => 'application/xml'
- ];
+ 'json' => 'application/json',
+ 'array' => 'application/json',
+ 'csv' => 'application/csv',
+ 'html' => 'text/html',
+ 'jsonp' => 'application/javascript',
+ 'php' => 'text/plain',
+ 'serialized' => 'application/vnd.php.serialized',
+ 'xml' => 'application/xml'
+ ];
/**
* Information about the current API user
@@ -335,7 +335,7 @@ abstract class REST_Controller extends CI_Controller {
* @var bool
*/
protected $_enable_xss = FALSE;
-
+
private $is_valid_request = TRUE;
/**
@@ -361,6 +361,15 @@ abstract class REST_Controller extends CI_Controller {
self::HTTP_NOT_IMPLEMENTED => 'NOT IMPLEMENTED'
];
+ /**
+ * @var Format
+ */
+ private $format;
+ /**
+ * @var bool
+ */
+ private $auth_override;
+
/**
* Extend this function to apply additional checking early on in the process
*
@@ -395,10 +404,18 @@ public function __construct($config = 'rest')
$this->_start_rtime = microtime(TRUE);
// Load the rest.php configuration file
- $this->load->config($config);
+ $this->get_local_config($config);
// At present the library is bundled with REST_Controller 2.5+, but will eventually be part of CodeIgniter (no citation)
- $this->load->library('format');
+ if(class_exists('Format'))
+ {
+ $this->format = new Format();
+ }
+ else
+ {
+ $this->load->library('format');
+ }
+
// Determine supported output formats from configuration
$supported_formats = $this->config->item('rest_supported_formats');
@@ -432,7 +449,7 @@ public function __construct($config = 'rest')
}
// Load the language file
- $this->lang->load('rest_controller', $language);
+ $this->lang->load('rest_controller', $language, FALSE, TRUE, __DIR__.'/../');
// Initialise the response, request and rest objects
$this->request = new stdClass();
@@ -477,7 +494,7 @@ public function __construct($config = 'rest')
$this->request->body = NULL;
$this->{'_parse_' . $this->request->method}();
-
+
// Fix parse method return arguments null
if($this->{'_'.$this->request->method.'_args'} === null)
{
@@ -544,15 +561,15 @@ public function __construct($config = 'rest')
{
// 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);
+ $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)))
+ ($this->config->item('allow_auth_and_keys') === TRUE && $this->_allow === TRUE)))
{
$rest_auth = strtolower($this->config->item('rest_auth'));
switch ($rest_auth)
@@ -574,6 +591,25 @@ public function __construct($config = 'rest')
}
}
+ /**
+ * @param $config_file
+ */
+ private function get_local_config($config_file)
+ {
+ if(file_exists(__DIR__."/../config/".$config_file.".php"))
+ {
+ $config = array();
+ include(__DIR__ . "/../config/" . $config_file . ".php");
+
+ foreach($config AS $key => $value)
+ {
+ $this->config->set_item($key, $value);
+ }
+ }
+
+ $this->load->config($config_file, FALSE, TRUE);
+ }
+
/**
* De-constructor
*
@@ -623,6 +659,7 @@ protected function preflight_checks()
* @access public
* @param string $object_called
* @param array $arguments The arguments passed to the controller method
+ * @throws Exception
*/
public function _remap($object_called, $arguments = [])
{
@@ -630,9 +667,9 @@ public function _remap($object_called, $arguments = [])
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);
+ $this->config->item('rest_status_field_name') => FALSE,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported')
+ ], self::HTTP_FORBIDDEN);
$this->is_valid_request = false;
}
@@ -641,11 +678,11 @@ public function _remap($object_called, $arguments = [])
$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);
- }
+ // 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);
@@ -667,9 +704,9 @@ public function _remap($object_called, $arguments = [])
}
$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);
+ $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);
$this->is_valid_request = false;
}
@@ -683,9 +720,9 @@ public function _remap($object_called, $arguments = [])
}
$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);
+ $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);
$this->is_valid_request = false;
}
@@ -694,9 +731,9 @@ public function _remap($object_called, $arguments = [])
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);
+ $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);
$this->is_valid_request = false;
}
@@ -762,8 +799,8 @@ public function _remap($object_called, $arguments = [])
}
// 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);
+ $_error = &load_class('Exceptions', 'core');
+ $_error->show_exception($ex);
}
}
@@ -778,7 +815,7 @@ public function _remap($object_called, $arguments = [])
*/
public function response($data = NULL, $http_code = NULL, $continue = FALSE)
{
- ob_start();
+ ob_start();
// If the HTTP status is not NULL, then cast as an integer
if ($http_code !== NULL)
{
@@ -847,10 +884,10 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
$this->output->_display();
exit;
}
- else
- {
- ob_end_flush();
- }
+ else
+ {
+ ob_end_flush();
+ }
// Otherwise dump the output automatically
}
@@ -1099,7 +1136,7 @@ protected function _detect_api_key()
* Preferred return language
*
* @access protected
- * @return string|NULL The language code
+ * @return string|NULL|array The language code
*/
protected function _detect_lang()
{
@@ -1177,28 +1214,28 @@ protected function _check_limit($controller_method)
switch ($this->config->item('rest_limits_method'))
{
- case 'IP_ADDRESS':
- $limited_uri = 'ip-address:' .$this->input->ip_address();
- $api_key = $this->input->ip_address();
- break;
+ case 'IP_ADDRESS':
+ $limited_uri = 'ip-address:' .$this->input->ip_address();
+ $api_key = $this->input->ip_address();
+ break;
- case 'API_KEY':
- $limited_uri = 'api-key:' . $api_key;
- break;
+ case 'API_KEY':
+ $limited_uri = 'api-key:' . $api_key;
+ break;
- case 'METHOD_NAME':
- $limited_uri = 'method-name:' . $controller_method;
- 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;
+ 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 )
@@ -1501,8 +1538,8 @@ protected function _parse_put()
}
else if ($this->input->method() === 'put')
{
- // If no file type is provided, then there are probably just arguments
- $this->_put_args = $this->input->input_stream();
+ // If no file type is provided, then there are probably just arguments
+ $this->_put_args = $this->input->input_stream();
}
}
@@ -1974,9 +2011,9 @@ protected function _check_php_session()
{
// 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);
+ $this->config->item('rest_status_field_name') => FALSE,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized')
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -2072,9 +2109,9 @@ protected function _prepare_digest_auth()
{
// 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);
+ $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);
}
}
@@ -2094,9 +2131,9 @@ protected function _check_blacklist_auth()
{
// 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);
+ $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);
}
}
@@ -2122,9 +2159,9 @@ protected function _check_whitelist_auth()
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);
+ $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);
}
}
@@ -2160,9 +2197,9 @@ protected function _force_login($nonce = '')
// 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);
+ $this->config->item('rest_status_field_name') => FALSE,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized')
+ ], self::HTTP_UNAUTHORIZED);
}
/**
@@ -2177,9 +2214,9 @@ protected function _log_access_time()
$payload['rtime'] = $this->_end_rtime - $this->_start_rtime;
return $this->rest->db->update(
- $this->config->item('rest_logs_table'), $payload, [
- 'id' => $this->_insert_id
- ]);
+ $this->config->item('rest_logs_table'), $payload, [
+ 'id' => $this->_insert_id
+ ]);
}
/**
@@ -2221,7 +2258,7 @@ protected function _check_access()
if (!empty($accessRow) && !empty($accessRow['all_access']))
{
- return TRUE;
+ return TRUE;
}
// Fetch controller based on path and controller name
@@ -2236,10 +2273,10 @@ protected function _check_access()
// Query the access table and get the number of results
return $this->rest->db
- ->where('key', $this->rest->key)
- ->where('controller', $controller)
- ->get($this->config->item('rest_access_table'))
- ->num_rows() > 0;
+ ->where('key', $this->rest->key)
+ ->where('controller', $controller)
+ ->get($this->config->item('rest_access_table'))
+ ->num_rows() > 0;
}
/**
diff --git a/composer.json b/composer.json
index a4d014d7..a4b9f670 100644
--- a/composer.json
+++ b/composer.json
@@ -1,9 +1,9 @@
{
"description": "REST Server for the CodeIgniter framework",
"name": "chriskacerguis/codeigniter-restserver",
- "type": "project",
+ "type": "library",
"homepage": "https://github.com/chriskacerguis/codeigniter-restserver",
- "authors": [
+ "authors": [
{
"name": "Chris Kacerguis",
"role": "Developer"
@@ -12,5 +12,15 @@
"license": "MIT",
"support": {
"source": "https://github.com/chriskacerguis/codeigniter-restserver"
+ },
+ "require": {
+ "php": ">=5.4.0",
+ "codeigniter/framework": "^3.0.4"
+ },
+ "autoload": {
+ "classmap": [
+ "application/libraries/Format.php",
+ "application/libraries/REST_Controller.php"
+ ]
}
}
\ No newline at end of file
From 27f26f093d37ab02ea420c0fbb2784cfa24dfbc4 Mon Sep 17 00:00:00 2001
From: Hanisch-IT
Date: Sat, 23 Sep 2017 03:11:53 +0200
Subject: [PATCH 039/129] Bugfix (#842)
- Fix: format initialization without composer
- Fix: Readme
---
README.md | 2 +-
application/libraries/REST_Controller.php | 3 ++-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 5a9423d2..c8cf8c0a 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,7 @@ Take a look at the "development" branch to see what's up.
## Installation & loading
-CodeIgniter Rest Server is available on [Packagist](https://packagist.org/packages/hanischit/kraken-api) (using semantic versioning), and installation via composer is the recommended way to install Kraken-api. Just add this line to your `composer.json` file:
+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:
```json
"chriskacerguis/codeigniter-restserver": "^3.0"
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 7a1566aa..e9a3023d 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -413,7 +413,8 @@ public function __construct($config = 'rest')
}
else
{
- $this->load->library('format');
+ $this->load->library('Format', NULL, 'libraryFormat');
+ $this->format = $this->libraryFormat;
}
From d3e39dbfd4d29d81e018396da0e5ea72ebd7face Mon Sep 17 00:00:00 2001
From: ganlei <769323213@qq.com>
Date: Fri, 22 Sep 2017 20:16:15 -0500
Subject: [PATCH 040/129] Fix: A Database Error Occurred when update logs
(_log_access_time and _log_response_code) (#830)
---
application/libraries/REST_Controller.php | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index e9a3023d..c797ab11 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2212,6 +2212,10 @@ protected function _force_login($nonce = '')
*/
protected function _log_access_time()
{
+ if($this->_insert_id == ''){
+ return false;
+ }
+
$payload['rtime'] = $this->_end_rtime - $this->_start_rtime;
return $this->rest->db->update(
@@ -2230,6 +2234,10 @@ protected function _log_access_time()
*/
protected function _log_response_code($http_code)
{
+ if($this->_insert_id == ''){
+ return false;
+ }
+
$payload['response_code'] = $http_code;
return $this->rest->db->update(
From 870a288f6570e4652d9b04909fe57b19e9f2de0e Mon Sep 17 00:00:00 2001
From: Hanisch-IT
Date: Sat, 23 Sep 2017 18:44:17 +0200
Subject: [PATCH 041/129] Bugfix/#844 ldap configuration (#847)
* Bugfix
- Fix: format initialization without composer
- Fix: Readme
* Bugfix: Make LDAP available
- Created missing config ldap.php
- Correct loading of config (remove .php)
---
application/config/ldap.php | 15 +++++++++++++++
application/libraries/REST_Controller.php | 2 +-
2 files changed, 16 insertions(+), 1 deletion(-)
create mode 100644 application/config/ldap.php
diff --git a/application/config/ldap.php b/application/config/ldap.php
new file mode 100644
index 00000000..e4165550
--- /dev/null
+++ b/application/config/ldap.php
@@ -0,0 +1,15 @@
+config->load('ldap.php', TRUE);
+ $this->config->load('ldap', TRUE);
$ldap = [
'timeout' => $this->config->item('timeout', 'ldap'),
From 3a5ba0dffdebd24cc215ef714b72208c88304203 Mon Sep 17 00:00:00 2001
From: Hanisch-IT
Date: Sat, 23 Sep 2017 18:44:55 +0200
Subject: [PATCH 042/129] Bugfix/#837 add http authorization (#848)
* Bugfix
- Fix: format initialization without composer
- Fix: Readme
* Make HTTP_AUTHORIZATION possible
- To hold backward compatibility HTTP_AUTHORIZATION and HTTP_AUTHANTICATION are possible
---
application/libraries/REST_Controller.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index bbb3dbc4..87a126ed 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2034,7 +2034,7 @@ protected function _prepare_basic_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');
+ $http_auth = $this->input->server('HTTP_AUTHENTICATION') ?: $this->input->server('HTTP_AUTHORIZATION');
$password = NULL;
if ($username !== NULL)
From 3cee80acab45804efca300a4f2030eb69b9a945b Mon Sep 17 00:00:00 2001
From: Hanisch-IT
Date: Mon, 25 Sep 2017 01:13:48 +0200
Subject: [PATCH 043/129] Issue #849 Adding AUTHORS.md (#850)
---
AUTHORS.md | 9 +++++++++
1 file changed, 9 insertions(+)
create mode 100644 AUTHORS.md
diff --git a/AUTHORS.md b/AUTHORS.md
new file mode 100644
index 00000000..0a41747e
--- /dev/null
+++ b/AUTHORS.md
@@ -0,0 +1,9 @@
+# The Core Team
+
+* [Chris Kacerguis](//github.com/chriskacerguis)
+
+### Special Thanks To
+
+* [Fabian Hanisch](//github.com/Hanisch-IT)
+
+*For a list of people who have contributed to the codebase, see [GitHub's list of contributors](https://github.com/chriskacerguis/codeigniter-restserver/graphs/contributors).*
\ No newline at end of file
From 3ec22ef11722b41653f21e4444af13ec13639b9f Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sun, 24 Sep 2017 18:15:15 -0500
Subject: [PATCH 044/129] added comment and Phil's name
---
AUTHORS.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/AUTHORS.md b/AUTHORS.md
index 0a41747e..4d281fc1 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -1,9 +1,10 @@
# The Core Team
* [Chris Kacerguis](//github.com/chriskacerguis)
+* [Phil Sturgeon] (https://github.com/philsturgeon)
### Special Thanks To
* [Fabian Hanisch](//github.com/Hanisch-IT)
-*For a list of people who have contributed to the codebase, see [GitHub's list of contributors](https://github.com/chriskacerguis/codeigniter-restserver/graphs/contributors).*
\ No newline at end of file
+*For a list of people who have contributed to the codebase, see [GitHub's list of contributors](https://github.com/chriskacerguis/codeigniter-restserver/graphs/contributors). Anyone who has contributed please do a PR and add to this file.*
From 3ba8186d941e3ae36c1e9fd484bd74bc36aa3855 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sun, 24 Sep 2017 18:15:34 -0500
Subject: [PATCH 045/129] fix typo
---
AUTHORS.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/AUTHORS.md b/AUTHORS.md
index 4d281fc1..ee3551f6 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -1,7 +1,7 @@
# The Core Team
* [Chris Kacerguis](//github.com/chriskacerguis)
-* [Phil Sturgeon] (https://github.com/philsturgeon)
+* [Phil Sturgeon](//github.com/philsturgeon)
### Special Thanks To
From 544f30b62a65ff81bc397c5077cd37b24102fff1 Mon Sep 17 00:00:00 2001
From: Zeeshan
Date: Wed, 4 Oct 2017 17:02:58 +0530
Subject: [PATCH 046/129] Profiling feature added to master (#855)
* Config,hook & default profiler parameters
Config,hook & default profiler parameters
* Added hook for profiler
Added hook for profiler
* check added for profiling enabled/disabled
check added for profiling enabled/disabled
* Rename file config.php to config.php.sample
Rename file config.php to config.php.sample
* Added profiling settings to readme
Added profiling settings to readme
---
README.md | 13 +
application/config/config.php.sample | 482 ++++++++++++++++++++++
application/config/hooks.php | 21 +
application/config/profiler.php | 26 ++
application/hooks/hooks.profiler.php | 18 +
application/libraries/REST_Controller.php | 157 +++----
6 files changed, 642 insertions(+), 75 deletions(-)
create mode 100644 application/config/config.php.sample
create mode 100644 application/config/hooks.php
create mode 100644 application/config/profiler.php
create mode 100644 application/hooks/hooks.profiler.php
diff --git a/README.md b/README.md
index c8cf8c0a..5eb82281 100644
--- a/README.md
+++ b/README.md
@@ -210,6 +210,19 @@ By default, the HTTP will be `X-API-KEY`. This can be configured in **config/res
```bash
$ curl -X POST -H "X-API-KEY: some_key_here" http://example.com/books
```
+## Profiling
+Codeigniter Profiler feature has been added to the library, so that you can use the power of CI profiler in your project just by setting config parameter to enable profile through out your application
+Turn it on in your **config/config.php** file:
+
+```php
+TRUE to turn profile ON, FALSE to turn it off
+$config['enable_profiling'] = FALSE;
+```
+Also you need to enable `hooks` in your config.php that looks like this
+```php
+$config['enable_hooks'] = TRUE;
+```
+Also you can refer to **config/config.php.sample**
## Other Documentation / Tutorials
diff --git a/application/config/config.php.sample b/application/config/config.php.sample
new file mode 100644
index 00000000..77411ce1
--- /dev/null
+++ b/application/config/config.php.sample
@@ -0,0 +1,482 @@
+]+$/i
+|
+| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
+|
+| Note: This option is ignored for CLI requests.
+|
+*/
+$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
+
+/*
+|--------------------------------------------------------------------------
+| Enable Query Strings
+|--------------------------------------------------------------------------
+|
+| By default CodeIgniter uses search-engine friendly segment based URLs:
+| example.com/who/what/where/
+|
+| You can optionally enable standard query string based URLs:
+| example.com?who=me&what=something&where=here
+|
+| Options are: TRUE or FALSE (boolean)
+|
+| The other items let you set the query string 'words' that will
+| invoke your controllers and its functions:
+| example.com/index.php?c=controller&m=function
+|
+| Please note that some of the helpers won't work as expected when
+| this feature is enabled, since CodeIgniter is designed primarily to
+| use segment based URLs.
+|
+*/
+$config['enable_query_strings'] = FALSE;
+$config['controller_trigger'] = 'c';
+$config['function_trigger'] = 'm';
+$config['directory_trigger'] = 'd';
+
+/*
+|--------------------------------------------------------------------------
+| Error Logging Threshold
+|--------------------------------------------------------------------------
+|
+| You can enable error logging by setting a threshold over zero. The
+| threshold determines what gets logged. Threshold options are:
+|
+| 0 = Disables logging, Error logging TURNED OFF
+| 1 = Error Messages (including PHP errors)
+| 2 = Debug Messages
+| 3 = Informational Messages
+| 4 = All Messages
+|
+| You can also pass an array with threshold levels to show individual error types
+|
+| array(2) = Debug Messages, without Error Messages
+|
+| For a live site you'll usually only enable Errors (1) to be logged otherwise
+| your log files will fill up very fast.
+|
+*/
+$config['log_threshold'] = 0;
+
+/*
+|--------------------------------------------------------------------------
+| Error Logging Directory Path
+|--------------------------------------------------------------------------
+|
+| Leave this BLANK unless you would like to set something other than the default
+| application/logs/ directory. Use a full server path.
+|
+*/
+$config['log_path'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| Log File Extension
+|--------------------------------------------------------------------------
+|
+| The default filename extension for log files. The default 'php' allows for
+| protecting the log files via basic scripting, when they are to be stored
+| under a publicly accessible directory.
+|
+| Note: Leaving it blank will default to 'php'.
+|
+*/
+$config['log_file_extension'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| Log File Permissions
+|--------------------------------------------------------------------------
+|
+| The file system permissions to be applied on newly created log files.
+|
+| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
+| integer notation (i.e. 0700, 0644, etc.)
+*/
+$config['log_file_permissions'] = 0644;
+
+/*
+|--------------------------------------------------------------------------
+| Date Format for Logs
+|--------------------------------------------------------------------------
+|
+| Each item that is logged has an associated date. You can use PHP date
+| codes to set your own date formatting
+|
+*/
+$config['log_date_format'] = 'Y-m-d H:i:s';
+
+/*
+|--------------------------------------------------------------------------
+| Error Views Directory Path
+|--------------------------------------------------------------------------
+|
+| Leave this BLANK unless you would like to set something other than the default
+| application/views/errors/ directory. Use a full server path.
+|
+*/
+$config['error_views_path'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| Cache Directory Path
+|--------------------------------------------------------------------------
+|
+| Leave this BLANK unless you would like to set something other than the default
+| application/cache/ directory. Use a full server path.
+|
+*/
+$config['cache_path'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| Cache Include Query String
+|--------------------------------------------------------------------------
+|
+| Whether to take the URL query string into consideration when generating
+| output cache files. Valid options are:
+|
+| FALSE = Disabled
+| TRUE = Enabled, take all query parameters into account.
+| Please be aware that this may result in numerous cache
+| files generated for the same page over and over again.
+| array('q') = Enabled, but only take into account the specified list
+| of query parameters.
+|
+*/
+$config['cache_query_string'] = FALSE;
+
+/*
+|--------------------------------------------------------------------------
+| Encryption Key
+|--------------------------------------------------------------------------
+|
+| If you use the Encryption class, you must set an encryption key.
+| See the user guide for more info.
+|
+| https://codeigniter.com/user_guide/libraries/encryption.html
+|
+*/
+$config['encryption_key'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| Session Variables
+|--------------------------------------------------------------------------
+|
+| 'sess_driver'
+|
+| The storage driver to use: files, database, redis, memcached
+|
+| 'sess_cookie_name'
+|
+| The session cookie name, must contain only [0-9a-z_-] characters
+|
+| 'sess_expiration'
+|
+| The number of SECONDS you want the session to last.
+| Setting to 0 (zero) means expire when the browser is closed.
+|
+| 'sess_save_path'
+|
+| The location to save sessions to, driver dependent.
+|
+| For the 'files' driver, it's a path to a writable directory.
+| WARNING: Only absolute paths are supported!
+|
+| For the 'database' driver, it's a table name.
+| Please read up the manual for the format with other session drivers.
+|
+| IMPORTANT: You are REQUIRED to set a valid save path!
+|
+| 'sess_match_ip'
+|
+| Whether to match the user's IP address when reading the session data.
+|
+| WARNING: If you're using the database driver, don't forget to update
+| your session table's PRIMARY KEY when changing this setting.
+|
+| 'sess_time_to_update'
+|
+| How many seconds between CI regenerating the session ID.
+|
+| 'sess_regenerate_destroy'
+|
+| Whether to destroy session data associated with the old session ID
+| when auto-regenerating the session ID. When set to FALSE, the data
+| will be later deleted by the garbage collector.
+|
+| Other session cookie settings are shared with the rest of the application,
+| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
+|
+*/
+$config['sess_driver'] = 'files';
+$config['sess_cookie_name'] = 'ci_session';
+$config['sess_expiration'] = 7200;
+$config['sess_save_path'] = NULL;
+$config['sess_match_ip'] = FALSE;
+$config['sess_time_to_update'] = 300;
+$config['sess_regenerate_destroy'] = FALSE;
+
+/*
+|--------------------------------------------------------------------------
+| Cookie Related Variables
+|--------------------------------------------------------------------------
+|
+| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
+| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
+| 'cookie_path' = Typically will be a forward slash
+| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
+| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
+|
+| Note: These settings (with the exception of 'cookie_prefix' and
+| 'cookie_httponly') will also affect sessions.
+|
+*/
+$config['cookie_prefix'] = '';
+$config['cookie_domain'] = '';
+$config['cookie_path'] = '/';
+$config['cookie_secure'] = FALSE;
+$config['cookie_httponly'] = FALSE;
+
+/*
+|--------------------------------------------------------------------------
+| Cross Site Request Forgery
+|--------------------------------------------------------------------------
+| Enables a CSRF cookie token to be set. When set to TRUE, token will be
+| checked on a submitted form. If you are accepting user data, it is strongly
+| recommended CSRF protection be enabled.
+|
+| 'csrf_token_name' = The token name
+| 'csrf_cookie_name' = The cookie name
+| 'csrf_expire' = The number in seconds the token should expire.
+| 'csrf_regenerate' = Regenerate token on every submission
+| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
+*/
+$config['csrf_protection'] = FALSE;
+$config['csrf_token_name'] = 'csrf_test_name';
+$config['csrf_cookie_name'] = 'csrf_cookie_name';
+$config['csrf_expire'] = 7200;
+$config['csrf_regenerate'] = TRUE;
+$config['csrf_exclude_uris'] = array();
+
+/*
+|--------------------------------------------------------------------------
+| Output Compression
+|--------------------------------------------------------------------------
+|
+| Enables Gzip output compression for faster page loads. When enabled,
+| the output class will test whether your server supports Gzip.
+| Even if it does, however, not all browsers support compression
+| so enable only if you are reasonably sure your visitors can handle it.
+|
+| Only used if zlib.output_compression is turned off in your php.ini.
+| Please do not use it together with httpd-level output compression.
+|
+| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
+| means you are prematurely outputting something to your browser. It could
+| even be a line of whitespace at the end of one of your scripts. For
+| compression to work, nothing can be sent before the output buffer is called
+| by the output class. Do not 'echo' any values with compression enabled.
+|
+*/
+$config['compress_output'] = FALSE;
+
+/*
+|--------------------------------------------------------------------------
+| Master Time Reference
+|--------------------------------------------------------------------------
+|
+| Options are 'local' or any PHP supported timezone. This preference tells
+| the system whether to use your server's local time as the master 'now'
+| reference, or convert it to the configured one timezone. See the 'date
+| helper' page of the user guide for information regarding date handling.
+|
+*/
+$config['time_reference'] = 'local';
+
+/*
+|--------------------------------------------------------------------------
+| Reverse Proxy IPs
+|--------------------------------------------------------------------------
+|
+| If your server is behind a reverse proxy, you must whitelist the proxy
+| IP addresses from which CodeIgniter should trust headers such as
+| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
+| the visitor's IP address.
+|
+| You can use both an array or a comma-separated list of proxy addresses,
+| as well as specifying whole subnets. Here are a few examples:
+|
+| Comma-separated: '10.0.1.200,192.168.5.0/24'
+| Array: array('10.0.1.200', '192.168.5.0/24')
+*/
+$config['proxy_ips'] = '';
diff --git a/application/config/hooks.php b/application/config/hooks.php
new file mode 100644
index 00000000..7268904b
--- /dev/null
+++ b/application/config/hooks.php
@@ -0,0 +1,21 @@
+ 'ProfilerEnabler',
+ 'function' => 'enableProfiler',
+ 'filename' => 'hooks.profiler.php',
+ 'filepath' => 'hooks',
+ 'params' => array()
+);
\ No newline at end of file
diff --git a/application/config/profiler.php b/application/config/profiler.php
new file mode 100644
index 00000000..ce026a7e
--- /dev/null
+++ b/application/config/profiler.php
@@ -0,0 +1,26 @@
+output->enable_profiler( config_item('enable_profiling') );
+ }
+}
+?>
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 87a126ed..b6055c6b 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -816,81 +816,88 @@ public function _remap($object_called, $arguments = [])
*/
public function response($data = NULL, $http_code = NULL, $continue = FALSE)
{
- ob_start();
- // If the HTTP status is not NULL, then cast as an integer
- if ($http_code !== NULL)
- {
- // So as to be safe later on in the process
- $http_code = (int) $http_code;
- }
-
- // Set the output as NULL by default
- $output = NULL;
-
- // If data is NULL and no HTTP status code provided, then display, error and exit
- if ($data === NULL && $http_code === NULL)
- {
- $http_code = self::HTTP_NOT_FOUND;
- }
-
- // If data is not NULL and a HTTP status code provided, then continue
- elseif ($data !== NULL)
- {
- // If the format method exists, call and return the output in that format
- if (method_exists($this->format, 'to_' . $this->response->format))
- {
- // Set the format header
- $this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
- $output = $this->format->factory($data)->{'to_' . $this->response->format}();
-
- // 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 = $this->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 = $this->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
- {
- ob_end_flush();
- }
-
- // Otherwise dump the output automatically
+ //if profiling enabled then print profiling data
+ $isProfilingEnabled = $this->config->item('enable_profiling');
+ if(!$isProfilingEnabled){
+ ob_start();
+ // If the HTTP status is not NULL, then cast as an integer
+ if ($http_code !== NULL)
+ {
+ // So as to be safe later on in the process
+ $http_code = (int) $http_code;
+ }
+
+ // Set the output as NULL by default
+ $output = NULL;
+
+ // If data is NULL and no HTTP status code provided, then display, error and exit
+ if ($data === NULL && $http_code === NULL)
+ {
+ $http_code = self::HTTP_NOT_FOUND;
+ }
+
+ // If data is not NULL and a HTTP status code provided, then continue
+ elseif ($data !== NULL)
+ {
+ // If the format method exists, call and return the output in that format
+ if (method_exists($this->format, 'to_' . $this->response->format))
+ {
+ // Set the format header
+ $this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
+ $output = $this->format->factory($data)->{'to_' . $this->response->format}();
+
+ // 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 = $this->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 = $this->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
+ {
+ ob_end_flush();
+ }
+
+ // Otherwise dump the output automatically
+ }
+ else{
+ echo json_encode($data);
+ }
}
/**
From cffc5904c625a22638852d53405096120b03898c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?J=C3=BAlio=20Sebasti=C3=A3o?=
Date: Fri, 6 Oct 2017 15:58:45 +0100
Subject: [PATCH 047/129] special chars encoding (#858)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Special chars, such as "ç" and "ã", that are abundant in my language (portuguese) were being transformed into strange things. with this change, they're showing up just right...
---
application/libraries/Format.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index 4b5ad3e6..60a83a35 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -406,21 +406,21 @@ public function to_json($data = NULL)
if (empty($callback) === TRUE)
{
- return json_encode($data);
+ 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).');';
+ 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);
+ return json_encode($data, JSON_UNESCAPED_UNICODE);
}
/**
From 60fcb7d08d6e30ad82218cd18e7f1b688b83b706 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Fri, 17 Nov 2017 20:48:15 -0600
Subject: [PATCH 048/129] added sponsor to readme
---
README.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/README.md b/README.md
index 5eb82281..49ffec65 100644
--- a/README.md
+++ b/README.md
@@ -237,3 +237,9 @@ Pull Requests are the best way to fix bugs or add features. I know loads of you
contribute if you have improvements to be made and I'll keep releasing versions over time.
[](https://raw.githubusercontent.com/chriskacerguis/codeigniter-restserver/master/LICENSE)
+
+## Sponsor
+
+
+
+
From 96b921db16f3a51fe782dbf4533fa17741687886 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 25 Nov 2017 10:56:44 -0600
Subject: [PATCH 049/129] remove sponsors
---
README.md | 6 ------
1 file changed, 6 deletions(-)
diff --git a/README.md b/README.md
index 49ffec65..5eb82281 100644
--- a/README.md
+++ b/README.md
@@ -237,9 +237,3 @@ Pull Requests are the best way to fix bugs or add features. I know loads of you
contribute if you have improvements to be made and I'll keep releasing versions over time.
[](https://raw.githubusercontent.com/chriskacerguis/codeigniter-restserver/master/LICENSE)
-
-## Sponsor
-
-
-
-
From 9791010d18d324638a36026c226f76a291068e38 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 25 Nov 2017 10:57:09 -0600
Subject: [PATCH 050/129] remove unneeded badge
---
README.md | 2 --
1 file changed, 2 deletions(-)
diff --git a/README.md b/README.md
index 5eb82281..d192d4ae 100644
--- a/README.md
+++ b/README.md
@@ -235,5 +235,3 @@ as he is no longer using it. As of 2013/11/20 further development and support w
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.
-
-[](https://raw.githubusercontent.com/chriskacerguis/codeigniter-restserver/master/LICENSE)
From 5a4467bfcc217497a56a649600d10737a8fdb31e Mon Sep 17 00:00:00 2001
From: Petko Bossakov
Date: Tue, 27 Feb 2018 23:34:26 +0200
Subject: [PATCH 051/129] bugfix: if the check_cors and rest_enable_logging
options are both enabled, an OPTIONS request will cause a fatal error (#882)
---
application/libraries/REST_Controller.php | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index b6055c6b..17c35388 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2336,6 +2336,11 @@ protected function _check_cors()
// 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;
}
}
From 0ad0310056756e88f8d328d65b2744e9cbc48762 Mon Sep 17 00:00:00 2001
From: Juan Manuel Herrera Carrera
Date: Tue, 27 Feb 2018 15:34:50 -0600
Subject: [PATCH 052/129] update translate (#871)
i translate the todo line, and put some changes in a words of the service, I hope it helps, thanks.
---
application/language/spanish/rest_controller_lang.php | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/application/language/spanish/rest_controller_lang.php b/application/language/spanish/rest_controller_lang.php
index 2ca81056..d96c62bc 100644
--- a/application/language/spanish/rest_controller_lang.php
+++ b/application/language/spanish/rest_controller_lang.php
@@ -4,15 +4,15 @@
* Spanish language
*/
-$lang['text_rest_invalid_api_key'] = 'API key %s No valida'; // %s is the REST API key
-$lang['text_rest_invalid_credentials'] = 'Credenciales Invalidas';
+$lang['text_rest_invalid_api_key'] = 'API key %s No válida'; // %s is the REST API key
+$lang['text_rest_invalid_credentials'] = 'Credenciales Inválidas';
$lang['text_rest_ip_denied'] = 'IP denegada';
$lang['text_rest_ip_unauthorized'] = 'IP no autorizada';
$lang['text_rest_unauthorized'] = 'Acceso no autorizado';
-$lang['text_rest_ajax_only'] = 'Solo peticiones ajax permitidas';
+$lang['text_rest_ajax_only'] = 'Sólo peticiones ajax permitidas';
$lang['text_rest_api_key_unauthorized'] = 'Esta clave de API no tiene acceso al controlador solicitado';
$lang['text_rest_api_key_permissions'] = 'Esta clave de API no tiene suficientes permisos';
$lang['text_rest_api_key_time_limit'] = 'Esta clave de API ha alcanzado el límite de tiempo para este método';
-$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
-$lang['text_rest_unknown_method'] = 'método desconocido';
+$lang['text_rest_ip_address_time_limit'] = 'Esta dirección IP ha alcanzado el límite de tiempo para este método';//todo translate
+$lang['text_rest_unknown_method'] = 'Método desconocido';
$lang['text_rest_unsupported'] = 'Protocolo no soportado';
From 579885ac21123ecfe007de46f6686a584a198ec2 Mon Sep 17 00:00:00 2001
From: Jason Gegere
Date: Tue, 27 Feb 2018 15:35:31 -0600
Subject: [PATCH 053/129] load rest config, correct missing vars - Migrations
(#820) (#897)
---
application/migrations/20170706030520_create_table_api_keys.php | 1 +
application/migrations/20170706031435_create_table_api_logs.php | 1 +
.../migrations/20170706032133_create_table_api_access.php | 1 +
.../migrations/20170706032825_create_table_api_limits.php | 1 +
4 files changed, 4 insertions(+)
diff --git a/application/migrations/20170706030520_create_table_api_keys.php b/application/migrations/20170706030520_create_table_api_keys.php
index d579614d..8c3954d8 100644
--- a/application/migrations/20170706030520_create_table_api_keys.php
+++ b/application/migrations/20170706030520_create_table_api_keys.php
@@ -15,6 +15,7 @@ class Migration_create_table_api_keys extends CI_Migration {
public function up()
{
+ $this->config->load('rest');
$table = config_item('rest_keys_table');
$fields = array(
'id' => [
diff --git a/application/migrations/20170706031435_create_table_api_logs.php b/application/migrations/20170706031435_create_table_api_logs.php
index bb52b866..03d6a567 100644
--- a/application/migrations/20170706031435_create_table_api_logs.php
+++ b/application/migrations/20170706031435_create_table_api_logs.php
@@ -15,6 +15,7 @@ class Migration_create_table_api_logs extends CI_Migration {
public function up()
{
+ $this->config->load('rest');
$table = config_item('rest_logs_table');
$fields = array(
'id' => [
diff --git a/application/migrations/20170706032133_create_table_api_access.php b/application/migrations/20170706032133_create_table_api_access.php
index ac863756..c78cbe3f 100644
--- a/application/migrations/20170706032133_create_table_api_access.php
+++ b/application/migrations/20170706032133_create_table_api_access.php
@@ -15,6 +15,7 @@ class Migration_create_table_api_access extends CI_Migration {
public function up()
{
+ $this->config->load('rest');
$table = config_item('rest_access_table');
$fields = array(
'id' => [
diff --git a/application/migrations/20170706032825_create_table_api_limits.php b/application/migrations/20170706032825_create_table_api_limits.php
index fdbff1ff..28f211bd 100644
--- a/application/migrations/20170706032825_create_table_api_limits.php
+++ b/application/migrations/20170706032825_create_table_api_limits.php
@@ -15,6 +15,7 @@ class Migration_create_table_api_limits extends CI_Migration {
public function up()
{
+ $this->config->load('rest');
$table = config_item('rest_limits_table');
$fields = array(
'id' => [
From 2c1c621ca79ff91a4a3f5bbe1c7aa6748b56ad27 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mattias=20Sandstr=C3=B6m?=
<1013635+tangix@users.noreply.github.com>
Date: Thu, 8 Mar 2018 20:39:58 +0100
Subject: [PATCH 054/129] Add config to force CORS pre-flight headers to be
included (#886)
* Added config option to force setting of CORS pre-flight headers.
* Updated the setting to be empty by default and updated the comment.
---
application/config/rest.php | 21 +++++++++++++++++++++
application/libraries/REST_Controller.php | 9 +++++++++
2 files changed, 30 insertions(+)
diff --git a/application/config/rest.php b/application/config/rest.php
index cdb92bf4..18327360 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -604,3 +604,24 @@
|
*/
$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'] = [];
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 17c35388..dfacaabf 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2333,6 +2333,15 @@ protected function _check_cors()
}
}
+ // 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')
{
From d70785d802a6361d268c7165f37b8cdf7d8b09e1 Mon Sep 17 00:00:00 2001
From: _bolek_
Date: Sat, 2 Jun 2018 22:50:51 +0200
Subject: [PATCH 055/129] Update composer.json (#922)
Thanks to this namespace will work for classes (with few changens in Format.php and Rest_controller.php)
---
composer.json | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/composer.json b/composer.json
index a4b9f670..637f86f8 100644
--- a/composer.json
+++ b/composer.json
@@ -21,6 +21,9 @@
"classmap": [
"application/libraries/Format.php",
"application/libraries/REST_Controller.php"
- ]
+ ],
+ "psr-4" : {
+ "Restserver\\Libraries\\" : "application/libraries/"
+ }
}
-}
\ No newline at end of file
+}
From d03f6141794fbf8ee1e011f24090ddbae9530fb1 Mon Sep 17 00:00:00 2001
From: _bolek_
Date: Sat, 2 Jun 2018 22:51:08 +0200
Subject: [PATCH 056/129] Patch 2 (#923)
* Update Format.php
Allow access to class witch USE statement
* Update Format.php
Remove notification "Non-static method ... should not be called statically"
---
application/libraries/Format.php | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
index 60a83a35..5ecb63f7 100644
--- a/application/libraries/Format.php
+++ b/application/libraries/Format.php
@@ -1,4 +1,6 @@
Date: Sat, 2 Jun 2018 22:51:34 +0200
Subject: [PATCH 057/129] Update REST_Controller.php (#924)
Support for namespece
---
application/libraries/REST_Controller.php | 36 +++++++++++++----------
1 file changed, 21 insertions(+), 15 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index dfacaabf..8c7501df 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1,5 +1,10 @@
get_local_config($config);
// At present the library is bundled with REST_Controller 2.5+, but will eventually be part of CodeIgniter (no citation)
- if(class_exists('Format'))
- {
- $this->format = new Format();
- }
- else
- {
- $this->load->library('Format', NULL, 'libraryFormat');
- $this->format = $this->libraryFormat;
- }
+ //if(class_exists('Format'))
+ //{
+ // $this->format = new Format();
+ //}
+ //else
+ //{
+ // $this->load->library('Format', NULL, 'libraryFormat');
+ // $this->format = $this->libraryFormat;
+ //}
// Determine supported output formats from configuration
@@ -505,8 +510,9 @@ public function __construct($config = 'rest')
// 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->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;
}
@@ -840,17 +846,17 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
elseif ($data !== NULL)
{
// If the format method exists, call and return the output in that format
- if (method_exists($this->format, 'to_' . $this->response->format))
+ if (method_exists(Format::class, 'to_' . $this->response->format))
{
// Set the format header
$this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
- $output = $this->format->factory($data)->{'to_' . $this->response->format}();
+ $output = Format::factory($data)->{'to_' . $this->response->format}();
// 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 = $this->format->factory($output)->{'to_json'}();
+ $output = Format::factory($output)->{'to_json'}();
}
}
else
@@ -858,7 +864,7 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
// If an array or object, then parse as a json, so as to be a 'string'
if (is_array($data) || is_object($data))
{
- $data = $this->format->factory($data)->{'to_json'}();
+ $data = Format::factory($data)->{'to_json'}();
}
// Format is not supported, so output the raw data as a string
From bc73533a57c14c2973aa359b74d5e612da328512 Mon Sep 17 00:00:00 2001
From: _bolek_
Date: Sat, 2 Jun 2018 22:51:47 +0200
Subject: [PATCH 058/129] Update Example.php (#925)
---
application/controllers/api/Example.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
index eb2f9069..7978ce4c 100644
--- a/application/controllers/api/Example.php
+++ b/application/controllers/api/Example.php
@@ -1,10 +1,10 @@
Date: Sat, 2 Jun 2018 22:52:25 +0200
Subject: [PATCH 059/129] Update Key.php (#926)
---
application/controllers/api/Key.php | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/application/controllers/api/Key.php b/application/controllers/api/Key.php
index 547334b6..8f3a64b4 100644
--- a/application/controllers/api/Key.php
+++ b/application/controllers/api/Key.php
@@ -1,10 +1,11 @@
Date: Tue, 31 Jul 2018 01:42:13 +0300
Subject: [PATCH 060/129] Patch 1 (#939)
* Update Example.php
Fix File REST_Controller not found problem
* Update REST_Controller.php
Class 'Restserver\Libraries\CI_Controller' not found
---
application/controllers/api/Example.php | 4 +++-
application/libraries/REST_Controller.php | 2 +-
2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
index 7978ce4c..9bc3a828 100644
--- a/application/controllers/api/Example.php
+++ b/application/controllers/api/Example.php
@@ -4,7 +4,9 @@
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
-//require APPPATH . 'libraries/REST_Controller.php';
+//To Solve File REST_Controller not found
+require APPPATH . 'libraries/REST_Controller.php';
+require APPPATH . 'libraries/Format.php';
/**
* This is an example of a few basic user interaction methods you could use
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 8c7501df..5dda5564 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1,7 +1,7 @@
Date: Thu, 20 Sep 2018 05:59:31 -1000
Subject: [PATCH 061/129] Move output format detection upwards (#947)
to allow responses earlier,
i.e. when handling exceptions, which might be thrown in Format::factory, in a REST_Controller subclass.
---
application/libraries/REST_Controller.php | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 5dda5564..13f79ef4 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -507,6 +507,12 @@ public function __construct($config = 'rest')
$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)
{
@@ -531,12 +537,6 @@ public function __construct($config = 'rest')
$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();
-
// Extend this function to apply additional checking early on in the process
$this->early_checks();
From d51e373ff151e3b7ed1aefbb6addb40fcedfaf17 Mon Sep 17 00:00:00 2001
From: "Januri D. P"
Date: Fri, 9 Nov 2018 19:33:01 +0700
Subject: [PATCH 062/129] Update rest_controller_lang.php (#955)
---
application/language/indonesia/rest_controller_lang.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/language/indonesia/rest_controller_lang.php b/application/language/indonesia/rest_controller_lang.php
index 771c6835..9931e18b 100644
--- a/application/language/indonesia/rest_controller_lang.php
+++ b/application/language/indonesia/rest_controller_lang.php
@@ -1,7 +1,7 @@
Date: Tue, 1 Jan 2019 10:45:39 +0800
Subject: [PATCH 063/129] Enhance: log execute time (#965)
---
application/libraries/REST_Controller.php | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 13f79ef4..0e936788 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -405,8 +405,12 @@ public function __construct($config = 'rest')
// when output is displayed for not damaging data accidentally
$this->output->parse_exec_vars = FALSE;
- // Start the timer for how long the request takes
- $this->_start_rtime = microtime(TRUE);
+ // 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);
+ }
// Load the rest.php configuration file
$this->get_local_config($config);
@@ -626,12 +630,12 @@ private function get_local_config($config_file)
*/
public function __destruct()
{
- // Get the current timestamp
- $this->_end_rtime = microtime(TRUE);
-
// 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();
}
}
From 5877df4599967d893e19bc1957cc1a9c5618c245 Mon Sep 17 00:00:00 2001
From: Mofasa
Date: Tue, 1 Jan 2019 10:46:17 +0800
Subject: [PATCH 064/129] Enhance: redundant _check_whitelist_auth checking
(#966)
---
application/libraries/REST_Controller.php | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 0e936788..256f16e2 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -595,10 +595,6 @@ public function __construct($config = 'rest')
$this->_check_php_session();
break;
}
- if ($this->config->item('rest_ip_whitelist_enabled') === TRUE)
- {
- $this->_check_whitelist_auth();
- }
}
}
@@ -2021,6 +2017,12 @@ protected function _check_login($username = NULL, $password = FALSE)
*/
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();
+ }
+
// Get the auth_source config item
$key = $this->config->item('auth_source');
From 3b82afc9afb8134e4e7be789a370cf1cc2068a17 Mon Sep 17 00:00:00 2001
From: Mofasa
Date: Tue, 1 Jan 2019 10:46:45 +0800
Subject: [PATCH 065/129] Enhance: no need to access db check twice (#967)
---
application/libraries/REST_Controller.php | 28 ++++++++++-------------
1 file changed, 12 insertions(+), 16 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 256f16e2..3c83ae03 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2279,16 +2279,6 @@ protected function _check_access()
return TRUE;
}
- //check if the key has all_access
- $accessRow = $this->rest->db
- ->where('key', $this->rest->key)
- ->get($this->config->item('rest_access_table'))->row_array();
-
- if (!empty($accessRow) && !empty($accessRow['all_access']))
- {
- return TRUE;
- }
-
// Fetch controller based on path and controller name
$controller = implode(
'/', [
@@ -2299,12 +2289,18 @@ protected function _check_access()
// Remove any double slashes for safety
$controller = str_replace('//', '/', $controller);
- // Query the access table and get the number of results
- return $this->rest->db
- ->where('key', $this->rest->key)
- ->where('controller', $controller)
- ->get($this->config->item('rest_access_table'))
- ->num_rows() > 0;
+ //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;
}
/**
From aca82471a2406e05ff846b2140a89342967c5f17 Mon Sep 17 00:00:00 2001
From: Mofasa
Date: Tue, 1 Jan 2019 10:47:27 +0800
Subject: [PATCH 066/129] Remove death code (#968)
---
application/libraries/REST_Controller.php | 14 --------------
1 file changed, 14 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 3c83ae03..06d915b8 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -677,8 +677,6 @@ public function _remap($object_called, $arguments = [])
$this->config->item('rest_status_field_name') => FALSE,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported')
], self::HTTP_FORBIDDEN);
-
- $this->is_valid_request = false;
}
// Remove the supported format from the function name e.g. index.json => index
@@ -714,8 +712,6 @@ public function _remap($object_called, $arguments = [])
$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);
-
- $this->is_valid_request = false;
}
// Check to see if this key has access to the requested controller
@@ -730,8 +726,6 @@ public function _remap($object_called, $arguments = [])
$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);
-
- $this->is_valid_request = false;
}
// Sure it exists, but can they do anything with it?
@@ -741,8 +735,6 @@ public function _remap($object_called, $arguments = [])
$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);
-
- $this->is_valid_request = false;
}
// Doing key related stuff? Can only do it if they have a key right?
@@ -753,8 +745,6 @@ public function _remap($object_called, $arguments = [])
{
$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);
-
- $this->is_valid_request = false;
}
// If no level is set use 0, they probably aren't using permissions
@@ -772,8 +762,6 @@ public function _remap($object_called, $arguments = [])
// 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);
-
- $this->is_valid_request = false;
}
}
@@ -782,8 +770,6 @@ public function _remap($object_called, $arguments = [])
{
$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);
-
- $this->is_valid_request = false;
}
// No key stuff, but record that stuff is happening
From 03383563745de74b792b577ba6d5020f9638604e Mon Sep 17 00:00:00 2001
From: Mofasa
Date: Tue, 1 Jan 2019 10:48:02 +0800
Subject: [PATCH 067/129] minus enhancement (#969)
---
application/libraries/REST_Controller.php | 11 ++++++-----
1 file changed, 6 insertions(+), 5 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 06d915b8..bfa4a4a2 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1104,11 +1104,12 @@ protected function _detect_api_key()
{
// 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 $ip_address)
{
- if ($this->input->ip_address() === trim($ip_address))
+ if ($ip_address === trim($ip_address))
{
// there is a match, set the the value to TRUE and break out of the loop
$found_address = TRUE;
@@ -1215,8 +1216,8 @@ protected function _check_limit($controller_method)
switch ($this->config->item('rest_limits_method'))
{
case 'IP_ADDRESS':
- $limited_uri = 'ip-address:' .$this->input->ip_address();
$api_key = $this->input->ip_address();
+ $limited_uri = 'ip-address:' . $api_key;
break;
case 'API_KEY':
@@ -2181,14 +2182,14 @@ protected function _check_whitelist_auth()
*/
protected function _force_login($nonce = '')
{
- $rest_auth = $this->config->item('rest_auth');
+ $rest_auth = strtolower($this->config->item('rest_auth'));
$rest_realm = $this->config->item('rest_realm');
- if (strtolower($rest_auth) === 'basic')
+ if ($rest_auth === 'basic')
{
// See http://tools.ietf.org/html/rfc2617#page-5
header('WWW-Authenticate: Basic realm="'.$rest_realm.'"');
}
- elseif (strtolower($rest_auth) === 'digest')
+ elseif ($rest_auth === 'digest')
{
// See http://tools.ietf.org/html/rfc2617#page-18
header(
From f3ba7d76cb14c11602f72b432926a17b8ff7c590 Mon Sep 17 00:00:00 2001
From: Mofasa
Date: Mon, 7 Jan 2019 12:50:14 +0800
Subject: [PATCH 068/129] bugfix
---
application/libraries/REST_Controller.php | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index bfa4a4a2..2691aff7 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2102,8 +2102,7 @@ protected function _prepare_digest_auth()
$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 (array_key_exists('username', $digest) === FALSE || $username === FALSE)
+ if (isset($digest['username']) === FALSE || $this->_check_login($digest['username'], TRUE) === FALSE)
{
$this->_force_login($unique_id);
}
From 570d4579c4ccfeeacc6204f421616ce364fbafe2 Mon Sep 17 00:00:00 2001
From: B0mb3tt4
Date: Tue, 15 Jan 2019 23:56:24 +0100
Subject: [PATCH 069/129] MD5 Response fix
---
application/libraries/REST_Controller.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 2691aff7..2363cfc4 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -2108,7 +2108,7 @@ protected function _prepare_digest_auth()
}
$md5 = md5(strtoupper($this->request->method).':'.$digest['uri']);
- $valid_response = md5($username.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$md5);
+ $valid_response = md5($digest['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)
From 359c2f84503b67eec0863cfc38848e5ab5ae74d4 Mon Sep 17 00:00:00 2001
From: rsmnarts <40693945+rsmnarts@users.noreply.github.com>
Date: Wed, 20 Feb 2019 13:25:03 +0700
Subject: [PATCH 070/129] rename $this->method to $this-methods
---
application/config/rest.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/config/rest.php b/application/config/rest.php
index 18327360..109cb671 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -483,7 +483,7 @@
| To specify the limits within the controller's __construct() method, add per-method
| limits with:
|
-| $this->method['METHOD_NAME']['limit'] = [NUM_REQUESTS_PER_HOUR];
+| $this->methods['METHOD_NAME']['limit'] = [NUM_REQUESTS_PER_HOUR];
|
| See application/controllers/api/example.php for examples
*/
From 2bb2fe4808cdf4f591ca55f480884909e026fbd1 Mon Sep 17 00:00:00 2001
From: CodeLingoBot
Date: Mon, 1 Apr 2019 10:49:35 +1300
Subject: [PATCH 071/129] Fix case of contants based on best practices from
PSR2
Signed-off-by: CodeLingoBot
---
application/config/ldap.php | 2 +-
application/config/profiler.php | 22 ++++++------
application/config/rest.php | 34 +++++++++----------
application/config/routes.php | 2 +-
application/controllers/api/Example.php | 12 +++----
application/controllers/api/Key.php | 28 +++++++--------
.../20170706025420_create_table_users.php | 10 +++---
.../20170706030520_create_table_api_keys.php | 12 +++----
.../20170706031435_create_table_api_logs.php | 12 +++----
...20170706032133_create_table_api_access.php | 8 ++---
...20170706032825_create_table_api_limits.php | 6 ++--
11 files changed, 74 insertions(+), 74 deletions(-)
diff --git a/application/config/ldap.php b/application/config/ldap.php
index e4165550..a54b985d 100644
--- a/application/config/ldap.php
+++ b/application/config/ldap.php
@@ -8,7 +8,7 @@
* There will be a delay while the code times out trying to talk to the main server but things will still work.
*/
$config['server'] = 'ldapserver1.example.org ldapserver2.example.org';
-$config['port'] = NULL;
+$config['port'] = null;
/*
* Controls the LDAP_OPT_NETWORK_TIMEOUT option, this is how long the code will attempt to talk to the primary server if it is unreachable.
*/
diff --git a/application/config/profiler.php b/application/config/profiler.php
index ce026a7e..870880d9 100644
--- a/application/config/profiler.php
+++ b/application/config/profiler.php
@@ -12,15 +12,15 @@
| http://codeigniter.com/user_guide/general/profiling.html
|
*/
-$config['benchmarks'] = TRUE;
-$config['config'] = TRUE;
-$config['controller_info'] = TRUE;
-$config['get'] = TRUE;
-$config['http_headers'] = TRUE;
-$config['memory_usage'] = TRUE;
-$config['post'] = TRUE;
-$config['queries'] = TRUE;
-$config['eloquent'] = FALSE;
-$config['uri_string'] = TRUE;
-$config['view_data'] = TRUE;
+$config['benchmarks'] = true;
+$config['config'] = true;
+$config['controller_info'] = true;
+$config['get'] = true;
+$config['http_headers'] = true;
+$config['memory_usage'] = true;
+$config['post'] = true;
+$config['queries'] = true;
+$config['eloquent'] = false;
+$config['uri_string'] = true;
+$config['view_data'] = true;
$config['query_toggle_count'] = 1000;
\ No newline at end of file
diff --git a/application/config/rest.php b/application/config/rest.php
index 109cb671..394937ce 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -10,7 +10,7 @@
| Set to force the use of HTTPS for REST API calls
|
*/
-$config['force_https'] = FALSE;
+$config['force_https'] = false;
/*
|--------------------------------------------------------------------------
@@ -82,7 +82,7 @@
| Should we enable emulation of the request (e.g. used in Mootools request)
|
*/
-$config['enable_emulate_request'] = TRUE;
+$config['enable_emulate_request'] = true;
/*
|--------------------------------------------------------------------------
@@ -110,7 +110,7 @@
| authorization key
|
*/
-$config['rest_auth'] = FALSE;
+$config['rest_auth'] = false;
/*
|--------------------------------------------------------------------------
@@ -137,8 +137,8 @@
| requests etc), set to TRUE;
|
*/
-$config['allow_auth_and_keys'] = TRUE;
-$config['strict_api_and_auth'] = TRUE; // force the use of both api and auth before a valid api request is made
+$config['allow_auth_and_keys'] = true;
+$config['strict_api_and_auth'] = true; // force the use of both api and auth before a valid api request is made
/*
|--------------------------------------------------------------------------
@@ -228,7 +228,7 @@
| restrict certain methods to IPs in your white-list
|
*/
-$config['rest_ip_whitelist_enabled'] = FALSE;
+$config['rest_ip_whitelist_enabled'] = false;
/*
|--------------------------------------------------------------------------
@@ -238,7 +238,7 @@
| Handle exceptions caused by the controller
|
*/
-$config['rest_handle_exceptions'] = TRUE;
+$config['rest_handle_exceptions'] = true;
/*
|--------------------------------------------------------------------------
@@ -266,7 +266,7 @@
| 1. Set to TRUE and add any IP address to 'rest_ip_blacklist'
|
*/
-$config['rest_ip_blacklist_enabled'] = FALSE;
+$config['rest_ip_blacklist_enabled'] = false;
/*
|--------------------------------------------------------------------------
@@ -324,7 +324,7 @@
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
*/
-$config['rest_enable_keys'] = FALSE;
+$config['rest_enable_keys'] = false;
/*
|--------------------------------------------------------------------------
@@ -404,7 +404,7 @@
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
*/
-$config['rest_enable_logging'] = FALSE;
+$config['rest_enable_logging'] = false;
/*
|--------------------------------------------------------------------------
@@ -437,7 +437,7 @@
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
*/
-$config['rest_enable_access'] = FALSE;
+$config['rest_enable_access'] = false;
/*
|--------------------------------------------------------------------------
@@ -459,7 +459,7 @@
| Set to FALSE to log as serialized PHP
|
*/
-$config['rest_logs_json_params'] = FALSE;
+$config['rest_logs_json_params'] = false;
/*
|--------------------------------------------------------------------------
@@ -487,7 +487,7 @@
|
| See application/controllers/api/example.php for examples
*/
-$config['rest_enable_limits'] = FALSE;
+$config['rest_enable_limits'] = false;
/*
|--------------------------------------------------------------------------
@@ -509,7 +509,7 @@
| Only do this if you are using the $this->rest_format or /format/xml in URLs
|
*/
-$config['rest_ignore_http_accept'] = FALSE;
+$config['rest_ignore_http_accept'] = false;
/*
|--------------------------------------------------------------------------
@@ -524,7 +524,7 @@
| Hint: This is good for production environments
|
*/
-$config['rest_ajax_only'] = FALSE;
+$config['rest_ajax_only'] = false;
/*
|--------------------------------------------------------------------------
@@ -546,7 +546,7 @@
| will access it through a browser
|
*/
-$config['check_cors'] = FALSE;
+$config['check_cors'] = false;
/*
|--------------------------------------------------------------------------
@@ -590,7 +590,7 @@
| source domain
|
*/
-$config['allow_any_cors_domain'] = FALSE;
+$config['allow_any_cors_domain'] = false;
/*
|--------------------------------------------------------------------------
diff --git a/application/config/routes.php b/application/config/routes.php
index f2d051f7..c0f8cee9 100644
--- a/application/config/routes.php
+++ b/application/config/routes.php
@@ -51,7 +51,7 @@
*/
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
-$route['translate_uri_dashes'] = TRUE;
+$route['translate_uri_dashes'] = true;
/*
| -------------------------------------------------------------------------
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
index 9bc3a828..3b6de553 100644
--- a/application/controllers/api/Example.php
+++ b/application/controllers/api/Example.php
@@ -46,7 +46,7 @@ public function users_get()
// If the id parameter doesn't exist return all the users
- if ($id === NULL)
+ if ($id === null)
{
// Check if the users data store contains users (in case the database result returns NULL)
if ($users)
@@ -58,7 +58,7 @@ public function users_get()
{
// Set the response and exit
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'No users were found'
], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
}
@@ -72,13 +72,13 @@ public function users_get()
if ($id <= 0)
{
// Invalid id, set the response and exit.
- $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
+ $this->response(null, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Get the user from the array, using the id as key for retrieval.
// Usually a model is to be used for this.
- $user = NULL;
+ $user = null;
if (!empty($users))
{
@@ -98,7 +98,7 @@ public function users_get()
else
{
$this->set_response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'User could not be found'
], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
}
@@ -125,7 +125,7 @@ public function users_delete()
if ($id <= 0)
{
// Set the response and exit
- $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
+ $this->response(null, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// $this->some_model->delete_something($id);
diff --git a/application/controllers/api/Key.php b/application/controllers/api/Key.php
index 8f3a64b4..585f9f60 100644
--- a/application/controllers/api/Key.php
+++ b/application/controllers/api/Key.php
@@ -46,14 +46,14 @@ public function index_put()
if ($this->_insert_key($key, ['level' => $level, 'ignore_limits' => $ignore_limits]))
{
$this->response([
- 'status' => TRUE,
+ 'status' => true,
'key' => $key
], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
else
{
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Could not save the key'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
@@ -74,7 +74,7 @@ public function index_delete()
{
// It doesn't appear the key exists
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
@@ -84,7 +84,7 @@ public function index_delete()
// Respond that the key was destroyed
$this->response([
- 'status' => TRUE,
+ 'status' => true,
'message' => 'API key was deleted'
], REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
}
@@ -105,7 +105,7 @@ public function level_post()
{
// It doesn't appear the key exists
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
@@ -114,14 +114,14 @@ public function level_post()
if ($this->_update_key($key, ['level' => $new_level]))
{
$this->response([
- 'status' => TRUE,
+ 'status' => true,
'message' => 'API key was updated'
], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Could not update the key level'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
@@ -142,7 +142,7 @@ public function suspend_post()
{
// It doesn't appear the key exists
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
@@ -151,14 +151,14 @@ public function suspend_post()
if ($this->_update_key($key, ['level' => 0]))
{
$this->response([
- 'status' => TRUE,
+ 'status' => true,
'message' => 'Key was suspended'
], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Could not suspend the user'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
@@ -180,7 +180,7 @@ public function regenerate_post()
{
// It doesn't appear the key exists
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Invalid API key'
], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
@@ -195,14 +195,14 @@ public function regenerate_post()
$this->_update_key($old_key, ['level' => 0]);
$this->response([
- 'status' => TRUE,
+ 'status' => true,
'key' => $new_key
], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
else
{
$this->response([
- 'status' => FALSE,
+ 'status' => false,
'message' => 'Could not save the key'
], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
@@ -218,7 +218,7 @@ private function _generate_key()
$salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 16, 36);
// If an error occurred, then fall back to the previous method
- if ($salt === FALSE)
+ if ($salt === false)
{
$salt = hash('sha256', time() . mt_rand());
}
diff --git a/application/migrations/20170706025420_create_table_users.php b/application/migrations/20170706025420_create_table_users.php
index aaeccb69..3553dad3 100644
--- a/application/migrations/20170706025420_create_table_users.php
+++ b/application/migrations/20170706025420_create_table_users.php
@@ -21,12 +21,12 @@ public function up()
$fields = array(
'id' => [
'type' => 'INT(11)',
- 'auto_increment' => TRUE,
- 'unsigned' => TRUE,
+ 'auto_increment' => true,
+ 'unsigned' => true,
],
'email' => [
'type' => 'VARCHAR(255)',
- 'unique' => TRUE,
+ 'unique' => true,
],
'password' => [
'type' => 'VARCHAR(64)',
@@ -42,8 +42,8 @@ public function up()
],
);
$this->dbforge->add_field($fields);
- $this->dbforge->add_key('id', TRUE);
- $this->dbforge->create_table($this->table, TRUE);
+ $this->dbforge->add_key('id', true);
+ $this->dbforge->create_table($this->table, true);
/*for ($i = 1; $i <= 100; $i++)
{
diff --git a/application/migrations/20170706030520_create_table_api_keys.php b/application/migrations/20170706030520_create_table_api_keys.php
index 8c3954d8..42fb5417 100644
--- a/application/migrations/20170706030520_create_table_api_keys.php
+++ b/application/migrations/20170706030520_create_table_api_keys.php
@@ -20,16 +20,16 @@ public function up()
$fields = array(
'id' => [
'type' => 'INT(11)',
- 'auto_increment' => TRUE,
- 'unsigned' => TRUE,
+ 'auto_increment' => true,
+ 'unsigned' => true,
],
'user_id' => [
'type' => 'INT(11)',
- 'unsigned' => TRUE,
+ 'unsigned' => true,
],
config_item('rest_key_column') => [
'type' => 'VARCHAR(' . config_item('rest_key_length') . ')',
- 'unique' => TRUE,
+ 'unique' => true,
],
'level' => [
'type' => 'INT(2)',
@@ -44,14 +44,14 @@ public function up()
],
'ip_addresses' => [
'type' => 'TEXT',
- 'null' => TRUE,
+ 'null' => true,
],
'date_created' => [
'type' => 'INT(11)',
],
);
$this->dbforge->add_field($fields);
- $this->dbforge->add_key('id', TRUE);
+ $this->dbforge->add_key('id', true);
$this->dbforge->create_table($table);
$this->db->query(add_foreign_key($table, 'user_id', 'users(id)', 'CASCADE', 'CASCADE'));
}
diff --git a/application/migrations/20170706031435_create_table_api_logs.php b/application/migrations/20170706031435_create_table_api_logs.php
index 03d6a567..db8b4be4 100644
--- a/application/migrations/20170706031435_create_table_api_logs.php
+++ b/application/migrations/20170706031435_create_table_api_logs.php
@@ -20,8 +20,8 @@ public function up()
$fields = array(
'id' => [
'type' => 'INT(11)',
- 'auto_increment' => TRUE,
- 'unsigned' => TRUE,
+ 'auto_increment' => true,
+ 'unsigned' => true,
],
'api_key' => [
'type' => 'VARCHAR(' . config_item('rest_key_length') . ')',
@@ -34,7 +34,7 @@ public function up()
],
'params' => [
'type' => 'TEXT',
- 'null' => TRUE,
+ 'null' => true,
],
'ip_address' => [
'type' => 'VARCHAR(45)',
@@ -44,19 +44,19 @@ public function up()
],
'rtime' => [
'type' => 'FLOAT',
- 'null' => TRUE,
+ 'null' => true,
],
'authorized' => [
'type' => 'VARCHAR(1)',
],
'response_code' => [
'type' => 'SMALLINT(3)',
- 'null' => TRUE,
+ 'null' => true,
'default' => 0,
],
);
$this->dbforge->add_field($fields);
- $this->dbforge->add_key('id', TRUE);
+ $this->dbforge->add_key('id', true);
$this->dbforge->create_table($table);
/*$this->db->query(add_foreign_key($table, 'api_key',
config_item('rest_keys_table') . '(' . config_item('rest_key_column') . ')', 'CASCADE', 'CASCADE'));*/
diff --git a/application/migrations/20170706032133_create_table_api_access.php b/application/migrations/20170706032133_create_table_api_access.php
index c78cbe3f..df004dda 100644
--- a/application/migrations/20170706032133_create_table_api_access.php
+++ b/application/migrations/20170706032133_create_table_api_access.php
@@ -20,8 +20,8 @@ public function up()
$fields = array(
'id' => [
'type' => 'INT(11)',
- 'auto_increment' => TRUE,
- 'unsigned' => TRUE,
+ 'auto_increment' => true,
+ 'unsigned' => true,
],
'key' => [
'type' => 'VARCHAR(' . config_item('rest_key_length') . ')',
@@ -35,14 +35,14 @@ public function up()
],
'date_created' => [
'type' => 'DATETIME',
- 'null' => TRUE,
+ 'null' => true,
],
'date_modified' => [
'type' => 'TIMESTAMP',
],
);
$this->dbforge->add_field($fields);
- $this->dbforge->add_key('id', TRUE);
+ $this->dbforge->add_key('id', true);
$this->dbforge->add_key('controller');
$this->dbforge->create_table($table);
$this->db->query(add_foreign_key($table, 'key',
diff --git a/application/migrations/20170706032825_create_table_api_limits.php b/application/migrations/20170706032825_create_table_api_limits.php
index 28f211bd..c7355cb7 100644
--- a/application/migrations/20170706032825_create_table_api_limits.php
+++ b/application/migrations/20170706032825_create_table_api_limits.php
@@ -20,8 +20,8 @@ public function up()
$fields = array(
'id' => [
'type' => 'INT(11)',
- 'auto_increment' => TRUE,
- 'unsigned' => TRUE,
+ 'auto_increment' => true,
+ 'unsigned' => true,
],
'api_key' => [
'type' => 'VARCHAR(' . config_item('rest_key_length') . ')',
@@ -37,7 +37,7 @@ public function up()
],
);
$this->dbforge->add_field($fields);
- $this->dbforge->add_key('id', TRUE);
+ $this->dbforge->add_key('id', true);
$this->dbforge->add_key('uri');
$this->dbforge->create_table($table);
$this->db->query(add_foreign_key($table, 'api_key',
From 6425ad60f7f108c1e52c2d939dd6b550a5e73a96 Mon Sep 17 00:00:00 2001
From: Kevin Hill
Date: Tue, 14 May 2019 16:59:19 -0400
Subject: [PATCH 072/129] Add support for CodeIgniter 3.1.0 and PHP 7.2
---
README.md | 29 +-
application/libraries/REST_Controller.php | 362 ++++++------------
.../libraries/REST_Controller_Definitions.php | 138 +++++++
composer.json | 4 +-
4 files changed, 271 insertions(+), 262 deletions(-)
create mode 100644 application/libraries/REST_Controller_Definitions.php
diff --git a/README.md b/README.md
index d192d4ae..7f54e719 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,4 @@
+
# CodeIgniter Rest Server
[](https://gitter.im/codeigniter-restserver/Lobby)
@@ -7,8 +8,8 @@ config file and one controller.
## Requirements
-1. PHP 5.4 or greater
-2. CodeIgniter 3.0+
+1. PHP 7.2 or greater
+2. CodeIgniter 3.1.10+
_Note: for 1.7.x support download v2.2 from Downloads tab_
@@ -39,8 +40,11 @@ When your controller extends from `REST_Controller`, the method names will be ap
This allows you to implement a RESTful interface easily:
```php
-class Books extends REST_Controller
+class Books extends CI_Controller
{
+ use REST_Controller {
+ REST_Controller::__construct as private __resTraitConstruct;
+ }
public function index_get()
{
// Display all books
@@ -69,9 +73,9 @@ The HTTP spec for DELETE requests precludes the use of parameters. For delete r
```php
public function index_delete($id)
{
- $this->response([
- 'returned from delete:' => $id,
- ]);
+ $this->response([
+ 'returned from delete:' => $id,
+ ]);
}
```
@@ -146,6 +150,7 @@ If your application uses language files to support multiple locales, `REST_Contr
public function __construct()
{
parent::__construct();
+ $this->__resTraitConstruct();
if (is_array($this->response->lang))
{
@@ -194,12 +199,12 @@ You'll need to create a new database table to store and access the keys. `REST_C
```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`)
+ `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;
```
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 2363cfc4..bcda5f63 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -1,7 +1,6 @@
'OK',
- self::HTTP_CREATED => 'CREATED',
- self::HTTP_NO_CONTENT => 'NO CONTENT',
- self::HTTP_NOT_MODIFIED => 'NOT MODIFIED',
- self::HTTP_BAD_REQUEST => 'BAD REQUEST',
- self::HTTP_UNAUTHORIZED => 'UNAUTHORIZED',
- self::HTTP_FORBIDDEN => 'FORBIDDEN',
- self::HTTP_NOT_FOUND => 'NOT FOUND',
- self::HTTP_METHOD_NOT_ALLOWED => 'METHOD NOT ALLOWED',
- self::HTTP_NOT_ACCEPTABLE => 'NOT ACCEPTABLE',
- self::HTTP_CONFLICT => 'CONFLICT',
- self::HTTP_INTERNAL_SERVER_ERROR => 'INTERNAL SERVER ERROR',
- self::HTTP_NOT_IMPLEMENTED => 'NOT IMPLEMENTED'
+ REST_Controller_Definitions::HTTP_OK => 'OK',
+ REST_Controller_Definitions::HTTP_CREATED => 'CREATED',
+ REST_Controller_Definitions::HTTP_NO_CONTENT => 'NO CONTENT',
+ REST_Controller_Definitions::HTTP_NOT_MODIFIED => 'NOT MODIFIED',
+ REST_Controller_Definitions::HTTP_BAD_REQUEST => 'BAD REQUEST',
+ REST_Controller_Definitions::HTTP_UNAUTHORIZED => 'UNAUTHORIZED',
+ REST_Controller_Definitions::HTTP_FORBIDDEN => 'FORBIDDEN',
+ REST_Controller_Definitions::HTTP_NOT_FOUND => 'NOT FOUND',
+ REST_Controller_Definitions::HTTP_METHOD_NOT_ALLOWED => 'METHOD NOT ALLOWED',
+ REST_Controller_Definitions::HTTP_NOT_ACCEPTABLE => 'NOT ACCEPTABLE',
+ REST_Controller_Definitions::HTTP_CONFLICT => 'CONFLICT',
+ REST_Controller_Definitions::HTTP_INTERNAL_SERVER_ERROR => 'INTERNAL SERVER ERROR',
+ REST_Controller_Definitions::HTTP_NOT_IMPLEMENTED => 'NOT IMPLEMENTED'
];
/**
@@ -409,8 +275,8 @@ public function __construct($config = 'rest')
if ($this->config->item('rest_enable_logging') === TRUE)
{
// Start the timer for how long the request takes
- $this->_start_rtime = microtime(TRUE);
- }
+ $this->_start_rtime = microtime(TRUE);
+ }
// Load the rest.php configuration file
$this->get_local_config($config);
@@ -521,8 +387,8 @@ public function __construct($config = 'rest')
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
+
+ // Assign payload arguments to proper method container
$this->{'_'.$this->request->method.'_args'} = $this->request->body;
}
@@ -574,7 +440,7 @@ public function __construct($config = 'rest')
$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);
+ ], REST_Controller_Definitions::HTTP_NOT_ACCEPTABLE);
}
// When there is no specific override for the current class/method, use the default auth value set in the config
@@ -676,7 +542,7 @@ public function _remap($object_called, $arguments = [])
$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);
+ ], REST_Controller_Definitions::HTTP_FORBIDDEN);
}
// Remove the supported format from the function name e.g. index.json => index
@@ -711,7 +577,7 @@ public function _remap($object_called, $arguments = [])
$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);
+ ], REST_Controller_Definitions::HTTP_FORBIDDEN);
}
// Check to see if this key has access to the requested controller
@@ -725,7 +591,7 @@ public function _remap($object_called, $arguments = [])
$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);
+ ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
// Sure it exists, but can they do anything with it?
@@ -734,7 +600,7 @@ public function _remap($object_called, $arguments = [])
$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);
+ ], REST_Controller_Definitions::HTTP_METHOD_NOT_ALLOWED);
}
// Doing key related stuff? Can only do it if they have a key right?
@@ -744,7 +610,7 @@ public function _remap($object_called, $arguments = [])
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);
+ $this->response($response, REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
// If no level is set use 0, they probably aren't using permissions
@@ -761,7 +627,7 @@ public function _remap($object_called, $arguments = [])
{
// 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);
+ $this->response($response, REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
}
@@ -769,7 +635,7 @@ public function _remap($object_called, $arguments = [])
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);
+ $this->response($response, REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
// No key stuff, but record that stuff is happening
@@ -809,87 +675,87 @@ public function _remap($object_called, $arguments = [])
public function response($data = NULL, $http_code = NULL, $continue = FALSE)
{
//if profiling enabled then print profiling data
- $isProfilingEnabled = $this->config->item('enable_profiling');
- if(!$isProfilingEnabled){
- ob_start();
- // If the HTTP status is not NULL, then cast as an integer
- if ($http_code !== NULL)
- {
- // So as to be safe later on in the process
- $http_code = (int) $http_code;
- }
-
- // Set the output as NULL by default
- $output = NULL;
-
- // If data is NULL and no HTTP status code provided, then display, error and exit
- if ($data === NULL && $http_code === NULL)
- {
- $http_code = self::HTTP_NOT_FOUND;
- }
-
- // If data is not NULL and a HTTP status code provided, then continue
- elseif ($data !== NULL)
- {
- // If the format method exists, call and return the output in that format
- if (method_exists(Format::class, 'to_' . $this->response->format))
- {
- // Set the format header
- $this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
- $output = Format::factory($data)->{'to_' . $this->response->format}();
-
- // 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
- {
- ob_end_flush();
- }
-
- // Otherwise dump the output automatically
- }
- else{
- echo json_encode($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 = REST_Controller_Definitions::HTTP_NOT_FOUND;
+ }
+
+ // If data is not NULL and a HTTP status code provided, then continue
+ elseif ($data !== NULL)
+ {
+ // If the format method exists, call and return the output in that format
+ if (method_exists(Format::class, 'to_' . $this->response->format))
+ {
+ // Set the format header
+ $this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
+ $output = Format::factory($data)->{'to_' . $this->response->format}();
+
+ // 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 = REST_Controller_Definitions::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
+ {
+ ob_end_flush();
+ }
+
+ // Otherwise dump the output automatically
+ }
+ else{
+ echo json_encode($data);
+ }
}
/**
@@ -1104,7 +970,7 @@ protected function _detect_api_key()
{
// 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();
+ $ip_address = $this->input->ip_address();
$found_address = FALSE;
foreach ($list_ip_addresses as $ip_address)
@@ -2020,7 +1886,7 @@ protected function _check_php_session()
$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);
+ ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
}
@@ -2117,7 +1983,7 @@ protected function _prepare_digest_auth()
$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);
+ ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
}
@@ -2139,7 +2005,7 @@ protected function _check_blacklist_auth()
$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);
+ ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
}
@@ -2167,7 +2033,7 @@ protected function _check_whitelist_auth()
$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);
+ ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
}
@@ -2205,7 +2071,7 @@ protected function _force_login($nonce = '')
$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);
+ ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
}
/**
@@ -2347,4 +2213,4 @@ protected function _check_cors()
exit;
}
}
-}
+}
\ No newline at end of file
diff --git a/application/libraries/REST_Controller_Definitions.php b/application/libraries/REST_Controller_Definitions.php
new file mode 100644
index 00000000..403842ad
--- /dev/null
+++ b/application/libraries/REST_Controller_Definitions.php
@@ -0,0 +1,138 @@
+=5.4.0",
- "codeigniter/framework": "^3.0.4"
+ "php": ">=7.1.0",
+ "codeigniter/framework": "^3.1.10"
},
"autoload": {
"classmap": [
From ae62b76bc6adc97cbed539eeb6df8ffc7e186fe5 Mon Sep 17 00:00:00 2001
From: azapater
Date: Thu, 8 Aug 2019 16:47:12 +0100
Subject: [PATCH 073/129] private variable $auth_override made protected.
This will avoid calling _auth_override_check() in case of need to check that info in the controller.
---
application/libraries/REST_Controller.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index bcda5f63..5df718ce 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -239,7 +239,7 @@ trait REST_Controller {
/**
* @var bool
*/
- private $auth_override;
+ protected $auth_override;
/**
* Extend this function to apply additional checking early on in the process
@@ -387,7 +387,7 @@ public function __construct($config = 'rest')
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;
}
From 3ed956559303e4025371cfb70a10ff0d4d7a3561 Mon Sep 17 00:00:00 2001
From: Ray Li
Date: Wed, 2 Oct 2019 01:11:24 -0500
Subject: [PATCH 074/129] QUICKFIX Continue Returns Response
Fixes issue #1023
The added lines returns the response to the client and allows code to continue executing.
`ob_end_flush; ` does not actually work correctly according to https://stackoverflow.com/questions/10579116/how-to-flush-data-to-browser-but-continue-executing
It is kept for legacy compatibility and to prevent regressions.
---
application/libraries/REST_Controller.php | 16 ++++++++++++++--
1 file changed, 14 insertions(+), 2 deletions(-)
diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php
index 5df718ce..ab836c3c 100644
--- a/application/libraries/REST_Controller.php
+++ b/application/libraries/REST_Controller.php
@@ -748,7 +748,19 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
}
else
{
- ob_end_flush();
+ 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();
+ }
}
// Otherwise dump the output automatically
@@ -2213,4 +2225,4 @@ protected function _check_cors()
exit;
}
}
-}
\ No newline at end of file
+}
From 67eaafb1cfb2ee0bb70034013b7359aaed11ac2f Mon Sep 17 00:00:00 2001
From: Salim Djerbouh
Date: Thu, 3 Oct 2019 12:26:39 +0100
Subject: [PATCH 075/129] add import to handling requests example
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 7f54e719..7121a5f5 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,8 @@ When your controller extends from `REST_Controller`, the method names will be ap
This allows you to implement a RESTful interface easily:
```php
+use Restserver\Libraries\REST_Controller;
+
class Books extends CI_Controller
{
use REST_Controller {
From fd04c3b44b02e78e5b61f663f36bb7a56e4f4ce2 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sun, 10 Nov 2019 13:56:25 -0600
Subject: [PATCH 076/129] latest changes for 3.1
---
.codeclimate.yml | 3 -
AUTHORS.md | 10 -
CHANGELOG.md | 66 -
README.md | 271 +-
application/config/config.php.sample | 482 --
application/config/hooks.php | 21 -
application/config/ldap.php | 15 -
application/config/profiler.php | 26 -
application/config/routes.php | 62 -
application/controllers/Rest_server.php | 13 -
application/controllers/Welcome.php | 27 -
application/controllers/api/Example.php | 140 -
application/controllers/api/Key.php | 274 --
application/helpers/db_helper.php | 69 -
application/hooks/hooks.profiler.php | 18 -
.../language/dutch/rest_controller_lang.php | 16 -
application/language/spanish/index.html | 11 -
.../language/traditional-chinese/index.html | 11 -
application/language/turkish/index.html | 11 -
.../libraries/REST_Controller_Definitions.php | 138 -
application/libraries/index.html | 11 -
.../20170706025420_create_table_users.php | 69 -
.../20170706030520_create_table_api_keys.php | 70 -
.../20170706031435_create_table_api_logs.php | 76 -
...20170706032133_create_table_api_access.php | 63 -
...20170706032825_create_table_api_limits.php | 58 -
application/migrations/index.html | 11 -
application/views/index.html | 11 -
application/views/rest_server.php | 222 -
application/views/welcome_message.php | 101 -
composer.json | 42 +-
documentation/404.html | 110 -
documentation/class-Example.html | 457 --
documentation/class-Format.html | 983 ----
documentation/class-Key.html | 512 ---
documentation/class-REST_Controller.html | 3956 -----------------
documentation/class-Rest_server.html | 190 -
documentation/class-Welcome.html | 203 -
documentation/elementlist.js | 3 -
documentation/index.html | 131 -
.../package-CodeIgniter.Libraries.html | 117 -
documentation/package-CodeIgniter.Rest.html | 123 -
documentation/package-CodeIgniter.html | 113 -
documentation/package-None.html | 127 -
documentation/resources/collapsed.png | Bin 238 -> 0 bytes
documentation/resources/combined.js | 1315 ------
documentation/resources/footer.png | Bin 7948 -> 0 bytes
documentation/resources/inherit.png | Bin 152 -> 0 bytes
documentation/resources/resize.png | Bin 216 -> 0 bytes
documentation/resources/sort.png | Bin 171 -> 0 bytes
documentation/resources/style.css | 614 ---
documentation/resources/tree-cleaner.png | Bin 126 -> 0 bytes
documentation/resources/tree-hasnext.png | Bin 128 -> 0 bytes
documentation/resources/tree-last.png | Bin 172 -> 0 bytes
documentation/resources/tree-vertical.png | Bin 127 -> 0 bytes
documentation/source-class-Example.html | 242 -
documentation/source-class-Format.html | 636 ---
documentation/source-class-Key.html | 377 --
.../source-class-REST_Controller.html | 2316 ----------
documentation/source-class-Rest_server.html | 118 -
documentation/source-class-Welcome.html | 132 -
.../config => language/bulgarian}/index.html | 0
.../bulgarian/rest_controller_lang.php | 0
.../api => language/dutch}/index.html | 0
language/dutch/rest_controller_lang.php | 16 +
.../english}/index.html | 0
.../english/rest_controller_lang.php | 0
.../helpers => language/french}/index.html | 0
.../french/rest_controller_lang.php | 2 +-
.../bulgarian => language/german}/index.html | 0
.../german/rest_controller_lang.php | 2 +-
.../greek/rest_controller_lang.php | 2 +-
.../language/dutch => language}/index.html | 0
.../english => language/indonesia}/index.html | 0
.../indonesia/rest_controller_lang.php | 0
.../french => language/italian}/index.html | 0
.../italian/rest_controller_lang.php | 0
.../german => language/korean}/index.html | 0
.../korean/rest_controller_lang.php | 2 +-
.../portuguese-brazilian}/index.html | 0
.../rest_controller_lang.php | 0
.../romanian}/index.html | 0
.../romanian/rest_controller_lang.php | 2 +-
.../serbian_cyr}/index.html | 0
.../serbian_cyr/rest_controller_lang.php | 2 +-
.../serbian_lat}/index.html | 0
.../serbian_lat/rest_controller_lang.php | 0
.../simplified-chinese/index.html | 0
.../rest_controller_lang.php | 2 +-
.../spanish}/index.html | 0
.../spanish/rest_controller_lang.php | 2 +-
.../traditional-chinese}/index.html | 0
.../rest_controller_lang.php | 0
.../turkish}/index.html | 0
.../turkish/rest_controller_lang.php | 0
{application/libraries => src}/Format.php | 268 +-
.../RestController.php | 1318 +++---
src/auth/apikey.php | 0
src/auth/basic.php | 0
src/auth/ldap.php | 0
.../language/serbian_lat => src}/index.html | 0
{application/config => src}/rest.php | 11 +-
102 files changed, 768 insertions(+), 16054 deletions(-)
delete mode 100644 .codeclimate.yml
delete mode 100644 AUTHORS.md
delete mode 100644 CHANGELOG.md
delete mode 100644 application/config/config.php.sample
delete mode 100644 application/config/hooks.php
delete mode 100644 application/config/ldap.php
delete mode 100644 application/config/profiler.php
delete mode 100644 application/config/routes.php
delete mode 100644 application/controllers/Rest_server.php
delete mode 100644 application/controllers/Welcome.php
delete mode 100644 application/controllers/api/Example.php
delete mode 100644 application/controllers/api/Key.php
delete mode 100755 application/helpers/db_helper.php
delete mode 100644 application/hooks/hooks.profiler.php
delete mode 100644 application/language/dutch/rest_controller_lang.php
delete mode 100644 application/language/spanish/index.html
delete mode 100644 application/language/traditional-chinese/index.html
delete mode 100644 application/language/turkish/index.html
delete mode 100644 application/libraries/REST_Controller_Definitions.php
delete mode 100755 application/libraries/index.html
delete mode 100644 application/migrations/20170706025420_create_table_users.php
delete mode 100644 application/migrations/20170706030520_create_table_api_keys.php
delete mode 100644 application/migrations/20170706031435_create_table_api_logs.php
delete mode 100644 application/migrations/20170706032133_create_table_api_access.php
delete mode 100644 application/migrations/20170706032825_create_table_api_limits.php
delete mode 100644 application/migrations/index.html
delete mode 100644 application/views/index.html
delete mode 100644 application/views/rest_server.php
delete mode 100644 application/views/welcome_message.php
delete mode 100644 documentation/404.html
delete mode 100644 documentation/class-Example.html
delete mode 100644 documentation/class-Format.html
delete mode 100644 documentation/class-Key.html
delete mode 100644 documentation/class-REST_Controller.html
delete mode 100644 documentation/class-Rest_server.html
delete mode 100644 documentation/class-Welcome.html
delete mode 100644 documentation/elementlist.js
delete mode 100644 documentation/index.html
delete mode 100644 documentation/package-CodeIgniter.Libraries.html
delete mode 100644 documentation/package-CodeIgniter.Rest.html
delete mode 100644 documentation/package-CodeIgniter.html
delete mode 100644 documentation/package-None.html
delete mode 100644 documentation/resources/collapsed.png
delete mode 100644 documentation/resources/combined.js
delete mode 100644 documentation/resources/footer.png
delete mode 100644 documentation/resources/inherit.png
delete mode 100644 documentation/resources/resize.png
delete mode 100644 documentation/resources/sort.png
delete mode 100644 documentation/resources/style.css
delete mode 100644 documentation/resources/tree-cleaner.png
delete mode 100644 documentation/resources/tree-hasnext.png
delete mode 100644 documentation/resources/tree-last.png
delete mode 100644 documentation/resources/tree-vertical.png
delete mode 100644 documentation/source-class-Example.html
delete mode 100644 documentation/source-class-Format.html
delete mode 100644 documentation/source-class-Key.html
delete mode 100644 documentation/source-class-REST_Controller.html
delete mode 100644 documentation/source-class-Rest_server.html
delete mode 100644 documentation/source-class-Welcome.html
rename {application/config => language/bulgarian}/index.html (100%)
rename {application/language => language}/bulgarian/rest_controller_lang.php (100%)
rename {application/controllers/api => language/dutch}/index.html (100%)
create mode 100644 language/dutch/rest_controller_lang.php
rename {application/controllers => language/english}/index.html (100%)
rename {application/language => language}/english/rest_controller_lang.php (100%)
rename {application/helpers => language/french}/index.html (100%)
rename {application/language => language}/french/rest_controller_lang.php (94%)
rename {application/language/bulgarian => language/german}/index.html (100%)
rename {application/language => language}/german/rest_controller_lang.php (94%)
rename {application/language => language}/greek/rest_controller_lang.php (95%)
rename {application/language/dutch => language}/index.html (100%)
rename {application/language/english => language/indonesia}/index.html (100%)
rename {application/language => language}/indonesia/rest_controller_lang.php (100%)
rename {application/language/french => language/italian}/index.html (100%)
rename {application/language => language}/italian/rest_controller_lang.php (100%)
rename {application/language/german => language/korean}/index.html (100%)
rename {application/language => language}/korean/rest_controller_lang.php (98%)
rename {application/language => language/portuguese-brazilian}/index.html (100%)
rename {application/language => language}/portuguese-brazilian/rest_controller_lang.php (100%)
rename {application/language/indonesia => language/romanian}/index.html (100%)
rename {application/language => language}/romanian/rest_controller_lang.php (93%)
rename {application/language/italian => language/serbian_cyr}/index.html (100%)
rename {application/language => language}/serbian_cyr/rest_controller_lang.php (96%)
rename {application/language/korean => language/serbian_lat}/index.html (100%)
rename {application/language => language}/serbian_lat/rest_controller_lang.php (100%)
rename {application/language => language}/simplified-chinese/index.html (100%)
rename {application/language => language}/simplified-chinese/rest_controller_lang.php (93%)
rename {application/language/portuguese-brazilian => language/spanish}/index.html (100%)
rename {application/language => language}/spanish/rest_controller_lang.php (92%)
rename {application/language/romanian => language/traditional-chinese}/index.html (100%)
rename {application/language => language}/traditional-chinese/rest_controller_lang.php (100%)
rename {application/language/serbian_cyr => language/turkish}/index.html (100%)
rename {application/language => language}/turkish/rest_controller_lang.php (100%)
rename {application/libraries => src}/Format.php (68%)
rename application/libraries/REST_Controller.php => src/RestController.php (63%)
create mode 100644 src/auth/apikey.php
create mode 100644 src/auth/basic.php
create mode 100644 src/auth/ldap.php
rename {application/language/serbian_lat => src}/index.html (100%)
mode change 100644 => 100755
rename {application/config => src}/rest.php (99%)
diff --git a/.codeclimate.yml b/.codeclimate.yml
deleted file mode 100644
index b1059fca..00000000
--- a/.codeclimate.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-exclude_paths:
-- "documentation/"
-- "application/language/"
\ No newline at end of file
diff --git a/AUTHORS.md b/AUTHORS.md
deleted file mode 100644
index ee3551f6..00000000
--- a/AUTHORS.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# The Core Team
-
-* [Chris Kacerguis](//github.com/chriskacerguis)
-* [Phil Sturgeon](//github.com/philsturgeon)
-
-### Special Thanks To
-
-* [Fabian Hanisch](//github.com/Hanisch-IT)
-
-*For a list of people who have contributed to the codebase, see [GitHub's list of contributors](https://github.com/chriskacerguis/codeigniter-restserver/graphs/contributors). Anyone who has contributed please do a PR and add to this file.*
diff --git a/CHANGELOG.md b/CHANGELOG.md
deleted file mode 100644
index ce83aeda..00000000
--- a/CHANGELOG.md
+++ /dev/null
@@ -1,66 +0,0 @@
-Changelog:
-===========
-
-### UNRELEASED
-* Added support for CodeIgniter controller's index methods (index_GET, index_POST...)
-* Added exceptions handling when the method could not be found
-
-### 2.7.2
-
-* Added $this->query() in which query parameters can now be obtained regardless of whether a GET request is sent or not
-* Added doc comments added to functions
-* Added HTTP status constants e.g. REST_Controller::HTTP_OK
-* Added new CSV formatting function
-* Fixed numerous bug fixes
-* Updated API calls limit can be based on API key, routed url or method name
-* Updated documentation
-* Updated examples (thanks @ivantcholakov and @lagaisse)
-* Updated many functions by re-writing (thanks @softwarespot)
-* Updated performance increase
-
-### 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 bug-fix 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 white-list option.
-
-### 2.5
-
-* Instead of just seeing item, item, item, the singular version of the base-node 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/README.md b/README.md
index 7121a5f5..4955bb84 100644
--- a/README.md
+++ b/README.md
@@ -1,30 +1,26 @@
+# CodeIgniter RestServer
-# CodeIgniter Rest Server
+[](https://github.styleci.io/repos/219224674)
-[](https://gitter.im/codeigniter-restserver/Lobby)
-
-A fully RESTful server implementation for CodeIgniter using one library, one
-config file and one controller.
+A fully RESTful server implementation for CodeIgniter using one library, one config file and one controller.
## Requirements
-1. PHP 7.2 or greater
-2. CodeIgniter 3.1.10+
-
-_Note: for 1.7.x support download v2.2 from Downloads tab_
-
-## Important Update on 4.0.0
+- PHP 7.2 or greater
+- CodeIgniter 3.1.11+
-Please note that version 4.0.0 is in the works, and is considered a breaking change (per SemVer). As CI 3.1.0 now has native support for Composer, this library will be moving to be composer based.
+## Installation
-Take a look at the "development" branch to see what's up.
+```sh
+composer require chriskacerguis/ci-restserver
+```
-## Installation & loading
+## Usage
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:
```json
-"chriskacerguis/codeigniter-restserver": "^3.0"
+"chriskacerguis/codeigniter-restserver": "^3.1"
```
or run
@@ -33,212 +29,63 @@ or run
composer require chriskacerguis/codeigniter-restserver
```
-## 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
-use Restserver\Libraries\REST_Controller;
-
-class Books extends CI_Controller
-{
- use REST_Controller {
- REST_Controller::__construct as private __resTraitConstruct;
- }
- 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
-```
-
-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([
- 'returned from delete:' => $id,
- ]);
-}
-```
-
-If query parameters are passed via the URL, regardless of whether it's a GET request, can be obtained by the query method:
-
-```php
-$this->query('blah'); // Query param
-```
-
-## Content Types
-
-`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
-```
-
-This can be flaky with URI segments, so the recommend approach is using the HTTP `Accept` header:
-
-```bash
-$ curl -H "Accept: application/json" http://example.com
-```
-
-Any responses you make from the class (see [responses](#responses) for more on this) will be serialised in the designated format.
-
-## Responses
-
-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:
-
-```php
-public function index_get()
-{
- $this->response($this->db->get('books')->result());
-}
-```
-
-This will automatically return an `HTTP 200 OK` response. You can specify the status code in the second parameter:
+Step 1: Add this to your controller (should be before any of your code)
```php
-public function index_post()
- {
- // ...create new book
- $this->response($book, 201); // Send an HTTP 201 Created
- }
+use chriskacerguis\RestServer\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`:
+Step 2: Extend your controller
```php
-$this->response([]); // HTTP 404 Not Found
+class Example extends RestController
```
-## Configuration
-
-You can overwrite all default configurations by creating a rest.php file in your config folder with your configs.
-All given configurations will overwrite the default ones.
-
-## Language
-
-You can overwrite all default language files. Just add a rest_controller_lang.php to your language and overwrite the what you want.
-
-
-## Multilingual Support
+## Basic GET example
-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:
+Here is a basic example of
```php
-public function __construct()
-{
- parent::__construct();
- $this->__resTraitConstruct();
-
- if (is_array($this->response->lang))
- {
- $this->load->language('application', $this->response->lang[0]);
- }
- else
- {
- $this->load->language('application', $this->response->lang);
- }
+ 1, 'name' => 'John', 'email' => 'john@example.com'],
+ ['id' => 2, '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);
+ }
+ }
+ }
}
-```
-
-## Authentication
-
-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:
-
-```php
-$config['rest_valid_logins'] = ['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.
-
-If you're tying this library into an AJAX endpoint where clients authenticate using PHP sessions then you may not like either of the digest nor basic authentication methods. In that case, you can tell the REST Library what PHP session variable to check for. If the variable exists, then the user is authorized. It will be up to your application to set that variable. You can define the variable in ``$config['auth_source']``. Then tell the library to use a php session variable by setting ``$config['rest_auth']`` to ``session``.
-
-All three methods of authentication can be secured further by using an IP white-list. If you enable `$config['rest_ip_whitelist_enabled']` in your config file, you can then set a list of allowed IPs.
-
-Any client connecting to your API will be checked against the white-listed IP array. If they're on the list, they'll be allowed access. If not, sorry, no can do hombre. The whitelist is a comma-separated string:
-
-```php
-$config['rest_ip_whitelist'] = '123.456.789.0, 987.654.32.1';
-```
-
-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:
-
-```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`.
-
-By default, the HTTP will be `X-API-KEY`. This can be configured in **config/rest.php**.
-
-```bash
-$ curl -X POST -H "X-API-KEY: some_key_here" http://example.com/books
-```
-## Profiling
-Codeigniter Profiler feature has been added to the library, so that you can use the power of CI profiler in your project just by setting config parameter to enable profile through out your application
-Turn it on in your **config/config.php** file:
-
-```php
-TRUE to turn profile ON, FALSE to turn it off
-$config['enable_profiling'] = FALSE;
-```
-Also you need to enable `hooks` in your config.php that looks like this
-```php
-$config['enable_hooks'] = TRUE;
-```
-Also you can refer to **config/config.php.sample**
-
-## 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 involvement has shifted
-as he is no longer using it. As of 2013/11/20 further development 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.
+```
\ No newline at end of file
diff --git a/application/config/config.php.sample b/application/config/config.php.sample
deleted file mode 100644
index 77411ce1..00000000
--- a/application/config/config.php.sample
+++ /dev/null
@@ -1,482 +0,0 @@
-]+$/i
-|
-| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
-|
-| Note: This option is ignored for CLI requests.
-|
-*/
-$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
-
-/*
-|--------------------------------------------------------------------------
-| Enable Query Strings
-|--------------------------------------------------------------------------
-|
-| By default CodeIgniter uses search-engine friendly segment based URLs:
-| example.com/who/what/where/
-|
-| You can optionally enable standard query string based URLs:
-| example.com?who=me&what=something&where=here
-|
-| Options are: TRUE or FALSE (boolean)
-|
-| The other items let you set the query string 'words' that will
-| invoke your controllers and its functions:
-| example.com/index.php?c=controller&m=function
-|
-| Please note that some of the helpers won't work as expected when
-| this feature is enabled, since CodeIgniter is designed primarily to
-| use segment based URLs.
-|
-*/
-$config['enable_query_strings'] = FALSE;
-$config['controller_trigger'] = 'c';
-$config['function_trigger'] = 'm';
-$config['directory_trigger'] = 'd';
-
-/*
-|--------------------------------------------------------------------------
-| Error Logging Threshold
-|--------------------------------------------------------------------------
-|
-| You can enable error logging by setting a threshold over zero. The
-| threshold determines what gets logged. Threshold options are:
-|
-| 0 = Disables logging, Error logging TURNED OFF
-| 1 = Error Messages (including PHP errors)
-| 2 = Debug Messages
-| 3 = Informational Messages
-| 4 = All Messages
-|
-| You can also pass an array with threshold levels to show individual error types
-|
-| array(2) = Debug Messages, without Error Messages
-|
-| For a live site you'll usually only enable Errors (1) to be logged otherwise
-| your log files will fill up very fast.
-|
-*/
-$config['log_threshold'] = 0;
-
-/*
-|--------------------------------------------------------------------------
-| Error Logging Directory Path
-|--------------------------------------------------------------------------
-|
-| Leave this BLANK unless you would like to set something other than the default
-| application/logs/ directory. Use a full server path.
-|
-*/
-$config['log_path'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| Log File Extension
-|--------------------------------------------------------------------------
-|
-| The default filename extension for log files. The default 'php' allows for
-| protecting the log files via basic scripting, when they are to be stored
-| under a publicly accessible directory.
-|
-| Note: Leaving it blank will default to 'php'.
-|
-*/
-$config['log_file_extension'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| Log File Permissions
-|--------------------------------------------------------------------------
-|
-| The file system permissions to be applied on newly created log files.
-|
-| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
-| integer notation (i.e. 0700, 0644, etc.)
-*/
-$config['log_file_permissions'] = 0644;
-
-/*
-|--------------------------------------------------------------------------
-| Date Format for Logs
-|--------------------------------------------------------------------------
-|
-| Each item that is logged has an associated date. You can use PHP date
-| codes to set your own date formatting
-|
-*/
-$config['log_date_format'] = 'Y-m-d H:i:s';
-
-/*
-|--------------------------------------------------------------------------
-| Error Views Directory Path
-|--------------------------------------------------------------------------
-|
-| Leave this BLANK unless you would like to set something other than the default
-| application/views/errors/ directory. Use a full server path.
-|
-*/
-$config['error_views_path'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| Cache Directory Path
-|--------------------------------------------------------------------------
-|
-| Leave this BLANK unless you would like to set something other than the default
-| application/cache/ directory. Use a full server path.
-|
-*/
-$config['cache_path'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| Cache Include Query String
-|--------------------------------------------------------------------------
-|
-| Whether to take the URL query string into consideration when generating
-| output cache files. Valid options are:
-|
-| FALSE = Disabled
-| TRUE = Enabled, take all query parameters into account.
-| Please be aware that this may result in numerous cache
-| files generated for the same page over and over again.
-| array('q') = Enabled, but only take into account the specified list
-| of query parameters.
-|
-*/
-$config['cache_query_string'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| Encryption Key
-|--------------------------------------------------------------------------
-|
-| If you use the Encryption class, you must set an encryption key.
-| See the user guide for more info.
-|
-| https://codeigniter.com/user_guide/libraries/encryption.html
-|
-*/
-$config['encryption_key'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| Session Variables
-|--------------------------------------------------------------------------
-|
-| 'sess_driver'
-|
-| The storage driver to use: files, database, redis, memcached
-|
-| 'sess_cookie_name'
-|
-| The session cookie name, must contain only [0-9a-z_-] characters
-|
-| 'sess_expiration'
-|
-| The number of SECONDS you want the session to last.
-| Setting to 0 (zero) means expire when the browser is closed.
-|
-| 'sess_save_path'
-|
-| The location to save sessions to, driver dependent.
-|
-| For the 'files' driver, it's a path to a writable directory.
-| WARNING: Only absolute paths are supported!
-|
-| For the 'database' driver, it's a table name.
-| Please read up the manual for the format with other session drivers.
-|
-| IMPORTANT: You are REQUIRED to set a valid save path!
-|
-| 'sess_match_ip'
-|
-| Whether to match the user's IP address when reading the session data.
-|
-| WARNING: If you're using the database driver, don't forget to update
-| your session table's PRIMARY KEY when changing this setting.
-|
-| 'sess_time_to_update'
-|
-| How many seconds between CI regenerating the session ID.
-|
-| 'sess_regenerate_destroy'
-|
-| Whether to destroy session data associated with the old session ID
-| when auto-regenerating the session ID. When set to FALSE, the data
-| will be later deleted by the garbage collector.
-|
-| Other session cookie settings are shared with the rest of the application,
-| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
-|
-*/
-$config['sess_driver'] = 'files';
-$config['sess_cookie_name'] = 'ci_session';
-$config['sess_expiration'] = 7200;
-$config['sess_save_path'] = NULL;
-$config['sess_match_ip'] = FALSE;
-$config['sess_time_to_update'] = 300;
-$config['sess_regenerate_destroy'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| Cookie Related Variables
-|--------------------------------------------------------------------------
-|
-| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
-| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
-| 'cookie_path' = Typically will be a forward slash
-| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
-| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
-|
-| Note: These settings (with the exception of 'cookie_prefix' and
-| 'cookie_httponly') will also affect sessions.
-|
-*/
-$config['cookie_prefix'] = '';
-$config['cookie_domain'] = '';
-$config['cookie_path'] = '/';
-$config['cookie_secure'] = FALSE;
-$config['cookie_httponly'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| Cross Site Request Forgery
-|--------------------------------------------------------------------------
-| Enables a CSRF cookie token to be set. When set to TRUE, token will be
-| checked on a submitted form. If you are accepting user data, it is strongly
-| recommended CSRF protection be enabled.
-|
-| 'csrf_token_name' = The token name
-| 'csrf_cookie_name' = The cookie name
-| 'csrf_expire' = The number in seconds the token should expire.
-| 'csrf_regenerate' = Regenerate token on every submission
-| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
-*/
-$config['csrf_protection'] = FALSE;
-$config['csrf_token_name'] = 'csrf_test_name';
-$config['csrf_cookie_name'] = 'csrf_cookie_name';
-$config['csrf_expire'] = 7200;
-$config['csrf_regenerate'] = TRUE;
-$config['csrf_exclude_uris'] = array();
-
-/*
-|--------------------------------------------------------------------------
-| Output Compression
-|--------------------------------------------------------------------------
-|
-| Enables Gzip output compression for faster page loads. When enabled,
-| the output class will test whether your server supports Gzip.
-| Even if it does, however, not all browsers support compression
-| so enable only if you are reasonably sure your visitors can handle it.
-|
-| Only used if zlib.output_compression is turned off in your php.ini.
-| Please do not use it together with httpd-level output compression.
-|
-| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
-| means you are prematurely outputting something to your browser. It could
-| even be a line of whitespace at the end of one of your scripts. For
-| compression to work, nothing can be sent before the output buffer is called
-| by the output class. Do not 'echo' any values with compression enabled.
-|
-*/
-$config['compress_output'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| Master Time Reference
-|--------------------------------------------------------------------------
-|
-| Options are 'local' or any PHP supported timezone. This preference tells
-| the system whether to use your server's local time as the master 'now'
-| reference, or convert it to the configured one timezone. See the 'date
-| helper' page of the user guide for information regarding date handling.
-|
-*/
-$config['time_reference'] = 'local';
-
-/*
-|--------------------------------------------------------------------------
-| Reverse Proxy IPs
-|--------------------------------------------------------------------------
-|
-| If your server is behind a reverse proxy, you must whitelist the proxy
-| IP addresses from which CodeIgniter should trust headers such as
-| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
-| the visitor's IP address.
-|
-| You can use both an array or a comma-separated list of proxy addresses,
-| as well as specifying whole subnets. Here are a few examples:
-|
-| Comma-separated: '10.0.1.200,192.168.5.0/24'
-| Array: array('10.0.1.200', '192.168.5.0/24')
-*/
-$config['proxy_ips'] = '';
diff --git a/application/config/hooks.php b/application/config/hooks.php
deleted file mode 100644
index 7268904b..00000000
--- a/application/config/hooks.php
+++ /dev/null
@@ -1,21 +0,0 @@
- 'ProfilerEnabler',
- 'function' => 'enableProfiler',
- 'filename' => 'hooks.profiler.php',
- 'filepath' => 'hooks',
- 'params' => array()
-);
\ No newline at end of file
diff --git a/application/config/ldap.php b/application/config/ldap.php
deleted file mode 100644
index a54b985d..00000000
--- a/application/config/ldap.php
+++ /dev/null
@@ -1,15 +0,0 @@
- my_controller/index
-| my-controller/my-method -> my_controller/my_method
-*/
-$route['default_controller'] = 'welcome';
-$route['404_override'] = '';
-$route['translate_uri_dashes'] = true;
-
-/*
-| -------------------------------------------------------------------------
-| Sample REST API Routes
-| -------------------------------------------------------------------------
-*/
-$route['api/example/users/(:num)'] = 'api/example/users/id/$1'; // Example 4
-$route['api/example/users/(:num)(\.)([a-zA-Z0-9_-]+)(.*)'] = 'api/example/users/id/$1/format/$3$4'; // Example 8
diff --git a/application/controllers/Rest_server.php b/application/controllers/Rest_server.php
deleted file mode 100644
index 5d44f921..00000000
--- a/application/controllers/Rest_server.php
+++ /dev/null
@@ -1,13 +0,0 @@
-load->helper('url');
-
- $this->load->view('rest_server');
- }
-}
diff --git a/application/controllers/Welcome.php b/application/controllers/Welcome.php
deleted file mode 100644
index 59818c7f..00000000
--- a/application/controllers/Welcome.php
+++ /dev/null
@@ -1,27 +0,0 @@
-
- * @see https://codeigniter.com/user_guide/general/urls.html
- */
- public function index()
- {
- $this->load->helper('url');
-
- $this->load->view('welcome_message');
- }
-}
diff --git a/application/controllers/api/Example.php b/application/controllers/api/Example.php
deleted file mode 100644
index 3b6de553..00000000
--- a/application/controllers/api/Example.php
+++ /dev/null
@@ -1,140 +0,0 @@
-methods['users_get']['limit'] = 500; // 500 requests per hour per user/key
- $this->methods['users_post']['limit'] = 100; // 100 requests per hour per user/key
- $this->methods['users_delete']['limit'] = 50; // 50 requests per hour per user/key
- }
-
- public function users_get()
- {
- // Users from a data store e.g. database
- $users = [
- ['id' => 1, 'name' => 'John', 'email' => 'john@example.com', 'fact' => 'Loves coding'],
- ['id' => 2, 'name' => 'Jim', 'email' => 'jim@example.com', 'fact' => 'Developed on CodeIgniter'],
- ['id' => 3, 'name' => 'Jane', 'email' => 'jane@example.com', 'fact' => 'Lives in the USA', ['hobbies' => ['guitar', 'cycling']]],
- ];
-
- $id = $this->get('id');
-
- // If the id parameter doesn't exist return all the users
-
- if ($id === null)
- {
- // Check if the users data store contains users (in case the database result returns NULL)
- if ($users)
- {
- // Set the response and exit
- $this->response($users, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
- }
- else
- {
- // Set the response and exit
- $this->response([
- 'status' => false,
- 'message' => 'No users were found'
- ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
- }
- }
-
- // Find and return a single record for a particular user.
-
- $id = (int) $id;
-
- // Validate the id.
- if ($id <= 0)
- {
- // Invalid id, set the response and exit.
- $this->response(null, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
- }
-
- // Get the user from the array, using the id as key for retrieval.
- // Usually a model is to be used for this.
-
- $user = null;
-
- if (!empty($users))
- {
- foreach ($users as $key => $value)
- {
- if (isset($value['id']) && $value['id'] === $id)
- {
- $user = $value;
- }
- }
- }
-
- if (!empty($user))
- {
- $this->set_response($user, REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
- }
- else
- {
- $this->set_response([
- 'status' => false,
- 'message' => 'User could not be found'
- ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
- }
- }
-
- public function users_post()
- {
- // $this->some_model->update_user( ... );
- $message = [
- 'id' => 100, // Automatically generated by the model
- 'name' => $this->post('name'),
- 'email' => $this->post('email'),
- 'message' => 'Added a resource'
- ];
-
- $this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
- }
-
- public function users_delete()
- {
- $id = (int) $this->get('id');
-
- // Validate the id.
- if ($id <= 0)
- {
- // Set the response and exit
- $this->response(null, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
- }
-
- // $this->some_model->delete_something($id);
- $message = [
- 'id' => $id,
- 'message' => 'Deleted the resource'
- ];
-
- $this->set_response($message, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
- }
-
-}
diff --git a/application/controllers/api/Key.php b/application/controllers/api/Key.php
deleted file mode 100644
index 585f9f60..00000000
--- a/application/controllers/api/Key.php
+++ /dev/null
@@ -1,274 +0,0 @@
- ['level' => 10, 'limit' => 10],
- 'index_delete' => ['level' => 10],
- 'level_post' => ['level' => 10],
- 'regenerate_post' => ['level' => 10],
- ];
-
- /**
- * Insert a key into the database
- *
- * @access public
- * @return void
- */
- public function index_put()
- {
- // Build a new key
- $key = $this->_generate_key();
-
- // If no key level provided, provide a generic key
- $level = $this->put('level') ? $this->put('level') : 1;
- $ignore_limits = ctype_digit($this->put('ignore_limits')) ? (int) $this->put('ignore_limits') : 1;
-
- // Insert the new key
- if ($this->_insert_key($key, ['level' => $level, 'ignore_limits' => $ignore_limits]))
- {
- $this->response([
- 'status' => true,
- 'key' => $key
- ], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
- }
- else
- {
- $this->response([
- 'status' => false,
- 'message' => 'Could not save the key'
- ], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
- }
- }
-
- /**
- * 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 exist?
- if (!$this->_key_exists($key))
- {
- // It doesn't appear the key exists
- $this->response([
- 'status' => false,
- 'message' => 'Invalid API key'
- ], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
- }
-
- // Destroy it
- $this->_delete_key($key);
-
- // Respond that the key was destroyed
- $this->response([
- 'status' => true,
- 'message' => 'API key was deleted'
- ], REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
- }
-
- /**
- * Change the level
- *
- * @access public
- * @return void
- */
- public function level_post()
- {
- $key = $this->post('key');
- $new_level = $this->post('level');
-
- // Does this key exist?
- if (!$this->_key_exists($key))
- {
- // It doesn't appear the key exists
- $this->response([
- 'status' => false,
- 'message' => 'Invalid API key'
- ], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
- }
-
- // Update the key level
- if ($this->_update_key($key, ['level' => $new_level]))
- {
- $this->response([
- 'status' => true,
- 'message' => 'API key was updated'
- ], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
- }
- else
- {
- $this->response([
- 'status' => false,
- 'message' => 'Could not update the key level'
- ], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
- }
- }
-
- /**
- * Suspend a key
- *
- * @access public
- * @return void
- */
- public function suspend_post()
- {
- $key = $this->post('key');
-
- // Does this key exist?
- if (!$this->_key_exists($key))
- {
- // It doesn't appear the key exists
- $this->response([
- 'status' => false,
- 'message' => 'Invalid API key'
- ], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
- }
-
- // Update the key level
- if ($this->_update_key($key, ['level' => 0]))
- {
- $this->response([
- 'status' => true,
- 'message' => 'Key was suspended'
- ], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
- }
- else
- {
- $this->response([
- 'status' => false,
- 'message' => 'Could not suspend the user'
- ], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
- }
- }
-
- /**
- * Regenerate a key
- *
- * @access public
- * @return void
- */
- public function regenerate_post()
- {
- $old_key = $this->post('key');
- $key_details = $this->_get_key($old_key);
-
- // Does this key exist?
- if (!$key_details)
- {
- // It doesn't appear the key exists
- $this->response([
- 'status' => false,
- 'message' => 'Invalid API key'
- ], REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
- }
-
- // Build a new key
- $new_key = $this->_generate_key();
-
- // Insert the new key
- if ($this->_insert_key($new_key, ['level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits]))
- {
- // Suspend old key
- $this->_update_key($old_key, ['level' => 0]);
-
- $this->response([
- 'status' => true,
- 'key' => $new_key
- ], REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
- }
- else
- {
- $this->response([
- 'status' => false,
- 'message' => 'Could not save the key'
- ], REST_Controller::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
- }
- }
-
- /* Helper Methods */
-
- private function _generate_key()
- {
- do
- {
- // Generate a random salt
- $salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 16, 36);
-
- // If an error occurred, then fall back to the previous method
- if ($salt === false)
- {
- $salt = hash('sha256', time() . mt_rand());
- }
-
- $new_key = substr($salt, 0, config_item('rest_key_length'));
- }
- while ($this->_key_exists($new_key));
-
- return $new_key;
- }
-
- /* Private Data Methods */
-
- private function _get_key($key)
- {
- return $this->rest->db
- ->where(config_item('rest_key_column'), $key)
- ->get(config_item('rest_keys_table'))
- ->row();
- }
-
- private function _key_exists($key)
- {
- return $this->rest->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->rest->db
- ->set($data)
- ->insert(config_item('rest_keys_table'));
- }
-
- private function _update_key($key, $data)
- {
- return $this->rest->db
- ->where(config_item('rest_key_column'), $key)
- ->update(config_item('rest_keys_table'), $data);
- }
-
- private function _delete_key($key)
- {
- return $this->rest->db
- ->where(config_item('rest_key_column'), $key)
- ->delete(config_item('rest_keys_table'));
- }
-
-}
diff --git a/application/helpers/db_helper.php b/application/helpers/db_helper.php
deleted file mode 100755
index 9a007a46..00000000
--- a/application/helpers/db_helper.php
+++ /dev/null
@@ -1,69 +0,0 @@
-
- */
-defined('BASEPATH') OR exit('No direct script access allowed');
-
-if ( ! function_exists('add_foreign_key'))
-{
- /**
- * @param string $table Table name
- * @param string $foreign_key Collumn name having the Foreign Key
- * @param string $references Table and column reference. Ex: users(id)
- * @param string $on_delete RESTRICT, NO ACTION, CASCADE, SET NULL, SET DEFAULT
- * @param string $on_update RESTRICT, NO ACTION, CASCADE, SET NULL, SET DEFAULT
- *
- * @return string SQL command
- */
- function add_foreign_key($table, $foreign_key, $references, $on_delete = 'RESTRICT', $on_update = 'RESTRICT')
- {
- $references = explode('(', str_replace(')', '', str_replace('`', '', $references)));
-
- return "ALTER TABLE `{$table}` ADD CONSTRAINT `{$table}_{$foreign_key}_fk` FOREIGN KEY (`{$foreign_key}`) REFERENCES `{$references[0]}`(`{$references[1]}`) ON DELETE {$on_delete} ON UPDATE {$on_update}";
- }
-}
-
-if ( ! function_exists('drop_foreign_key'))
-{
- /**
- * @param string $table Table name
- * @param string $foreign_key Collumn name having the Foreign Key
- *
- * @return string SQL command
- */
- function drop_foreign_key($table, $foreign_key)
- {
- return "ALTER TABLE `{$table}` DROP FOREIGN KEY `{$table}_{$foreign_key}_fk`";
- }
-}
-
-if ( ! function_exists('add_trigger'))
-{
- /**
- * @param string $trigger_name Trigger name
- * @param string $table Table name
- * @param string $statement Command to run
- * @param string $time BEFORE or AFTER
- * @param string $event INSERT, UPDATE or DELETE
- * @param string $type FOR EACH ROW [FOLLOWS|PRECEDES]
- *
- * @return string SQL Command
- */
- function add_trigger($trigger_name, $table, $statement, $time = 'BEFORE', $event = 'INSERT', $type = 'FOR EACH ROW')
- {
- return 'DELIMITER ;;' . PHP_EOL . "CREATE TRIGGER `{$trigger_name}` {$time} {$event} ON `{$table}` {$type}" . PHP_EOL . 'BEGIN' . PHP_EOL . $statement . PHP_EOL . 'END;' . PHP_EOL . 'DELIMITER ;;';
- }
-}
-
-if ( ! function_exists('drop_trigger'))
-{
- /**
- * @param string $trigger_name Trigger name
- *
- * @return string SQL Command
- */
- function drop_trigger($trigger_name)
- {
- return "DROP TRIGGER {$trigger_name};";
- }
-}
diff --git a/application/hooks/hooks.profiler.php b/application/hooks/hooks.profiler.php
deleted file mode 100644
index c376fdb8..00000000
--- a/application/hooks/hooks.profiler.php
+++ /dev/null
@@ -1,18 +0,0 @@
-output->enable_profiler( config_item('enable_profiling') );
- }
-}
-?>
diff --git a/application/language/dutch/rest_controller_lang.php b/application/language/dutch/rest_controller_lang.php
deleted file mode 100644
index 182ca61c..00000000
--- a/application/language/dutch/rest_controller_lang.php
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
- 403 Forbidden
-
-
-
-
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, 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
-
-
-
-
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 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
-
-
-
-
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
Gets the default format from the configuration. Fallbacks to 'json'
-if the corresponding configuration option $config['rest_default_format']
-is missing or is empty
-
-
-
-
Gets the default format from the configuration. Fallbacks to 'json'
-if the corresponding configuration option $config['rest_default_format']
-is missing or is empty
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
-
-
-
-
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
Maps to the following URL http://example.com/index.php/welcome
-- or - http://example.com/index.php/welcome/index
-- or -
-Since this controller is set as the default controller in
-config/routes.php, it's displayed at http://example.com/
-
-
So any other public methods not prefixed with an underscore will
-map to /index.php/welcome/
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="
1: <?php
- 2: defined('BASEPATH') ORexit('No direct script access allowed');
- 3:
- 4: class Welcome extends CI_Controller {
- 5:
- 6: /**
- 7: * Index Page for this controller.
- 8: *
- 9: * Maps to the following URL
-10: * http://example.com/index.php/welcome
-11: * - or -
-12: * http://example.com/index.php/welcome/index
-13: * - or -
-14: * Since this controller is set as the default controller in
-15: * config/routes.php, it's displayed at http://example.com/
-16: *
-17: * So any other public methods not prefixed with an underscore will
-18: * map to /index.php/welcome/<method_name>
-19: * @see https://codeigniter.com/user_guide/general/urls.html
-20: */
-21: publicfunction index()
-22: {
-23: $this->load->helper('url');
-24:
-25: $this->load->view('welcome_message');
-26: }
-27: }
-28:
-
-
-
-
-
-
-
-
diff --git a/application/config/index.html b/language/bulgarian/index.html
similarity index 100%
rename from application/config/index.html
rename to language/bulgarian/index.html
diff --git a/application/language/bulgarian/rest_controller_lang.php b/language/bulgarian/rest_controller_lang.php
similarity index 100%
rename from application/language/bulgarian/rest_controller_lang.php
rename to language/bulgarian/rest_controller_lang.php
diff --git a/application/controllers/api/index.html b/language/dutch/index.html
similarity index 100%
rename from application/controllers/api/index.html
rename to language/dutch/index.html
diff --git a/language/dutch/rest_controller_lang.php b/language/dutch/rest_controller_lang.php
new file mode 100644
index 00000000..45fd9c25
--- /dev/null
+++ b/language/dutch/rest_controller_lang.php
@@ -0,0 +1,16 @@
+_CI = &get_instance();
@@ -91,14 +93,10 @@ public function __construct($data = NULL, $from_type = NULL)
$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))
- {
+ if ($from_type !== null) {
+ if (method_exists($this, '_from_'.$from_type)) {
$data = call_user_func([$this, '_from_'.$from_type], $data);
- }
- else
- {
+ } else {
throw new Exception('Format class does not support conversion from "'.$from_type.'".');
}
}
@@ -109,14 +107,14 @@ public function __construct($data = NULL, $from_type = NULL)
/**
* Create an instance of the format class
- * e.g: echo $this->format->factory(['foo' => 'bar'])->to_csv();
+ * e.g: echo $this->format->factory(['foo' => 'bar'])->to_csv();.
*
- * @param mixed $data Data to convert/parse
+ * @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)
+ public static function factory($data, $from_type = null)
{
// $class = __CLASS__;
// return new $class();
@@ -127,36 +125,31 @@ public static function factory($data, $from_type = NULL)
// FORMATTING OUTPUT ---------------------------------------------------------
/**
- * Format data as an array
+ * Format data as an array.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
*
- * @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)
+ 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)
- {
+ if ($data === null && func_num_args() === 0) {
$data = $this->_data;
}
// Cast as an array if not already
- if (is_array($data) === FALSE)
- {
+ if (is_array($data) === false) {
$data = (array) $data;
}
$array = [];
- foreach ((array) $data as $key => $value)
- {
- if (is_object($value) === TRUE || is_array($value) === TRUE)
- {
+ foreach ((array) $data as $key => $value) {
+ if (is_object($value) === true || is_array($value) === true) {
$array[$key] = $this->to_array($value);
- }
- else
- {
+ } else {
$array[$key] = $value;
}
}
@@ -165,44 +158,39 @@ public function to_array($data = NULL)
}
/**
- * Format data as XML
+ * 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
*
- * @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')
+ public function to_xml($data = null, $structure = null, $basenode = 'xml')
{
- if ($data === NULL && func_num_args() === 0)
- {
+ if ($data === null && func_num_args() === 0) {
$data = $this->_data;
}
- if ($structure === NULL)
- {
+ if ($structure === null) {
$structure = simplexml_load_string("<$basenode />");
}
// Force it to be something useful
- if (is_array($data) === FALSE && is_object($data) === FALSE)
- {
+ if (is_array($data) === false && is_object($data) === false) {
$data = (array) $data;
}
- foreach ($data as $key => $value)
- {
+ foreach ($data as $key => $value) {
//change false/true to 0/1
- if (is_bool($value))
- {
+ if (is_bool($value)) {
$value = (int) $value;
}
// no numeric keys in our xml please!
- if (is_numeric($key))
- {
+ if (is_numeric($key)) {
// make string key...
$key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
}
@@ -210,29 +198,23 @@ public function to_xml($data = NULL, $structure = NULL, $basenode = 'xml')
// replace anything not alpha numeric
$key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
- if ($key === '_attributes' && (is_array($value) || is_object($value)))
- {
+ if ($key === '_attributes' && (is_array($value) || is_object($value))) {
$attributes = $value;
- if (is_object($attributes))
- {
+ if (is_object($attributes)) {
$attributes = get_object_vars($attributes);
}
- foreach ($attributes as $attribute_name => $attribute_value)
- {
+ 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))
- {
+ elseif (is_array($value) || is_object($value)) {
$node = $structure->addChild($key);
// recursive call.
$this->to_xml($value, $node, $key);
- }
- else
- {
+ } else {
// add single node.
$value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
@@ -244,35 +226,31 @@ public function to_xml($data = NULL, $structure = NULL, $basenode = 'xml')
}
/**
- * Format data as HTML
+ * Format data as HTML.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
*
- * @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)
+ 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)
- {
+ if ($data === null && func_num_args() === 0) {
$data = $this->_data;
}
// Cast as an array if not already
- if (is_array($data) === FALSE)
- {
+ 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))
- {
+ if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE)) {
// Multi-dimensional array
$headings = array_keys($data[0]);
- }
- else
- {
+ } else {
// Single array
$headings = array_keys($data);
$data = [$data];
@@ -283,8 +261,7 @@ public function to_html($data = NULL)
$this->_CI->table->set_heading($headings);
- foreach ($data as $row)
- {
+ foreach ($data as $row) {
// Suppressing the "array to string conversion" notice
// Keep the "evil" @ here
$row = @array_map('strval', $row);
@@ -297,56 +274,50 @@ public function to_html($data = NULL)
/**
* @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 (")
+ *
+ * @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 = '"')
+ 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 NULL;
+ 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)
- {
+ if ($data === null && func_num_args() === 0) {
$data = $this->_data;
}
// If NULL, then set as the default delimiter
- if ($delimiter === NULL)
- {
+ if ($delimiter === null) {
$delimiter = ',';
}
// If NULL, then set as the default enclosure
- if ($enclosure === NULL)
- {
+ if ($enclosure === null) {
$enclosure = '"';
}
// Cast as an array if not already
- if (is_array($data) === FALSE)
- {
+ 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))
- {
+ if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE)) {
// Multi-dimensional array
$headings = array_keys($data[0]);
- }
- else
- {
+ } else {
// Single array
$headings = array_keys($data);
$data = [$data];
@@ -355,18 +326,16 @@ public function to_csv($data = NULL, $delimiter = ',', $enclosure = '"')
// Apply the headings
fputcsv($handle, $headings, $delimiter, $enclosure);
- foreach ($data as $record)
- {
+ 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)
- {
+ if (is_array($record) === false) {
break;
}
// Suppressing the "array to string conversion" notice.
// Keep the "evil" @ here.
- $record = @ array_map('strval', $record);
+ $record = @array_map('strval', $record);
// Returns the length of the string written or FALSE
fputcsv($handle, $record, $delimiter, $enclosure);
@@ -388,32 +357,30 @@ public function to_csv($data = NULL, $delimiter = ',', $enclosure = '"')
}
/**
- * Encode data as json
+ * Encode data as json.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
*
- * @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)
+ 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)
- {
+ 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)
- {
+ 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))
- {
+ 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).');';
}
@@ -426,18 +393,18 @@ public function to_json($data = NULL)
}
/**
- * Encode data as a serialized array
+ * Encode data as a serialized array.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
*
- * @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)
+ 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)
- {
+ if ($data === null && func_num_args() === 0) {
$data = $this->_data;
}
@@ -445,28 +412,29 @@ public function to_serialized($data = NULL)
}
/**
- * Format data using a PHP structure
+ * Format data using a PHP structure.
+ *
+ * @param mixed|null $data Optional data to pass, so as to override the data passed
+ * to the constructor
*
- * @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)
+ 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)
- {
+ if ($data === null && func_num_args() === 0) {
$data = $this->_data;
}
- return var_export($data, TRUE);
+ 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)
@@ -475,25 +443,24 @@ protected function _from_xml($data)
}
/**
- * @param string $data CSV string
+ * @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 (,)
+ * 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 (")
+ * 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
+ * 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)
- {
+ if ($delimiter === null) {
$delimiter = ',';
}
// If NULL, then set as the default enclosure
- if ($enclosure === NULL)
- {
+ if ($enclosure === null) {
$enclosure = '"';
}
@@ -502,6 +469,7 @@ protected function _from_csv($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)
@@ -511,6 +479,7 @@ protected function _from_json($data)
/**
* @param string $data Data to unserialize
+ *
* @return mixed Unserialized data
*/
protected function _from_serialize($data)
@@ -520,6 +489,7 @@ protected function _from_serialize($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)
diff --git a/application/libraries/REST_Controller.php b/src/RestController.php
similarity index 63%
rename from application/libraries/REST_Controller.php
rename to src/RestController.php
index ab836c3c..6ae504a1 100644
--- a/application/libraries/REST_Controller.php
+++ b/src/RestController.php
@@ -1,42 +1,39 @@
'application/json',
- 'array' => 'application/json',
- 'csv' => 'application/csv',
- 'html' => 'text/html',
- 'jsonp' => 'application/javascript',
- 'php' => 'text/plain',
+ 'json' => 'application/json',
+ 'array' => 'application/json',
+ 'csv' => 'application/csv',
+ 'html' => 'text/html',
+ 'jsonp' => 'application/javascript',
+ 'php' => 'text/plain',
'serialized' => 'application/vnd.php.serialized',
- 'xml' => 'application/xml'
+ 'xml' => 'application/xml',
];
/**
- * Information about the current API user
+ * 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
+ * Whether or not to perform a CORS check and apply CORS headers to the request.
*
* @var bool
*/
- protected $check_cors = NULL;
+ 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
+ * Set automatically based on config setting.
*
* @var bool
*/
- protected $_enable_xss = FALSE;
+ protected $_enable_xss = false;
- private $is_valid_request = TRUE;
+ private $is_valid_request = true;
/**
- * HTTP status codes and their respective description
- * Note: Only the widely used HTTP status codes are used
+ * Common HTTP status codes and their respective description.
*
- * @var array
* @link http://www.restapitutorial.com/httpstatuscodes.html
*/
- protected $http_status_codes = [
- REST_Controller_Definitions::HTTP_OK => 'OK',
- REST_Controller_Definitions::HTTP_CREATED => 'CREATED',
- REST_Controller_Definitions::HTTP_NO_CONTENT => 'NO CONTENT',
- REST_Controller_Definitions::HTTP_NOT_MODIFIED => 'NOT MODIFIED',
- REST_Controller_Definitions::HTTP_BAD_REQUEST => 'BAD REQUEST',
- REST_Controller_Definitions::HTTP_UNAUTHORIZED => 'UNAUTHORIZED',
- REST_Controller_Definitions::HTTP_FORBIDDEN => 'FORBIDDEN',
- REST_Controller_Definitions::HTTP_NOT_FOUND => 'NOT FOUND',
- REST_Controller_Definitions::HTTP_METHOD_NOT_ALLOWED => 'METHOD NOT ALLOWED',
- REST_Controller_Definitions::HTTP_NOT_ACCEPTABLE => 'NOT ACCEPTABLE',
- REST_Controller_Definitions::HTTP_CONFLICT => 'CONFLICT',
- REST_Controller_Definitions::HTTP_INTERNAL_SERVER_ERROR => 'INTERNAL SERVER ERROR',
- REST_Controller_Definitions::HTTP_NOT_IMPLEMENTED => 'NOT IMPLEMENTED'
- ];
+ 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_NOT_ACCEPTABLE = 406;
+ const HTTP_INTERNAL_ERROR = 500;
/**
* @var Format
*/
private $format;
+
/**
* @var bool
*/
protected $auth_override;
/**
- * Extend this function to apply additional checking early on in the process
+ * Extend this function to apply additional checking early on in the process.
*
- * @access protected
* @return void
*/
protected function early_checks()
@@ -252,65 +241,46 @@ protected function early_checks()
}
/**
- * Constructor for the REST API
+ * Constructor for the REST API.
*
- * @access public
* @param string $config Configuration filename minus the file extension
- * e.g: my_rest.php is passed as 'my_rest'
+ * e.g: my_rest.php is passed as 'my_rest'
*/
public function __construct($config = 'rest')
{
parent::__construct();
- $this->preflight_checks();
-
// Set the default value of global xss filtering. Same approach as CodeIgniter 3
- $this->_enable_xss = ($this->config->item('global_xss_filtering') === TRUE);
+ $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;
+ $this->output->parse_exec_vars = false;
// 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);
- }
+ if ($this->config->item('rest_enable_logging') === true) {
+ // Start the timer for how long the request takes
+ $this->_start_rtime = microtime(true);
+ }
// Load the rest.php configuration file
$this->get_local_config($config);
- // At present the library is bundled with REST_Controller 2.5+, but will eventually be part of CodeIgniter (no citation)
- //if(class_exists('Format'))
- //{
- // $this->format = new Format();
- //}
- //else
- //{
- // $this->load->library('Format', NULL, 'libraryFormat');
- // $this->format = $this->libraryFormat;
- //}
-
-
// Determine supported output formats from configuration
$supported_formats = $this->config->item('rest_supported_formats');
// Validate the configuration setting output formats
- if (empty($supported_formats))
- {
+ if (empty($supported_formats)) {
$supported_formats = [];
}
- if ( ! is_array($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))
- {
+ if (!in_array($default_format, $supported_formats)) {
$supported_formats[] = $default_format;
}
@@ -319,13 +289,12 @@ public function __construct($config = 'rest')
// Get the language
$language = $this->config->item('rest_language');
- if ($language === NULL)
- {
+ if ($language === null) {
$language = 'english';
}
// Load the language file
- $this->lang->load('rest_controller', $language, FALSE, TRUE, __DIR__.'/../');
+ $this->lang->load('rest_controller', $language, false, true, __DIR__.'/../');
// Initialise the response, request and rest objects
$this->request = new stdClass();
@@ -333,8 +302,7 @@ public function __construct($config = 'rest')
$this->rest = new stdClass();
// Check to see if the current IP address is blacklisted
- if ($this->config->item('rest_ip_blacklist_enabled') === TRUE)
- {
+ if ($this->config->item('rest_ip_blacklist_enabled') === true) {
$this->_check_blacklist_auth();
}
@@ -346,14 +314,12 @@ public function __construct($config = 'rest')
// Check for CORS access request
$check_cors = $this->config->item('check_cors');
- if ($check_cors === TRUE)
- {
+ 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)
- {
+ if (isset($this->{'_'.$this->request->method.'_args'}) === false) {
$this->{'_'.$this->request->method.'_args'} = [];
}
@@ -367,13 +333,12 @@ public function __construct($config = 'rest')
$this->request->format = $this->_detect_input_format();
// Not all methods have a body attached with them
- $this->request->body = NULL;
+ $this->request->body = null;
- $this->{'_parse_' . $this->request->method}();
+ $this->{'_parse_'.$this->request->method}();
// Fix parse method return arguments null
- if($this->{'_'.$this->request->method.'_args'} === null)
- {
+ if ($this->{'_'.$this->request->method.'_args'} === null) {
$this->{'_'.$this->request->method.'_args'} = [];
}
@@ -384,11 +349,10 @@ public function __construct($config = 'rest')
$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)
- {
+ 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
+ // Assign payload arguments to proper method container
$this->{'_'.$this->request->method.'_args'} = $this->request->body;
}
@@ -411,14 +375,12 @@ public function __construct($config = 'rest')
$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);
+ 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'))
- {
+ elseif (property_exists($this, 'db')) {
$this->rest->db = $this->db;
}
@@ -428,29 +390,25 @@ public function __construct($config = 'rest')
// 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)
- {
+ 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'))
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_NOT_ACCEPTABLE);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ajax_only'),
+ ], 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)))
- {
+ 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)
- {
+ switch ($rest_auth) {
case 'basic':
$this->_prepare_basic_auth();
break;
@@ -464,85 +422,74 @@ public function __construct($config = 'rest')
}
}
+ /**
+ * 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(__DIR__."/../config/".$config_file.".php"))
- {
- $config = array();
- include(__DIR__ . "/../config/" . $config_file . ".php");
+ if (file_exists(__DIR__.'/'.$config_file.'.php')) {
+ $config = [];
+ include __DIR__.'/'.$config_file.'.php';
- foreach($config AS $key => $value)
- {
+ foreach ($config as $key => $value) {
$this->config->set_item($key, $value);
}
+ } else {
+ $this->load->config($config_file, false, true);
}
-
- $this->load->config($config_file, FALSE, TRUE);
}
/**
- * De-constructor
+ * De-constructor.
*
* @author Chris Kacerguis
- * @access public
+ *
* @return void
*/
public function __destruct()
{
// Log the loading time to the log table
- if ($this->config->item('rest_enable_logging') === TRUE)
- {
+ if ($this->config->item('rest_enable_logging') === true) {
// Get the current timestamp
- $this->_end_rtime = microtime(TRUE);
+ $this->_end_rtime = microtime(true);
$this->_log_access_time();
}
}
- /**
- * Checks to see if we have everything we need to run this library.
- *
- * @access protected
- * @throws Exception
- */
- protected function preflight_checks()
- {
- // Check to see if PHP is equal to or greater than 5.4.x
- if (is_php('5.4') === FALSE)
- {
- // CodeIgniter 3 is recommended for v5.4 or above
- throw new Exception('Using PHP v'.PHP_VERSION.', though PHP v5.4 or greater is required');
- }
-
- // Check to see if this is CI 3.x
- if (explode('.', CI_VERSION, 2)[0] < 3)
- {
- throw new Exception('REST Server requires CodeIgniter 3.x');
- }
- }
-
/**
* 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
+ * Controller method.
*
- * @access public
* @param string $object_called
- * @param array $arguments The arguments passed to the controller method
+ * @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)
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_FORBIDDEN);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported'),
+ ], HTTP_FORBIDDEN);
}
// Remove the supported format from the function name e.g. index.json => index
@@ -551,66 +498,59 @@ public function _remap($object_called, $arguments = [])
$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;
+ $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);
+ $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);
+ $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)
- {
+ 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') {
+ 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)
- ], REST_Controller_Definitions::HTTP_FORBIDDEN);
+ $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),
+ ], 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)
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_unauthorized'),
+ ], HTTP_UNAUTHORIZED);
}
// Sure it exists, but can they do anything with it?
- if (! method_exists($this, $controller_method))
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_METHOD_NOT_ALLOWED);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unknown_method'),
+ ], $this->http_status['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)
- {
+ 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, REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ 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, HTTP_UNAUTHORIZED);
}
// If no level is set use 0, they probably aren't using permissions
@@ -619,41 +559,34 @@ public function _remap($object_called, $arguments = [])
// 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)
- {
+ if ($this->config->item('rest_enable_logging') && $log_method) {
$this->_log_request($authorized);
}
- if($authorized === FALSE)
- {
+ 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, REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ $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, 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, REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ 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, 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);
+ elseif ($this->config->item('rest_enable_logging') && $log_method) {
+ $this->_log_request($authorized = true);
}
// Call the controller method and passed arguments
- try
- {
+ 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) {
+ } catch (Exception $ex) {
+ if ($this->config->item('rest_handle_exceptions') === false) {
throw $ex;
}
@@ -664,58 +597,49 @@ public function _remap($object_called, $arguments = [])
}
/**
- * Takes mixed data and optionally a status code, then creates the response
+ * Takes mixed data and optionally a status code, then creates the response.
*
- * @access public
- * @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
+ * @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)
+ 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){
+ if (!$isProfilingEnabled) {
ob_start();
// If the HTTP status is not NULL, then cast as an integer
- if ($http_code !== NULL)
- {
+ 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;
+ $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 = REST_Controller_Definitions::HTTP_NOT_FOUND;
+ if ($data === null && $http_code === null) {
+ $http_code = HTTP_NOT_FOUND;
}
// If data is not NULL and a HTTP status code provided, then continue
- elseif ($data !== NULL)
- {
+ elseif ($data !== null) {
// If the format method exists, call and return the output in that format
- if (method_exists(Format::class, 'to_' . $this->response->format))
- {
+ if (method_exists(Format::class, 'to_'.$this->response->format)) {
// Set the format header
$this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
- $output = Format::factory($data)->{'to_' . $this->response->format}();
+ $output = Format::factory($data)->{'to_'.$this->response->format}();
// 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')
- {
+ if ($this->response->format === 'array') {
$output = Format::factory($output)->{'to_json'}();
}
- }
- else
- {
+ } else {
// If an array or object, then parse as a json, so as to be a 'string'
- if (is_array($data) || is_object($data))
- {
+ if (is_array($data) || is_object($data)) {
$data = Format::factory($data)->{'to_json'}();
}
@@ -727,45 +651,37 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
// 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 = REST_Controller_Definitions::HTTP_OK;
+ $http_code > 0 || $http_code = 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)
- {
+ 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)
- {
+ if ($continue === false) {
// Display the data and exit execution
$this->output->_display();
exit;
- }
- else
- {
- if (is_callable('fastcgi_finish_request'))
- {
+ } 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
- {
+ } else {
// Legacy compatibility.
ob_end_flush();
}
}
// Otherwise dump the output automatically
- }
- else{
+ } else {
echo json_encode($data);
}
}
@@ -774,70 +690,62 @@ public function response($data = NULL, $http_code = NULL, $continue = FALSE)
* 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
+ * All the hooks after the controller's method termination are executable.
*
- * @access public
- * @param array|NULL $data Data to output to the user
- * @param int|NULL $http_code HTTP status code
+ * @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)
+ public function set_response($data = null, $http_code = null)
{
- $this->response($data, $http_code, TRUE);
+ $this->response($data, $http_code, true);
}
/**
- * Get the input format e.g. json or xml
+ * Get the input format e.g. json or xml.
*
- * @access protected
- * @return string|NULL Supported input format; otherwise, NULL
+ * @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 (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);
+ $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)
- {
+ 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)
- {
+ if ($content_type === $mime) {
return $type;
}
}
}
-
- return NULL;
}
/**
* Gets the default format from the configuration. Fallbacks to 'json'
* if the corresponding configuration option $config['rest_default_format']
- * is missing or is empty
+ * is missing or is empty.
*
- * @access protected
* @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
+ * Detect which format should be used to output the data.
*
- * @access protected
- * @return mixed|NULL|string Output format
+ * @return mixed|null|string Output format
*/
protected function _detect_output_format()
{
@@ -846,18 +754,15 @@ protected function _detect_output_format()
$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))
- {
+ 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']))
- {
+ if (isset($this->_get_args['format'])) {
$format = strtolower($this->_get_args['format']);
- if (isset($this->_supported_formats[$format]) === TRUE)
- {
+ if (isset($this->_supported_formats[$format]) === true) {
return $format;
}
}
@@ -866,27 +771,19 @@ protected function _detect_output_format()
$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)
- {
+ 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)
- {
+ 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 (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)
- {
+ } 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;
- }
- else if ($format === 'xml' && strpos($http_accept, 'html') === FALSE)
- {
+ } elseif ($format === 'xml' && strpos($http_accept, 'html') === false) {
// If it is truly XML, it wont want any HTML
return $format;
}
@@ -895,8 +792,7 @@ protected function _detect_output_format()
}
// Check if the controller has a default format
- if (empty($this->rest_format) === FALSE)
- {
+ if (empty($this->rest_format) === false) {
return $this->rest_format;
}
@@ -905,41 +801,36 @@ protected function _detect_output_format()
}
/**
- * Get the HTTP request string e.g. get or post
+ * Get the HTTP request string e.g. get or post.
*
- * @access protected
- * @return string|NULL Supported request method as a lowercase string; otherwise, NULL if not supported
+ * @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;
+ $method = null;
// Determine whether the 'enable_emulate_request' setting is enabled
- if ($this->config->item('enable_emulate_request') === TRUE)
- {
+ if ($this->config->item('enable_emulate_request') === true) {
$method = $this->input->post('_method');
- if ($method === NULL)
- {
+ if ($method === null) {
$method = $this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE');
}
$method = strtolower($method);
}
- if (empty($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';
+ return in_array($method, $this->allowed_http_methods) && method_exists($this, '_parse_'.$method) ? $method : 'get';
}
/**
- * See if the user has provided an API key
+ * See if the user has provided an API key.
*
- * @access protected
* @return bool
*/
protected function _detect_api_key()
@@ -948,19 +839,17 @@ protected function _detect_api_key()
$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));
+ $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;
+ $this->rest->key = null;
+ $this->rest->level = null;
+ $this->rest->user_id = null;
+ $this->rest->ignore_limits = false;
// Find the key from server or arguments
- if (($key = isset($this->_args[$api_key_variable]) ? $this->_args[$api_key_variable] : $this->input->server($key_name)))
- {
- if ( ! ($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row()))
- {
- return FALSE;
+ if (($key = isset($this->_args[$api_key_variable]) ? $this->_args[$api_key_variable] : $this->input->server($key_name))) {
+ if (!($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row())) {
+ return false;
}
$this->rest->key = $row->{$this->config->item('rest_key_column')};
@@ -975,64 +864,54 @@ protected function _detect_api_key()
* 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)
- {
+ if (empty($row->is_private_key) === false) {
// Check for a list of valid ip addresses
- if (isset($row->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;
+ $ip_address = $this->input->ip_address();
+ $found_address = false;
- foreach ($list_ip_addresses as $ip_address)
- {
- if ($ip_address === trim($ip_address))
- {
+ foreach ($list_ip_addresses as $ip_address) {
+ if ($ip_address === trim($ip_address)) {
// there is a match, set the the value to TRUE and break out of the loop
- $found_address = TRUE;
+ $found_address = true;
break;
}
}
return $found_address;
- }
- else
- {
+ } else {
// There should be at least one IP address for this private key
- return FALSE;
+ return false;
}
}
- return TRUE;
+ return true;
}
// No key has been sent
- return FALSE;
+ return false;
}
/**
- * Preferred return language
+ * Preferred return language.
*
- * @access protected
- * @return string|NULL|array The language code
+ * @return string|null|array The language code
*/
protected function _detect_lang()
{
$lang = $this->input->server('HTTP_ACCEPT_LANGUAGE');
- if ($lang === NULL)
- {
- return NULL;
+ if ($lang === null) {
+ return;
}
// It appears more than one language has been sent using a comma delimiter
- if (strpos($lang, ',') !== FALSE)
- {
+ if (strpos($lang, ',') !== false) {
$langs = explode(',', $lang);
$return_langs = [];
- foreach ($langs as $lang)
- {
+ foreach ($langs as $lang) {
// Remove weight and trim leading and trailing whitespace
list($lang) = explode(';', $lang);
$return_langs[] = trim($lang);
@@ -1046,25 +925,25 @@ protected function _detect_lang()
}
/**
- * Add the request to the log table
+ * Add the request to the log table.
*
- * @access protected
* @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)
+ 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 : '',
+ '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
+ 'time' => time(),
+ 'authorized' => $authorized,
]);
// Get the last insert id to update at a later stage of the request
@@ -1074,53 +953,49 @@ protected function _log_request($authorized = FALSE)
}
/**
- * Check if the requests to a controller method exceed a limit
+ * Check if the requests to a controller method exceed a limit.
*
- * @access protected
* @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)
- {
+ if (empty($this->rest->ignore_limits) === false) {
// Everything is fine
- return TRUE;
+ return true;
}
$api_key = isset($this->rest->key) ? $this->rest->key : '';
- switch ($this->config->item('rest_limits_method'))
- {
+ switch ($this->config->item('rest_limits_method')) {
case 'IP_ADDRESS':
$api_key = $this->input->ip_address();
- $limited_uri = 'ip-address:' . $api_key;
+ $limited_uri = 'ip-address:'.$api_key;
break;
case 'API_KEY':
- $limited_uri = 'api-key:' . $api_key;
+ $limited_uri = 'api-key:'.$api_key;
break;
case 'METHOD_NAME':
- $limited_uri = 'method-name:' . $controller_method;
+ $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);
+ 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 )
- {
+ if (isset($this->methods[$controller_method]['limit']) === false) {
// Everything is fine
- return TRUE;
+ return true;
}
// How many times can you get to this method in a defined time_limit (default: 1 hour)?
@@ -1136,20 +1011,18 @@ protected function _check_limit($controller_method)
->row();
// No calls have been made for this key
- if ($result === NULL)
- {
+ 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()
+ '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))
- {
+ elseif ($result->hour_started < (time() - $time_limit)) {
// Reset the started period and count
$this->rest->db
->where('uri', $limited_uri)
@@ -1160,29 +1033,26 @@ protected function _check_limit($controller_method)
}
// They have called within the hour, so lets update
- else
- {
+ else {
// The limit has been exceeded
- if ($result->count >= $limit)
- {
- return FALSE;
+ 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)
+ ->set('count', 'count + 1', false)
->update($this->config->item('rest_limits_table'));
}
- return TRUE;
+ return true;
}
/**
- * Check if there is a specific auth type set for the current class/method/HTTP-method being called
+ * Check if there is a specific auth type set for the current class/method/HTTP-method being called.
*
- * @access protected
* @return bool
*/
protected function _auth_override_check()
@@ -1191,89 +1061,76 @@ protected function _auth_override_check()
$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))
- {
+ 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
- {
+ 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;
+ 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')
- {
+ if ($auth_override_class_method[$this->router->class]['*'] === 'basic') {
$this->_prepare_basic_auth();
- return TRUE;
+ return true;
}
// Digest auth override found, prepare digest
- if ($auth_override_class_method[$this->router->class]['*'] === 'digest')
- {
+ if ($auth_override_class_method[$this->router->class]['*'] === 'digest') {
$this->_prepare_digest_auth();
- return TRUE;
+ return true;
}
// Session auth override found, check session
- if ($auth_override_class_method[$this->router->class]['*'] === 'session')
- {
+ if ($auth_override_class_method[$this->router->class]['*'] === 'session') {
$this->_check_php_session();
- return TRUE;
+ return true;
}
// Whitelist auth override found, check client's ip against config whitelist
- if ($auth_override_class_method[$this->router->class]['*'] === 'whitelist')
- {
+ if ($auth_override_class_method[$this->router->class]['*'] === 'whitelist') {
$this->_check_whitelist_auth();
- return TRUE;
+ 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]))
- {
+ 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;
+ 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')
- {
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'basic') {
$this->_prepare_basic_auth();
- return TRUE;
+ return true;
}
// Digest auth override found, prepare digest
- if ($auth_override_class_method[$this->router->class][$this->router->method] === 'digest')
- {
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'digest') {
$this->_prepare_digest_auth();
- return TRUE;
+ return true;
}
// Session auth override found, check session
- if ($auth_override_class_method[$this->router->class][$this->router->method] === 'session')
- {
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'session') {
$this->_check_php_session();
- return TRUE;
+ 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')
- {
+ if ($auth_override_class_method[$this->router->class][$this->router->method] === 'whitelist') {
$this->_check_whitelist_auth();
- return TRUE;
+ return true;
}
}
}
@@ -1282,99 +1139,86 @@ protected function _auth_override_check()
$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))
- {
+ 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]))
- {
+ 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;
+ 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')
- {
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'basic') {
$this->_prepare_basic_auth();
- return TRUE;
+ return true;
}
// Digest auth override found, prepare digest
- if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'digest')
- {
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'digest') {
$this->_prepare_digest_auth();
- return TRUE;
+ return true;
}
// Session auth override found, check session
- if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'session')
- {
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'session') {
$this->_check_php_session();
- return TRUE;
+ 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')
- {
+ if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'whitelist') {
$this->_check_whitelist_auth();
- return TRUE;
+ 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]))
- {
+ 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;
+ 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')
- {
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'basic') {
$this->_prepare_basic_auth();
- return TRUE;
+ return true;
}
// Digest auth override found, prepare digest
- if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'digest')
- {
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'digest') {
$this->_prepare_digest_auth();
- return TRUE;
+ return true;
}
// Session auth override found, check session
- if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'session')
- {
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'session') {
$this->_check_php_session();
- return TRUE;
+ 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')
- {
+ if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'whitelist') {
$this->_check_whitelist_auth();
- return TRUE;
+ return true;
}
}
}
- return FALSE;
+
+ return false;
}
/**
- * Parse the GET request arguments
+ * Parse the GET request arguments.
*
- * @access protected
* @return void
*/
protected function _parse_get()
@@ -1384,48 +1228,40 @@ protected function _parse_get()
}
/**
- * Parse the POST request arguments
+ * Parse the POST request arguments.
*
- * @access protected
* @return void
*/
protected function _parse_post()
{
$this->_post_args = $_POST;
- if ($this->request->format)
- {
+ if ($this->request->format) {
$this->request->body = $this->input->raw_input_stream;
}
}
/**
- * Parse the PUT request arguments
+ * Parse the PUT request arguments.
*
- * @access protected
* @return void
*/
protected function _parse_put()
{
- if ($this->request->format)
- {
+ if ($this->request->format) {
$this->request->body = $this->input->raw_input_stream;
- if ($this->request->format === 'json')
- {
+ if ($this->request->format === 'json') {
$this->_put_args = json_decode($this->input->raw_input_stream);
}
- }
- else if ($this->input->method() === 'put')
- {
+ } 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
+ * Parse the HEAD request arguments.
*
- * @access protected
* @return void
*/
protected function _parse_head()
@@ -1438,9 +1274,8 @@ protected function _parse_head()
}
/**
- * Parse the OPTIONS request arguments
+ * Parse the OPTIONS request arguments.
*
- * @access protected
* @return void
*/
protected function _parse_options()
@@ -1453,44 +1288,37 @@ protected function _parse_options()
}
/**
- * Parse the PATCH request arguments
+ * Parse the PATCH request arguments.
*
- * @access protected
* @return void
*/
protected function _parse_patch()
{
// It might be a HTTP body
- if ($this->request->format)
- {
+ if ($this->request->format) {
$this->request->body = $this->input->raw_input_stream;
- }
- else if ($this->input->method() === 'patch')
- {
+ } 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
+ * Parse the DELETE request arguments.
*
- * @access protected
* @return void
*/
protected function _parse_delete()
{
// These should exist if a DELETE request
- if ($this->input->method() === 'delete')
- {
+ if ($this->input->method() === 'delete') {
$this->_delete_args = $this->input->input_stream();
}
}
/**
- * Parse the query parameters
+ * Parse the query parameters.
*
- * @access protected
* @return void
*/
protected function _parse_query()
@@ -1501,177 +1329,168 @@ protected function _parse_query()
// INPUT FUNCTION --------------------------------------------------------------
/**
- * Retrieve a value from a GET request
+ * 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
*
- * @access public
- * @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
+ * @return array|string|null Value from the GET request; otherwise, NULL
*/
- public function get($key = NULL, $xss_clean = NULL)
+ public function get($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_get_args;
}
- return isset($this->_get_args[$key]) ? $this->_xss_clean($this->_get_args[$key], $xss_clean) : NULL;
+ return isset($this->_get_args[$key]) ? $this->_xss_clean($this->_get_args[$key], $xss_clean) : null;
}
/**
- * Retrieve a value from a OPTIONS request
+ * 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
*
- * @access public
- * @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
+ * @return array|string|null Value from the OPTIONS request; otherwise, NULL
*/
- public function options($key = NULL, $xss_clean = NULL)
+ public function options($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_options_args;
}
- return isset($this->_options_args[$key]) ? $this->_xss_clean($this->_options_args[$key], $xss_clean) : NULL;
+ return isset($this->_options_args[$key]) ? $this->_xss_clean($this->_options_args[$key], $xss_clean) : null;
}
/**
- * Retrieve a value from a HEAD request
+ * Retrieve a value from a HEAD request.
*
- * @access public
- * @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
+ * @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)
+ public function head($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_head_args;
}
- return isset($this->_head_args[$key]) ? $this->_xss_clean($this->_head_args[$key], $xss_clean) : NULL;
+ return isset($this->_head_args[$key]) ? $this->_xss_clean($this->_head_args[$key], $xss_clean) : null;
}
/**
- * Retrieve a value from a POST request
+ * 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
*
- * @access public
- * @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
+ * @return array|string|null Value from the POST request; otherwise, NULL
*/
- public function post($key = NULL, $xss_clean = NULL)
+ public function post($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_post_args;
}
- return isset($this->_post_args[$key]) ? $this->_xss_clean($this->_post_args[$key], $xss_clean) : NULL;
+ return isset($this->_post_args[$key]) ? $this->_xss_clean($this->_post_args[$key], $xss_clean) : null;
}
/**
- * Retrieve a value from a PUT request
+ * 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
*
- * @access public
- * @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
+ * @return array|string|null Value from the PUT request; otherwise, NULL
*/
- public function put($key = NULL, $xss_clean = NULL)
+ public function put($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_put_args;
}
- return isset($this->_put_args[$key]) ? $this->_xss_clean($this->_put_args[$key], $xss_clean) : NULL;
+ return isset($this->_put_args[$key]) ? $this->_xss_clean($this->_put_args[$key], $xss_clean) : null;
}
/**
- * Retrieve a value from a DELETE request
+ * Retrieve a value from a DELETE request.
*
- * @access public
- * @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
+ * @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)
+ public function delete($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_delete_args;
}
- return isset($this->_delete_args[$key]) ? $this->_xss_clean($this->_delete_args[$key], $xss_clean) : NULL;
+ return isset($this->_delete_args[$key]) ? $this->_xss_clean($this->_delete_args[$key], $xss_clean) : null;
}
/**
- * Retrieve a value from a PATCH request
+ * 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
*
- * @access public
- * @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
+ * @return array|string|null Value from the PATCH request; otherwise, NULL
*/
- public function patch($key = NULL, $xss_clean = NULL)
+ public function patch($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_patch_args;
}
- return isset($this->_patch_args[$key]) ? $this->_xss_clean($this->_patch_args[$key], $xss_clean) : NULL;
+ return isset($this->_patch_args[$key]) ? $this->_xss_clean($this->_patch_args[$key], $xss_clean) : null;
}
/**
- * Retrieve a value from the query parameters
+ * 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
*
- * @access public
- * @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
+ * @return array|string|null Value from the query parameters; otherwise, NULL
*/
- public function query($key = NULL, $xss_clean = NULL)
+ public function query($key = null, $xss_clean = null)
{
- if ($key === NULL)
- {
+ if ($key === null) {
return $this->_query_args;
}
- return isset($this->_query_args[$key]) ? $this->_xss_clean($this->_query_args[$key], $xss_clean) : NULL;
+ 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
+ * prevented.
+ *
+ * @param string $value Input data
+ * @param bool $xss_clean Whether to apply XSS filtering
*
- * @access protected
- * @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;
+ return $xss_clean === true ? $this->security->xss_clean($value) : $value;
}
/**
- * Retrieve the validation errors
+ * Retrieve the validation errors.
*
- * @access public
* @return array
*/
public function validation_errors()
@@ -1684,40 +1503,39 @@ public function validation_errors()
// SECURITY FUNCTIONS ---------------------------------------------------------
/**
- * Perform LDAP Authentication
+ * Perform LDAP Authentication.
*
- * @access protected
* @param string $username The username to validate
* @param string $password The password to validate
+ *
* @return bool
*/
- protected function _perform_ldap_auth($username = '', $password = NULL)
+ protected function _perform_ldap_auth($username = '', $password = null)
{
- if (empty($username))
- {
+ if (empty($username)) {
log_message('debug', 'LDAP Auth: failure, empty username');
- return FALSE;
+
+ return false;
}
log_message('debug', 'LDAP Auth: Loading configuration');
- $this->config->load('ldap', TRUE);
+ $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'),
+ '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($ldaphost) ? $ldaphost : '[ldap not configured]'));
+ log_message('debug', 'LDAP Auth: Connect to '.(isset($ldaphost) ? $ldaphost : '[ldap not configured]'));
// Connect to the ldap server
$ldapconn = ldap_connect($ldap['host'], $ldap['port']);
- if ($ldapconn)
- {
+ if ($ldapconn) {
log_message('debug', 'Setting timeout to '.$ldap['timeout'].' seconds');
ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, $ldap['timeout']);
@@ -1728,45 +1546,45 @@ protected function _perform_ldap_auth($username = '', $password = NULL)
$ldapbind = ldap_bind($ldapconn, $ldap['rdn'], $ldap['pass']);
// Verify the binding
- if ($ldapbind === FALSE)
- {
+ if ($ldapbind === false) {
log_message('error', 'LDAP Auth: bind was unsuccessful');
- return FALSE;
+
+ return false;
}
log_message('debug', 'LDAP Auth: bind successful');
}
// Search for user
- if (($res_id = ldap_search($ldapconn, $ldap['basedn'], "uid=$username")) === FALSE)
- {
+ if (($res_id = ldap_search($ldapconn, $ldap['basedn'], "uid=$username")) === false) {
log_message('error', 'LDAP Auth: User '.$username.' not found in search');
- return FALSE;
+
+ return false;
}
- if (ldap_count_entries($ldapconn, $res_id) !== 1)
- {
+ if (ldap_count_entries($ldapconn, $res_id) !== 1) {
log_message('error', 'LDAP Auth: Failure, username '.$username.'found more than once');
- return FALSE;
+
+ return false;
}
- if (($entry_id = ldap_first_entry($ldapconn, $res_id)) === 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;
+
+ return false;
}
- if (($user_dn = ldap_get_dn($ldapconn, $entry_id)) === 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;
+
+ 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;
+ 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');
@@ -1775,42 +1593,41 @@ protected function _perform_ldap_auth($username = '', $password = NULL)
ldap_close($ldapconn);
- return TRUE;
+ return true;
}
/**
- * Perform Library Authentication - Override this function to change the way the library is called
+ * 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 bool
*/
- protected function _perform_library_auth($username = '', $password = NULL)
+ protected function _perform_library_auth($username = '', $password = null)
{
- if (empty($username))
- {
+ if (empty($username)) {
log_message('error', 'Library Auth: Failure, empty username');
- return FALSE;
+
+ 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))
- {
+ if (empty($auth_library_class)) {
log_message('debug', 'Library Auth: Failure, empty auth_library_class');
- return FALSE;
+
+ return false;
}
- if (empty($auth_library_function))
- {
+ if (empty($auth_library_function)) {
log_message('debug', 'Library Auth: Failure, empty auth_library_function');
- return FALSE;
+
+ return false;
}
- if (is_callable([$auth_library_class, $auth_library_function]) === FALSE)
- {
+ if (is_callable([$auth_library_class, $auth_library_function]) === false) {
$this->load->library($auth_library_class);
}
@@ -1818,73 +1635,64 @@ protected function _perform_library_auth($username = '', $password = NULL)
}
/**
- * Check if the user is logged in
+ * Check if the user is logged in.
*
- * @access protected
- * @param string $username The user's name
+ * @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)
+ protected function _check_login($username = null, $password = false)
{
- if (empty($username))
- {
- return 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')
- {
+ 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 ($password === false) {
+ return false;
}
- if ($auth_source === 'ldap')
- {
+ if ($auth_source === 'ldap') {
log_message('debug', "Performing LDAP authentication for $username");
return $this->_perform_ldap_auth($username, $password);
}
- if ($auth_source === 'library')
- {
+ 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 (array_key_exists($username, $valid_logins) === false) {
+ return false;
}
- if ($valid_logins[$username] !== $password)
- {
- return FALSE;
+ if ($valid_logins[$username] !== $password) {
+ return false;
}
- return TRUE;
+ return true;
}
/**
- * Check to see if the user is logged in with a PHP session key
+ * Check to see if the user is logged in with a PHP session key.
*
- * @access protected
* @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'))
- {
+ if ($this->config->item('rest_ip_whitelist_enabled')) {
$this->_check_whitelist_auth();
}
@@ -1892,27 +1700,24 @@ protected function _check_php_session()
$key = $this->config->item('auth_source');
// If false, then the user isn't logged in
- if ( ! $this->session->userdata($key))
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
+ ], $this->http_status['UNAUTHORIZED']);
}
}
/**
- * Prepares for basic authentication
+ * Prepares for basic authentication.
*
- * @access protected
* @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'))
- {
+ if ($this->config->item('rest_ip_whitelist_enabled')) {
$this->_check_whitelist_auth();
}
@@ -1920,48 +1725,40 @@ protected function _prepare_basic_auth()
$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 = null;
+ if ($username !== null) {
$password = $this->input->server('PHP_AUTH_PW');
- }
- elseif ($http_auth !== NULL)
- {
+ } 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)
- {
+ 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)
- {
+ if ($this->_check_login($username, $password) === false) {
$this->_force_login();
}
}
/**
- * Prepares for digest authentication
+ * Prepares for digest authentication.
*
- * @access protected
* @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'))
- {
+ 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)
- {
+ if ($digest_string === null) {
$digest_string = $this->input->server('HTTP_AUTHORIZATION');
}
@@ -1969,8 +1766,7 @@ protected function _prepare_digest_auth()
// 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))
- {
+ if (empty($digest_string)) {
$this->_force_login($unique_id);
}
@@ -1980,8 +1776,7 @@ protected function _prepare_digest_auth()
$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
- if (isset($digest['username']) === FALSE || $this->_check_login($digest['username'], TRUE) === FALSE)
- {
+ if (isset($digest['username']) === false || $this->_check_login($digest['username'], true) === false) {
$this->_force_login($unique_id);
}
@@ -1989,20 +1784,18 @@ protected function _prepare_digest_auth()
$valid_response = md5($digest['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)
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_invalid_credentials'),
+ ], $this->http_status['UNAUTHORIZED']);
}
}
/**
- * Checks if the client's ip is in the 'rest_ip_blacklist' config and generates a 401 response
+ * Checks if the client's ip is in the 'rest_ip_blacklist' config and generates a 401 response.
*
- * @access protected
* @return void
*/
protected function _check_blacklist_auth()
@@ -2011,20 +1804,18 @@ protected function _check_blacklist_auth()
$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')))
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_denied'),
+ ], $this->http_status['UNAUTHORIZED']);
}
}
/**
- * Check if the client's ip is in the 'rest_ip_whitelist' config and generates a 401 response
+ * Check if the client's ip is in the 'rest_ip_whitelist' config and generates a 401 response.
*
- * @access protected
* @return void
*/
protected function _check_whitelist_auth()
@@ -2033,46 +1824,41 @@ protected function _check_whitelist_auth()
array_push($whitelist, '127.0.0.1', '0.0.0.0');
- foreach ($whitelist as &$ip)
- {
+ 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)
- {
+ 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')
- ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_unauthorized'),
+ ], $this->http_status['UNAUTHORIZED']);
}
}
/**
- * Force logging in by setting the WWW-Authenticate header
+ * Force logging in by setting the WWW-Authenticate header.
*
- * @access protected
* @param string $nonce A server-specified data string which should be uniquely generated
- * each time
+ * 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')
- {
+ if ($rest_auth === 'basic') {
// See http://tools.ietf.org/html/rfc2617#page-5
header('WWW-Authenticate: Basic realm="'.$rest_realm.'"');
- }
- elseif ($rest_auth === 'digest')
- {
+ } 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).'"');
+ .'", opaque="'.md5($rest_realm).'"');
}
if ($this->config->item('strict_api_and_auth') === true) {
@@ -2081,21 +1867,21 @@ protected function _force_login($nonce = '')
// 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')
- ], REST_Controller_Definitions::HTTP_UNAUTHORIZED);
+ $this->config->item('rest_status_field_name') => false,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
+ ], $this->http_status['UNAUTHORIZED']);
}
/**
- * Updates the log table with the total access time
+ * Updates the log table with the total access time.
*
- * @access protected
* @author Chris Kacerguis
+ *
* @return bool TRUE log table updated; otherwise, FALSE
*/
protected function _log_access_time()
{
- if($this->_insert_id == ''){
+ if ($this->_insert_id == '') {
return false;
}
@@ -2103,21 +1889,22 @@ protected function _log_access_time()
return $this->rest->db->update(
$this->config->item('rest_logs_table'), $payload, [
- 'id' => $this->_insert_id
+ 'id' => $this->_insert_id,
]);
}
/**
- * Updates the log table with HTTP response code
+ * Updates the log table with HTTP response code.
*
- * @access protected
* @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 == ''){
+ if ($this->_insert_id == '') {
return false;
}
@@ -2125,29 +1912,27 @@ protected function _log_response_code($http_code)
return $this->rest->db->update(
$this->config->item('rest_logs_table'), $payload, [
- 'id' => $this->_insert_id
+ 'id' => $this->_insert_id,
]);
}
/**
- * Check to see if the API key has access to the controller and methods
+ * Check to see if the API key has access to the controller and methods.
*
- * @access protected
* @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;
+ 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
+ $this->router->class,
]);
// Remove any double slashes for safety
@@ -2159,18 +1944,16 @@ protected function _check_access()
->where('controller', $controller)
->get($this->config->item('rest_access_table'))->row_array();
- if (!empty($accessRow) && !empty($accessRow['all_access']))
- {
- return TRUE;
+ if (!empty($accessRow) && !empty($accessRow['all_access'])) {
+ return true;
}
return false;
}
/**
- * Checks allowed domains, and adds appropriate headers for HTTP access control (CORS)
+ * Checks allowed domains, and adds appropriate headers for HTTP access control (CORS).
*
- * @access protected
* @return void
*/
protected function _check_cors()
@@ -2180,25 +1963,20 @@ protected function _check_cors()
$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)
- {
+ 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
- {
+ } else {
// We're going to allow only certain domains access
// Store the HTTP Origin header
$origin = $this->input->server('HTTP_ORIGIN');
- if ($origin === NULL)
- {
+ 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')))
- {
+ 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);
@@ -2206,21 +1984,17 @@ protected function _check_cors()
}
// 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 (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')
- {
+ 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);
+ 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/application/language/serbian_lat/index.html b/src/index.html
old mode 100644
new mode 100755
similarity index 100%
rename from application/language/serbian_lat/index.html
rename to src/index.html
diff --git a/application/config/rest.php b/src/rest.php
similarity index 99%
rename from application/config/rest.php
rename to src/rest.php
index 394937ce..887141c6 100644
--- a/application/config/rest.php
+++ b/src/rest.php
@@ -1,6 +1,6 @@
Date: Sun, 10 Nov 2019 13:58:04 -0600
Subject: [PATCH 077/129] fix correct repo
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 4955bb84..0a7b6b4b 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# CodeIgniter RestServer
-[](https://github.styleci.io/repos/219224674)
+[](https://github.styleci.io/repos/230589)
A fully RESTful server implementation for CodeIgniter using one library, one config file and one controller.
From 1ec3b03ad566203643b7c21d6f4ffa68d10f5894 Mon Sep 17 00:00:00 2001
From: Flor27
Date: Tue, 12 Nov 2019 11:21:39 +0100
Subject: [PATCH 078/129] response method update for CORB protection
CORB protection was added to Chromium based browsers to add further cross-origin resource loads protection.
Details about the protection here : https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md
Without this update, some AJAX requests from those browsers fall in the CORB and fail.
The update consists of sending the right Content-Type header for callback encapsuled JSON output : application/javascript instead of application/json
---
src/RestController.php | 14 +++++++++++---
1 file changed, 11 insertions(+), 3 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 6ae504a1..b6555713 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -628,10 +628,18 @@ public function response($data = null, $http_code = null, $continue = false)
elseif ($data !== null) {
// If the format method exists, call and return the output in that format
if (method_exists(Format::class, 'to_'.$this->response->format)) {
- // Set the format header
- $this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
+ // CORB protection
+ // First, get the output content.
$output = Format::factory($data)->{'to_'.$this->response->format}();
-
+
+ // Set the format header
+ // Then, check if the client asked for a callback, and if the output contains this callback :
+ if (isset($this->_get_args['callback']) && $this->response->format == 'json' && preg_match('/^' . $this->_get_args['callback'] . '/', $output)) {
+ $this->output->set_content_type($this->_supported_formats['jsonp'], strtolower($this->config->item('charset')));
+ } else {
+ $this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
+ }
+
// An array must be parsed as a string, so as not to cause an array to string error
// Json is the most appropriate form for such a data type
if ($this->response->format === 'array') {
From 8bbcf0d5ae26982b5c6f9a65faed35832bc06284 Mon Sep 17 00:00:00 2001
From: Flor27
Date: Tue, 12 Nov 2019 11:30:37 +0100
Subject: [PATCH 079/129] continuous-integration/styleci/pr corrections
continuous-integration/styleci/pr corrections
---
src/RestController.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index b6555713..a98efd39 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -631,15 +631,15 @@ public function response($data = null, $http_code = null, $continue = false)
// CORB protection
// First, get the output content.
$output = Format::factory($data)->{'to_'.$this->response->format}();
-
+
// Set the format header
// Then, check if the client asked for a callback, and if the output contains this callback :
- if (isset($this->_get_args['callback']) && $this->response->format == 'json' && preg_match('/^' . $this->_get_args['callback'] . '/', $output)) {
+ 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') {
From 6155eb0df588470f9d71ac0c4a5ba962d4c11cdf Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 08:37:51 -0600
Subject: [PATCH 080/129] fixes #1032
---
src/RestController.php | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index a98efd39..7b23106c 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -442,15 +442,13 @@ private function do_auth($method = false)
*/
private function get_local_config($config_file)
{
- if (file_exists(__DIR__.'/'.$config_file.'.php')) {
+ if (!$this->load->config($config_file, false))
+ {
$config = [];
include __DIR__.'/'.$config_file.'.php';
-
foreach ($config as $key => $value) {
$this->config->set_item($key, $value);
}
- } else {
- $this->load->config($config_file, false, true);
}
}
From 1086cb3ab7e9165183fb298bf32d51fd07db7759 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 08:38:55 -0600
Subject: [PATCH 081/129] style ci fix
---
src/RestController.php | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 7b23106c..534338bc 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -442,8 +442,7 @@ private function do_auth($method = false)
*/
private function get_local_config($config_file)
{
- if (!$this->load->config($config_file, false))
- {
+ if (!$this->load->config($config_file, false)) {
$config = [];
include __DIR__.'/'.$config_file.'.php';
foreach ($config as $key => $value) {
From f7eb9a8a03aee3fc81fefef934292a748792d467 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 08:40:14 -0600
Subject: [PATCH 082/129] fixes #1027
---
src/RestController.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 534338bc..e7b8d914 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -877,8 +877,8 @@ protected function _detect_api_key()
$ip_address = $this->input->ip_address();
$found_address = false;
- foreach ($list_ip_addresses as $ip_address) {
- if ($ip_address === trim($ip_address)) {
+ 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;
From 69e4cc1b005cfae60a162ac04e7748be3f3720c0 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 08:50:46 -0600
Subject: [PATCH 083/129] fixes #933 and #877
---
src/RestController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index e7b8d914..6886f9a1 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -684,7 +684,7 @@ public function response($data = null, $http_code = null, $continue = false)
ob_end_flush();
}
}
-
+ ob_end_flush();
// Otherwise dump the output automatically
} else {
echo json_encode($data);
From ed4d5d7184c1d6cf58bdeb6914882f19ea2479d5 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 14:54:30 +0000
Subject: [PATCH 084/129] Apply fixes from StyleCI
---
src/RestController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index 6886f9a1..6ee932eb 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -685,7 +685,7 @@ public function response($data = null, $http_code = null, $continue = false)
}
}
ob_end_flush();
- // Otherwise dump the output automatically
+ // Otherwise dump the output automatically
} else {
echo json_encode($data);
}
From 03403924968cae8bb46883611409061585e782f6 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 09:39:30 -0600
Subject: [PATCH 085/129] added github sponsor stuff
---
.github/FUNDING.yml | 1 +
1 file changed, 1 insertion(+)
create mode 100644 .github/FUNDING.yml
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 00000000..a7b75f10
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: chriskacerguis
\ No newline at end of file
From e1910747f5a044aa3691efd9dc604a289bec1579 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 17:16:09 -0600
Subject: [PATCH 086/129] added example
---
examples/get.php | 55 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
create mode 100644 examples/get.php
diff --git a/examples/get.php b/examples/get.php
new file mode 100644
index 00000000..cd15405f
--- /dev/null
+++ b/examples/get.php
@@ -0,0 +1,55 @@
+ 1, 'name' => 'John', 'email' => 'john@example.com'],
+ ['id' => 2, '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);
+ }
+ }
+ }
+}
\ No newline at end of file
From 29d10878cacda817d15bd9cf639dc71ae8485663 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 23:17:07 +0000
Subject: [PATCH 087/129] Apply fixes from StyleCI
---
examples/get.php | 28 +++++++++++-----------------
1 file changed, 11 insertions(+), 17 deletions(-)
diff --git a/examples/get.php b/examples/get.php
index cd15405f..bb2c94d0 100644
--- a/examples/get.php
+++ b/examples/get.php
@@ -1,5 +1,6 @@
get('id');
- if ($id === null)
- {
+ if ($id === null) {
// Check if the users data store contains users
- if ($users)
- {
+ if ($users) {
// Set the response and exit
$this->response($users, 200);
- }
- else
- {
+ } else {
// Set the response and exit
$this->response([
- 'status' => false,
- 'message' => 'No users were found'
+ 'status' => false,
+ 'message' => 'No users were found',
], 404);
}
}
}
-}
\ No newline at end of file
+}
From 4df17d7681155b45bbab0c7df97611ba7fef50f9 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 12 Nov 2019 18:33:01 -0600
Subject: [PATCH 088/129] quick doc fix
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 0a7b6b4b..82d6e35c 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@ A fully RESTful server implementation for CodeIgniter using one library, one con
## Installation
```sh
-composer require chriskacerguis/ci-restserver
+composer require chriskacerguis/codeigniter-restserver
```
## Usage
From 7bbf32df32db7f1e8a6b0d1c7e3eb88c0ab81e88 Mon Sep 17 00:00:00 2001
From: Hojjat Salmasian
Date: Tue, 19 Nov 2019 14:20:25 -0500
Subject: [PATCH 089/129] Delete example
The example in README.md is sufficient
---
examples/get.php | 49 ------------------------------------------------
1 file changed, 49 deletions(-)
delete mode 100644 examples/get.php
diff --git a/examples/get.php b/examples/get.php
deleted file mode 100644
index bb2c94d0..00000000
--- a/examples/get.php
+++ /dev/null
@@ -1,49 +0,0 @@
- 1, 'name' => 'John', 'email' => 'john@example.com'],
- ['id' => 2, '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);
- }
- }
- }
-}
From b471a60514dfcf1651927f2f58c65070135d776e Mon Sep 17 00:00:00 2001
From: Hojjat Salmasian
Date: Tue, 19 Nov 2019 14:26:54 -0500
Subject: [PATCH 090/129] Making the example in README.md work
Also expanding the example to demonstrate how the id parameter is used
---
README.md | 41 ++++++++++++++++++++++++++++++-----------
1 file changed, 30 insertions(+), 11 deletions(-)
diff --git a/README.md b/README.md
index 82d6e35c..f7f4e305 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,8 @@ or run
composer require chriskacerguis/codeigniter-restserver
```
+Note that you will need to copy `rest.php` to your `config` directory (e.g. `application/config`)
+
Step 1: Add this to your controller (should be before any of your code)
```php
@@ -43,7 +45,10 @@ class Example extends RestController
## Basic GET example
-Here is a basic example of
+Here is a basic example. This controller, which should be saved as `Api.php`, can be called in two ways:
+
+* `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
1, 'name' => 'John', 'email' => 'john@example.com'],
- ['id' => 2, 'name' => 'Jim', 'email' => 'jim@example.com'],
+ ['id' => 0, 'name' => 'John', 'email' => 'john@example.com'],
+ ['id' => 1, 'name' => 'Jim', 'email' => 'jim@example.com'],
];
- $id = $this->get('id');
+ $id = $this->get( 'id' );
- if ($id === null)
+ if ( $id === null )
{
// Check if the users data store contains users
- if ($users)
+ if ( $users )
{
// Set the response and exit
- $this->response($users, 200);
+ $this->response( $users, 200 );
}
else
{
// Set the response and exit
- $this->response([
+ $this->response( [
'status' => false,
'message' => 'No users were found'
- ], 404);
+ ], 404 );
+ }
+ }
+ else
+ {
+ if ( array_key_exists( $id, $users ) )
+ {
+ $this->response( $users[$id], 200 );
+ }
+ else
+ {
+ $this->response( [
+ 'status' => false,
+ 'message' => 'No such user found'
+ ], 404 );
}
}
}
}
-```
\ No newline at end of file
+```
From d708cbbb8ddc3e4beae2030e3f44b3434d896fdd Mon Sep 17 00:00:00 2001
From: Ale
Date: Sat, 23 Nov 2019 08:22:24 -0300
Subject: [PATCH 091/129] Repair undefined variable.
---
src/RestController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index 6ee932eb..f7a2d8bf 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -1536,7 +1536,7 @@ protected function _perform_ldap_auth($username = '', $password = null)
'basedn' => $this->config->item('basedn', 'ldap'),
];
- log_message('debug', 'LDAP Auth: Connect to '.(isset($ldaphost) ? $ldaphost : '[ldap not configured]'));
+ 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']);
From 3aa10fe1f48eca967cc5e63bfd2a7ef20f75591d Mon Sep 17 00:00:00 2001
From: Ale
Date: Sat, 23 Nov 2019 20:04:43 -0300
Subject: [PATCH 092/129] Replace old http_status array by http status
constants
---
src/RestController.php | 13 +++++++------
1 file changed, 7 insertions(+), 6 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index f7a2d8bf..c31e0b18 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -218,6 +218,7 @@ class RestController extends \CI_Controller
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;
@@ -539,7 +540,7 @@ public function _remap($object_called, $arguments = [])
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unknown_method'),
- ], $this->http_status['METHOD_NOT_ALLOWED']);
+ ], HTTP_METHOD_NOT_ALLOWED);
}
// Doing key related stuff? Can only do it if they have a key right?
@@ -1710,7 +1711,7 @@ protected function _check_php_session()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], HTTP_UNAUTHORIZED);
}
}
@@ -1794,7 +1795,7 @@ protected function _prepare_digest_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_invalid_credentials'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], HTTP_UNAUTHORIZED);
}
}
@@ -1814,7 +1815,7 @@ protected function _check_blacklist_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_denied'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], HTTP_UNAUTHORIZED);
}
}
@@ -1839,7 +1840,7 @@ protected function _check_whitelist_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_unauthorized'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], HTTP_UNAUTHORIZED);
}
}
@@ -1874,7 +1875,7 @@ protected function _force_login($nonce = '')
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], HTTP_UNAUTHORIZED);
}
/**
From 39443559e39afc509e4b6e8064623c99f35592b3 Mon Sep 17 00:00:00 2001
From: Ale
Date: Tue, 3 Dec 2019 17:55:22 -0300
Subject: [PATCH 093/129] Add self before the http constants for prevent php 7
warning of undefined constants
---
src/RestController.php | 30 +++++++++++++++---------------
1 file changed, 15 insertions(+), 15 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index c31e0b18..722575c5 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -401,7 +401,7 @@ public function __construct($config = 'rest')
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ajax_only'),
- ], HTTP_NOT_ACCEPTABLE);
+ ], self::HTTP_NOT_ACCEPTABLE);
}
// When there is no specific override for the current class/method, use the default auth value set in the config
@@ -487,7 +487,7 @@ public function _remap($object_called, $arguments = [])
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported'),
- ], HTTP_FORBIDDEN);
+ ], self::HTTP_FORBIDDEN);
}
// Remove the supported format from the function name e.g. index.json => index
@@ -520,7 +520,7 @@ public function _remap($object_called, $arguments = [])
$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),
- ], HTTP_FORBIDDEN);
+ ], self::HTTP_FORBIDDEN);
}
// Check to see if this key has access to the requested controller
@@ -532,7 +532,7 @@ public function _remap($object_called, $arguments = [])
$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'),
- ], HTTP_UNAUTHORIZED);
+ ], self::HTTP_UNAUTHORIZED);
}
// Sure it exists, but can they do anything with it?
@@ -540,7 +540,7 @@ public function _remap($object_called, $arguments = [])
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unknown_method'),
- ], HTTP_METHOD_NOT_ALLOWED);
+ ], self::HTTP_METHOD_NOT_ALLOWED);
}
// Doing key related stuff? Can only do it if they have a key right?
@@ -548,7 +548,7 @@ public function _remap($object_called, $arguments = [])
// 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, HTTP_UNAUTHORIZED);
+ $this->response($response, self::HTTP_UNAUTHORIZED);
}
// If no level is set use 0, they probably aren't using permissions
@@ -563,14 +563,14 @@ public function _remap($object_called, $arguments = [])
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, HTTP_UNAUTHORIZED);
+ $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, HTTP_UNAUTHORIZED);
+ $this->response($response, self::HTTP_UNAUTHORIZED);
}
// No key stuff, but record that stuff is happening
@@ -619,7 +619,7 @@ public function response($data = null, $http_code = null, $continue = false)
// If data is NULL and no HTTP status code provided, then display, error and exit
if ($data === null && $http_code === null) {
- $http_code = HTTP_NOT_FOUND;
+ $http_code = self::HTTP_NOT_FOUND;
}
// If data is not NULL and a HTTP status code provided, then continue
@@ -657,7 +657,7 @@ public function response($data = null, $http_code = null, $continue = false)
// 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 = HTTP_OK;
+ $http_code > 0 || $http_code = self::HTTP_OK;
$this->output->set_status_header($http_code);
@@ -1711,7 +1711,7 @@ protected function _check_php_session()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
- ], HTTP_UNAUTHORIZED);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1795,7 +1795,7 @@ protected function _prepare_digest_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_invalid_credentials'),
- ], HTTP_UNAUTHORIZED);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1815,7 +1815,7 @@ protected function _check_blacklist_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_denied'),
- ], HTTP_UNAUTHORIZED);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1840,7 +1840,7 @@ protected function _check_whitelist_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_unauthorized'),
- ], HTTP_UNAUTHORIZED);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1875,7 +1875,7 @@ protected function _force_login($nonce = '')
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
- ], HTTP_UNAUTHORIZED);
+ ], self::HTTP_UNAUTHORIZED);
}
/**
From cb24641947accfa0bf0a9208073a780f300cccfe Mon Sep 17 00:00:00 2001
From: wandu-ar
Date: Sun, 22 Dec 2019 08:36:11 -0300
Subject: [PATCH 094/129] Bug fix: Load config before call it
---
src/RestController.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 722575c5..2147f83b 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -258,15 +258,15 @@ public function __construct($config = 'rest')
// 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);
}
- // Load the rest.php configuration file
- $this->get_local_config($config);
-
// Determine supported output formats from configuration
$supported_formats = $this->config->item('rest_supported_formats');
From 98457e649b3dfa0887500f32e7e77408d9529cf1 Mon Sep 17 00:00:00 2001
From: Leandro Corsino
Date: Sun, 12 Apr 2020 15:23:27 -0300
Subject: [PATCH 095/129] Fix valid_response on _prepare_digest_auth
---
src/RestController.php | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 2147f83b..9a2711f1 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -1782,12 +1782,13 @@ protected function _prepare_digest_auth()
$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
- if (isset($digest['username']) === false || $this->_check_login($digest['username'], true) === false) {
+ $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($digest['username'].':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$md5);
+ $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) {
From 750b92820a1408b31bff4812207396c92f977ac8 Mon Sep 17 00:00:00 2001
From: =W530 Lenovo Cmder Vendor Git <=w530.lenovo@ericariyanto.com>
Date: Mon, 23 Mar 2020 22:45:38 +0700
Subject: [PATCH 096/129] ^ Fix Bugs - failed load custom rest config - failed
access constant HTTP return code
---
src/RestController.php | 38 +++++++++++++++++++++-----------------
1 file changed, 21 insertions(+), 17 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 9a2711f1..09ca48f0 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -258,15 +258,15 @@ public function __construct($config = 'rest')
// 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);
}
+ // Load the rest.php configuration file
+ $this->get_local_config($config);
+
// Determine supported output formats from configuration
$supported_formats = $this->config->item('rest_supported_formats');
@@ -443,11 +443,15 @@ private function do_auth($method = false)
*/
private function get_local_config($config_file)
{
- if (!$this->load->config($config_file, false)) {
- $config = [];
- include __DIR__.'/'.$config_file.'.php';
- foreach ($config as $key => $value) {
- $this->config->set_item($key, $value);
+ 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);
+ }
}
}
}
@@ -540,7 +544,7 @@ public function _remap($object_called, $arguments = [])
$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);
+ ], $this->http_status['METHOD_NOT_ALLOWED']);
}
// Doing key related stuff? Can only do it if they have a key right?
@@ -619,7 +623,7 @@ public function response($data = null, $http_code = null, $continue = false)
// 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;
+ $http_code = HTTP_NOT_FOUND;
}
// If data is not NULL and a HTTP status code provided, then continue
@@ -657,7 +661,7 @@ public function response($data = null, $http_code = null, $continue = false)
// 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;
+ $http_code > 0 || $http_code = HTTP_OK;
$this->output->set_status_header($http_code);
@@ -1537,7 +1541,7 @@ protected function _perform_ldap_auth($username = '', $password = null)
'basedn' => $this->config->item('basedn', 'ldap'),
];
- log_message('debug', 'LDAP Auth: Connect to '.(isset($ldap['host']) ? $ldap['host'] : '[ldap not configured]'));
+ log_message('debug', 'LDAP Auth: Connect to '.(isset($ldaphost) ? $ldaphost : '[ldap not configured]'));
// Connect to the ldap server
$ldapconn = ldap_connect($ldap['host'], $ldap['port']);
@@ -1711,7 +1715,7 @@ protected function _check_php_session()
$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);
+ ], $this->http_status['UNAUTHORIZED']);
}
}
@@ -1796,7 +1800,7 @@ protected function _prepare_digest_auth()
$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);
+ ], $this->http_status['UNAUTHORIZED']);
}
}
@@ -1816,7 +1820,7 @@ protected function _check_blacklist_auth()
$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);
+ ], $this->http_status['UNAUTHORIZED']);
}
}
@@ -1841,7 +1845,7 @@ protected function _check_whitelist_auth()
$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);
+ ], $this->http_status['UNAUTHORIZED']);
}
}
@@ -1876,7 +1880,7 @@ protected function _force_login($nonce = '')
$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);
+ ], $this->http_status['UNAUTHORIZED']);
}
/**
From c726a496c0d72f05cf05cf9193fcd44590fe5e5c Mon Sep 17 00:00:00 2001
From: Moch Zawaruddin Abdullah
Date: Tue, 18 Feb 2020 22:37:16 +0700
Subject: [PATCH 097/129] maybe "auth" is a folder than prefix-file
---
src/RestController.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 09ca48f0..cfc80fb5 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -433,8 +433,8 @@ private function do_auth($method = false)
return true;
}
- if (file_exists(__DIR__.'/auth-'.$method.'.php')) {
- include __DIR__.'/auth-'.$method.'.php';
+ if (file_exists(__DIR__.'/auth/'.$method.'.php')) {
+ include __DIR__.'/auth/'.$method.'.php';
}
}
From 4f0777c5231a7a13d3f884e0e2d08ae51bffea71 Mon Sep 17 00:00:00 2001
From: krishna0102
Date: Fri, 20 Dec 2019 18:00:30 +0530
Subject: [PATCH 098/129] For fixing use of undefined constant issue
---
src/RestController.php | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index cfc80fb5..fe250e3c 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -32,6 +32,11 @@ class RestController extends \CI_Controller
*/
protected $methods = [];
+ /**
+ * Defines https status
+ */
+ protected $http_status = [];
+
/**
* List of allowed HTTP methods.
*
@@ -218,7 +223,6 @@ class RestController extends \CI_Controller
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;
@@ -623,7 +627,7 @@ public function response($data = null, $http_code = null, $continue = false)
// If data is NULL and no HTTP status code provided, then display, error and exit
if ($data === null && $http_code === null) {
- $http_code = HTTP_NOT_FOUND;
+ $http_code = self::HTTP_NOT_FOUND;
}
// If data is not NULL and a HTTP status code provided, then continue
@@ -661,7 +665,7 @@ public function response($data = null, $http_code = null, $continue = false)
// 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 = HTTP_OK;
+ $http_code > 0 || $http_code = self::HTTP_OK;
$this->output->set_status_header($http_code);
From 88a63ccd8a1dec23e1373c0a2a8a7658d44600e2 Mon Sep 17 00:00:00 2001
From: Syaiful Huda <49975659+hudamida@users.noreply.github.com>
Date: Thu, 23 Apr 2020 10:03:46 +0700
Subject: [PATCH 099/129] Update RestController.php
It looks like the _check_php_session function needs a Codeigniter session library.
---
src/RestController.php | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/RestController.php b/src/RestController.php
index fe250e3c..ba82b731 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -1709,6 +1709,9 @@ protected function _check_php_session()
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');
From becfe9b44b6239d12663feafd13cbf6dc2d80c40 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Wed, 6 May 2020 17:27:48 -0500
Subject: [PATCH 100/129] Delete FUNDING.yml
---
.github/FUNDING.yml | 1 -
1 file changed, 1 deletion(-)
delete mode 100644 .github/FUNDING.yml
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
deleted file mode 100644
index a7b75f10..00000000
--- a/.github/FUNDING.yml
+++ /dev/null
@@ -1 +0,0 @@
-github: chriskacerguis
\ No newline at end of file
From b1c15aa13b803bc01e2df1f5d5271190c95386c3 Mon Sep 17 00:00:00 2001
From: leanec
Date: Wed, 15 Apr 2020 11:11:42 -0300
Subject: [PATCH 101/129] Restoring deleted fixes
---
src/RestController.php | 20 ++++++++++----------
1 file changed, 10 insertions(+), 10 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index ba82b731..0127f49e 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -262,15 +262,15 @@ public function __construct($config = 'rest')
// 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);
}
- // Load the rest.php configuration file
- $this->get_local_config($config);
-
// Determine supported output formats from configuration
$supported_formats = $this->config->item('rest_supported_formats');
@@ -548,7 +548,7 @@ public function _remap($object_called, $arguments = [])
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unknown_method'),
- ], $this->http_status['METHOD_NOT_ALLOWED']);
+ ], self::HTTP_METHOD_NOT_ALLOWED);
}
// Doing key related stuff? Can only do it if they have a key right?
@@ -1545,7 +1545,7 @@ protected function _perform_ldap_auth($username = '', $password = null)
'basedn' => $this->config->item('basedn', 'ldap'),
];
- log_message('debug', 'LDAP Auth: Connect to '.(isset($ldaphost) ? $ldaphost : '[ldap not configured]'));
+ 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']);
@@ -1722,7 +1722,7 @@ protected function _check_php_session()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1807,7 +1807,7 @@ protected function _prepare_digest_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_invalid_credentials'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1827,7 +1827,7 @@ protected function _check_blacklist_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_denied'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1852,7 +1852,7 @@ protected function _check_whitelist_auth()
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_unauthorized'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], self::HTTP_UNAUTHORIZED);
}
}
@@ -1887,7 +1887,7 @@ protected function _force_login($nonce = '')
$this->response([
$this->config->item('rest_status_field_name') => false,
$this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized'),
- ], $this->http_status['UNAUTHORIZED']);
+ ], self::HTTP_UNAUTHORIZED);
}
/**
From 49e02df8effae4d37c721b809c46c034d4323ebb Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 15 Aug 2020 13:34:52 -0500
Subject: [PATCH 102/129] Create stale.yml
---
.github/workflows/stale.yml | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
create mode 100644 .github/workflows/stale.yml
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
new file mode 100644
index 00000000..34045177
--- /dev/null
+++ b/.github/workflows/stale.yml
@@ -0,0 +1,19 @@
+name: Mark stale issues and pull requests
+
+on:
+ schedule:
+ - cron: "30 1 * * *"
+
+jobs:
+ stale:
+
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/stale@v1
+ with:
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
+ stale-issue-message: 'Stale issue message'
+ stale-pr-message: 'Stale pull request message'
+ stale-issue-label: 'no-issue-activity'
+ stale-pr-label: 'no-pr-activity'
From 65828c3556a012a94d90f514ac812317a2130fe8 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 15 Aug 2020 13:37:26 -0500
Subject: [PATCH 103/129] fixes #1099
---
src/RestController.php | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/RestController.php b/src/RestController.php
index 0127f49e..6e433378 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -223,6 +223,7 @@ class RestController extends \CI_Controller
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;
From 0f683ff9579500f1f5a17a8e781ca10c2f27d522 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 15 Aug 2020 13:45:47 -0500
Subject: [PATCH 104/129] Update issue templates
---
.github/ISSUE_TEMPLATE/bug_report.md | 38 ++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 00000000..b2676296
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,38 @@
+---
+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**
+Steps to reproduce the behavior, or a code snippet (properly formatted):
+1. Go to '...'
+2. Click on '....'
+3. Scroll down to '....'
+4. See error
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**Screenshots**
+If applicable, add screenshots to help explain your problem.
+
+**Desktop (please complete the following information):**
+ - OS: [e.g. iOS]
+ - Browser [e.g. chrome, safari]
+ - Version [e.g. 22]
+
+**Smartphone (please complete the following information):**
+ - Device: [e.g. iPhone6]
+ - OS: [e.g. iOS8.1]
+ - Browser [e.g. stock browser, safari]
+ - Version [e.g. 22]
+
+**Additional context**
+Add any other context about the problem here.
From 6e3335c6a08b2320c810530cfbc08b8380413447 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 15 Aug 2020 13:49:23 -0500
Subject: [PATCH 105/129] Update bug_report.md
---
.github/ISSUE_TEMPLATE/bug_report.md | 29 +++++++++++++---------------
1 file changed, 13 insertions(+), 16 deletions(-)
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index b2676296..34ee3d3c 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -11,27 +11,24 @@ assignees: ''
A clear and concise description of what the bug is.
**To Reproduce**
-Steps to reproduce the behavior, or a code snippet (properly formatted):
-1. Go to '...'
-2. Click on '....'
-3. Scroll down to '....'
-4. See error
+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**
-If applicable, add screenshots to help explain your problem.
-
-**Desktop (please complete the following information):**
- - OS: [e.g. iOS]
- - Browser [e.g. chrome, safari]
- - Version [e.g. 22]
+**Screenshots / Error Messages**
+If applicable, add screenshots and/or error messages to help explain your problem.
-**Smartphone (please complete the following information):**
- - Device: [e.g. iPhone6]
- - OS: [e.g. iOS8.1]
- - Browser [e.g. stock browser, safari]
+**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**
From f05eafea520633028bcae9a6c12fe45463b7ee5a Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sat, 15 Aug 2020 19:00:21 +0000
Subject: [PATCH 106/129] Apply fixes from StyleCI
---
src/RestController.php | 59 +++++++++++++++++++++++++-----------------
src/rest.php | 22 ++++++++--------
2 files changed, 46 insertions(+), 35 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 6e433378..078cf535 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -33,7 +33,7 @@ class RestController extends \CI_Controller
protected $methods = [];
/**
- * Defines https status
+ * Defines https status.
*/
protected $http_status = [];
@@ -448,10 +448,10 @@ private function do_auth($method = false)
*/
private function get_local_config($config_file)
{
- if ( file_exists(APPPATH . 'config/' . $config_file . '.php') ) {
+ if (file_exists(APPPATH.'config/'.$config_file.'.php')) {
$this->load->config($config_file, false);
} else {
- if ( file_exists(__DIR__.'/'.$config_file.'.php') ) {
+ if (file_exists(__DIR__.'/'.$config_file.'.php')) {
$config = [];
include __DIR__.'/'.$config_file.'.php';
foreach ($config as $key => $value) {
@@ -951,15 +951,17 @@ 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,
- ]);
+ $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();
@@ -1710,7 +1712,7 @@ protected function _check_php_session()
if ($this->config->item('rest_ip_whitelist_enabled')) {
$this->_check_whitelist_auth();
}
-
+
// Load library session of CodeIgniter
$this->load->library('session');
@@ -1877,7 +1879,8 @@ protected function _force_login($nonce = '')
header(
'WWW-Authenticate: Digest realm="'.$rest_realm
.'", qop="auth", nonce="'.$nonce
- .'", opaque="'.md5($rest_realm).'"');
+ .'", opaque="'.md5($rest_realm).'"'
+ );
}
if ($this->config->item('strict_api_and_auth') === true) {
@@ -1907,9 +1910,12 @@ protected function _log_access_time()
$payload['rtime'] = $this->_end_rtime - $this->_start_rtime;
return $this->rest->db->update(
- $this->config->item('rest_logs_table'), $payload, [
- 'id' => $this->_insert_id,
- ]);
+ $this->config->item('rest_logs_table'),
+ $payload,
+ [
+ 'id' => $this->_insert_id,
+ ]
+ );
}
/**
@@ -1930,9 +1936,12 @@ protected function _log_response_code($http_code)
$payload['response_code'] = $http_code;
return $this->rest->db->update(
- $this->config->item('rest_logs_table'), $payload, [
- 'id' => $this->_insert_id,
- ]);
+ $this->config->item('rest_logs_table'),
+ $payload,
+ [
+ 'id' => $this->_insert_id,
+ ]
+ );
}
/**
@@ -1949,10 +1958,12 @@ protected function _check_access()
// Fetch controller based on path and controller name
$controller = implode(
- '/', [
- $this->router->directory,
- $this->router->class,
- ]);
+ '/',
+ [
+ $this->router->directory,
+ $this->router->class,
+ ]
+ );
// Remove any double slashes for safety
$controller = str_replace('//', '/', $controller);
diff --git a/src/rest.php b/src/rest.php
index 887141c6..d58d7ce1 100644
--- a/src/rest.php
+++ b/src/rest.php
@@ -556,11 +556,11 @@
|
*/
$config['allowed_cors_headers'] = [
- 'Origin',
- 'X-Requested-With',
- 'Content-Type',
- 'Accept',
- 'Access-Control-Request-Method',
+ 'Origin',
+ 'X-Requested-With',
+ 'Content-Type',
+ 'Accept',
+ 'Access-Control-Request-Method',
];
/*
@@ -572,12 +572,12 @@
|
*/
$config['allowed_cors_methods'] = [
- 'GET',
- 'POST',
- 'OPTIONS',
- 'PUT',
- 'PATCH',
- 'DELETE',
+ 'GET',
+ 'POST',
+ 'OPTIONS',
+ 'PUT',
+ 'PATCH',
+ 'DELETE',
];
/*
From 24eab8a5231608cd1fc89c17e90e2e432a23d410 Mon Sep 17 00:00:00 2001
From: Kobus Myburgh
Date: Sat, 19 Sep 2020 01:20:19 +0200
Subject: [PATCH 107/129] Attempt to fix issue 1069 - XSS filtering
---
src/RestController.php | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/RestController.php b/src/RestController.php
index 078cf535..879c8998 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -1411,6 +1411,9 @@ public function head($key = null, $xss_clean = 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;
}
From 399d9bcefabf19242260581aa12bcd6245b6b5e3 Mon Sep 17 00:00:00 2001
From: Kobus Myburgh
Date: Sat, 19 Sep 2020 01:26:38 +0200
Subject: [PATCH 108/129] Added new line, as per CI error.
---
src/RestController.php | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/RestController.php b/src/RestController.php
index 879c8998..a5ac91f7 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -1414,6 +1414,7 @@ public function post($key = null, $xss_clean = 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;
}
From 949d5ad8b35962d74bd8510a9d429c9b43e19cd6 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sun, 28 Feb 2021 09:33:53 -0600
Subject: [PATCH 109/129] Update RestController.php
fixes #1115
---
src/RestController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index a5ac91f7..83d9f2d2 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -11,7 +11,7 @@
* CodeIgniter Rest Controller
* A fully RESTful server implementation for CodeIgniter using one library, one config file and one controller.
*
- * @link https://github.com/chriskacerguis/ci-restserver
+ * @link https://github.com/chriskacerguis/codeigniter-restserver
*
* @version 4.0.0
*/
From 99d996275ebc323a00f35a4ab004f18c2f48be3d Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Sun, 28 Feb 2021 09:35:11 -0600
Subject: [PATCH 110/129] Update stale.yml
---
.github/workflows/stale.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index 34045177..0a753df8 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -13,7 +13,7 @@ jobs:
- uses: actions/stale@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- stale-issue-message: 'Stale issue message'
+ stale-issue-message: 'There has been no activity on this issue, so it will be closed.'
stale-pr-message: 'Stale pull request message'
stale-issue-label: 'no-issue-activity'
stale-pr-label: 'no-pr-activity'
From 4c5b88b08f10089a1b939e484c8f26e067c04dda Mon Sep 17 00:00:00 2001
From: Jamie Burchell
Date: Thu, 3 Feb 2022 10:11:19 +0000
Subject: [PATCH 111/129] Fix RecursiveIteratorIterator not found
Fixes https://github.com/chriskacerguis/codeigniter-restserver/issues/1111
---
src/RestController.php | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/RestController.php b/src/RestController.php
index 83d9f2d2..b8f36c71 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -4,6 +4,7 @@
use Exception;
use stdClass;
+use RecursiveIteratorIterator;
defined('BASEPATH') or exit('No direct script access allowed');
From c01570892b25bf87c49a92c8889be20c3813bfd0 Mon Sep 17 00:00:00 2001
From: Jamie Burchell
Date: Thu, 3 Feb 2022 10:12:51 +0000
Subject: [PATCH 112/129] Fix code style
---
src/RestController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index b8f36c71..765f0598 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -3,8 +3,8 @@
namespace chriskacerguis\RestServer;
use Exception;
-use stdClass;
use RecursiveIteratorIterator;
+use stdClass;
defined('BASEPATH') or exit('No direct script access allowed');
From 4571473e69fc830176cdd132938f5b8d25bea511 Mon Sep 17 00:00:00 2001
From: Jamie Burchell
Date: Thu, 3 Feb 2022 10:15:29 +0000
Subject: [PATCH 113/129] Fix RecursiveArrayIterator not found
---
src/RestController.php | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/RestController.php b/src/RestController.php
index 765f0598..9ab38913 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -3,6 +3,7 @@
namespace chriskacerguis\RestServer;
use Exception;
+use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use stdClass;
From f386f4e0013daadaa213681a0a41af69aa81d9de Mon Sep 17 00:00:00 2001
From: Jamie Burchell
Date: Wed, 23 Feb 2022 14:52:03 +0000
Subject: [PATCH 114/129] Don't attempt to lowercase a NULL
Fixes PHP 8.1 deprecation notice when trying to `strtolower` `NULL`
---
src/RestController.php | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index 9ab38913..0e0aa4bc 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -834,7 +834,9 @@ protected function _detect_method()
$method = $this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE');
}
- $method = strtolower($method);
+ if ($method !== null) {
+ $method = strtolower($method);
+ }
}
if (empty($method)) {
From 2e1cbd347625cb489776528696f7980984e9b7f5 Mon Sep 17 00:00:00 2001
From: alex-monte <61494531+alex-monte@users.noreply.github.com>
Date: Fri, 21 Apr 2023 14:16:18 +0200
Subject: [PATCH 115/129] Update RestController.php
I propose this simple change so that in case $row is false, the message 'text_rest_invalid_api_key' has the information in '$this->rest->key' to display it correctly.
---
src/RestController.php | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 0e0aa4bc..ab46a570 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -867,12 +867,13 @@ protected function _detect_api_key()
// 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;
}
- $this->rest->key = $row->{$this->config->item('rest_key_column')};
-
isset($row->user_id) && $this->rest->user_id = $row->user_id;
isset($row->level) && $this->rest->level = $row->level;
isset($row->ignore_limits) && $this->rest->ignore_limits = $row->ignore_limits;
From a16bdd648db2fa2cb3c386e7bb9b06d3ddb73fb9 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis
Date: Tue, 2 May 2023 11:16:52 -0500
Subject: [PATCH 116/129] Update README.md
---
README.md | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/README.md b/README.md
index f7f4e305..2078f9fd 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,12 @@
A fully RESTful server implementation for CodeIgniter using one library, one config file and one controller.
+## Important!!
+
+CodeIgniter 4 includes REST support out of the box and therefore does not require the RestServer.
+
+See the documentation here: [RESTful Resource Handling](https://codeigniter4.github.io/userguide/incoming/restful.html)
+
## Requirements
- PHP 7.2 or greater
From f36aa04e1d31ff83d447b170cef31ffb557ff0c3 Mon Sep 17 00:00:00 2001
From: tenzap
Date: Tue, 20 Jun 2023 12:35:39 +0200
Subject: [PATCH 117/129] add SQL CREATE TABLE queries for PostgreSQL
---
src/rest.php | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 62 insertions(+)
diff --git a/src/rest.php b/src/rest.php
index d58d7ce1..b4cc7984 100644
--- a/src/rest.php
+++ b/src/rest.php
@@ -322,6 +322,19 @@
| 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,
+| PRIMARY KEY (id)
+| ) ;
+| |
*/
$config['rest_enable_keys'] = false;
@@ -402,6 +415,20 @@
| 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;
@@ -435,6 +462,31 @@
| 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;
@@ -479,6 +531,16 @@
| 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:
|
From 57b74957b95e0f1b2cd85d1adf6607b11ab3eda2 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis <2414647+chriskacerguis@users.noreply.github.com>
Date: Sat, 29 Jul 2023 13:14:25 -0500
Subject: [PATCH 118/129] Updated to MIT license
---
src/Format.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Format.php b/src/Format.php
index ce5b2de6..d2058634 100644
--- a/src/Format.php
+++ b/src/Format.php
@@ -11,7 +11,7 @@
* Help convert between various formats such as XML, JSON, CSV, etc.
*
* @author Phil Sturgeon, Chris Kacerguis, @softwarespot
- * @license http://www.dbad-license.org/
+ * @license MIT (See LICENSE)
*/
class Format
{
From 63c5ccad5581c3e0035c400aa929ba1ef0822418 Mon Sep 17 00:00:00 2001
From: StyleCI Bot
Date: Sat, 29 Jul 2023 18:18:03 +0000
Subject: [PATCH 119/129] Apply fixes from StyleCI
---
src/Format.php | 1 -
src/RestController.php | 5 ++---
2 files changed, 2 insertions(+), 4 deletions(-)
diff --git a/src/Format.php b/src/Format.php
index d2058634..54dc4c46 100644
--- a/src/Format.php
+++ b/src/Format.php
@@ -183,7 +183,6 @@ public function to_xml($data = null, $structure = null, $basenode = 'xml')
}
foreach ($data as $key => $value) {
-
//change false/true to 0/1
if (is_bool($value)) {
$value = (int) $value;
diff --git a/src/RestController.php b/src/RestController.php
index ab46a570..09f37163 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -697,7 +697,7 @@ public function response($data = null, $http_code = null, $continue = false)
}
}
ob_end_flush();
- // Otherwise dump the output automatically
+ // Otherwise dump the output automatically
} else {
echo json_encode($data);
}
@@ -866,8 +866,7 @@ protected function _detect_api_key()
$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 ($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())) {
From 94c779f0f995fddedb00b703ac1e3682c71574fe Mon Sep 17 00:00:00 2001
From: Chris Kacerguis <2414647+chriskacerguis@users.noreply.github.com>
Date: Sat, 29 Jul 2023 13:23:44 -0500
Subject: [PATCH 120/129] Delete stale.yml
---
.github/workflows/stale.yml | 19 -------------------
1 file changed, 19 deletions(-)
delete mode 100644 .github/workflows/stale.yml
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
deleted file mode 100644
index 0a753df8..00000000
--- a/.github/workflows/stale.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-name: Mark stale issues and pull requests
-
-on:
- schedule:
- - cron: "30 1 * * *"
-
-jobs:
- stale:
-
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/stale@v1
- with:
- repo-token: ${{ secrets.GITHUB_TOKEN }}
- stale-issue-message: 'There has been no activity on this issue, so it will be closed.'
- stale-pr-message: 'Stale pull request message'
- stale-issue-label: 'no-issue-activity'
- stale-pr-label: 'no-pr-activity'
From bdf3548de32dc7305de6b93a47c6adb5c99c9878 Mon Sep 17 00:00:00 2001
From: Ivan Peevski <133036+ipeevski@users.noreply.github.com>
Date: Wed, 11 Sep 2024 09:32:43 +0930
Subject: [PATCH 121/129] Fix handling null in to_xml()
---
src/Format.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Format.php b/src/Format.php
index 54dc4c46..4c55a430 100644
--- a/src/Format.php
+++ b/src/Format.php
@@ -215,7 +215,7 @@ public function to_xml($data = null, $structure = null, $basenode = 'xml')
$this->to_xml($value, $node, $key);
} else {
// add single node.
- $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
+ $value = htmlspecialchars(html_entity_decode($value ?? '', ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
$structure->addChild($key, $value);
}
From 548cc4161f86aefdab7059e9ef6b29745c7152eb Mon Sep 17 00:00:00 2001
From: StyleCI Bot
Date: Wed, 11 Sep 2024 00:05:07 +0000
Subject: [PATCH 122/129] Apply fixes from StyleCI
---
src/RestController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index 09f37163..99a99148 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -697,7 +697,7 @@ public function response($data = null, $http_code = null, $continue = false)
}
}
ob_end_flush();
- // Otherwise dump the output automatically
+ // Otherwise dump the output automatically
} else {
echo json_encode($data);
}
From 8ab48d53ea542030dea71f96dfbd28a0ba6efb1a Mon Sep 17 00:00:00 2001
From: Ivan Peevski
Date: Wed, 11 Sep 2024 15:39:08 +0930
Subject: [PATCH 123/129] Allow extending Formatter class
---
src/RestController.php | 13 ++++++++++---
1 file changed, 10 insertions(+), 3 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 99a99148..9c2c9b13 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -232,7 +232,7 @@ class RestController extends \CI_Controller
/**
* @var Format
*/
- private $format;
+ protected $format;
/**
* @var bool
@@ -636,10 +636,17 @@ public function response($data = null, $http_code = null, $continue = false)
// If data is not NULL and a HTTP status code provided, then continue
elseif ($data !== null) {
// If the format method exists, call and return the output in that format
- if (method_exists(Format::class, 'to_'.$this->response->format)) {
+ $formatter = null;
+ if ($this->format && method_exists($this->format, 'to_'.$this->response->format)) {
+ $formatter = $this->format::factory($data);
+ } else if (method_exists(Format::class, 'to_'.$this->response->format)) {
+ $formatter = Format::factory($data);
+ }
+
+ if ($formatter !== null) {
// CORB protection
// First, get the output content.
- $output = Format::factory($data)->{'to_'.$this->response->format}();
+ $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 :
From d0e5bd68cd5f704645b63fb79eafe520e596283a Mon Sep 17 00:00:00 2001
From: Ivan Peevski
Date: Wed, 11 Sep 2024 15:50:30 +0930
Subject: [PATCH 124/129] Fix style
---
src/RestController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/RestController.php b/src/RestController.php
index 9c2c9b13..c5fddefb 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -639,7 +639,7 @@ public function response($data = null, $http_code = null, $continue = false)
$formatter = null;
if ($this->format && method_exists($this->format, 'to_'.$this->response->format)) {
$formatter = $this->format::factory($data);
- } else if (method_exists(Format::class, 'to_'.$this->response->format)) {
+ } elseif (method_exists(Format::class, 'to_'.$this->response->format)) {
$formatter = Format::factory($data);
}
From 70bcd18e590df90b33949153455695ac8a6e2bd7 Mon Sep 17 00:00:00 2001
From: Ivan Peevski
Date: Tue, 17 Sep 2024 11:36:09 +0930
Subject: [PATCH 125/129] Update Readme file to add example for extending
Format
---
README.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 53 insertions(+)
diff --git a/README.md b/README.md
index 2078f9fd..0390fcff 100644
--- a/README.md
+++ b/README.md
@@ -114,3 +114,56 @@ class Api extends RestController {
}
}
```
+
+## Extending supported formats
+
+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
+format = new Format();
+ }
+}
+```
+
+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
+_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;
+ }
+}
+```
From 05245888ae49dc97a34fafe1dd4ffa068c690f26 Mon Sep 17 00:00:00 2001
From: Ashton Smith
Date: Thu, 21 Nov 2024 15:01:00 +1300
Subject: [PATCH 126/129] add support for expiring api keys
---
src/RestController.php | 4 ++++
src/rest.php | 15 +++++++++++++++
2 files changed, 19 insertions(+)
diff --git a/src/RestController.php b/src/RestController.php
index c5fddefb..3c7298c2 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -880,6 +880,10 @@ protected function _detect_api_key()
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;
diff --git a/src/rest.php b/src/rest.php
index b4cc7984..28cd6ea8 100644
--- a/src/rest.php
+++ b/src/rest.php
@@ -319,6 +319,7 @@
| `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;
|
@@ -332,6 +333,7 @@
| 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)
| ) ;
| |
@@ -348,6 +350,19 @@
|
*/
$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';
/*
|--------------------------------------------------------------------------
From 60b2009982b27ff29e7b7554d2de776519e4ca8e Mon Sep 17 00:00:00 2001
From: Ashton Smith
Date: Thu, 21 Nov 2024 15:07:30 +1300
Subject: [PATCH 127/129] style fixes for #1159
---
src/RestController.php | 2 +-
src/rest.php | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/RestController.php b/src/RestController.php
index 3c7298c2..7f292a98 100644
--- a/src/RestController.php
+++ b/src/RestController.php
@@ -880,7 +880,7 @@ protected function _detect_api_key()
return false;
}
- if ($this->config->item('rest_keys_expire')===true && $row->{$this->config->item('rest_keys_expiry_column')} < time()) {
+ if ($this->config->item('rest_keys_expire') === true && $row->{$this->config->item('rest_keys_expiry_column')} < time()) {
return false;
}
diff --git a/src/rest.php b/src/rest.php
index 28cd6ea8..7c8c4c9b 100644
--- a/src/rest.php
+++ b/src/rest.php
@@ -355,9 +355,9 @@
| REST Table Key Expiry Config and Column Name
|--------------------------------------------------------------------------
|
-| Configure wether or not api keys should expire, and the column name to
+| 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
+| Note: the value in the column will be treated as a unix timestamp and
| compared with php function time()
|
*/
From 55c1a5b099f581d2a3cabf5d9bd5887b175737f3 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis <2414647+chriskacerguis@users.noreply.github.com>
Date: Thu, 25 Sep 2025 08:33:11 -0500
Subject: [PATCH 128/129] Update README to reflect current CodeIgniter status
Removed outdated information about CodeIgniter 4 and updated the description.
Signed-off-by: Chris Kacerguis <2414647+chriskacerguis@users.noreply.github.com>
---
README.md | 11 +++--------
1 file changed, 3 insertions(+), 8 deletions(-)
diff --git a/README.md b/README.md
index 0390fcff..59776fe9 100644
--- a/README.md
+++ b/README.md
@@ -1,14 +1,9 @@
# CodeIgniter RestServer
-[](https://github.styleci.io/repos/230589)
+A fully RESTful server implementation for CodeIgniter 3 using one library, one config file and one controller.
-A fully RESTful server implementation for CodeIgniter using one library, one config file and one controller.
-
-## Important!!
-
-CodeIgniter 4 includes REST support out of the box and therefore does not require the RestServer.
-
-See the documentation here: [RESTful Resource Handling](https://codeigniter4.github.io/userguide/incoming/restful.html)
+> [!IMPORTANT]
+> I have published the first "beta" of codeigniter-restserver 4. See the "development" branch. Please be sure to note the system requirments.
## Requirements
From 13811da74d1eb259e76f0a8fce4255cb571b5795 Mon Sep 17 00:00:00 2001
From: Chris Kacerguis <2414647+chriskacerguis@users.noreply.github.com>
Date: Thu, 25 Sep 2025 18:36:07 -0500
Subject: [PATCH 129/129] Add CODEOWNERS file for repository ownership
Signed-off-by: Chris Kacerguis <2414647+chriskacerguis@users.noreply.github.com>
---
.github/CODEOWNERS | 1 +
1 file changed, 1 insertion(+)
create mode 100644 .github/CODEOWNERS
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 00000000..5d609ac7
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1 @@
+* @chriskacerguis