diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000..5d609ac7 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @chriskacerguis diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..34ee3d3c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Please provide either a cleanly formatted code snippet or a link to repo / gist with code that I can use to reproduce: + +```php + public function set_response($data = null, $http_code = null) + { + $this->response($data, $http_code, true); + } +``` + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots / Error Messages** +If applicable, add screenshots and/or error messages to help explain your problem. + +**Environment (please complete the following information):** + - PHP Version: [e.g. 7.2.1] + - CodeIgniter Version [e.g. 4.0.1] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a761a8b8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +vendor +.idea \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f9121e51 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2012 - 2015 Phil Sturgeon, Chris Kacerguis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md index 676c7f10..59776fe9 100644 --- a/README.md +++ b/README.md @@ -1,223 +1,164 @@ -# CodeIgniter Rest Server +# CodeIgniter RestServer -A fully RESTful server implementation for CodeIgniter using one library, one -config file and one controller. +A fully RESTful server implementation for CodeIgniter 3 using one library, one config file and one controller. -## Requirements +> [!IMPORTANT] +> I have published the first "beta" of codeigniter-restserver 4. See the "development" branch. Please be sure to note the system requirments. -1. PHP 5.2 or greater -2. CodeIgniter 2.1.0 to 3.0-dev +## Requirements -_Note: for 1.7.x support download v2.2 from Downloads tab_ +- PHP 7.2 or greater +- CodeIgniter 3.1.11+ ## Installation -Drag and drop the **application/libraries/Format.php** and **application/libraries/REST_Controller.php** files into your application's directories. Either autoload the `REST_Controller` class or `require_once` it at the top of your controllers to load it into the scope. Additionally, copy the **rest.php** file from **application/config** in your application's configuration directory. - -## Handling Requests - -When your controller extends from `REST_Controller`, the method names will be appended with the HTTP method used to access the request. If you're making an HTTP `GET` call to `/books`, for instance, it would call a `Books#index_get()` method. - -This allows you to implement a RESTful interface easily: - - class Books extends REST_Controller - { - public function index_get() - { - // Display all books - } - - public function index_post() - { - // Create a new book - } - } - -`REST_Controller` also supports `PUT` and `DELETE` methods, allowing you to support a truly RESTful interface. - -Accessing parameters is also easy. Simply use the name of the HTTP verb as a method: - - $this->get('blah'); // GET param - $this->post('blah'); // POST param - $this->put('blah'); // PUT param - $this->delete('blah'); // DELETE 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: - - $ 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: - - 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: - - public function index_post() - { - // ...create new book - - $this->response($book, 201); // Send an HTTP 201 Created - } - -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`: - - $this->response(array()); // HTTP 404 Not Found - -## 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: - - public function __construct() - { - parent::__construct(); - - if (is_array($this->response->lang)) - { - $this->load->language('application', $this->response->lang[0]); - } - else - { - $this->load->language('application', $this->response->lang); - } - } - -## 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: - - $config['rest_valid_logins'] = array( 'username' => 'password', 'other_person' => 'secure123' ); - -Enabling digest auth is similarly easy. Configure your desired logins in the config file like above, and set `$config['rest_auth']` to `'digest'`. The class will automatically send out the headers to enable digest auth. - -Both 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. - -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: - - $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: - - $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: - - 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=MyISAM 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**. - - $ curl -X POST -H "X-API-KEY: some_key_here" http://example.com/books - -## Other Documentation / Tutorials - -* [NetTuts: Working with RESTful Services in CodeIgniter](http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/) - -## Change Log - -### 2.6.2 - -* Update CodeIgniter files to 2.1.3 -* Fixed issue #165 - -### 2.6.1 - -* Update CodeIgniter files to 2.1.2 -* Log Table support for IPv6 & NULL parameters -* Abstract out the processes of firing a controller method within _remap() to an separate method -* Moved GET, POST, PUT, and DELETE parsing to separate methods, allowing them to be overridden as needed -* Small bugfix for a PHP 5.3 strlen error -* Fixed some PHP 5.4 warnings -* Fix for bug in Format.php's to_html() which failed to detect if $data was really a multidimensional array. -* Fix for empty node on XML output format, for false = 0, true = 1. - -### 2.6.0 - -* Added loads of PHPDoc comments. -* Response where method doesn't exist is now "HTTP 405 Method Not Allowed", not "HTTP 404 Not Found". -* Compatible with PHP 5.4. -* Added support for gzip compression. -* Fix the apache\_request\_header function with CGI. -* Fixed up correctly .foo extensions to work when get arguments provided. -* Allows method emulation via X-HTTP-Method-Override -* Support for Backbone.emulateHTTP improved. -* Combine both URI segment and GET params instead of using one or the other -* Separate each piece of the WWW-Authenticate header for digest requests with a comma. -* Added IP whitelist option. - -### 2.5 - -* Instead of just seeing item, item, item, the singular version of the basenode will be used if possible. [Example](http://d.pr/RS46). -* Re-factored to use the Format library, which will soon be merged with CodeIgniter. -* Fixed Limit bug (limit of 5 would allow 6 requests). -* Added logging for invalid API key requests. -* Changed serialize to serialized. -* Changed all visibility 'private' to 'protected'. -* MIME's with character encodings on the end will now work. -* Fixed PUT arguments. Once again just sending a body query string works. [Example](http://d.pr/cY0b) -* Fixed up all .foo extensions to work when no get arguments provided, and moved .html to Format library. -* Updated key.php example to use config_item('rest_keys_table') instead of hardcoded 'keys' table name. -* Updated REST_Controller to use config_item('rest_limits_table') instead of hardcoded 'limits'. - -### 2.4 - -* Added support for UTF-8 characters in XML. -* Added JSONP as a return type. -* Loaded the Security lib before use in case it is not loaded in the application. -* Emulate the Request method for MooTools support. -* Upgraded everything to use CodeIgniter Reactor 2.0.0. -* Added the ability to set or override the Auth type per controller / method. -* Adding ability to only accept AJAX requests. - -### 2.3 - -* Upgraded to CodeIgniter 2.0 and stopped supporting CodeIgniter 1.7.2. -* After $this->response() is called the controller will stop processing. - -### 2.2 - -* Added config options to set table names for keys, limits and logs. -* FALSE values were coming out as empty strings in xml or rawxml mode, now they will be 0/1. -* key => FALSE can now be used to override the keys_enabled option for a specific method, and level is now optional. If no level is set it will assume the method has a level of 0. -* Fixed issue where calls to ->get('foo') would error is foo was not set. Reported by Paul Barto. - -## Contributions - -This project has been funded and made possible through my clients kindly allowing me to -open-source the functionality as I build it into their projects. I am no longer actively developing -features for this as I no longer require it, but I will continue to maintain pull requests and try to -fix issues as and when they are reported (within a week or two). - -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. +```sh +composer require chriskacerguis/codeigniter-restserver +``` + +## 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.1" +``` + +or run + +```sh +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 +use chriskacerguis\RestServer\RestController; +``` + +Step 2: Extend your controller + +```php +class Example extends RestController +``` + +## Basic GET example + +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 + 0, 'name' => 'John', 'email' => 'john@example.com'], + ['id' => 1, 'name' => 'Jim', 'email' => 'jim@example.com'], + ]; + + $id = $this->get( 'id' ); + + if ( $id === null ) + { + // Check if the users data store contains users + if ( $users ) + { + // Set the response and exit + $this->response( $users, 200 ); + } + else + { + // Set the response and exit + $this->response( [ + 'status' => false, + 'message' => 'No users were found' + ], 404 ); + } + } + else + { + if ( array_key_exists( $id, $users ) ) + { + $this->response( $users[$id], 200 ); + } + else + { + $this->response( [ + 'status' => false, + 'message' => 'No such user found' + ], 404 ); + } + } + } +} +``` + +## 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; + } +} +``` diff --git a/application/cache/.htaccess b/application/cache/.htaccess deleted file mode 100755 index 3418e55a..00000000 --- a/application/cache/.htaccess +++ /dev/null @@ -1 +0,0 @@ -deny from all \ No newline at end of file diff --git a/application/config/autoload.php b/application/config/autoload.php deleted file mode 100755 index 90b1a808..00000000 --- a/application/config/autoload.php +++ /dev/null @@ -1,116 +0,0 @@ - '', - 'xhtml1-strict' => '', - 'xhtml1-trans' => '', - 'xhtml1-frame' => '', - 'html5' => '', - 'html4-strict' => '', - 'html4-trans' => '', - 'html4-frame' => '' - ); - -/* End of file doctypes.php */ -/* Location: ./application/config/doctypes.php */ \ No newline at end of file diff --git a/application/config/foreign_chars.php b/application/config/foreign_chars.php deleted file mode 100755 index 14b0d737..00000000 --- a/application/config/foreign_chars.php +++ /dev/null @@ -1,64 +0,0 @@ - 'ae', - '/ö|œ/' => 'oe', - '/ü/' => 'ue', - '/Ä/' => 'Ae', - '/Ü/' => 'Ue', - '/Ö/' => 'Oe', - '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A', - '/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a', - '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', - '/ç|ć|ĉ|ċ|č/' => 'c', - '/Ð|Ď|Đ/' => 'D', - '/ð|ď|đ/' => 'd', - '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E', - '/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e', - '/Ĝ|Ğ|Ġ|Ģ/' => 'G', - '/ĝ|ğ|ġ|ģ/' => 'g', - '/Ĥ|Ħ/' => 'H', - '/ĥ|ħ/' => 'h', - '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I', - '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i', - '/Ĵ/' => 'J', - '/ĵ/' => 'j', - '/Ķ/' => 'K', - '/ķ/' => 'k', - '/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L', - '/ĺ|ļ|ľ|ŀ|ł/' => 'l', - '/Ñ|Ń|Ņ|Ň/' => 'N', - '/ñ|ń|ņ|ň|ʼn/' => 'n', - '/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O', - '/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o', - '/Ŕ|Ŗ|Ř/' => 'R', - '/ŕ|ŗ|ř/' => 'r', - '/Ś|Ŝ|Ş|Š/' => 'S', - '/ś|ŝ|ş|š|ſ/' => 's', - '/Ţ|Ť|Ŧ/' => 'T', - '/ţ|ť|ŧ/' => 't', - '/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U', - '/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u', - '/Ý|Ÿ|Ŷ/' => 'Y', - '/ý|ÿ|ŷ/' => 'y', - '/Ŵ/' => 'W', - '/ŵ/' => 'w', - '/Ź|Ż|Ž/' => 'Z', - '/ź|ż|ž/' => 'z', - '/Æ|Ǽ/' => 'AE', - '/ß/'=> 'ss', - '/IJ/' => 'IJ', - '/ij/' => 'ij', - '/Œ/' => 'OE', - '/ƒ/' => 'f' -); - -/* End of file foreign_chars.php */ -/* Location: ./application/config/foreign_chars.php */ \ No newline at end of file diff --git a/application/config/hooks.php b/application/config/hooks.php deleted file mode 100755 index a4ad2be6..00000000 --- a/application/config/hooks.php +++ /dev/null @@ -1,16 +0,0 @@ - diff --git a/application/config/mimes.php b/application/config/mimes.php deleted file mode 100644 index 100f7d44..00000000 --- a/application/config/mimes.php +++ /dev/null @@ -1,106 +0,0 @@ - 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'), - 'bin' => 'application/macbinary', - 'dms' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'exe' => array('application/octet-stream', 'application/x-msdownload'), - 'class' => 'application/octet-stream', - 'psd' => 'application/x-photoshop', - 'so' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => array('application/pdf', 'application/x-download'), - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'), - 'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'), - 'wbxml' => 'application/wbxml', - 'wmlc' => 'application/wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'gz' => 'application/x-gzip', - 'php' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php3' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'js' => 'application/x-javascript', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => array('application/x-tar', 'application/x-gzip-compressed'), - 'xhtml' => 'application/xhtml+xml', - 'xht' => 'application/xhtml+xml', - 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'), - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mpga' => 'audio/mpeg', - 'mp2' => 'audio/mpeg', - 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'), - 'aif' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'ram' => 'audio/x-pn-realaudio', - 'rm' => 'audio/x-pn-realaudio', - 'rpm' => 'audio/x-pn-realaudio-plugin', - 'ra' => 'audio/x-realaudio', - 'rv' => 'video/vnd.rn-realvideo', - 'wav' => array('audio/x-wav', 'audio/wave', 'audio/wav'), - 'bmp' => array('image/bmp', 'image/x-windows-bmp'), - 'gif' => 'image/gif', - 'jpeg' => array('image/jpeg', 'image/pjpeg'), - 'jpg' => array('image/jpeg', 'image/pjpeg'), - 'jpe' => array('image/jpeg', 'image/pjpeg'), - 'png' => array('image/png', 'image/x-png'), - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'txt' => 'text/plain', - 'text' => 'text/plain', - 'log' => array('text/plain', 'text/x-log'), - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'qt' => 'video/quicktime', - 'mov' => 'video/quicktime', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie', - 'doc' => 'application/msword', - 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'), - 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'), - 'word' => array('application/msword', 'application/octet-stream'), - 'xl' => 'application/excel', - 'eml' => 'message/rfc822', - 'json' => array('application/json', 'text/json') - ); - - -/* End of file mimes.php */ -/* Location: ./application/config/mimes.php */ diff --git a/application/config/profiler.php b/application/config/profiler.php deleted file mode 100755 index f8a5b1a1..00000000 --- a/application/config/profiler.php +++ /dev/null @@ -1,17 +0,0 @@ - '1234') -| -*/ -$config['rest_valid_logins'] = array('admin' => '1234'); - -/* -|-------------------------------------------------------------------------- -| Global IP Whitelisting -|-------------------------------------------------------------------------- -| -| Limit connections to your REST server to whitelisted IP addresses. -| -| Usage: -| 1. Set to true *and* select an auth option for extreme security (client's IP -| address must be in whitelist and they must also log in) -| 2. Set to true with auth set to false to allow whitelisted IPs access with no login. -| 3. Set to false here but set 'auth_override_class_method' to 'whitelist' to -| restrict certain methods to IPs in your whitelist -| -*/ -$config['rest_ip_whitelist_enabled'] = false; - -/* -|-------------------------------------------------------------------------- -| REST IP Whitelist -|-------------------------------------------------------------------------- -| -| Limit connections to your REST server to a comma separated -| list of IP addresses -| -| Example: $config['rest_ip_whitelist'] = '123.456.789.0, 987.654.32.1'; -| -| 127.0.0.1 and 0.0.0.0 are allowed by default. -| -*/ -$config['rest_ip_whitelist'] = ''; - -/* -|-------------------------------------------------------------------------- -| REST Database Group -|-------------------------------------------------------------------------- -| -| Connect to a database group for keys, logging, etc. It will only connect -| if you have any of these features enabled. -| -| 'default' -| -*/ -$config['rest_database_group'] = 'default'; - -/* -|-------------------------------------------------------------------------- -| REST API Keys Table Name -|-------------------------------------------------------------------------- -| -| The table name in your database that stores API Keys. -| -| 'keys' -| -*/ -$config['rest_keys_table'] = 'keys'; - -/* -|-------------------------------------------------------------------------- -| REST Enable Keys -|-------------------------------------------------------------------------- -| -| When set to true REST_Controller will look for a key and match it to the DB. -| If no key is provided, the request will return an error. -| -| FALSE - - CREATE TABLE `keys` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `key` varchar(40) NOT NULL, - `level` int(2) NOT NULL, - `ignore_limits` tinyint(1) NOT NULL DEFAULT '0', - `is_private_key` tinyint(1) NOT NULL DEFAULT '0', - `ip_addresses` TEXT NULL DEFAULT NULL, - `date_created` int(11) NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -| -*/ -$config['rest_enable_keys'] = FALSE; - -/* -|-------------------------------------------------------------------------- -| REST Table Key Column Name -|-------------------------------------------------------------------------- -| -| If you are not using the default table schema as shown above, what is the -| name of the db column that holds the api key value? -| -*/ -$config['rest_key_column'] = 'key'; - -/* -|-------------------------------------------------------------------------- -| REST Key Length -|-------------------------------------------------------------------------- -| -| How long should created keys be? Double check this in your db schema. -| -| Default: 32 -| Max: 40 -| -*/ -$config['rest_key_length'] = 40; - -/* -|-------------------------------------------------------------------------- -| REST API Key Variable -|-------------------------------------------------------------------------- -| -| Which variable will provide us the API Key -| -| Default: X-API-KEY -| -*/ -$config['rest_key_name'] = 'X-API-KEY'; - -/* -|-------------------------------------------------------------------------- -| REST API Logs Table Name -|-------------------------------------------------------------------------- -| -| The table name in your database that stores logs. -| -| 'logs' -| -*/ -$config['rest_logs_table'] = 'logs'; - -/* -|-------------------------------------------------------------------------- -| REST Enable Logging -|-------------------------------------------------------------------------- -| -| When set to true REST_Controller will log actions based on key, date, -| time and IP address. This is a general rule that can be overridden in the -| $this->method array in each controller. -| -| FALSE -| - CREATE TABLE `logs` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `uri` varchar(255) NOT NULL, - `method` varchar(6) NOT NULL, - `params` text DEFAULT NULL, - `api_key` varchar(40) NOT NULL, - `ip_address` varchar(45) NOT NULL, - `time` int(11) NOT NULL, - `authorized` tinyint(1) NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -| -*/ -$config['rest_enable_logging'] = FALSE; - -/* -|-------------------------------------------------------------------------- -| REST API Limits Table Name -|-------------------------------------------------------------------------- -| -| The table name in your database that stores limits. -| -| 'logs' -| -*/ -$config['rest_limits_table'] = 'limits'; - -/* -|-------------------------------------------------------------------------- -| REST Enable Limits -|-------------------------------------------------------------------------- -| -| When set to true REST_Controller will count the number of uses of each method -| by an API key each hour. This is a general rule that can be overridden in the -| $this->method array in each controller. -| -| FALSE -| - CREATE TABLE `limits` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `uri` varchar(255) NOT NULL, - `count` int(10) NOT NULL, - `hour_started` int(11) NOT NULL, - `api_key` varchar(40) NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -| -*/ -$config['rest_enable_limits'] = FALSE; - -/* -|-------------------------------------------------------------------------- -| REST Ignore HTTP Accept -|-------------------------------------------------------------------------- -| -| Set to TRUE to ignore the HTTP Accept and speed up each request a little. -| Only do this if you are using the $this->rest_format or /format/xml in URLs -| -| FALSE -| -*/ -$config['rest_ignore_http_accept'] = FALSE; - -/* -|-------------------------------------------------------------------------- -| REST AJAX Only -|-------------------------------------------------------------------------- -| -| Set to TRUE to only allow AJAX requests. If TRUE and the request is not -| coming from AJAX, a 505 response with the error message "Only AJAX -| requests are accepted." will be returned. This is good for production -| environments. Set to FALSE to also accept HTTP requests. -| -| FALSE -| -*/ -$config['rest_ajax_only'] = FALSE; - -/* End of file config.php */ -/* Location: ./system/application/config/rest.php */ diff --git a/application/config/routes.php b/application/config/routes.php deleted file mode 100755 index 5f9a5834..00000000 --- a/application/config/routes.php +++ /dev/null @@ -1,46 +0,0 @@ - array('grin.gif', '19', '19', 'grin'), - ':lol:' => array('lol.gif', '19', '19', 'LOL'), - ':cheese:' => array('cheese.gif', '19', '19', 'cheese'), - ':)' => array('smile.gif', '19', '19', 'smile'), - ';-)' => array('wink.gif', '19', '19', 'wink'), - ';)' => array('wink.gif', '19', '19', 'wink'), - ':smirk:' => array('smirk.gif', '19', '19', 'smirk'), - ':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'), - ':-S' => array('confused.gif', '19', '19', 'confused'), - ':wow:' => array('surprise.gif', '19', '19', 'surprised'), - ':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'), - ':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'), - '%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'), - ';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'), - ':P' => array('raspberry.gif', '19', '19', 'raspberry'), - ':blank:' => array('blank.gif', '19', '19', 'blank stare'), - ':long:' => array('longface.gif', '19', '19', 'long face'), - ':ohh:' => array('ohh.gif', '19', '19', 'ohh'), - ':grrr:' => array('grrr.gif', '19', '19', 'grrr'), - ':gulp:' => array('gulp.gif', '19', '19', 'gulp'), - '8-/' => array('ohoh.gif', '19', '19', 'oh oh'), - ':down:' => array('downer.gif', '19', '19', 'downer'), - ':red:' => array('embarrassed.gif', '19', '19', 'red face'), - ':sick:' => array('sick.gif', '19', '19', 'sick'), - ':shut:' => array('shuteye.gif', '19', '19', 'shut eye'), - ':-/' => array('hmm.gif', '19', '19', 'hmmm'), - '>:(' => array('mad.gif', '19', '19', 'mad'), - ':mad:' => array('mad.gif', '19', '19', 'mad'), - '>:-(' => array('angry.gif', '19', '19', 'angry'), - ':angry:' => array('angry.gif', '19', '19', 'angry'), - ':zip:' => array('zip.gif', '19', '19', 'zipper'), - ':kiss:' => array('kiss.gif', '19', '19', 'kiss'), - ':ahhh:' => array('shock.gif', '19', '19', 'shock'), - ':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'), - ':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'), - ':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'), - ':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'), - ':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'), - ':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'), - ':vampire:' => array('vampire.gif', '19', '19', 'vampire'), - ':snake:' => array('snake.gif', '19', '19', 'snake'), - ':exclaim:' => array('exclaim.gif', '19', '19', 'excaim'), - ':question:' => array('question.gif', '19', '19', 'question') // no comma after last item - - ); - -/* End of file smileys.php */ -/* Location: ./application/config/smileys.php */ \ No newline at end of file diff --git a/application/config/user_agents.php b/application/config/user_agents.php deleted file mode 100644 index e2d3c3af..00000000 --- a/application/config/user_agents.php +++ /dev/null @@ -1,178 +0,0 @@ - 'Windows Longhorn', - 'windows nt 5.2' => 'Windows 2003', - 'windows nt 5.0' => 'Windows 2000', - 'windows nt 5.1' => 'Windows XP', - 'windows nt 4.0' => 'Windows NT 4.0', - 'winnt4.0' => 'Windows NT 4.0', - 'winnt 4.0' => 'Windows NT', - 'winnt' => 'Windows NT', - 'windows 98' => 'Windows 98', - 'win98' => 'Windows 98', - 'windows 95' => 'Windows 95', - 'win95' => 'Windows 95', - 'windows' => 'Unknown Windows OS', - 'os x' => 'Mac OS X', - 'ppc mac' => 'Power PC Mac', - 'freebsd' => 'FreeBSD', - 'ppc' => 'Macintosh', - 'linux' => 'Linux', - 'debian' => 'Debian', - 'sunos' => 'Sun Solaris', - 'beos' => 'BeOS', - 'apachebench' => 'ApacheBench', - 'aix' => 'AIX', - 'irix' => 'Irix', - 'osf' => 'DEC OSF', - 'hp-ux' => 'HP-UX', - 'netbsd' => 'NetBSD', - 'bsdi' => 'BSDi', - 'openbsd' => 'OpenBSD', - 'gnu' => 'GNU/Linux', - 'unix' => 'Unknown Unix OS' - ); - - -// The order of this array should NOT be changed. Many browsers return -// multiple browser types so we want to identify the sub-type first. -$browsers = array( - 'Flock' => 'Flock', - 'Chrome' => 'Chrome', - 'Opera' => 'Opera', - 'MSIE' => 'Internet Explorer', - 'Internet Explorer' => 'Internet Explorer', - 'Shiira' => 'Shiira', - 'Firefox' => 'Firefox', - 'Chimera' => 'Chimera', - 'Phoenix' => 'Phoenix', - 'Firebird' => 'Firebird', - 'Camino' => 'Camino', - 'Netscape' => 'Netscape', - 'OmniWeb' => 'OmniWeb', - 'Safari' => 'Safari', - 'Mozilla' => 'Mozilla', - 'Konqueror' => 'Konqueror', - 'icab' => 'iCab', - 'Lynx' => 'Lynx', - 'Links' => 'Links', - 'hotjava' => 'HotJava', - 'amaya' => 'Amaya', - 'IBrowse' => 'IBrowse' - ); - -$mobiles = array( - // legacy array, old values commented out - 'mobileexplorer' => 'Mobile Explorer', -// 'openwave' => 'Open Wave', -// 'opera mini' => 'Opera Mini', -// 'operamini' => 'Opera Mini', -// 'elaine' => 'Palm', - 'palmsource' => 'Palm', -// 'digital paths' => 'Palm', -// 'avantgo' => 'Avantgo', -// 'xiino' => 'Xiino', - 'palmscape' => 'Palmscape', -// 'nokia' => 'Nokia', -// 'ericsson' => 'Ericsson', -// 'blackberry' => 'BlackBerry', -// 'motorola' => 'Motorola' - - // Phones and Manufacturers - 'motorola' => "Motorola", - 'nokia' => "Nokia", - 'palm' => "Palm", - 'iphone' => "Apple iPhone", - 'ipad' => "iPad", - 'ipod' => "Apple iPod Touch", - 'sony' => "Sony Ericsson", - 'ericsson' => "Sony Ericsson", - 'blackberry' => "BlackBerry", - 'cocoon' => "O2 Cocoon", - 'blazer' => "Treo", - 'lg' => "LG", - 'amoi' => "Amoi", - 'xda' => "XDA", - 'mda' => "MDA", - 'vario' => "Vario", - 'htc' => "HTC", - 'samsung' => "Samsung", - 'sharp' => "Sharp", - 'sie-' => "Siemens", - 'alcatel' => "Alcatel", - 'benq' => "BenQ", - 'ipaq' => "HP iPaq", - 'mot-' => "Motorola", - 'playstation portable' => "PlayStation Portable", - 'hiptop' => "Danger Hiptop", - 'nec-' => "NEC", - 'panasonic' => "Panasonic", - 'philips' => "Philips", - 'sagem' => "Sagem", - 'sanyo' => "Sanyo", - 'spv' => "SPV", - 'zte' => "ZTE", - 'sendo' => "Sendo", - - // Operating Systems - 'symbian' => "Symbian", - 'SymbianOS' => "SymbianOS", - 'elaine' => "Palm", - 'palm' => "Palm", - 'series60' => "Symbian S60", - 'windows ce' => "Windows CE", - - // Browsers - 'obigo' => "Obigo", - 'netfront' => "Netfront Browser", - 'openwave' => "Openwave Browser", - 'mobilexplorer' => "Mobile Explorer", - 'operamini' => "Opera Mini", - 'opera mini' => "Opera Mini", - - // Other - 'digital paths' => "Digital Paths", - 'avantgo' => "AvantGo", - 'xiino' => "Xiino", - 'novarra' => "Novarra Transcoder", - 'vodafone' => "Vodafone", - 'docomo' => "NTT DoCoMo", - 'o2' => "O2", - - // Fallback - 'mobile' => "Generic Mobile", - 'wireless' => "Generic Mobile", - 'j2me' => "Generic Mobile", - 'midp' => "Generic Mobile", - 'cldc' => "Generic Mobile", - 'up.link' => "Generic Mobile", - 'up.browser' => "Generic Mobile", - 'smartphone' => "Generic Mobile", - 'cellphone' => "Generic Mobile" - ); - -// There are hundreds of bots but these are the most common. -$robots = array( - 'googlebot' => 'Googlebot', - 'msnbot' => 'MSNBot', - 'slurp' => 'Inktomi Slurp', - 'yahoo' => 'Yahoo', - 'askjeeves' => 'AskJeeves', - 'fastcrawler' => 'FastCrawler', - 'infoseek' => 'InfoSeek Robot 1.0', - 'lycos' => 'Lycos' - ); - -/* End of file user_agents.php */ -/* Location: ./application/config/user_agents.php */ \ No newline at end of file diff --git a/application/controllers/api/example.php b/application/controllers/api/example.php deleted file mode 100644 index edfd1e32..00000000 --- a/application/controllers/api/example.php +++ /dev/null @@ -1,95 +0,0 @@ -get('id')) - { - $this->response(NULL, 400); - } - - // $user = $this->some_model->getSomething( $this->get('id') ); - $users = array( - 1 => array('id' => 1, 'name' => 'Some Guy', 'email' => 'example1@example.com', 'fact' => 'Loves swimming'), - 2 => array('id' => 2, 'name' => 'Person Face', 'email' => 'example2@example.com', 'fact' => 'Has a huge face'), - 3 => array('id' => 3, 'name' => 'Scotty', 'email' => 'example3@example.com', 'fact' => 'Is a Scott!', array('hobbies' => array('fartings', 'bikes'))), - ); - - $user = @$users[$this->get('id')]; - - if($user) - { - $this->response($user, 200); // 200 being the HTTP response code - } - - else - { - $this->response(array('error' => 'User could not be found'), 404); - } - } - - function user_post() - { - //$this->some_model->updateUser( $this->get('id') ); - $message = array('id' => $this->get('id'), 'name' => $this->post('name'), 'email' => $this->post('email'), 'message' => 'ADDED!'); - - $this->response($message, 200); // 200 being the HTTP response code - } - - function user_delete() - { - //$this->some_model->deletesomething( $this->get('id') ); - $message = array('id' => $this->get('id'), 'message' => 'DELETED!'); - - $this->response($message, 200); // 200 being the HTTP response code - } - - function users_get() - { - //$users = $this->some_model->getSomething( $this->get('limit') ); - $users = array( - array('id' => 1, 'name' => 'Some Guy', 'email' => 'example1@example.com'), - array('id' => 2, 'name' => 'Person Face', 'email' => 'example2@example.com'), - 3 => array('id' => 3, 'name' => 'Scotty', 'email' => 'example3@example.com', 'fact' => array('hobbies' => array('fartings', 'bikes'))), - ); - - if($users) - { - $this->response($users, 200); // 200 being the HTTP response code - } - - else - { - $this->response(array('error' => 'Couldn\'t find any users!'), 404); - } - } - - - public function send_post() - { - var_dump($this->request->body); - } - - - public function send_put() - { - var_dump($this->put('foo')); - } -} \ No newline at end of file diff --git a/application/controllers/api/key.php b/application/controllers/api/key.php deleted file mode 100644 index e4468862..00000000 --- a/application/controllers/api/key.php +++ /dev/null @@ -1,251 +0,0 @@ - array('level' => 10, 'limit' => 10), - 'index_delete' => array('level' => 10), - 'level_post' => array('level' => 10), - 'regenerate_post' => array('level' => 10), - ); - - /** - * Key Create - * - * Insert a key into the database. - * - * @access public - * @return void - */ - public function index_put() - { - // Build a new key - $key = self::_generate_key(); - - // If no key level provided, give them a rubbish one - $level = $this->put('level') ? $this->put('level') : 1; - $ignore_limits = $this->put('ignore_limits') ? $this->put('ignore_limits') : 1; - - // Insert the new key - if (self::_insert_key($key, array('level' => $level, 'ignore_limits' => $ignore_limits))) - { - $this->response(array('status' => 1, 'key' => $key), 201); // 201 = Created - } - - else - { - $this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error - } - } - - // -------------------------------------------------------------------- - - /** - * Key Delete - * - * Remove a key from the database to stop it working. - * - * @access public - * @return void - */ - public function index_delete() - { - $key = $this->delete('key'); - - // Does this key even exist? - if ( ! self::_key_exists($key)) - { - // NOOOOOOOOO! - $this->response(array('status' => 0, 'error' => 'Invalid API Key.'), 400); - } - - // Kill it - self::_delete_key($key); - - // Tell em we killed it - $this->response(array('status' => 1, 'success' => 'API Key was deleted.'), 200); - } - - // -------------------------------------------------------------------- - - /** - * Update Key - * - * Change the level - * - * @access public - * @return void - */ - public function level_post() - { - $key = $this->post('key'); - $new_level = $this->post('level'); - - // Does this key even exist? - if ( ! self::_key_exists($key)) - { - // NOOOOOOOOO! - $this->response(array('error' => 'Invalid API Key.'), 400); - } - - // Update the key level - if (self::_update_key($key, array('level' => $new_level))) - { - $this->response(array('status' => 1, 'success' => 'API Key was updated.'), 200); // 200 = OK - } - - else - { - $this->response(array('status' => 0, 'error' => 'Could not update the key level.'), 500); // 500 = Internal Server Error - } - } - - // -------------------------------------------------------------------- - - /** - * Update Key - * - * Change the level - * - * @access public - * @return void - */ - public function suspend_post() - { - $key = $this->post('key'); - - // Does this key even exist? - if ( ! self::_key_exists($key)) - { - // NOOOOOOOOO! - $this->response(array('error' => 'Invalid API Key.'), 400); - } - - // Update the key level - if (self::_update_key($key, array('level' => 0))) - { - $this->response(array('status' => 1, 'success' => 'Key was suspended.'), 200); // 200 = OK - } - - else - { - $this->response(array('status' => 0, 'error' => 'Could not suspend the user.'), 500); // 500 = Internal Server Error - } - } - - // -------------------------------------------------------------------- - - /** - * Regenerate Key - * - * Remove a key from the database to stop it working. - * - * @access public - * @return void - */ - public function regenerate_post() - { - $old_key = $this->post('key'); - $key_details = self::_get_key($old_key); - - // The key wasnt found - if ( ! $key_details) - { - // NOOOOOOOOO! - $this->response(array('status' => 0, 'error' => 'Invalid API Key.'), 400); - } - - // Build a new key - $new_key = self::_generate_key(); - - // Insert the new key - if (self::_insert_key($new_key, array('level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits))) - { - // Suspend old key - self::_update_key($old_key, array('level' => 0)); - - $this->response(array('status' => 1, 'key' => $new_key), 201); // 201 = Created - } - - else - { - $this->response(array('status' => 0, 'error' => 'Could not save the key.'), 500); // 500 = Internal Server Error - } - } - - // -------------------------------------------------------------------- - - /* Helper Methods */ - - private function _generate_key() - { - //$this->load->helper('security'); - - do - { - $salt = do_hash(time().mt_rand()); - $new_key = substr($salt, 0, config_item('rest_key_length')); - } - - // Already in the DB? Fail. Try again - while (self::_key_exists($new_key)); - - return $new_key; - } - - // -------------------------------------------------------------------- - - /* Private Data Methods */ - - private function _get_key($key) - { - return $this->db->where('key', $key)->get(config_item('rest_keys_table'))->row(); - } - - // -------------------------------------------------------------------- - - private function _key_exists($key) - { - return $this->db->where('key', $key)->count_all_results(config_item('rest_keys_table')) > 0; - } - - // -------------------------------------------------------------------- - - private function _insert_key($key, $data) - { - - $data['key'] = $key; - $data['date_created'] = function_exists('now') ? now() : time(); - - return $this->db->set($data)->insert(config_item('rest_keys_table')); - } - - // -------------------------------------------------------------------- - - private function _update_key($key, $data) - { - return $this->db->where('key', $key)->update(config_item('rest_keys_table'), $data); - } - - // -------------------------------------------------------------------- - - private function _delete_key($key) - { - return $this->db->where('key', $key)->delete(config_item('rest_keys_table')); - } -} diff --git a/application/controllers/welcome.php b/application/controllers/welcome.php deleted file mode 100644 index 57151c6e..00000000 --- a/application/controllers/welcome.php +++ /dev/null @@ -1,18 +0,0 @@ -load->helper('url'); - $this->load->view('welcome_message'); - } -} - -/* End of file welcome.php */ -/* Location: ./system/application/controllers/welcome.php */ \ No newline at end of file diff --git a/application/errors/error_404.php b/application/errors/error_404.php deleted file mode 100755 index a304f456..00000000 --- a/application/errors/error_404.php +++ /dev/null @@ -1,34 +0,0 @@ - -
-Severity:
-Message:
-Filename:
-Line Number:
- -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/helpers/index.html b/application/helpers/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/helpers/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/hooks/index.html b/application/hooks/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/hooks/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/index.html b/application/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/language/english/index.html b/application/language/english/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/language/english/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/libraries/Format.php b/application/libraries/Format.php deleted file mode 100644 index acb13699..00000000 --- a/application/libraries/Format.php +++ /dev/null @@ -1,270 +0,0 @@ -format->factory(array('foo' => 'bar'))->to_xml(); - * - * @param mixed general date to be converted - * @param string data format the file was provided in - * @return Factory - */ - public function factory($data, $from_type = null) - { - // Stupid stuff to emulate the "new static()" stuff in this libraries PHP 5.3 equivalent - $class = __CLASS__; - return new $class($data, $from_type); - } - - /** - * Do not use this directly, call factory() - */ - public function __construct($data = null, $from_type = null) - { - get_instance()->load->helper('inflector'); - - // If the provided data is already formatted we should probably convert it to an array - if ($from_type !== null) - { - if (method_exists($this, '_from_' . $from_type)) - { - $data = call_user_func(array($this, '_from_' . $from_type), $data); - } - - else - { - throw new Exception('Format class does not support conversion from "' . $from_type . '".'); - } - } - - $this->_data = $data; - } - - // FORMATING OUTPUT --------------------------------------------------------- - - public function to_array($data = null) - { - // If not just null, but nothing is provided - if ($data === null and ! func_num_args()) - { - $data = $this->_data; - } - - $array = array(); - - foreach ((array) $data as $key => $value) - { - if (is_object($value) or is_array($value)) - { - $array[$key] = $this->to_array($value); - } - - else - { - $array[$key] = $value; - } - } - - return $array; - } - - // Format XML for output - public function to_xml($data = null, $structure = null, $basenode = 'xml') - { - if ($data === null and ! func_num_args()) - { - $data = $this->_data; - } - - // turn off compatibility mode as simple xml throws a wobbly if you don't. - if (ini_get('zend.ze1_compatibility_mode') == 1) - { - ini_set('zend.ze1_compatibility_mode', 0); - } - - if ($structure === null) - { - $structure = simplexml_load_string("<$basenode />"); - } - - // Force it to be something useful - if ( ! is_array($data) AND ! is_object($data)) - { - $data = (array) $data; - } - - foreach ($data as $key => $value) - { - - //change false/true to 0/1 - if(is_bool($value)) - { - $value = (int) $value; - } - - // no numeric keys in our xml please! - if (is_numeric($key)) - { - // make string key... - $key = (singular($basenode) != $basenode) ? singular($basenode) : 'item'; - } - - // replace anything not alpha numeric - $key = preg_replace('/[^a-z_\-0-9]/i', '', $key); - - // if there is another array found recursively call this function - if (is_array($value) || is_object($value)) - { - $node = $structure->addChild($key); - - // recursive call. - $this->to_xml($value, $node, $key); - } - - else - { - // add single node. - $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8"); - - $structure->addChild($key, $value); - } - } - - return $structure->asXML(); - } - - // Format HTML for output - public function to_html() - { - $data = $this->_data; - - // Multi-dimensional array - if (isset($data[0]) && is_array($data[0])) - { - $headings = array_keys($data[0]); - } - - // Single array - else - { - $headings = array_keys($data); - $data = array($data); - } - - $ci = get_instance(); - $ci->load->library('table'); - - $ci->table->set_heading($headings); - - foreach ($data as &$row) - { - $ci->table->add_row($row); - } - - return $ci->table->generate(); - } - - // Format CSV for output - public function to_csv() - { - $data = $this->_data; - - // Multi-dimensional array - if (isset($data[0]) && is_array($data[0])) - { - $headings = array_keys($data[0]); - } - - // Single array - else - { - $headings = array_keys($data); - $data = array($data); - } - - $output = implode(',', $headings).PHP_EOL; - foreach ($data as &$row) - { - $output .= '"'.implode('","', $row).'"'.PHP_EOL; - } - - return $output; - } - - // Encode as JSON - public function to_json() - { - return json_encode($this->_data); - } - - // Encode as Serialized array - public function to_serialized() - { - return serialize($this->_data); - } - - // Output as a string representing the PHP structure - public function to_php() - { - return var_export($this->_data, TRUE); - } - - // Format XML for output - protected function _from_xml($string) - { - return $string ? (array) simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array(); - } - - // Format CSV for output - // This function is DODGY! Not perfect CSV support but works with my REST_Controller - protected function _from_csv($string) - { - $data = array(); - - // Splits - $rows = explode("\n", trim($string)); - $headings = explode(',', array_shift($rows)); - foreach ($rows as $row) - { - // The substr removes " from start and end - $data_fields = explode('","', trim(substr($row, 1, -1))); - - if (count($data_fields) == count($headings)) - { - $data[] = array_combine($headings, $data_fields); - } - } - - return $data; - } - - // Encode as JSON - private function _from_json($string) - { - return json_decode(trim($string)); - } - - // Encode as Serialized array - private function _from_serialize($string) - { - return unserialize(trim($string)); - } - -} - -/* End of file format.php */ \ No newline at end of file diff --git a/application/libraries/REST_Controller.php b/application/libraries/REST_Controller.php deleted file mode 100644 index 552a0789..00000000 --- a/application/libraries/REST_Controller.php +++ /dev/null @@ -1,1264 +0,0 @@ - 'application/xml', - 'json' => 'application/json', - 'jsonp' => 'application/javascript', - 'serialized' => 'application/vnd.php.serialized', - 'php' => 'text/plain', - 'html' => 'text/html', - 'csv' => 'application/csv' - ); - - /** - * Developers can extend this class and add a check in here. - */ - protected function early_checks() - { - - } - - /** - * Constructor function - * @todo Document more please. - */ - public function __construct() - { - parent::__construct(); - - $this->_zlib_oc = @ini_get('zlib.output_compression'); - - // Lets grab the config and get ready to party - $this->load->config('rest'); - - // let's learn about the request - $this->request = new stdClass(); - - // Is it over SSL? - $this->request->ssl = $this->_detect_ssl(); - - // How is this request being made? POST, DELETE, GET, PUT? - $this->request->method = $this->_detect_method(); - - // Create argument container, if nonexistent - if ( ! isset($this->{'_'.$this->request->method.'_args'})) - { - $this->{'_'.$this->request->method.'_args'} = array(); - } - - // Set up our GET variables - $this->_get_args = array_merge($this->_get_args, $this->uri->ruri_to_assoc()); - - $this->load->library('security'); - - // This library is bundled with REST_Controller 2.5+, but will eventually be part of CodeIgniter itself - $this->load->library('format'); - - // Try to find a format for the request (means we have a request body) - $this->request->format = $this->_detect_input_format(); - - // Some Methods cant have a body - $this->request->body = NULL; - - $this->{'_parse_' . $this->request->method}(); - - // Now we know all about our request, let's try and parse the body if it exists - if ($this->request->format and $this->request->body) - { - $this->request->body = $this->format->factory($this->request->body, $this->request->format)->to_array(); - // Assign payload arguments to proper method container - $this->{'_'.$this->request->method.'_args'} = $this->request->body; - } - - // Merge both for one mega-args variable - $this->_args = array_merge($this->_get_args, $this->_put_args, $this->_post_args, $this->_delete_args, $this->{'_'.$this->request->method.'_args'}); - - // Which format should the data be returned in? - $this->response = new stdClass(); - $this->response->format = $this->_detect_output_format(); - - // Which format should the data be returned in? - $this->response->lang = $this->_detect_lang(); - - // Developers can extend this class and add a check in here - $this->early_checks(); - - // Check if there is a specific auth type for the current class/method - $this->auth_override = $this->_auth_override_check(); - - // When there is no specific override for the current class/method, use the default auth value set in the config - if ($this->auth_override !== TRUE) - { - if ($this->config->item('rest_auth') == 'basic') - { - $this->_prepare_basic_auth(); - } - elseif ($this->config->item('rest_auth') == 'digest') - { - $this->_prepare_digest_auth(); - } - elseif ($this->config->item('rest_ip_whitelist_enabled')) - { - $this->_check_whitelist_auth(); - } - } - - $this->rest = new StdClass(); - // Load DB if its enabled - if (config_item('rest_database_group') AND (config_item('rest_enable_keys') OR config_item('rest_enable_logging'))) - { - $this->rest->db = $this->load->database(config_item('rest_database_group'), TRUE); - } - - // Use whatever database is in use (isset returns false) - elseif (@$this->db) - { - $this->rest->db = $this->db; - } - - // Checking for keys? GET TO WORK! - if (config_item('rest_enable_keys')) - { - $this->_allow = $this->_detect_api_key(); - } - - // only allow ajax requests - if ( ! $this->input->is_ajax_request() AND config_item('rest_ajax_only')) - { - $this->response(array('status' => false, 'error' => 'Only AJAX requests are accepted.'), 505); - } - } - - /** - * Remap - * - * Requests are not made to methods directly, the request will be for - * an "object". This simply maps the object and method to the correct - * Controller method. - * - * @param string $object_called - * @param array $arguments The arguments passed to the controller method. - */ - public function _remap($object_called, $arguments) - { - // Should we answer if not over SSL? - if (config_item('force_https') AND !$this->_detect_ssl()) - { - $this->response(array('status' => false, 'error' => 'Unsupported protocol'), 403); - } - - $pattern = '/^(.*)\.('.implode('|', array_keys($this->_supported_formats)).')$/'; - if (preg_match($pattern, $object_called, $matches)) - { - $object_called = $matches[1]; - } - - $controller_method = $object_called.'_'.$this->request->method; - - // Do we want to log this method (if allowed by config)? - $log_method = !(isset($this->methods[$controller_method]['log']) AND $this->methods[$controller_method]['log'] == FALSE); - - // Use keys for this method? - $use_key = ! (isset($this->methods[$controller_method]['key']) AND $this->methods[$controller_method]['key'] == FALSE); - - // Get that useless shitty key out of here - if (config_item('rest_enable_keys') AND $use_key AND $this->_allow === FALSE) - { - if (config_item('rest_enable_logging') AND $log_method) - { - $this->_log_request(); - } - - $this->response(array('status' => false, 'error' => 'Invalid API Key.'), 403); - } - - // Sure it exists, but can they do anything with it? - if ( ! method_exists($this, $controller_method)) - { - $this->response(array('status' => false, 'error' => 'Unknown method.'), 404); - } - - // Doing key related stuff? Can only do it if they have a key right? - if (config_item('rest_enable_keys') AND !empty($this->rest->key)) - { - // Check the limit - if (config_item('rest_enable_limits') AND !$this->_check_limit($controller_method)) - { - $this->response(array('status' => false, 'error' => 'This API key has reached the hourly limit for this method.'), 401); - } - - // If no level is set use 0, they probably aren't using permissions - $level = isset($this->methods[$controller_method]['level']) ? $this->methods[$controller_method]['level'] : 0; - - // If no level is set, or it is lower than/equal to the key's level - $authorized = $level <= $this->rest->level; - - // IM TELLIN! - if (config_item('rest_enable_logging') AND $log_method) - { - $this->_log_request($authorized); - } - - // They don't have good enough perms - $authorized OR $this->response(array('status' => false, 'error' => 'This API key does not have enough permissions.'), 401); - } - - // No key stuff, but record that stuff is happening - else if (config_item('rest_enable_logging') AND $log_method) - { - $this->_log_request($authorized = TRUE); - } - - // And...... GO! - $this->_fire_method(array($this, $controller_method), $arguments); - } - - /** - * Fire Method - * - * Fires the designated controller method with the given arguments. - * - * @param array $method The controller method to fire - * @param array $args The arguments to pass to the controller method - */ - protected function _fire_method($method, $args) - { - call_user_func_array($method, $args); - } - - /** - * Response - * - * Takes pure data and optionally a status code, then creates the response. - * - * @param array $data - * @param null|int $http_code - */ - public function response($data = array(), $http_code = null) - { - global $CFG; - - // If data is empty and not code provide, error and bail - if (empty($data) && $http_code === null) - { - $http_code = 404; - - // create the output variable here in the case of $this->response(array()); - $output = NULL; - } - - // Otherwise (if no data but 200 provided) or some data, carry on camping! - else - { - // Is compression requested? - if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE) - { - if (extension_loaded('zlib')) - { - if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) - { - ob_start('ob_gzhandler'); - } - } - } - - is_numeric($http_code) OR $http_code = 200; - - // If the format method exists, call and return the output in that format - if (method_exists($this, '_format_'.$this->response->format)) - { - // Set the correct format header - header('Content-Type: '.$this->_supported_formats[$this->response->format]); - - $output = $this->{'_format_'.$this->response->format}($data); - } - - // If the format method exists, call and return the output in that format - elseif (method_exists($this->format, 'to_'.$this->response->format)) - { - // Set the correct format header - header('Content-Type: '.$this->_supported_formats[$this->response->format]); - - $output = $this->format->factory($data)->{'to_'.$this->response->format}(); - } - - // Format not supported, output directly - else - { - $output = $data; - } - } - - header('HTTP/1.1: ' . $http_code); - header('Status: ' . $http_code); - - // If zlib.output_compression is enabled it will compress the output, - // but it will not modify the content-length header to compensate for - // the reduction, causing the browser to hang waiting for more data. - // We'll just skip content-length in those cases. - if ( ! $this->_zlib_oc && ! $CFG->item('compress_output')) - { - header('Content-Length: ' . strlen($output)); - } - - exit($output); - } - - /* - * Detect SSL use - * - * Detect whether SSL is being used or not - */ - protected function _detect_ssl() - { - return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on"); - } - - - /* - * Detect input format - * - * Detect which format the HTTP Body is provided in - */ - protected function _detect_input_format() - { - if ($this->input->server('CONTENT_TYPE')) - { - // Check all formats against the HTTP_ACCEPT header - foreach ($this->_supported_formats as $format => $mime) - { - if (strpos($match = $this->input->server('CONTENT_TYPE'), ';')) - { - $match = current(explode(';', $match)); - } - - if ($match == $mime) - { - return $format; - } - } - } - - return NULL; - } - - /** - * Detect format - * - * Detect which format should be used to output the data. - * - * @return string The output format. - */ - protected function _detect_output_format() - { - $pattern = '/\.('.implode('|', array_keys($this->_supported_formats)).')$/'; - - // Check if a file extension is used - if (preg_match($pattern, $this->uri->uri_string(), $matches)) - { - return $matches[1]; - } - - // Check if a file extension is used - elseif ($this->_get_args AND !is_array(end($this->_get_args)) AND preg_match($pattern, end($this->_get_args), $matches)) - { - // The key of the last argument - $last_key = end(array_keys($this->_get_args)); - - // Remove the extension from arguments too - $this->_get_args[$last_key] = preg_replace($pattern, '', $this->_get_args[$last_key]); - $this->_args[$last_key] = preg_replace($pattern, '', $this->_args[$last_key]); - - return $matches[1]; - } - - // A format has been passed as an argument in the URL and it is supported - if (isset($this->_get_args['format']) AND array_key_exists($this->_get_args['format'], $this->_supported_formats)) - { - return $this->_get_args['format']; - } - - // Otherwise, check the HTTP_ACCEPT (if it exists and we are allowed) - if ($this->config->item('rest_ignore_http_accept') === FALSE AND $this->input->server('HTTP_ACCEPT')) - { - // Check all formats against the HTTP_ACCEPT header - foreach (array_keys($this->_supported_formats) as $format) - { - // Has this format been requested? - if (strpos($this->input->server('HTTP_ACCEPT'), $format) !== FALSE) - { - // If not HTML or XML assume its right and send it on its way - if ($format != 'html' AND $format != 'xml') - { - - return $format; - } - - // HTML or XML have shown up as a match - else - { - // If it is truly HTML, it wont want any XML - if ($format == 'html' AND strpos($this->input->server('HTTP_ACCEPT'), 'xml') === FALSE) - { - return $format; - } - - // If it is truly XML, it wont want any HTML - elseif ($format == 'xml' AND strpos($this->input->server('HTTP_ACCEPT'), 'html') === FALSE) - { - return $format; - } - } - } - } - } // End HTTP_ACCEPT checking - - // Well, none of that has worked! Let's see if the controller has a default - if ( ! empty($this->rest_format)) - { - return $this->rest_format; - } - - // Just use the default format - return config_item('rest_default_format'); - } - - /** - * Detect method - * - * Detect which HTTP method is being used - * - * @return string - */ - protected function _detect_method() - { - $method = strtolower($this->input->server('REQUEST_METHOD')); - - if ($this->config->item('enable_emulate_request')) - { - if ($this->input->post('_method')) - { - $method = strtolower($this->input->post('_method')); - } - elseif ($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE')) - { - $method = strtolower($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE')); - } - } - - if (in_array($method, $this->allowed_http_methods) && method_exists($this, '_parse_' . $method)) - { - return $method; - } - - return 'get'; - } - - /** - * Detect API Key - * - * See if the user has provided an API key - * - * @return boolean - */ - protected function _detect_api_key() - { - // Get the api key name variable set in the rest config file - $api_key_variable = config_item('rest_key_name'); - - // Work out the name of the SERVER entry based on config - $key_name = 'HTTP_'.strtoupper(str_replace('-', '_', $api_key_variable)); - - $this->rest->key = NULL; - $this->rest->level = NULL; - $this->rest->user_id = NULL; - $this->rest->ignore_limits = FALSE; - - // Find the key from server or arguments - if (($key = isset($this->_args[$api_key_variable]) ? $this->_args[$api_key_variable] : $this->input->server($key_name))) - { - if ( ! ($row = $this->rest->db->where(config_item('rest_key_column'), $key)->get(config_item('rest_keys_table'))->row())) - { - return FALSE; - } - - $this->rest->key = $row->{config_item('rest_key_column')}; - - isset($row->user_id) AND $this->rest->user_id = $row->user_id; - isset($row->level) AND $this->rest->level = $row->level; - isset($row->ignore_limits) AND $this->rest->ignore_limits = $row->ignore_limits; - - /* - * If "is private key" is enabled, compare the ip address with the list - * of valid ip addresses stored in the database. - */ - if(!empty($row->is_private_key)) - { - // Check for a list of valid ip addresses - if(isset($row->ip_addresses)) - { - // multiple ip addresses must be separated using a comma, explode and loop - $list_ip_addresses = explode(",", $row->ip_addresses); - $found_address = FALSE; - - foreach($list_ip_addresses as $ip_address) - { - if($this->input->ip_address() == trim($ip_address)) - { - // there is a match, set the the value to true and break out of the loop - $found_address = TRUE; - break; - } - } - - return $found_address; - } - else - { - // There should be at least one IP address for this private key. - return FALSE; - } - } - - return $row; - } - - // No key has been sent - return FALSE; - } - - /** - * Detect language(s) - * - * What language do they want it in? - * - * @return null|string The language code. - */ - protected function _detect_lang() - { - if ( ! $lang = $this->input->server('HTTP_ACCEPT_LANGUAGE')) - { - return NULL; - } - - // They might have sent a few, make it an array - if (strpos($lang, ',') !== FALSE) - { - $langs = explode(',', $lang); - - $return_langs = array(); - $i = 1; - foreach ($langs as $lang) - { - // Remove weight and strip space - list($lang) = explode(';', $lang); - $return_langs[] = trim($lang); - } - - return $return_langs; - } - - // Nope, just return the string - return $lang; - } - - /** - * Log request - * - * Record the entry for awesomeness purposes - * - * @param boolean $authorized - * @return object - */ - protected function _log_request($authorized = FALSE) - { - return $this->rest->db->insert(config_item('rest_logs_table'), array( - 'uri' => $this->uri->uri_string(), - 'method' => $this->request->method, - 'params' => $this->_args ? serialize($this->_args) : null, - 'api_key' => isset($this->rest->key) ? $this->rest->key : '', - 'ip_address' => $this->input->ip_address(), - 'time' => function_exists('now') ? now() : time(), - 'authorized' => $authorized - )); - } - - /** - * Limiting requests - * - * Check if the requests are coming in a tad too fast. - * - * @param string $controller_method The method being called. - * @return boolean - */ - protected function _check_limit($controller_method) - { - // They are special, or it might not even have a limit - if ( ! empty($this->rest->ignore_limits) OR !isset($this->methods[$controller_method]['limit'])) - { - // On your way sonny-jim. - return TRUE; - } - - // How many times can you get to this method an hour? - $limit = $this->methods[$controller_method]['limit']; - - // Get data on a keys usage - $result = $this->rest->db - ->where('uri', $this->uri->uri_string()) - ->where('api_key', $this->rest->key) - ->get(config_item('rest_limits_table')) - ->row(); - - // No calls yet, or been an hour since they called - if ( ! $result OR $result->hour_started < time() - (60 * 60)) - { - // Right, set one up from scratch - $this->rest->db->insert(config_item('rest_limits_table'), array( - 'uri' => $this->uri->uri_string(), - 'api_key' => isset($this->rest->key) ? $this->rest->key : '', - 'count' => 1, - 'hour_started' => time() - )); - } - - // They have called within the hour, so lets update - else - { - // Your luck is out, you've called too many times! - if ($result->count >= $limit) - { - return FALSE; - } - - $this->rest->db - ->where('uri', $this->uri->uri_string()) - ->where('api_key', $this->rest->key) - ->set('count', 'count + 1', FALSE) - ->update(config_item('rest_limits_table')); - } - - return TRUE; - } - - /** - * Auth override check - * - * Check if there is a specific auth type set for the current class/method - * being called. - * - * @return boolean - */ - protected function _auth_override_check() - { - - // Assign the class/method auth type override array from the config - $this->overrides_array = $this->config->item('auth_override_class_method'); - - // Check to see if the override array is even populated, otherwise return false - if (empty($this->overrides_array)) - { - return false; - } - - // Check to see if there's an override value set for the current class/method being called - if (empty($this->overrides_array[$this->router->class][$this->router->method])) - { - return false; - } - - // None auth override found, prepare nothing but send back a true override flag - if ($this->overrides_array[$this->router->class][$this->router->method] == 'none') - { - return true; - } - - // Basic auth override found, prepare basic - if ($this->overrides_array[$this->router->class][$this->router->method] == 'basic') - { - $this->_prepare_basic_auth(); - return true; - } - - // Digest auth override found, prepare digest - if ($this->overrides_array[$this->router->class][$this->router->method] == 'digest') - { - $this->_prepare_digest_auth(); - return true; - } - - // Whitelist auth override found, check client's ip against config whitelist - if ($this->overrides_array[$this->router->class][$this->router->method] == 'whitelist') - { - $this->_check_whitelist_auth(); - return true; - } - - // Return false when there is an override value set but it does not match - // 'basic', 'digest', or 'none'. (the value was misspelled) - return false; - } - - /** - * Parse GET - */ - protected function _parse_get() - { - // Grab proper GET variables - parse_str(parse_url(http://github.com/$_SERVER['REQUEST_URI'],%20PHP_URL_QUERY), $get); - - // Merge both the URI segments and GET params - $this->_get_args = array_merge($this->_get_args, $get); - } - - /** - * Parse POST - */ - protected function _parse_post() - { - $this->_post_args = $_POST; - - $this->request->format and $this->request->body = file_get_contents('php://input'); - } - - /** - * Parse PUT - */ - protected function _parse_put() - { - // It might be a HTTP body - if ($this->request->format) - { - $this->request->body = file_get_contents('php://input'); - } - - // If no file type is provided, this is probably just arguments - else - { - parse_str(file_get_contents('php://input'), $this->_put_args); - } - } - - /** - * Parse DELETE - */ - protected function _parse_delete() - { - // Set up out DELETE variables (which shouldn't really exist, but sssh!) - parse_str(file_get_contents('php://input'), $this->_delete_args); - } - - // INPUT FUNCTION -------------------------------------------------------------- - - /** - * Retrieve a value from the GET request arguments. - * - * @param string $key The key for the GET request argument to retrieve - * @param boolean $xss_clean Whether the value should be XSS cleaned or not. - * @return string The GET argument value. - */ - public function get($key = NULL, $xss_clean = TRUE) - { - if ($key === NULL) - { - return $this->_get_args; - } - - return array_key_exists($key, $this->_get_args) ? $this->_xss_clean($this->_get_args[$key], $xss_clean) : FALSE; - } - - /** - * Retrieve a value from the POST request arguments. - * - * @param string $key The key for the POST request argument to retrieve - * @param boolean $xss_clean Whether the value should be XSS cleaned or not. - * @return string The POST argument value. - */ - public function post($key = NULL, $xss_clean = TRUE) - { - if ($key === NULL) - { - return $this->_post_args; - } - - return array_key_exists($key, $this->_post_args) ? $this->_xss_clean($this->_post_args[$key], $xss_clean) : FALSE; - } - - /** - * Retrieve a value from the PUT request arguments. - * - * @param string $key The key for the PUT request argument to retrieve - * @param boolean $xss_clean Whether the value should be XSS cleaned or not. - * @return string The PUT argument value. - */ - public function put($key = NULL, $xss_clean = TRUE) - { - if ($key === NULL) - { - return $this->_put_args; - } - - return array_key_exists($key, $this->_put_args) ? $this->_xss_clean($this->_put_args[$key], $xss_clean) : FALSE; - } - - /** - * Retrieve a value from the DELETE request arguments. - * - * @param string $key The key for the DELETE request argument to retrieve - * @param boolean $xss_clean Whether the value should be XSS cleaned or not. - * @return string The DELETE argument value. - */ - public function delete($key = NULL, $xss_clean = TRUE) - { - if ($key === NULL) - { - return $this->_delete_args; - } - - return array_key_exists($key, $this->_delete_args) ? $this->_xss_clean($this->_delete_args[$key], $xss_clean) : FALSE; - } - - /** - * Process to protect from XSS attacks. - * - * @param string $val The input. - * @param boolean $process Do clean or note the input. - * @return string - */ - protected function _xss_clean($val, $process) - { - if (CI_VERSION < 2) - { - return $process ? $this->input->xss_clean($val) : $val; - } - - return $process ? $this->security->xss_clean($val) : $val; - } - - /** - * Retrieve the validation errors. - * - * @return array - */ - public function validation_errors() - { - $string = strip_tags($this->form_validation->error_string()); - - return explode("\n", trim($string, "\n")); - } - - // SECURITY FUNCTIONS --------------------------------------------------------- - - /** - * Perform LDAP Authentication - * - * @param string $username The username to validate - * @param string $password The password to validate - * @return boolean - */ - protected function _perform_ldap_auth($username = '', $password = NULL) - { - if (empty($username)) - { - log_message('debug', 'LDAP Auth: failure, empty username'); - return false; - } - - log_message('debug', 'LDAP Auth: Loading Config'); - - $this->config->load('ldap.php', true); - - $ldaptimeout = $this->config->item('timeout', 'ldap'); - $ldaphost = $this->config->item('server', 'ldap'); - $ldapport = $this->config->item('port', 'ldap'); - $ldaprdn = $this->config->item('binduser', 'ldap'); - $ldappass = $this->config->item('bindpw', 'ldap'); - $ldapbasedn = $this->config->item('basedn', 'ldap'); - - log_message('debug', 'LDAP Auth: Connect to ' . $ldaphost); - - $ldapconfig['authrealm'] = $this->config->item('domain', 'ldap'); - - // connect to ldap server - $ldapconn = ldap_connect($ldaphost, $ldapport); - - if ($ldapconn) { - - log_message('debug', 'Setting timeout to ' . $ldaptimeout . ' seconds'); - - ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, $ldaptimeout); - - log_message('debug', 'LDAP Auth: Binding to ' . $ldaphost . ' with dn ' . $ldaprdn); - - // binding to ldap server - $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass); - - // verify binding - if ($ldapbind) { - log_message('debug', 'LDAP Auth: bind successful'); - } else { - log_message('error', 'LDAP Auth: bind unsuccessful'); - return false; - } - - } - - // search for user - if (($res_id = ldap_search( $ldapconn, $ldapbasedn, "uid=$username")) == false) { - log_message('error', 'LDAP Auth: User ' . $username . ' not found in search'); - return false; - } - - if (ldap_count_entries($ldapconn, $res_id) != 1) { - log_message('error', 'LDAP Auth: failure, username ' . $username . 'found more than once'); - return false; - } - - if (( $entry_id = ldap_first_entry($ldapconn, $res_id))== false) { - log_message('error', 'LDAP Auth: failure, entry of searchresult could not be fetched'); - return false; - } - - if (( $user_dn = ldap_get_dn($ldapconn, $entry_id)) == false) { - log_message('error', 'LDAP Auth: failure, user-dn could not be fetched'); - return false; - } - - // User found, could not authenticate as user - if (($link_id = ldap_bind($ldapconn, $user_dn, $password)) == false) { - log_message('error', 'LDAP Auth: failure, username/password did not match: ' . $user_dn); - return false; - } - - log_message('debug', 'LDAP Auth: Success ' . $user_dn . ' authenticated successfully'); - - $this->_user_ldap_dn = $user_dn; - ldap_close($ldapconn); - return true; - } - - /** - * Check if the user is logged in. - * - * @param string $username The user's name - * @param string $password The user's password - * @return boolean - */ - protected function _check_login($username = '', $password = NULL) - { - if (empty($username)) - { - return FALSE; - } - - $auth_source = strtolower($this->config->item('auth_source')); - - if ($auth_source == 'ldap') - { - log_message('debug', 'performing LDAP authentication for $username'); - return $this->_perform_ldap_auth($username, $password); - } - - $valid_logins = & $this->config->item('rest_valid_logins'); - - if ( ! array_key_exists($username, $valid_logins)) - { - return FALSE; - } - - // If actually NULL (not empty string) then do not check it - if ($password !== NULL AND $valid_logins[$username] != $password) - { - return FALSE; - } - - return TRUE; - } - - /** - * @todo document this. - */ - protected function _prepare_basic_auth() - { - // If whitelist is enabled it has the first chance to kick them out - if (config_item('rest_ip_whitelist_enabled')) - { - $this->_check_whitelist_auth(); - } - - $username = NULL; - $password = NULL; - - // mod_php - if ($this->input->server('PHP_AUTH_USER')) - { - $username = $this->input->server('PHP_AUTH_USER'); - $password = $this->input->server('PHP_AUTH_PW'); - } - - // most other servers - elseif ($this->input->server('HTTP_AUTHENTICATION')) - { - if (strpos(strtolower($this->input->server('HTTP_AUTHENTICATION')), 'basic') === 0) - { - list($username, $password) = explode(':', base64_decode(substr($this->input->server('HTTP_AUTHORIZATION'), 6))); - } - } - - if ( ! $this->_check_login($username, $password)) - { - $this->_force_login(); - } - } - - /** - * @todo Document this. - */ - protected function _prepare_digest_auth() - { - // If whitelist is enabled it has the first chance to kick them out - if (config_item('rest_ip_whitelist_enabled')) - { - $this->_check_whitelist_auth(); - } - - $uniqid = uniqid(""); // Empty argument for backward compatibility - // We need to test which server authentication variable to use - // because the PHP ISAPI module in IIS acts different from CGI - if ($this->input->server('PHP_AUTH_DIGEST')) - { - $digest_string = $this->input->server('PHP_AUTH_DIGEST'); - } - elseif ($this->input->server('HTTP_AUTHORIZATION')) - { - $digest_string = $this->input->server('HTTP_AUTHORIZATION'); - } - else - { - $digest_string = ""; - } - - // The $_SESSION['error_prompted'] variable is used to ask the password - // again if none given or if the user enters wrong auth information. - if (empty($digest_string)) - { - $this->_force_login($uniqid); - } - - // We need to retrieve authentication informations from the $auth_data variable - preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches); - $digest = array_combine($matches[1], $matches[2]); - - if ( ! array_key_exists('username', $digest) OR !$this->_check_login($digest['username'])) - { - $this->_force_login($uniqid); - } - - $valid_logins = & $this->config->item('rest_valid_logins'); - $valid_pass = $valid_logins[$digest['username']]; - - // This is the valid response expected - $A1 = md5($digest['username'].':'.$this->config->item('rest_realm').':'.$valid_pass); - $A2 = md5(strtoupper($this->request->method).':'.$digest['uri']); - $valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2); - - if ($digest['response'] != $valid_response) - { - header('HTTP/1.0 401 Unauthorized'); - header('HTTP/1.1 401 Unauthorized'); - exit; - } - } - - /** - * Check if the client's ip is in the 'rest_ip_whitelist' config - */ - protected function _check_whitelist_auth() - { - $whitelist = explode(',', config_item('rest_ip_whitelist')); - - array_push($whitelist, '127.0.0.1', '0.0.0.0'); - - foreach ($whitelist AS &$ip) - { - $ip = trim($ip); - } - - if ( ! in_array($this->input->ip_address(), $whitelist)) - { - $this->response(array('status' => false, 'error' => 'Not authorized'), 401); - } - } - - /** - * @todo Document this. - * - * @param string $nonce - */ - protected function _force_login($nonce = '') - { - if ($this->config->item('rest_auth') == 'basic') - { - header('WWW-Authenticate: Basic realm="'.$this->config->item('rest_realm').'"'); - } - elseif ($this->config->item('rest_auth') == 'digest') - { - header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm').'", qop="auth", nonce="'.$nonce.'", opaque="'.md5($this->config->item('rest_realm')).'"'); - } - - $this->response(array('status' => false, 'error' => 'Not authorized'), 401); - } - - /** - * Force it into an array - * - * @param object|array $data - * @return array - */ - protected function _force_loopable($data) - { - // Force it to be something useful - if ( ! is_array($data) AND !is_object($data)) - { - $data = (array) $data; - } - - return $data; - } - - // FORMATING FUNCTIONS --------------------------------------------------------- - // Many of these have been moved to the Format class for better separation, but these methods will be checked too - - /** - * Encode as JSONP - * - * @param array $data The input data. - * @return string The JSONP data string (loadable from Javascript). - */ - protected function _format_jsonp($data = array()) - { - return $this->get('callback').'('.json_encode($data).')'; - } - -} diff --git a/application/libraries/index.html b/application/libraries/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/libraries/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/logs/index.html b/application/logs/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/logs/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/models/index.html b/application/models/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/models/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/third_party/index.html b/application/third_party/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/third_party/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/views/index.html b/application/views/index.html deleted file mode 100755 index c942a79c..00000000 --- a/application/views/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - -Directory access is forbidden.
- - - \ No newline at end of file diff --git a/application/views/welcome_message.php b/application/views/welcome_message.php deleted file mode 100755 index 2c8f9e29..00000000 --- a/application/views/welcome_message.php +++ /dev/null @@ -1,89 +0,0 @@ - - - - -The page you are looking at is being generated dynamically by CodeIgniter.
- -If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.
- -
Page rendered in {elapsed_time} seconds
Directory access is forbidden.
- \ No newline at end of file +