This commit is contained in:
Stefan Puraner
2016-04-11 09:11:37 +02:00
691 changed files with 64471 additions and 509 deletions
+58 -46
View File
@@ -1,6 +1,7 @@
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if (! defined('BASEPATH'))
exit('No direct script access allowed');
/**
* Database Class
@@ -15,28 +16,27 @@ class DBTools extends FHC_Controller
*
* @var string
*/
protected $_seed_path = APPPATH.'seeds/';
protected $seed_path = APPPATH.'seeds/';
/**
* Seed basename regex
*
* @var string
*/
protected $_seed_regex = '/^\d{3}_(\w+)$/';
protected $seed_regex = '/^\d{3}_(\w+)$/';
/**
* Initialize DB-Tools Class
*
* @return void
*/
function __construct()
public function __construct()
{
parent::__construct();
if ($this->input->is_cli_request())
{
$cli=true;
$cli = true;
}
else
{
@@ -45,16 +45,15 @@ class DBTools extends FHC_Controller
}
// can only be run in the development environment
if (ENVIRONMENT !== 'development') {
if (ENVIRONMENT !== 'development')
exit('Wowsers! You don\'t want to do that!');
}
$this->load->database('system'); //Use the system-Connection for DB-Manipulation
$this->load->library('migration');
// If not set, set it
//$this->_seed_path !== '' OR $this->_seed_path = APPPATH.'seeds/';
//$this->seed_path !== '' OR $this->seed_path = APPPATH.'seeds/';
// Add trailing slash if not set
//$this->_seed_path = rtrim($this->_seed_path, '/').'/';
//$this->seed_path = rtrim($this->seed_path, '/').'/';
// Load seed language
$this->lang->load('seed');
@@ -68,43 +67,51 @@ class DBTools extends FHC_Controller
log_message('info', 'DB-Tools Controller Initialized');
}
public function index()
/**
* Main function index as help
*
* @return void
*/
public function index()
{
$result = "The following are the available command line interface commands\n\n";
$result .= "php index.ci.php DBTools migrate [\"version_number\"] Run all migrations. The version number is optional.\n";
$result .= "php index.ci.php DBTools migrate [\"version_number\"] Run all migrations. ";
$result .= "The version number is optional.\n";
$result .= "php index.ci.php DBTools seed \"file_name\" Run the specified seed file.\n";
echo $result . PHP_EOL;
echo $result.PHP_EOL;
}
/**
* Migrate to latest or current version
*
* @param string $version One of either "latest" or "current"
* @param string $version [optional] One of either "latest" or "current"
* @return void
*/
public function migrate($version = 'latest')
{
if ($this->cli && $this->migration->current() === FALSE)
if ($this->cli && $this->migration->current() === false)
{
show_error($this->migration->error_string());
}
elseif ($version != 'latest' && $version != 'current')
{
$this->_failed('Migration version must be either latest or current');
$this->__failed('Migration version must be either latest or current');
}
if (!$this->migration->$version())
{
$this->_failed();
$this->__failed();
}
$this->_succeeded();
$this->__succeeded();
}
/**
* Migrate to a specific version
*
* @return void
*/
public function version()
{
@@ -116,36 +123,39 @@ class DBTools extends FHC_Controller
if (!$this->migrate->version($version))
{
$this->_failed();
$this->__failed();
}
$this->_succeeded();
$this->__succeeded();
}
/**
* Roll-back to the last version before current
*
* @param int $version The migration to rollback to, defaults to previous
* @return void
*/
public function rollback($version = null)
{
if (is_null($version))
{
$version = $this->_get_version() ?: 1;
$version = $this->__getVersion() ?: 1;
$version--;
}
// Check it's definitely false, we could be rolling back to v0
if (false === $this->migration->version($version))
{
$this->_failed();
$this->__failed();
}
$this->_succeeded('rolled back');
$this->__succeeded('rolled back');
}
/**
* ROLLBACK ALL THE THINGS!
*
* @return void
*/
public function uninstall()
{
@@ -155,17 +165,17 @@ class DBTools extends FHC_Controller
/**
* Seeds DB with Testdata
*
* @param string $name
* @param string $name Name of the seed file.
* @return bool
*/
function seed($name = null)
public function seed($name = null)
{
$seeds = $this->find_seeds();
$seeds = $this->findSeeds();
if (empty($seeds))
{
$this->_error_string = $this->lang->line('seed_none_found');
return FALSE;
return false;
}
$method = 'seed';
@@ -173,21 +183,21 @@ class DBTools extends FHC_Controller
foreach ($seeds as $number => $file)
{
include_once($file);
$class = 'Seed_'.ucfirst(strtolower($this->_get_seed_name(basename($file, '.php'))));
$class = 'Seed_'.ucfirst(strtolower($this->_getSeedName(basename($file, '.php'))));
// Validate the seed file structure
if ( ! class_exists($class, FALSE))
if (! class_exists($class, false))
{
$this->_error_string = sprintf($this->lang->line('seed_class_doesnt_exist'), $class);
return FALSE;
return false;
}
// method_exists() returns true for non-public methods,
// while is_callable() can't be used without instantiating.
// Only get_class_methods() satisfies both conditions.
elseif ( ! in_array($method, array_map('strtolower', get_class_methods($class))))
elseif (! in_array($method, array_map('strtolower', get_class_methods($class))))
{
$this->_error_string = sprintf($this->lang->line('seed_missing_'.$method.'_method'), $class);
return FALSE;
return false;
}
$pending[$number] = array($class, $method);
@@ -207,19 +217,19 @@ class DBTools extends FHC_Controller
*
* @return array list of seed file paths sorted by version
*/
public function find_seeds()
public function findSeeds()
{
$seeds = array();
// Load all *_*.php files in the seeds path
foreach (glob($this->_seed_path.'*_*.php') as $file)
foreach (glob($this->seed_path.'*_*.php') as $file)
{
$name = basename($file, '.php');
// Filter out non-seed files
if (preg_match($this->_seed_regex, $name))
if (preg_match($this->seed_regex, $name))
{
$number = $this->_get_seed_number($name);
$number = $this->_getSeedNumber($name);
// There cannot be duplicate seed numbers
if (isset($seeds[$number]))
@@ -239,10 +249,10 @@ class DBTools extends FHC_Controller
/**
* Extracts the seed number from a filename
*
* @param string $seed
* @param string $seed Filename of the seed.
* @return string Numeric portion of a seed filename
*/
protected function _get_seed_number($seed)
protected function _getSeedNumber($seed)
{
return sscanf($seed, '%[0-9]+', $number)
? $number : '0';
@@ -250,10 +260,10 @@ class DBTools extends FHC_Controller
/**
* Extracts the seed class name from a filename
*
* @param string $seed
* @param string $seed Filename of the seed.
* @return string text portion of a migration filename
*/
protected function _get_seed_name($seed)
protected function _getSeedName($seed)
{
$parts = explode('_', $seed);
array_shift($parts);
@@ -264,10 +274,11 @@ class DBTools extends FHC_Controller
* Yay, it worked! Tell the user.
*
* @param string $task What did we just do? We...
* @return void
*/
private function _succeeded($task = 'migrated')
private function __succeeded($task = 'migrated')
{
$version = $this->_get_version();
$version = $this->__getVersion();
exit('Successfully '.$task.' to version '.$version);
}
@@ -275,19 +286,20 @@ class DBTools extends FHC_Controller
* Output an error message when it all goes tits up
*
* @param string $message Error to output (default to CI's migration error)
* @return void
*/
private function _failed($message = null)
private function __failed($message = null)
{
$message = $message ?: $this->migration->error_string();
show_error($message);
}
/**
* Carbon copy of parent::_get_version, but that's protected.
* Carbon copy of parent::__getVersion, but that's protected.
*
* @return int Currently installed migration number
*/
private function _get_version()
private function __getVersion()
{
$row = $this->db->get('ci_migrations')->row();
return $row ? $row->version : 0;
+35 -37
View File
@@ -1,6 +1,7 @@
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Examples extends CI_Controller {
class Examples extends CI_Controller
{
public function __construct()
{
@@ -14,7 +15,7 @@ class Examples extends CI_Controller {
public function _example_output($output = null)
{
$this->load->view('example.php',$output);
$this->load->view('example.php', $output);
}
public function offices()
@@ -38,12 +39,11 @@ class Examples extends CI_Controller {
$crud->set_table('offices');
$crud->set_subject('Office');
$crud->required_fields('city');
$crud->columns('city','country','phone','addressLine1','postalCode');
$crud->columns('city', 'country', 'phone', 'addressLine1', 'postalCode');
$output = $crud->render();
$this->_example_output($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
@@ -55,13 +55,13 @@ class Examples extends CI_Controller {
$crud->set_theme('datatables');
$crud->set_table('employees');
$crud->set_relation('officeCode','offices','city');
$crud->display_as('officeCode','Office City');
$crud->set_relation('officeCode', 'offices', 'city');
$crud->display_as('officeCode', 'Office City');
$crud->set_subject('Employee');
$crud->required_fields('lastName');
$crud->set_field_upload('file_url','assets/uploads/files');
$crud->set_field_upload('file_url', 'assets/uploads/files');
$output = $crud->render();
@@ -73,12 +73,12 @@ class Examples extends CI_Controller {
$crud = new grocery_CRUD();
$crud->set_table('customers');
$crud->columns('customername','contactlastname','phone','city','country','salesrepemployeenumber','creditlimit');
$crud->display_as('salesrepemployeenumber','from Employeer')
->display_as('customername','Name')
->display_as('contactlastname','Last Name');
$crud->columns('customername', 'contactlastname', 'phone', 'city', 'country', 'salesrepemployeenumber', 'creditlimit');
$crud->display_as('salesrepemployeenumber', 'from Employeer')
->display_as('customername', 'Name')
->display_as('contactlastname', 'Last Name');
$crud->set_subject('Customer');
$crud->set_relation('salesrepemployeenumber','employees','lastname');
$crud->set_relation('salesrepemployeenumber', 'employees', 'lastname');
$output = $crud->render();
@@ -89,8 +89,8 @@ class Examples extends CI_Controller {
{
$crud = new grocery_CRUD();
$crud->set_relation('customerNumber','customers','{contactLastName} {contactFirstName}');
$crud->display_as('customerNumber','Customer');
$crud->set_relation('customerNumber', 'customers', '{contactLastName} {contactFirstName}');
$crud->display_as('customerNumber', 'Customer');
$crud->set_table('orders');
$crud->set_subject('Order');
$crud->unset_add();
@@ -108,7 +108,7 @@ class Examples extends CI_Controller {
$crud->set_table('products');
$crud->set_subject('Product');
$crud->unset_columns('productDescription');
$crud->callback_column('buyPrice',array($this,'valueToEuro'));
$crud->callback_column('buyPrice', array($this,'valueToEuro'));
$output = $crud->render();
@@ -125,11 +125,11 @@ class Examples extends CI_Controller {
$crud = new grocery_CRUD();
$crud->set_table('film');
$crud->set_relation_n_n('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname','priority');
$crud->set_relation_n_n('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname', 'priority');
$crud->set_relation_n_n('category', 'film_category', 'category', 'film_id', 'category_id', 'name');
$crud->unset_columns('special_features','description','actors');
$crud->unset_columns('special_features', 'description', 'actors');
$crud->fields('title', 'description', 'actors' , 'category' ,'release_year', 'rental_duration', 'rental_rate', 'length', 'replacement_cost', 'rating', 'special_features');
$crud->fields('title', 'description', 'actors', 'category', 'release_year', 'rental_duration', 'rental_rate', 'length', 'replacement_cost', 'rating', 'special_features');
$output = $crud->render();
@@ -143,15 +143,14 @@ class Examples extends CI_Controller {
$crud->set_theme('twitter-bootstrap');
$crud->set_table('film');
$crud->set_relation_n_n('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname','priority');
$crud->set_relation_n_n('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname', 'priority');
$crud->set_relation_n_n('category', 'film_category', 'category', 'film_id', 'category_id', 'name');
$crud->unset_columns('special_features','description','actors');
$crud->unset_columns('special_features', 'description', 'actors');
$crud->fields('title', 'description', 'actors' , 'category' ,'release_year', 'rental_duration', 'rental_rate', 'length', 'replacement_cost', 'rating', 'special_features');
$crud->fields('title', 'description', 'actors', 'category', 'release_year', 'rental_duration', 'rental_rate', 'length', 'replacement_cost', 'rating', 'special_features');
$output = $crud->render();
$this->_example_output($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
@@ -160,8 +159,8 @@ class Examples extends CI_Controller {
function multigrids()
{
$this->config->load('grocery_crud');
$this->config->set_item('grocery_crud_dialog_forms',true);
$this->config->set_item('grocery_crud_default_per_page',10);
$this->config->set_item('grocery_crud_dialog_forms', true);
$this->config->set_item('grocery_crud_default_per_page', 10);
$output1 = $this->offices_management2();
@@ -186,7 +185,7 @@ class Examples extends CI_Controller {
$crud->set_table('offices');
$crud->set_subject('Office');
$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)),site_url(strtolower(__CLASS__."/multigrids")));
$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)), site_url(strtolower(__CLASS__."/multigrids")));
$output = $crud->render();
@@ -203,15 +202,15 @@ class Examples extends CI_Controller {
$crud->set_theme('datatables');
$crud->set_table('employees');
$crud->set_relation('officeCode','offices','city');
$crud->display_as('officeCode','Office City');
$crud->set_relation('officeCode', 'offices', 'city');
$crud->display_as('officeCode', 'Office City');
$crud->set_subject('Employee');
$crud->required_fields('lastName');
$crud->set_field_upload('file_url','assets/uploads/files');
$crud->set_field_upload('file_url', 'assets/uploads/files');
$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)),site_url(strtolower(__CLASS__."/multigrids")));
$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)), site_url(strtolower(__CLASS__."/multigrids")));
$output = $crud->render();
@@ -227,14 +226,14 @@ class Examples extends CI_Controller {
$crud = new grocery_CRUD();
$crud->set_table('customers');
$crud->columns('customerName','contactLastName','phone','city','country','salesRepEmployeeNumber','creditLimit');
$crud->display_as('salesRepEmployeeNumber','from Employeer')
->display_as('customerName','Name')
->display_as('contactLastName','Last Name');
$crud->columns('customerName', 'contactLastName', 'phone', 'city', 'country', 'salesRepEmployeeNumber', 'creditLimit');
$crud->display_as('salesRepEmployeeNumber', 'from Employeer')
->display_as('customerName', 'Name')
->display_as('contactLastName', 'Last Name');
$crud->set_subject('Customer');
$crud->set_relation('salesRepEmployeeNumber','employees','lastName');
$crud->set_relation('salesRepEmployeeNumber', 'employees', 'lastName');
$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)),site_url(strtolower(__CLASS__."/multigrids")));
$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)), site_url(strtolower(__CLASS__."/multigrids")));
$output = $crud->render();
@@ -244,5 +243,4 @@ class Examples extends CI_Controller {
return $output;
}
}
}
-160
View File
@@ -1,160 +0,0 @@
<?php
class Migrate extends FHC_Controller
{
private $class_version = '1.0';
private $cli = false;
public function __construct()
{
parent::__construct();
if ($this->input->is_cli_request())
{
$cli=true;
}
else
{
//$this->output->set_status_header(403, 'Migrations must be run from the CLI');
//exit;
}
$this->load->database('system'); //Use the system-Connection for DB-Manipulation
$this->load->library('migration');
$this->load->library('FHC_Seed');
}
public function help() {
$result = "The following are the available command line interface commands\n\n";
$result .= "php index.ci.php db migrate [\"version_number\"] Run all migrations. The version number is optional.\n";
$result .= "php index.ci.php db seed \"file_name\" Run the specified seed file. Filename is optional.\n";
echo $result . PHP_EOL;
}
/**
* Migrate to latest or current version
*
* @param string $version One of either "latest" or "current"
*/
public function migrate($version = 'latest')
{
if ($this->cli && $this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
elseif ($version != 'latest' && $version != 'current')
{
$this->_failed('Migration version must be either latest or current');
}
if (!$this->migration->version())
{
$this->_failed();
}
$this->_succeeded();
}
/**
* Migrate to a specific version
*/
public function version()
{
if ($version == 'latest' || $version == 'current')
{
$this->index($version);
exit;
}
if (!$this->migrate->version($version))
{
$this->_failed();
}
$this->_succeeded();
}
/**
* Roll-back to the last version before current
*
* @param int $version The migration to rollback to, defaults to previous
*/
public function rollback($version = null)
{
if (is_null($version))
{
$version = $this->_get_version() ?: 1;
$version--;
}
// Check it's definitely false, we could be rolling back to v0
if (false === $this->migration->version($version))
{
$this->_failed();
}
$this->_succeeded('rolled back');
}
/**
* ROLLBACK ALL THE THINGS!
*/
public function uninstall()
{
$this->rollback(0);
}
/**
* Seed DB with TestData
*
* @param string $name Name of the SeedFile
*/
public function seed($name = null)
{
$this->fhc_seed->seed($name);
}
/**
* Yay, it worked! Tell the user.
*
* @param string $task What did we just do? We...
*/
private function _succeeded($task = 'migrated')
{
$version = $this->_get_version();
exit('Successfully '.$task.' to version '.$version);
}
/**
* Output an error message when it all goes tits up
*
* @param string $message Error to output (default to CI's migration error)
*/
private function _failed($message = null)
{
$message = $message ?: $this->migration->error_string();
show_error($message);
}
/**
* Carbon copy of parent::_get_version, but that's protected.
*
* @return int Currently installed migration number
*/
private function _get_version()
{
$row = $this->db->get('ci_migrations')->row();
return $row ? $row->version : 0;
}
public function about()
{
echo "CI-Migrate_CLI v".$this->class_version;
echo "\nCheck http://github.com/dshoreman/ci-migrate_cli/ for updates";
exit;
}
}
+12 -7
View File
@@ -21,20 +21,25 @@
* @return some value on success.
*/
defined('BASEPATH') OR exit('No direct script access allowed');
defined('BASEPATH') || exit('No direct script access allowed');
/**
/**
* @class Rest_server
* @brief Rest Server Controller
*
* A more detailed class description.
*/
class Rest_server extends MY_Controller {
public function index()
*/
class Rest_server extends FHC_Controller
{
/**
* Index Method for default function.
*
* @return void
*
*/
public function index()
{
$this->load->helper('url');
$this->load->view('rest_server');
}
}
+12 -5
View File
@@ -1,7 +1,8 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
defined('BASEPATH') || exit('No direct script access allowed');
class Vilesci extends CI_Controller {
class Vilesci extends CI_Controller
{
/**
* Index Page for this controller.
@@ -17,10 +18,12 @@ class Vilesci extends CI_Controller {
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
* @return void
*/
public function index()
{
if (false)//$this->dbupdate())
// ToDo: check if update is needed
if (false && $this->dbupdate())
echo 'System-DB needs update!';
else
{
@@ -30,11 +33,15 @@ class Vilesci extends CI_Controller {
}
}
private function dbupdate()
/**
*
* @return bool
*/
private function __dbupdate()
{
// Check for update (codeigniter migration)
$this->load->library('migration');
if ($this->migration->current() === FALSE)
if ($this->migration->current() === false)
show_error($this->migration->error_string());
if ($this->migration->current() != $this->migration->latest())
return true;
@@ -14,22 +14,23 @@
// ------------------------------------------------------------------------
defined('BASEPATH') OR exit('No direct script access allowed');
if (! defined('BASEPATH'))
exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';
//require APPPATH . '/libraries/REST_Controller.php';
/**
* Handles user authentication and registration process
*/
class AuthAPI extends REST_Controller {
class AuthAPI extends APIv1_Controller
{
/**
* Userauth-Controller constructor.
* A more elaborate description of the constructor.
* {@inheritdoc}
*/
function __construct()
public function __construct()
{
// Construct the parent class
parent::__construct();
@@ -39,16 +40,18 @@ class AuthAPI extends REST_Controller {
$this->methods['login_get']['limit'] = 500; // 500 requests per hour per user/key
// Load helper
$this->load->helper('fhcauth');
//$this->load->helper('fhcauth');
$this->load->library('session');
$this->load->library('FHC_Auth');
}
/**
* Checks user credentials and creates a new session
* @return string JSON that indicates success/failure of login
*
* @example normal account: http://wsp.fortyseeds.at/backend/api/userauth/login/username/foo%40bar.at/password/secret/device_id/abcdef123
* @example OAuth Google: http://wsp.fortyseeds.at/backend/api/userauth/login/username/foo%40bar.at/device_id/abcdef123/google_token/qwert321
* @example OAuth Facebook: http://wsp.fortyseeds.at/backend/api/userauth/login/username/foo%40bar.at/device_id/abcdef123/fb_token/qwert321
* @return void JSON that indicates success/failure of login.
*/
public function login_get()
{
@@ -57,8 +60,8 @@ class AuthAPI extends REST_Controller {
$httpstatus = null;
$username = urldecode($this->get('username'));
$password = urldecode($this->get('password'));
$account = auth($username,$password);
$account = $this->FHCAuth->auth($username, $password);
// perform login checks
if (!$account)
@@ -92,8 +95,9 @@ class AuthAPI extends REST_Controller {
/**
* Logs out user by destroying session
* @return string JSON that indicates success/failure of logout
*
* @example http://wsp.fortyseeds.at/backend/api/userauth/logout/username/foo%40bar.at/session_id/55afab8ba6f1b/device_id/abcdef123
* @return void JSON that indicates success/failure of logout
*/
public function logout_get()
{
@@ -125,6 +129,4 @@ class AuthAPI extends REST_Controller {
// Set the response and exit
$this->response($payload, $httpstatus);
}
}
@@ -1,9 +1,10 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (! defined('BASEPATH'))
exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';
require APPPATH.'/libraries/REST_Controller.php';
/**
* Keys Controller
@@ -16,8 +17,8 @@ require APPPATH . '/libraries/REST_Controller.php';
* @license MIT
* @link https://github.com/chriskacerguis/codeigniter-restserver
*/
class Key extends REST_Controller {
class APIKey extends REST_Controller
{
protected $methods = [
'index_put' => ['level' => 10, 'limit' => 10],
'index_delete' => ['level' => 10],
@@ -34,24 +35,24 @@ class Key extends REST_Controller {
public function index_put()
{
// Build a new key
$key = $this->_generate_key();
$key = $this->__generateKey();
// 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;
$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,
'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
}
@@ -72,7 +73,7 @@ class Key extends REST_Controller {
{
// 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
}
@@ -82,7 +83,7 @@ class Key extends REST_Controller {
// 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
}
@@ -103,7 +104,7 @@ class Key extends REST_Controller {
{
// 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
}
@@ -112,14 +113,14 @@ class Key extends REST_Controller {
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
}
@@ -140,7 +141,7 @@ class Key extends REST_Controller {
{
// 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
}
@@ -149,14 +150,14 @@ class Key extends REST_Controller {
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
}
@@ -171,20 +172,20 @@ class Key extends REST_Controller {
public function regenerate_post()
{
$old_key = $this->post('key');
$key_details = $this->_get_key($old_key);
$key_details = $this->__getKey($old_key);
// Does this key exist?
if (!$key_details)
{
// 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
}
// Build a new key
$new_key = $this->_generate_key();
$new_key = $this->__generateKey();
// Insert the new key
if ($this->_insert_key($new_key, ['level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits]))
@@ -193,14 +194,14 @@ class Key extends REST_Controller {
$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
}
@@ -208,7 +209,13 @@ class Key extends REST_Controller {
/* Helper Methods */
private function _generate_key()
/**
* Generate a key
*
* @access private
* @return void
*/
private function __generateKey()
{
do
{
@@ -216,9 +223,9 @@ class Key extends REST_Controller {
$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());
$salt = hash('sha256', time().mt_rand());
}
$new_key = substr($salt, 0, config_item('rest_key_length'));
@@ -230,7 +237,14 @@ class Key extends REST_Controller {
/* Private Data Methods */
private function _get_key($key)
/**
* Get a key
*
* @access private
* @param string $key The API-Key.
* @return array
*/
private function __getKey($key)
{
return $this->db
->where(config_item('rest_key_column'), $key)
@@ -238,6 +252,13 @@ class Key extends REST_Controller {
->row();
}
/**
* Check if key exists
*
* @access private
* @param string $key The API-Key.
* @return bool
*/
private function _key_exists($key)
{
return $this->db
@@ -245,6 +266,14 @@ class Key extends REST_Controller {
->count_all_results(config_item('rest_keys_table')) > 0;
}
/**
* Insert a key
*
* @access private
* @param string $key The API-Key.
* @param array $data The API-Key-Data.
* @return bool
*/
private function _insert_key($key, $data)
{
$data[config_item('rest_key_column')] = $key;
@@ -255,6 +284,14 @@ class Key extends REST_Controller {
->insert(config_item('rest_keys_table'));
}
/**
* Update a key
*
* @access private
* @param string $key The API-Key.
* @param array $data The API-Key-Data.
* @return bool
*/
private function _update_key($key, $data)
{
return $this->db
@@ -262,6 +299,13 @@ class Key extends REST_Controller {
->update(config_item('rest_keys_table'), $data);
}
/**
* Delete a key
*
* @access private
* @param string $key The API-Key.
* @return bool
*/
private function _delete_key($key)
{
return $this->db
+29 -19
View File
@@ -11,17 +11,18 @@
* @license MIT
* @link https://github.com/chriskacerguis/codeigniter-restserver
*/
defined('BASEPATH') OR exit('No direct script access allowed');
if (! defined('BASEPATH'))
exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';
require APPPATH.'/libraries/REST_Controller.php';
class Example extends REST_Controller {
/**
* @copydoc REST_Controller::__construct()
*/
function __construct()
class Example extends REST_Controller
{
/**
* @copydoc REST_Controller::__construct()
*/
public function __construct()
{
// Construct the parent class
parent::__construct();
@@ -33,6 +34,9 @@ class Example extends REST_Controller {
$this->methods['user_delete']['limit'] = 50; // 50 requests per hour per user/key
}
/**
* @return void
*/
public function users_get()
{
// Users from a data store e.g. database
@@ -46,9 +50,9 @@ class Example extends REST_Controller {
// 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)
// Check if the users data store contains users (in case the database result returns null)
if ($users)
{
// Set the response and exit
@@ -58,7 +62,7 @@ class Example extends REST_Controller {
{
// 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
}
@@ -66,19 +70,19 @@ class Example extends REST_Controller {
// Find and return a single record for a particular user.
$id = (int) $id;
$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
$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.
// Usually a model is to be used for this.
$user = NULL;
$user = null;
if (!empty($users))
{
@@ -98,12 +102,15 @@ class Example extends REST_Controller {
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
}
}
/**
* @return void
*/
public function users_post()
{
// $this->some_model->update_user( ... );
@@ -117,15 +124,18 @@ class Example extends REST_Controller {
$this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
/**
* @return void
*/
public function users_delete()
{
$id = (int) $this->get('id');
$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->response(null, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// $this->some_model->delete_something($id);
@@ -134,7 +144,7 @@ class Example extends REST_Controller {
'message' => 'Deleted the resource'
];
$this->set_response($message, REST_Controller::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
// NO_CONTENT (204) being the HTTP response code
$this->set_response($message, REST_Controller::HTTP_NO_CONTENT);
}
}
@@ -0,0 +1,188 @@
<?php
/**
* FH-Complete
*
* @package FHC-API
* @author FHC-Team
* @copyright Copyright (c) 2016, fhcomplete.org
* @license GPLv3
* @link http://fhcomplete.org
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
if (! defined('BASEPATH'))
exit('No direct script access allowed');
class Person extends APIv1_Controller
{
/**
* Person API constructor.
*/
public function __construct()
{
parent::__construct();
$this->load->model('person/person_model');
}
/**
* @return void
*/
public function person_get()
{
//if(!$this->session_model->validate($this->get('session_id'), $this->get('device_id')))
// $this->response(array(['success' => false, 'message' => 'access denied']), REST_Controller::HTTP_UNAUTHORIZED);
$code = $this->get('code');
$person_id = $this->get('person_id');
if (! is_null($code))
{
$result = $this->person_model->getPersonByCode($code);
}
elseif (! is_null($person_id))
{
$result = $this->person_model->getPerson($person_id);
}
else
{
$result = $this->person_model->getPerson();
}
if ($result['err'])
{
$payload = [
'success' => false,
'message' => $result['msg'].': '.$result['retval']
];
$httpstatus = REST_Controller::HTTP_OK;
}
else
{
// return all available persons
$payload = [
'success' => true,
'message' => 'Persons found'
];
$payload['data'] = $result;
$httpstatus = REST_Controller::HTTP_OK;
}
if (empty($result))
{
$payload = [
'success' => false,
'message' => 'Person not found'
];
$httpstatus = REST_Controller::HTTP_OK;
}
else
{
// return all available persons
$payload = [
'success' => true,
'message' => 'Persons found'
];
$payload['data'] = $result;
$httpstatus = REST_Controller::HTTP_OK;
}
// Set the response and exit
$this->response($payload, $httpstatus);
}
/**
* @return void
*/
public function person_post()
{
$result = $this->person_model->savePerson($this->post());
if ($result != false)
{
$httpstatus = REST_Controller::HTTP_OK;
$payload = [
'success' => true,
'message' => 'Person saved.'
];
$payload['data'] = $result;
}
else
{
$payload = [
'success' => false,
'message' => 'Could not save person.'
];
$httpstatus = REST_Controller::HTTP_OK;
}
$this->response($payload, $httpstatus);
}
/**
* @return void
*/
public function personUpdate_post()
{
$result = $this->person_model->updatePerson($this->post());
if ($result != false)
{
$httpstatus = REST_Controller::HTTP_OK;
$payload = [
'success' => true,
'message' => 'Person updated.'
];
$payload['data'] = $result;
}
else
{
$payload = [
'success' => false,
'message' => 'Could not update person.'
];
$httpstatus = REST_Controller::HTTP_OK;
}
$this->response($payload, $httpstatus);
}
/**
* @return void
*/
public function checkBewerbung_get()
{
$result = $this->person_model->checkBewerbung($this->get("email"), $this->get("studiensemester_kurzbz"));
$httpstatus = REST_Controller::HTTP_OK;
$payload = [
'success' => true,
'message' => 'Bewerbung exists.'
];
$payload['data'] = $result;
$this->response($payload, $httpstatus);
}
/**
* @return void
*/
public function checkZugangscodePerson_get()
{
$result = $this->person_model->checkZugangscodePerson($this->get("code"));
$httpstatus = REST_Controller::HTTP_OK;
if (!empty($result))
{
$payload = [
'success' => true,
'message' => 'Zugangscode exists.'
];
$payload['data'] = $result;
}
else
{
$payload = [
'success' => false,
'message' => 'Zugangscode does not exist.'
];
$httpstatus = REST_Controller::HTTP_OK;
}
$this->response($payload, $httpstatus);
}
}