diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d712a143..fe2a855d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -119,7 +119,7 @@
- **[DEPRECATED]** Spalte ort_kurzbz in tbl_reihungstest wird nicht mehr verwendet und in zukünftigen Versionen entfernt
Zum Update auf diese Version folgen Sie den Anweisungen auf folgender Seite:
-http://fhcomplete.technikum-wien.at/dokuwiki/doku.php?id=fh-complete:codeigniter
+https://wiki.fhcomplete.org/doku.php?id=fh-complete:codeigniter
## [3.1.0] - 2015-11-12
### Added
diff --git a/README.md b/README.md
index c4b24c64d..d5620010a 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,5 @@
# FH-Complete
-* [FH-Complete Homepage](http://www.fhcomplete.org)
-* [Wiki](http://fhcomplete.technikum-wien.at/dokuwiki/)
+* [FH-Complete Homepage](https://www.fhcomplete.org)
+* [Wiki](https://wiki.fhcomplete.org/)
* [Changelog](CHANGELOG.md)
diff --git a/application/config/config.php b/application/config/config.php
index 1c0993c92..591b84f2c 100644
--- a/application/config/config.php
+++ b/application/config/config.php
@@ -503,3 +503,15 @@ $config['rewrite_short_tags'] = FALSE;
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
+
+/*
+|--------------------------------------------------------------------------
+| FHComplete Build Version
+|--------------------------------------------------------------------------
+|
+| Version Number of the Current Build
+| This is used to invalidate Cache for JS and CSS Files
+|
+| Example: 2019102901
+*/
+$config['fhcomplete_build_version'] = '2019102903';
diff --git a/application/config/navigation.php b/application/config/navigation.php
index 839859686..d8ec2ae75 100644
--- a/application/config/navigation.php
+++ b/application/config/navigation.php
@@ -92,6 +92,13 @@ $config['navigation_header'] = array(
'expand' => true,
'sort' => 10,
'requiredPermissions' => 'admin:r'
+ ),
+ 'logsviewer' => array(
+ 'link' => site_url('system/LogsViewer'),
+ 'description' => 'Logs',
+ 'expand' => true,
+ 'sort' => 20,
+ 'requiredPermissions' => 'system/developer:r'
)
)
)
diff --git a/application/config/rest.php b/application/config/rest.php
index 9bbbf40ef..833a99881 100644
--- a/application/config/rest.php
+++ b/application/config/rest.php
@@ -1,6 +1,6 @@
'1234', 'test' => 'test'];
-
-/*
-|--------------------------------------------------------------------------
-| Global IP Whitelisting
-|--------------------------------------------------------------------------
-|
-| Limit connections to your REST server to whitelisted IP addresses
+| Limit connections to your REST server to White-listed IP addresses
|
| Usage:
| 1. Set to TRUE and select an auth option for extreme security (client's IP
-| address must be in whitelist and they must also log in)
-| 2. Set to TRUE with auth set to FALSE to allow whitelisted IPs access with no login
-| 3. Set to FALSE but set 'auth_override_class_method' to 'whitelist' to
-| restrict certain methods to IPs in your whitelist
+| address must be in white-list and they must also log in)
+| 2. Set to TRUE with auth set to FALSE to allow White-listed IPs access with no login
+| 3. Set to FALSE but set 'auth_override_class_method' to 'white-list' to
+| restrict certain methods to IPs in your white-list
|
*/
$config['rest_ip_whitelist_enabled'] = TRUE;
/*
|--------------------------------------------------------------------------
-| REST IP Whitelist
+| REST IP White-list
|--------------------------------------------------------------------------
|
| Limit connections to your REST server with a comma separated
@@ -240,42 +107,6 @@ $config['rest_ip_whitelist_enabled'] = TRUE;
*/
$config['rest_ip_whitelist'] = '127.0.0.1';
-/*
-|--------------------------------------------------------------------------
-| Global IP Blacklisting
-|--------------------------------------------------------------------------
-|
-| Prevent connections to the REST server from blacklisted IP addresses
-|
-| Usage:
-| 1. Set to TRUE and add any IP address to 'rest_ip_blacklist'
-|
-*/
-$config['rest_ip_blacklist_enabled'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST IP Blacklist
-|--------------------------------------------------------------------------
-|
-| Prevent connections from the following IP addresses
-|
-| e.g: '123.456.789.0, 987.654.32.1'
-|
-*/
-$config['rest_ip_blacklist'] = '';
-
-/*
-|--------------------------------------------------------------------------
-| REST Database Group
-|--------------------------------------------------------------------------
-|
-| Connect to a database group for keys, logging, etc. It will only connect
-| if you have any of these features enabled
-|
-*/
-$config['rest_database_group'] = 'default';
-
/*
|--------------------------------------------------------------------------
| REST API Keys Table Name
@@ -298,6 +129,7 @@ $config['rest_keys_table'] = 'ci_apikey';
| Default table schema:
| CREATE TABLE `keys` (
| `id` INT(11) NOT NULL AUTO_INCREMENT,
+| `user_id` INT(11) NOT NULL,
| `key` VARCHAR(40) NOT NULL,
| `level` INT(2) NOT NULL,
| `ignore_limits` TINYINT(1) NOT NULL DEFAULT '0',
@@ -310,45 +142,6 @@ $config['rest_keys_table'] = 'ci_apikey';
*/
$config['rest_enable_keys'] = TRUE;
-/*
-|--------------------------------------------------------------------------
-| REST Table Key Column Name
-|--------------------------------------------------------------------------
-|
-| If not using the default table schema in 'rest_enable_keys', specify the
-| column name to match e.g. my_key
-|
-*/
-$config['rest_key_column'] = 'key';
-
-/*
-|--------------------------------------------------------------------------
-| REST API Limits method
-|--------------------------------------------------------------------------
-|
-| Specify the method used to limit the API calls
-|
-| Available methods are :
-| $config['rest_limits_method'] = 'API_KEY'; // Put a limit per api key
-| $config['rest_limits_method'] = 'METHOD_NAME'; // Put a limit on method calls
-| $config['rest_limits_method'] = 'ROUTED_URL'; // Put a limit on the routed URL
-|
-*/
-$config['rest_limits_method'] = 'ROUTED_URL';
-
-/*
-|--------------------------------------------------------------------------
-| REST Key Length
-|--------------------------------------------------------------------------
-|
-| Length of the created keys. Check your default database schema on the
-| maximum length allowed
-|
-| Note: The maximum length is 40
-|
-*/
-$config['rest_key_length'] = 40;
-
/*
|--------------------------------------------------------------------------
| REST API Key Variable
@@ -364,156 +157,10 @@ $config['rest_key_name'] = 'FHC-API-KEY';
/*
|--------------------------------------------------------------------------
-| REST Enable Logging
+| REST Methods name format
|--------------------------------------------------------------------------
|
-| When set to TRUE, the REST API will log actions based on the column names 'key', 'date',
-| 'time' and 'ip_address'. This is a general rule that can be overridden in the
-| $this->method array for each controller
-|
-| Default table schema:
-| CREATE TABLE `logs` (
-| `id` INT(11) NOT NULL AUTO_INCREMENT,
-| `uri` VARCHAR(255) NOT NULL,
-| `method` VARCHAR(6) NOT NULL,
-| `params` TEXT DEFAULT NULL,
-| `api_key` VARCHAR(40) NOT NULL,
-| `ip_address` VARCHAR(45) NOT NULL,
-| `time` INT(11) NOT NULL,
-| `rtime` FLOAT DEFAULT NULL,
-| `authorized` VARCHAR(1) NOT NULL,
-| `response_code` smallint(3) DEFAULT '0',
-| PRIMARY KEY (`id`)
-| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+| REST Controllers methods name format
|
*/
-$config['rest_enable_logging'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST API Logs Table Name
-|--------------------------------------------------------------------------
-|
-| If not using the default table schema in 'rest_enable_logging', specify the
-| table name to match e.g. my_logs
-|
-*/
-$config['rest_logs_table'] = 'logs';
-
-/*
-|--------------------------------------------------------------------------
-| REST Method Access Control
-|--------------------------------------------------------------------------
-| When set to TRUE, the REST API will check the access table to see if
-| the API key can access that controller. 'rest_enable_keys' must be enabled
-| to use this
-|
-| Default table schema:
-| CREATE TABLE `access` (
-| `id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
-| `key` VARCHAR(40) NOT NULL DEFAULT '',
-| `controller` VARCHAR(50) NOT NULL DEFAULT '',
-| `date_created` DATETIME DEFAULT NULL,
-| `date_modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-| PRIMARY KEY (`id`)
-| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-|
-*/
-$config['rest_enable_access'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST API Access Table Name
-|--------------------------------------------------------------------------
-|
-| If not using the default table schema in 'rest_enable_access', specify the
-| table name to match e.g. my_access
-|
-*/
-$config['rest_access_table'] = 'access';
-
-/*
-|--------------------------------------------------------------------------
-| REST API Param Log Format
-|--------------------------------------------------------------------------
-|
-| When set to TRUE, the REST API log parameters will be stored in the database as JSON
-| Set to FALSE to log as serialized PHP
-|
-*/
-$config['rest_logs_json_params'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST Enable Limits
-|--------------------------------------------------------------------------
-|
-| When set to TRUE, the REST API will count the number of uses of each method
-| by an API key each hour. This is a general rule that can be overridden in the
-| $this->method array in each controller
-|
-| Default table schema:
-| CREATE TABLE `limits` (
-| `id` INT(11) NOT NULL AUTO_INCREMENT,
-| `uri` VARCHAR(255) NOT NULL,
-| `count` INT(10) NOT NULL,
-| `hour_started` INT(11) NOT NULL,
-| `api_key` VARCHAR(40) NOT NULL,
-| PRIMARY KEY (`id`)
-| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-|
-| To specify the limits within the controller's __construct() method, add per-method
-| limits with:
-|
-| $this->method['METHOD_NAME']['limit'] = [NUM_REQUESTS_PER_HOUR];
-|
-| See application/controllers/api/example.php for examples
-*/
-$config['rest_enable_limits'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST API Limits Table Name
-|--------------------------------------------------------------------------
-|
-| If not using the default table schema in 'rest_enable_limits', specify the
-| table name to match e.g. my_limits
-|
-*/
-$config['rest_limits_table'] = 'limits';
-
-/*
-|--------------------------------------------------------------------------
-| REST Ignore HTTP Accept
-|--------------------------------------------------------------------------
-|
-| Set to TRUE to ignore the HTTP Accept and speed up each request a little.
-| Only do this if you are using the $this->rest_format or /format/xml in URLs
-|
-*/
-$config['rest_ignore_http_accept'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST AJAX Only
-|--------------------------------------------------------------------------
-|
-| Set to TRUE to allow AJAX requests only. Set to FALSE to accept HTTP requests
-|
-| Note: If set to TRUE and the request is not AJAX, a 505 response with the
-| error message 'Only AJAX requests are accepted.' will be returned.
-|
-| Hint: This is good for production environments
-|
-*/
-$config['rest_ajax_only'] = FALSE;
-
-/*
-|--------------------------------------------------------------------------
-| REST Language File
-|--------------------------------------------------------------------------
-|
-| Language file to load from the language directory
-|
-*/
-$config['rest_language'] = 'english';
+$config['rest_methods_name_format'] = '%2$s%1$s';
diff --git a/application/config/routes.php b/application/config/routes.php
index 791b6d03c..36bfdcb1e 100644
--- a/application/config/routes.php
+++ b/application/config/routes.php
@@ -1,5 +1,6 @@
my_controller/index
-| my-controller/my-method -> my_controller/my_method
+| Examples: my-controller/index -> my_controller/index
+| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'Vilesci';
-$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
// Class name conflicts
@@ -59,4 +59,4 @@ $route['api/v1/organisation/[F|f]achbereich/(:any)'] = 'api/v1/organisation/fach
$route['api/v1/organisation/[G|g]eschaeftsjahr/(:any)'] = 'api/v1/organisation/geschaeftsjahr2/$1';
$route['api/v1/organisation/[O|o]rganisationseinheit/(:any)'] = 'api/v1/organisation/organisationseinheit2/$1';
$route['api/v1/ressource/[B|b]etriebsmittelperson/(:any)'] = 'api/v1/ressource/betriebsmittelperson2/$1';
-$route['api/v1/system/[S|s]prache/(:any)'] = 'api/v1/system/sprache2/$1';
\ No newline at end of file
+$route['api/v1/system/[S|s]prache/(:any)'] = 'api/v1/system/sprache2/$1';
diff --git a/application/controllers/api/v1/CheckUserAuth.php b/application/controllers/api/v1/CheckUserAuth.php
index 4d6522fe2..ee751e886 100644
--- a/application/controllers/api/v1/CheckUserAuth.php
+++ b/application/controllers/api/v1/CheckUserAuth.php
@@ -2,7 +2,7 @@
if (!defined('BASEPATH')) exit('No direct script access allowed');
-class CheckUserAuth extends REST_Controller
+class CheckUserAuth extends RESTFul_Controller
{
/**
* Course API constructor.
diff --git a/application/controllers/api/v1/Test.php b/application/controllers/api/v1/Test.php
index 41feb1a16..c9918f52b 100644
--- a/application/controllers/api/v1/Test.php
+++ b/application/controllers/api/v1/Test.php
@@ -5,7 +5,7 @@ if (! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Testing class for REST calls and authentication
*/
-class Test extends REST_Controller
+class Test extends RESTFul_Controller
{
public function __construct()
{
diff --git a/application/controllers/api/v1/person/Benutzer.php b/application/controllers/api/v1/person/Benutzer.php
index 23fcdadac..f1ea4f149 100644
--- a/application/controllers/api/v1/person/Benutzer.php
+++ b/application/controllers/api/v1/person/Benutzer.php
@@ -37,7 +37,7 @@ class Benutzer extends APIv1_Controller
if (isset($uid))
{
- $result = $this->BenutzerModel->load($uid);
+ $result = $this->BenutzerModel->load(array('uid' => $uid));
$this->response($result, REST_Controller::HTTP_OK);
}
diff --git a/application/controllers/api/v1/system/CallerLibrary.php b/application/controllers/api/v1/system/CallerLibrary.php
deleted file mode 100644
index 594786384..000000000
--- a/application/controllers/api/v1/system/CallerLibrary.php
+++ /dev/null
@@ -1,77 +0,0 @@
- 'admin:rw'));
-
- // Loads the CallerLib
- $this->load->library('CallerLib');
- }
-
- /**
- * Manages a HTTP get call
- */
- public function getCall()
- {
- // Start me up!
- $result = $this->callerlib->callLibrary($this->get());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-
- /**
- * @return void
- */
- public function postCall()
- {
- // Start me up!
- $result = $this->callerlib->callLibrary($this->post());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-
- /**
- * @return void
- */
- public function putCall()
- {
- // Start me up!
- $result = $this->callerlib->callLibrary($this->put());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-
- /**
- * @return void
- */
- public function deleteCall()
- {
- // Start me up!
- $result = $this->callerlib->callLibrary($this->delete());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-}
diff --git a/application/controllers/api/v1/system/CallerModel.php b/application/controllers/api/v1/system/CallerModel.php
deleted file mode 100644
index 68296aff8..000000000
--- a/application/controllers/api/v1/system/CallerModel.php
+++ /dev/null
@@ -1,77 +0,0 @@
- 'admin:rw'));
-
- // Loads the CallerLib
- $this->load->library('CallerLib');
- }
-
- /**
- * Manages a HTTP get call
- */
- public function getCall()
- {
- // Start me up!
- $result = $this->callerlib->callModel($this->get());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-
- /**
- * @return void
- */
- public function postCall()
- {
- // Start me up!
- $result = $this->callerlib->callModel($this->post());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-
- /**
- * @return void
- */
- public function putCall()
- {
- // Start me up!
- $result = $this->callerlib->callModel($this->put());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-
- /**
- * @return void
- */
- public function deleteCall()
- {
- // Start me up!
- $result = $this->callerlib->callModel($this->delete());
-
- // Print the result
- $this->response($result, REST_Controller::HTTP_OK);
- }
-}
diff --git a/application/controllers/jobs/Prestudentstatus.php b/application/controllers/jobs/Prestudentstatus.php
index 27cafeb0e..e5b015753 100644
--- a/application/controllers/jobs/Prestudentstatus.php
+++ b/application/controllers/jobs/Prestudentstatus.php
@@ -37,7 +37,8 @@ class Prestudentstatus extends CLI_Controller
tbl_prestudent.studiengang_kz,
tbl_prestudentstatus.studienplan_id,
tbl_studienplan.orgform_kurzbz,
- tbl_prestudent.person_id');
+ tbl_prestudent.person_id,
+ tbl_studienplan.sprache');
$this->PrestudentstatusModel->addJoin('public.tbl_prestudent', 'prestudent_id');
$this->PrestudentstatusModel->addJoin('lehre.tbl_studienplan', 'studienplan_id','LEFT');
$this->PrestudentstatusModel->addJoin('lehre.tbl_studienordnung', 'studienordnung_id','LEFT');
@@ -64,7 +65,8 @@ class Prestudentstatus extends CLI_Controller
$row_status->studiengang_kz,
$row_status->studiensemester_kurzbz,
$row_status->ausbildungssemester,
- $row_status->orgform_kurzbz);
+ $row_status->orgform_kurzbz,
+ $row_status->sprache);
if(isSuccess($studienplan) && count($studienplan->retval) == 1)
{
diff --git a/application/controllers/system/UDF.php b/application/controllers/system/FAS_UDF.php
similarity index 66%
rename from application/controllers/system/UDF.php
rename to application/controllers/system/FAS_UDF.php
index dafa3f8f7..cd78d64d2 100644
--- a/application/controllers/system/UDF.php
+++ b/application/controllers/system/FAS_UDF.php
@@ -2,8 +2,10 @@
if (! defined('BASEPATH')) exit('No direct script access allowed');
-class UDF extends Auth_Controller
+class FAS_UDF extends Auth_Controller
{
+ const FAS_UDF_SESSION_NAME = 'fasUdfSessionName';
+
public function __construct()
{
parent::__construct(
@@ -22,31 +24,33 @@ class UDF extends Auth_Controller
*/
public function index()
{
+ $fasUdfSession = getSession(self::FAS_UDF_SESSION_NAME);
+
$person_id = $this->input->get('person_id');
- if (isset($this->session->person_id))
+ if (isset($fasUdfSession['person_id']))
{
if (!isset($person_id))
{
- $person_id = $this->session->person_id;
+ $person_id = $fasUdfSession['person_id'];
}
- unset($this->session->person_id);
+ unset($fasUdfSession['person_id']);
}
$prestudent_id = $this->input->get('prestudent_id');
- if (isset($this->session->prestudent_id))
+ if (isset($fasUdfSession['prestudent_id']))
{
if (!isset($prestudent_id))
{
- $prestudent_id = $this->session->prestudent_id;
+ $prestudent_id = $fasUdfSession['prestudent_id'];
}
- unset($this->session->prestudent_id);
+ unset($fasUdfSession['prestudent_id']);
}
$result = null;
- if (isset($this->session->result))
+ if (isset($fasUdfSession['result']))
{
- $result = clone $this->session->result;
- $this->session->set_userdata('result', null);
+ $result = clone $fasUdfSession['result'];
+ setSessionElement(self::FAS_UDF_SESSION_NAME, 'result', null);
}
$data = array('result' => $result);
@@ -71,7 +75,7 @@ class UDF extends Auth_Controller
}
}
- $this->load->view('system/udf', $data);
+ $this->load->view('system/fas_udf', $data);
}
/**
@@ -90,9 +94,9 @@ class UDF extends Auth_Controller
if (isSuccess($validation))
{
// Load model UDF_model
- $this->load->model('system/UDF_model', 'UDFModel');
+ $this->load->model('system/FAS_UDF_model', 'FASUDFModel');
- $result = $this->UDFModel->saveUDFs($udfs);
+ $result = $this->FASUDFModel->saveUDFs($udfs);
$userdata['result'] = $result;
}
@@ -101,8 +105,11 @@ class UDF extends Auth_Controller
$userdata['result'] = $validation;
}
- $this->session->set_userdata($userdata);
- redirect('system/UDF');
+ setSessionElement(self::FAS_UDF_SESSION_NAME, 'person_id', $userdata['person_id']);
+ setSessionElement(self::FAS_UDF_SESSION_NAME, 'prestudent_id', $userdata['prestudent_id']);
+ setSessionElement(self::FAS_UDF_SESSION_NAME, 'result', $userdata['result']);
+
+ redirect('system/FAS_UDF');
}
/**
diff --git a/application/controllers/system/LogsViewer.php b/application/controllers/system/LogsViewer.php
new file mode 100644
index 000000000..8caf9f3a7
--- /dev/null
+++ b/application/controllers/system/LogsViewer.php
@@ -0,0 +1,44 @@
+ 'system/developer:r'
+ )
+ );
+
+ // Loads WidgetLib
+ $this->load->library('WidgetLib');
+
+ // Loads phrases system
+ $this->loadPhrases(
+ array(
+ 'global',
+ 'ui',
+ 'filter'
+ )
+ );
+ }
+
+ // -----------------------------------------------------------------------------------------------------------------
+ // Public methods
+
+ /**
+ * Main page of the InfoCenter tool
+ */
+ public function index()
+ {
+ $this->load->view('system/logs/logsViewer.php');
+ }
+}
diff --git a/application/controllers/system/Variables.php b/application/controllers/system/Variables.php
new file mode 100644
index 000000000..20303118b
--- /dev/null
+++ b/application/controllers/system/Variables.php
@@ -0,0 +1,78 @@
+ 'basis/variable:rw',
+ 'getVar' => 'basis/variable:rw',
+ 'changeStudiensemesterVar' => 'basis/variable:rw'
+ )
+ );
+
+ $this->load->model('system/variable_model', 'VariableModel');
+
+ $this->_setAuthUID();
+
+ $this->load->library('VariableLib', array('uid' => $this->_uid));
+ }
+
+ /**
+ * Sets a user variable based on received post parameters, outputs JSON response.
+ */
+ public function setVar()
+ {
+ $name = $this->input->post('name');
+ $wert = $this->input->post('wert');
+
+ $result = $this->VariableModel->setVariable($this->_uid, $name, $wert);
+
+ $this->outputJson($result);
+ }
+
+ /**
+ * gets a user variable based on received post parameter, outputs JSON response.
+ */
+ public function getVar()
+ {
+ $name = $this->input->get('name');
+ $this->outputJson($this->VariableModel->getVariables($this->_uid, array($name)));
+ }
+
+ /**
+ * Changes a user variable containing a Studiensemester based on received post parameters, outputs JSON response.
+ */
+ public function changeStudiensemesterVar()
+ {
+ $name = $this->input->post('name');
+ $change = $this->input->post('change');
+
+ $result = $this->variablelib->changeStudiensemesterVar($this->_uid, $name, $change);
+
+ $this->outputJson($result);
+ }
+
+ /**
+ * Retrieve the UID of the logged user and checks if it is valid
+ */
+ private function _setAuthUID()
+ {
+ $this->_uid = getAuthUID();
+
+ if (!$this->_uid) show_error('User authentification failed');
+ }
+}
diff --git a/application/controllers/system/infocenter/InfoCenter.php b/application/controllers/system/infocenter/InfoCenter.php
index d59c058cf..2f66e0e2d 100644
--- a/application/controllers/system/infocenter/InfoCenter.php
+++ b/application/controllers/system/infocenter/InfoCenter.php
@@ -24,6 +24,8 @@ class InfoCenter extends Auth_Controller
const FILTER_ID = 'filter_id';
const PREV_FILTER_ID = 'prev_filter_id';
+ const RELOAD_DATASET = 'reloadDataset';
+ const KEEP_TABLESORTER_FILTER = 'keepTsFilter';
private $_uid; // contains the UID of the logged user
@@ -100,9 +102,11 @@ class InfoCenter extends Auth_Controller
'reloadNotizen' => 'infocenter:r',
'reloadLogs' => 'infocenter:r',
'outputAkteContent' => 'infocenter:r',
- 'getParkedDate' => 'infocenter:r',
+ 'getPostponeDate' => 'infocenter:r',
'park' => 'infocenter:rw',
'unpark' => 'infocenter:rw',
+ 'setOnHold' => 'infocenter:rw',
+ 'removeOnHold' => 'infocenter:rw',
'getStudienjahrEnd' => 'infocenter:r',
'setNavigationMenuArrayJson' => 'infocenter:r'
)
@@ -136,6 +140,8 @@ class InfoCenter extends Auth_Controller
$this->_setAuthUID(); // sets property uid
+ $this->load->library('VariableLib', array('uid' => $this->_uid));
+
$this->setControllerId(); // sets the controller id
}
@@ -232,7 +238,7 @@ class InfoCenter extends Auth_Controller
$redirectLink = '/'.self::INFOCENTER_URI.'?'.self::FHC_CONTROLLER_ID.'='.$this->getControllerId();
// Force reload of Dataset after Unlock
- $redirectLink .= '&reloadDataset=true';
+ $redirectLink .= '&'.self::RELOAD_DATASET.'=true&'.self::KEEP_TABLESORTER_FILTER.'=true';
$currentFilterId = $this->input->get(self::FILTER_ID);
if (isset($currentFilterId))
@@ -709,11 +715,32 @@ class InfoCenter extends Auth_Controller
* Gets the date until which a person is parked
* @param $person_id
*/
- public function getParkedDate($person_id)
+ public function getPostponeDate($person_id)
{
+ $result = array(
+ 'type' => null,
+ 'date' => null
+ );
+
$parkedDate = $this->personloglib->getParkedDate($person_id);
- $this->outputJsonSuccess(array($parkedDate));
+ if (isset($parkedDate))
+ {
+ $result['type'] = 'parked';
+ $result['date'] = $parkedDate;
+ }
+ else
+ {
+ $onholdDate = $this->personloglib->getOnHoldDate($person_id);
+
+ if (isset($onholdDate))
+ {
+ $result['type'] = 'onhold';
+ $result['date'] = $onholdDate;
+ }
+ }
+
+ $this->outputJsonSuccess($result);
}
/**
@@ -741,6 +768,31 @@ class InfoCenter extends Auth_Controller
$this->outputJson($result);
}
+ /**
+ * Sets a person on hold ("zurückstellen")
+ */
+ public function setOnHold()
+ {
+ $person_id = $this->input->post('person_id');
+ $date = $this->input->post('onholddate');
+
+ $result = $this->personloglib->setOnHold($person_id, date_format(date_create($date), 'Y-m-d'), self::TAETIGKEIT, self::APP, null, $this->_uid);
+
+ $this->outputJson($result);
+ }
+
+ /**
+ * Removed on hold status of a person
+ */
+ public function removeOnHold()
+ {
+ $person_id = $this->input->post('person_id');
+
+ $result = $this->personloglib->removeOnHold($person_id);
+
+ $this->outputJson($result);
+ }
+
/**
* Gets the End date of the current Studienjahr
*/
@@ -892,10 +944,16 @@ class InfoCenter extends Auth_Controller
$freigegebenLink = site_url(self::INFOCENTER_URI.'/'.self::FREIGEGEBEN_PAGE);
$reihungstestAbsolviertLink = site_url(self::INFOCENTER_URI.'/'.self::REIHUNGSTESTABSOLVIERT_PAGE);
$currentFilterId = $this->input->get(self::FILTER_ID);
+ $reloadDatasetParam = self::RELOAD_DATASET.'=true';
if (isset($currentFilterId))
{
- $freigegebenLink .= '?'.self::PREV_FILTER_ID.'='.$currentFilterId;
- $reihungstestAbsolviertLink .= '?'.self::PREV_FILTER_ID.'='.$currentFilterId;
+ $freigegebenLink .= '?'.self::PREV_FILTER_ID.'='.$currentFilterId.'&'.$reloadDatasetParam;
+ $reihungstestAbsolviertLink .= '?'.self::PREV_FILTER_ID.'='.$currentFilterId.'&'.$reloadDatasetParam;
+ }
+ else
+ {
+ $freigegebenLink .= '?'.$reloadDatasetParam;
+ $reihungstestAbsolviertLink .= '?'.$reloadDatasetParam;
}
$this->navigationlib->setSessionMenu(
@@ -948,7 +1006,7 @@ class InfoCenter extends Auth_Controller
$origin_page = $this->input->get(self::ORIGIN_PAGE);
- $link = site_url(self::INFOCENTER_URI.'/'.self::INDEX_PAGE);
+ $link = site_url(self::INFOCENTER_URI);
if ($origin_page == self::FREIGEGEBEN_PAGE)
{
$link = site_url(self::INFOCENTER_URI.'/'.self::FREIGEGEBEN_PAGE);
@@ -961,7 +1019,7 @@ class InfoCenter extends Auth_Controller
$prevFilterId = $this->input->get(self::PREV_FILTER_ID);
if (isset($prevFilterId))
{
- $link .= '?'.self::FILTER_ID.'='.$prevFilterId;
+ $link .= '?'.self::FILTER_ID.'='.$prevFilterId.'&'.self::RELOAD_DATASET.'=true&'.self::KEEP_TABLESORTER_FILTER.'=true';
}
$this->navigationlib->setSessionMenu(
@@ -991,13 +1049,14 @@ class InfoCenter extends Auth_Controller
$this->load->library('NavigationLib', array(self::NAVIGATION_PAGE => self::INFOCENTER_URI.'/'.$page));
// Generate the home link with the eventually loaded filter
- $homeLink = site_url(self::INFOCENTER_URI.'/'.self::INDEX_PAGE);
- $freigegebenLink = site_url(self::INFOCENTER_URI.'/'.self::FREIGEGEBEN_PAGE);
- $absolviertLink = site_url(self::INFOCENTER_URI.'/'.self::REIHUNGSTESTABSOLVIERT_PAGE);
+ $reloadDatasetParam = '?'.self::RELOAD_DATASET.'=true';
+ $homeLink = site_url(self::INFOCENTER_URI.'/'.self::INDEX_PAGE.$reloadDatasetParam);
+ $freigegebenLink = site_url(self::INFOCENTER_URI.'/'.self::FREIGEGEBEN_PAGE.$reloadDatasetParam);
+ $absolviertLink = site_url(self::INFOCENTER_URI.'/'.self::REIHUNGSTESTABSOLVIERT_PAGE.$reloadDatasetParam);
$prevFilterId = $this->input->get(self::PREV_FILTER_ID);
if (isset($prevFilterId))
{
- $homeLink .= '?'.self::FILTER_ID.'='.$prevFilterId;
+ $homeLink .= '&'.self::FILTER_ID.'='.$prevFilterId;
}
$this->navigationlib->setSessionElementMenu(
diff --git a/application/controllers/widgets/Filters.php b/application/controllers/widgets/Filters.php
index a4b23dc8a..2a264736b 100644
--- a/application/controllers/widgets/Filters.php
+++ b/application/controllers/widgets/Filters.php
@@ -216,6 +216,16 @@ class Filters extends FHC_Controller
$this->outputJsonSuccess('Success');
}
+ /**
+ * Reloads the dataset
+ */
+ public function reloadDataset()
+ {
+ $this->filterslib->reloadDataset();
+
+ $this->outputJsonSuccess('Success');
+ }
+
//------------------------------------------------------------------------------------------------------------------
// Private methods
diff --git a/application/controllers/widgets/Tables.php b/application/controllers/widgets/Tables.php
new file mode 100644
index 000000000..21161ff9f
--- /dev/null
+++ b/application/controllers/widgets/Tables.php
@@ -0,0 +1,105 @@
+load->library('AuthLib');
+
+ // Loads the tablewidgetlib with HTTP GET/POST parameters
+ $this->_loadTableWidgetLib();
+
+ // Checks if the caller is allow to read this data
+ $this->_isAllowed();
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // Public methods
+
+ /**
+ * Retrieves data about the current filter from the session and will be written on the output in JSON format
+ */
+ public function getTable()
+ {
+ $this->outputJsonSuccess($this->tablewidgetlib->getSession());
+ }
+
+ /**
+ * Retrieves the number of records present in the current dataset and will be written on the output in JSON format
+ */
+ public function rowNumber()
+ {
+ $rowNumber = 0;
+ $dataset = $this->tablewidgetlib->getSessionElement(TableWidgetLib::SESSION_DATASET);
+
+ if (isset($dataset) && is_array($dataset))
+ {
+ $rowNumber = count($dataset);
+ }
+
+ $this->outputJsonSuccess($rowNumber);
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // Private methods
+
+ /**
+ * Checks if the user is allowed to use this filter
+ */
+ private function _isAllowed()
+ {
+ if (!$this->tablewidgetlib->isAllowed())
+ {
+ $this->terminateWithJsonError('You are not allowed to access to this content');
+ }
+ }
+
+ /**
+ * Loads the tablewidgetlib with the TABLE_UNIQUE_ID parameter
+ * If the parameter TABLE_UNIQUE_ID is not given then the execution of the controller is terminated and
+ * an error message is printed
+ */
+ private function _loadTableWidgetLib()
+ {
+ // If the parameter TABLE_UNIQUE_ID is present in the HTTP GET or POST
+ if (isset($_GET[self::TABLE_UNIQUE_ID]) || isset($_POST[self::TABLE_UNIQUE_ID]))
+ {
+ // If it is present in the HTTP GET
+ if (isset($_GET[self::TABLE_UNIQUE_ID]))
+ {
+ $tableUniqueId = $this->input->get(self::TABLE_UNIQUE_ID); // is retrieved from the HTTP GET
+ }
+ elseif (isset($_POST[self::TABLE_UNIQUE_ID])) // Else if it is present in the HTTP POST
+ {
+ $tableUniqueId = $this->input->post(self::TABLE_UNIQUE_ID); // is retrieved from the HTTP POST
+ }
+
+ // Loads the tablewidgetlib that contains all the used logic
+ $this->load->library('TableWidgetLib');
+
+ $this->tablewidgetlib->setTableUniqueId($tableUniqueId);
+ }
+ else // Otherwise an error will be written in the output
+ {
+ $this->terminateWithJsonError('Parameter "'.self::TABLE_UNIQUE_ID.'" not provided!');
+ }
+ }
+}
diff --git a/application/core/APIv1_Controller.php b/application/core/APIv1_Controller.php
index 6432c87db..14b4b626d 100644
--- a/application/core/APIv1_Controller.php
+++ b/application/core/APIv1_Controller.php
@@ -1,9 +1,11 @@
isEntitled
* - Checks if the caller is allowed to access to this content with the given permissions
* if it is not allowed will set the HTTP header with code 401
* - Calls the parent (REST_Controller) _remap method to performs other checks
+ * NOTE: this methods override the parent method!!!
*/
- public function _remap($object_called, $arguments)
+ public function _remap($object_called, $arguments = [])
{
if (isset($this->authlib)) // if set then the authentication is ok
{
diff --git a/application/core/Auth_Controller.php b/application/core/Auth_Controller.php
index 5d03091f0..c407a106f 100644
--- a/application/core/Auth_Controller.php
+++ b/application/core/Auth_Controller.php
@@ -1,8 +1,11 @@
load->library('LogLib', array(
+ 'classIndex' => 5,
+ 'functionIndex' => 5,
+ 'lineIndex' => 4,
+ 'dbLogType' => 'job', // required
+ 'dbExecuteUser' => 'Cronjob system'
+ ));
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // Protected methods
+
+ /**
+ * Writes a cronjob info log
+ */
+ protected function logInfo($response, $parameters = null)
+ {
+ $this->_log(LogLib::INFO, 'Cronjob info', $response, $parameters);
+ }
+
+ /**
+ * Writes a cronjob debug log
+ */
+ protected function logDebug($response, $parameters = null)
+ {
+ $this->_log(LogLib::DEBUG, 'Cronjob debug', $response, $parameters);
+ }
+
+ /**
+ * Writes a cronjob warning log
+ */
+ protected function logWarning($response, $parameters = null)
+ {
+ $this->_log(LogLib::WARNING, 'Cronjob warning', $response, $parameters);
+ }
+
+ /**
+ * Writes a cronjob error log
+ */
+ protected function logError($response, $parameters = null)
+ {
+ $this->_log(LogLib::ERROR, 'Cronjob error', $response, $parameters);
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // Private methods
+
+ /**
+ * Writes a log to database
+ */
+ private function _log($level, $requestId, $response, $parameters)
+ {
+ $data = new stdClass();
+
+ $data->response = $response;
+ if ($parameters != null) $data->parameters = $parameters;
+
+ switch($level)
+ {
+ case LogLib::INFO:
+ $this->loglib->logInfoDB($requestId, json_encode(success($data, LogLib::INFO)));
+ break;
+ case LogLib::DEBUG:
+ $this->loglib->logDebugDB($requestId, json_encode(success($data, LogLib::DEBUG)));
+ break;
+ case LogLib::WARNING:
+ $this->loglib->logWarningDB($requestId, json_encode(error($data, LogLib::WARNING)));
+ break;
+ case LogLib::ERROR:
+ $this->loglib->logErrorDB($requestId, json_encode(error($data, LogLib::ERROR)));
+ break;
+ }
+ }
+}
diff --git a/application/core/RESTFul_Controller.php b/application/core/RESTFul_Controller.php
new file mode 100644
index 000000000..984f193de
--- /dev/null
+++ b/application/core/RESTFul_Controller.php
@@ -0,0 +1,215 @@
+load->helper('hlp_return_object');
+
+ // Loads helper session to manage the php session
+ $this->load->helper('hlp_session');
+
+ // Loads helper with generic utility function
+ $this->load->helper('hlp_common');
+ }
+
+ /**
+ * Totally overrode parent's _perform_library_auth method to keep file and class name
+ * for AuthLib and to call AuthLib with the extra parameter
+ */
+ protected function _perform_library_auth($username = '', $password = NULL)
+ {
+ if (empty($username))
+ {
+ log_message('error', 'Library Auth: Failure, empty username');
+ return FALSE;
+ }
+
+ $auth_library_class = $this->config->item('auth_library_class');
+ $auth_library_function = $this->config->item('auth_library_function');
+
+ if (empty($auth_library_class))
+ {
+ log_message('debug', 'Library Auth: Failure, empty auth_library_class');
+ return FALSE;
+ }
+
+ if (empty($auth_library_function))
+ {
+ log_message('debug', 'Library Auth: Failure, empty auth_library_function');
+ return FALSE;
+ }
+
+ if (is_callable([$auth_library_class, $auth_library_function]) === FALSE)
+ {
+ $this->load->library($auth_library_class, array(false));
+ }
+
+ return $this->{strtolower($auth_library_class)}->$auth_library_function($username, $password);
+ }
+
+ /**
+ * Totally overrode parent's _remap method to change the naming convention of controllers methods
+ */
+ public function _remap($object_called, $arguments = [])
+ {
+ // Should we answer if not over SSL?
+ if ($this->config->item('force_https') && $this->request->ssl === FALSE)
+ {
+ $this->response([
+ $this->config->item('rest_status_field_name') => FALSE,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported')
+ ], self::HTTP_FORBIDDEN);
+
+ $this->is_valid_request = false;
+ }
+
+ // Remove the supported format from the function name e.g. index.json => index
+ $object_called = preg_replace('/^(.*)\.(?:'.implode('|', array_keys($this->_supported_formats)).')$/', '$1', $object_called);
+
+ // NOTE: START changes
+ $controller_method = $object_called.'_'.$this->request->method; // Method name fallback
+ // If the config entry rest_methods_name_format is provided and is not empty then use it to produce the method name
+ if (!empty($this->config->item('rest_methods_name_format')))
+ {
+ $controller_method = sprintf($this->config->item('rest_methods_name_format'), $object_called, $this->request->method);
+ }
+ // END changes
+
+ // Does this method exist? If not, try executing an index method
+ if (!method_exists($this, $controller_method)) {
+ $controller_method = "index_" . $this->request->method;
+ array_unshift($arguments, $object_called);
+ }
+
+ // Do we want to log this method (if allowed by config)?
+ $log_method = ! (isset($this->methods[$controller_method]['log']) && $this->methods[$controller_method]['log'] === FALSE);
+
+ // Use keys for this method?
+ $use_key = ! (isset($this->methods[$controller_method]['key']) && $this->methods[$controller_method]['key'] === FALSE);
+
+ // They provided a key, but it wasn't valid, so get them out of here
+ if ($this->config->item('rest_enable_keys') && $use_key && $this->_allow === FALSE)
+ {
+ if ($this->config->item('rest_enable_logging') && $log_method)
+ {
+ $this->_log_request();
+ }
+
+ // fix cross site to option request error
+ if($this->request->method == 'options') {
+ exit;
+ }
+
+ $this->response([
+ $this->config->item('rest_status_field_name') => FALSE,
+ $this->config->item('rest_message_field_name') => sprintf($this->lang->line('text_rest_invalid_api_key'), $this->rest->key)
+ ], self::HTTP_FORBIDDEN);
+
+ $this->is_valid_request = false;
+ }
+
+ // Check to see if this key has access to the requested controller
+ if ($this->config->item('rest_enable_keys') && $use_key && empty($this->rest->key) === FALSE && $this->_check_access() === FALSE)
+ {
+ if ($this->config->item('rest_enable_logging') && $log_method)
+ {
+ $this->_log_request();
+ }
+
+ $this->response([
+ $this->config->item('rest_status_field_name') => FALSE,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_unauthorized')
+ ], self::HTTP_UNAUTHORIZED);
+
+ $this->is_valid_request = false;
+ }
+
+ // Sure it exists, but can they do anything with it?
+ if (! method_exists($this, $controller_method))
+ {
+ $this->response([
+ $this->config->item('rest_status_field_name') => FALSE,
+ $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unknown_method')
+ ], self::HTTP_METHOD_NOT_ALLOWED);
+
+ $this->is_valid_request = false;
+ }
+
+ // Doing key related stuff? Can only do it if they have a key right?
+ if ($this->config->item('rest_enable_keys') && empty($this->rest->key) === FALSE)
+ {
+ // Check the limit
+ if ($this->config->item('rest_enable_limits') && $this->_check_limit($controller_method) === FALSE)
+ {
+ $response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_time_limit')];
+ $this->response($response, self::HTTP_UNAUTHORIZED);
+
+ $this->is_valid_request = false;
+ }
+
+ // If no level is set use 0, they probably aren't using permissions
+ $level = isset($this->methods[$controller_method]['level']) ? $this->methods[$controller_method]['level'] : 0;
+
+ // If no level is set, or it is lower than/equal to the key's level
+ $authorized = $level <= $this->rest->level;
+ // IM TELLIN!
+ if ($this->config->item('rest_enable_logging') && $log_method)
+ {
+ $this->_log_request($authorized);
+ }
+ if($authorized === FALSE)
+ {
+ // They don't have good enough perms
+ $response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_permissions')];
+ $this->response($response, self::HTTP_UNAUTHORIZED);
+
+ $this->is_valid_request = false;
+ }
+ }
+
+ //check request limit by ip without login
+ elseif ($this->config->item('rest_limits_method') == "IP_ADDRESS" && $this->config->item('rest_enable_limits') && $this->_check_limit($controller_method) === FALSE)
+ {
+ $response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_address_time_limit')];
+ $this->response($response, self::HTTP_UNAUTHORIZED);
+
+ $this->is_valid_request = false;
+ }
+
+ // No key stuff, but record that stuff is happening
+ elseif ($this->config->item('rest_enable_logging') && $log_method)
+ {
+ $this->_log_request($authorized = TRUE);
+ }
+
+ // Call the controller method and passed arguments
+ try
+ {
+ if ($this->is_valid_request) {
+ call_user_func_array([$this, $controller_method], $arguments);
+ }
+ }
+ catch (Exception $ex)
+ {
+ if ($this->config->item('rest_handle_exceptions') === FALSE) {
+ throw $ex;
+ }
+
+ // If the method doesn't exist, then the error will be caught and an error response shown
+ $_error = &load_class('Exceptions', 'core');
+ $_error->show_exception($ex);
+ }
+ }
+}
diff --git a/application/core/REST_Controller.php b/application/core/REST_Controller.php
deleted file mode 100644
index 9cd276556..000000000
--- a/application/core/REST_Controller.php
+++ /dev/null
@@ -1,2166 +0,0 @@
- 'application/json',
- 'array' => 'application/json',
- 'csv' => 'application/csv',
- 'html' => 'text/html',
- 'jsonp' => 'application/javascript',
- 'php' => 'text/plain',
- 'serialized' => 'application/vnd.php.serialized',
- 'xml' => 'application/xml'
- ];
-
- /**
- * Information about the current API user
- *
- * @var object
- */
- protected $_apiuser;
-
- /**
- * Enable XSS flag
- * Determines whether the XSS filter is always active when
- * GET, OPTIONS, HEAD, POST, PUT, DELETE and PATCH data is encountered.
- * Set automatically based on config setting
- *
- * @var bool
- */
- protected $_enable_xss = FALSE;
-
- /**
- * HTTP status codes and their respective description
- * Note: Only the widely used HTTP status codes are used
- *
- * @var array
- * @link http://www.restapitutorial.com/httpstatuscodes.html
- */
- protected $http_status_codes = [
- self::HTTP_OK => 'OK',
- self::HTTP_CREATED => 'CREATED',
- self::HTTP_NO_CONTENT => 'NO CONTENT',
- self::HTTP_NOT_MODIFIED => 'NOT MODIFIED',
- self::HTTP_BAD_REQUEST => 'BAD REQUEST',
- self::HTTP_UNAUTHORIZED => 'UNAUTHORIZED',
- self::HTTP_FORBIDDEN => 'FORBIDDEN',
- self::HTTP_NOT_FOUND => 'NOT FOUND',
- self::HTTP_METHOD_NOT_ALLOWED => 'METHOD NOT ALLOWED',
- self::HTTP_NOT_ACCEPTABLE => 'NOT ACCEPTABLE',
- self::HTTP_CONFLICT => 'CONFLICT',
- self::HTTP_INTERNAL_SERVER_ERROR => 'INTERNAL SERVER ERROR',
- self::HTTP_NOT_IMPLEMENTED => 'NOT IMPLEMENTED'
- ];
-
- /**
- * Extend this function to apply additional checking early on in the process
- *
- * @access protected
- * @return void
- */
- protected function early_checks()
- {
- // Loads helper message to manage returning messages
- $this->load->helper('hlp_return_object');
-
- // Loads helper session to manage the php session
- $this->load->helper('hlp_session');
-
- // Loads helper with generic utility function
- $this->load->helper('hlp_common');
- }
-
- /**
- * Constructor for the REST API
- *
- * @access public
- * @param string $config Configuration filename minus the file extension
- * e.g: my_rest.php is passed as 'my_rest'
- * @return void
- */
- public function __construct($config = 'rest')
- {
- parent::__construct();
-
- // Disable XML Entity (security vulnerability)
- libxml_disable_entity_loader(TRUE);
-
- // Check to see if PHP is equal to or greater than 5.4.x
- if (is_php('5.4') === FALSE)
- {
- // CodeIgniter 3 is recommended for v5.4 or above
- throw new Exception('Using PHP v' . PHP_VERSION . ', though PHP v5.4 or greater is required');
- }
-
- // Check to see if this is CI 3.x
- $ci_version_number = explode('.', CI_VERSION, 2);
- if ($ci_version_number[0] < 3)
- {
- throw new Exception('REST Server requires CodeIgniter 3.x');
- }
-
- // Set the default value of global xss filtering. Same approach as CodeIgniter 3
- $this->_enable_xss = ($this->config->item('global_xss_filtering') === TRUE);
-
- // Don't try to parse template variables like {elapsed_time} and {memory_usage}
- // when output is displayed for not damaging data accidentally
- $this->output->parse_exec_vars = FALSE;
-
- // Start the timer for how long the request takes
- $this->_start_rtime = microtime(TRUE);
-
- // Load the rest.php configuration file
- $this->load->config($config);
-
- // At present the library is bundled with REST_Controller 2.5+, but will eventually be part of CodeIgniter (no citation)
- $this->load->library('format');
-
- // Determine supported output formats from configiguration.
- $supported_formats = $this->config->item('rest_supported_formats');
-
- // Validate the configuration setting output formats
- if (empty($supported_formats))
- {
- $supported_formats = [];
- }
-
- if (!is_array($supported_formats))
- {
- $supported_formats = [$supported_formats];
- }
-
- // Add silently the default output format if it is missing.
- $default_format = $this->_get_default_output_format();
- if (!in_array($default_format, $supported_formats))
- {
- $supported_formats[] = $default_format;
- }
-
- // Now update $this->_supported_formats
- $this->_supported_formats = array_intersect_key($this->_supported_formats, array_flip($supported_formats));
-
- // Get the language
- $language = $this->config->item('rest_language');
- if ($language === NULL)
- {
- $language = 'en-US';
- }
-
- // Load the language file
- $this->lang->load('rest_controller', $language);
-
- // Initialise the response, request and rest objects
- $this->request = new stdClass();
- $this->response = new stdClass();
- $this->rest = new stdClass();
-
- // Check to see if the current IP address is blacklisted
- if ($this->config->item('rest_ip_blacklist_enabled') === TRUE)
- {
- $this->_check_blacklist_auth();
- }
-
- // Determine whether the connection is HTTPS
- $this->request->ssl = is_https();
-
- // How is this request being made? GET, POST, PATCH, DELETE, INSERT, PUT, HEAD or OPTIONS
- $this->request->method = $this->_detect_method();
-
- // Create an argument container if it doesn't exist e.g. _get_args
- if (isset($this->{'_' . $this->request->method . '_args'}) === FALSE)
- {
- $this->{'_' . $this->request->method . '_args'} = [];
- }
-
- // Set up the query parameters
- $this->_parse_query();
-
- // Set up the GET variables
- $this->_get_args = array_merge($this->_get_args, $this->uri->ruri_to_assoc());
-
- // Try to find a format for the request (means we have a request body)
- $this->request->format = $this->_detect_input_format();
-
- // Not all methods have a body attached with them
- $this->request->body = NULL;
-
- $this->{'_parse_' . $this->request->method}();
-
- // Now we know all about our request, let's try and parse the body if it exists
- if ($this->request->format && $this->request->body)
- {
- $this->request->body = $this->format->factory($this->request->body, $this->request->format)->to_array();
- // Assign payload arguments to proper method container
- $this->{'_' . $this->request->method . '_args'} = $this->request->body;
- }
-
- // Merge both for one mega-args variable
- $this->_args = array_merge(
- $this->_get_args,
- $this->_options_args,
- $this->_patch_args,
- $this->_head_args,
- $this->_put_args,
- $this->_post_args,
- $this->_delete_args,
- $this->{'_' . $this->request->method . '_args'}
- );
-
- // Which format should the data be returned in?
- $this->response->format = $this->_detect_output_format();
-
- // Which language should the data be returned in?
- $this->response->lang = $this->_detect_lang();
-
- // Extend this function to apply additional checking early on in the process
- $this->early_checks();
-
- // Load DB if its enabled
- if ($this->config->item('rest_database_group') && ($this->config->item('rest_enable_keys') || $this->config->item('rest_enable_logging')))
- {
- $this->rest->db = $this->load->database($this->config->item('rest_database_group'), TRUE);
- }
-
- // Use whatever database is in use (isset returns FALSE)
- elseif (property_exists($this, 'db'))
- {
- $this->rest->db = $this->db;
- }
-
- // Check if there is a specific auth type for the current class/method
- // _auth_override_check could exit so we need $this->rest->db initialized before
- $this->auth_override = $this->_auth_override_check();
-
- // Checking for keys? GET TO WorK!
- // Skip keys test for $config['auth_override_class_method']['class'['method'] = 'none'
- if ($this->config->item('rest_enable_keys') && $this->auth_override !== TRUE)
- {
- $this->_allow = $this->_detect_api_key();
- }
-
- // Only allow ajax requests
- if ($this->input->is_ajax_request() === FALSE && $this->config->item('rest_ajax_only'))
- {
- // Display an error response
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ajax_only')
- ], self::HTTP_NOT_ACCEPTABLE);
- }
-
- // When there is no specific override for the current class/method, use the default auth value set in the config
- if ($this->auth_override === FALSE && ($this->config->item('rest_enable_keys') && $this->_allow === TRUE))
- {
- $rest_auth = strtolower($this->config->item('rest_auth'));
- switch ($rest_auth)
- {
- case 'basic':
- $this->_prepare_basic_auth();
- break;
- case 'digest':
- $this->_prepare_digest_auth();
- break;
- case 'session':
- $this->_check_php_session();
- break;
- }
- if ($this->config->item('rest_ip_whitelist_enabled') === TRUE)
- {
- $this->_check_whitelist_auth();
- }
- }
- }
-
- /**
- * Deconstructor
- *
- * @author Chris Kacerguis
- * @access public
- * @return void
- */
- public function __destruct()
- {
- // Get the current timestamp
- $this->_end_rtime = microtime(TRUE);
-
- // Log the loading time to the log table
- if ($this->config->item('rest_enable_logging') === TRUE)
- {
- $this->_log_access_time();
- }
- }
-
- /**
- * Requests are not made to methods directly, the request will be for
- * an "object". This simply maps the object and method to the correct
- * Controller method
- *
- * @access public
- * @param string $object_called
- * @param array $arguments The arguments passed to the controller method
- */
- public function _remap($object_called, $arguments)
- {
- // Should we answer if not over SSL?
- if ($this->config->item('force_https') && $this->request->ssl === FALSE)
- {
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unsupported')
- ], self::HTTP_FORBIDDEN);
- }
-
- // Remove the supported format from the function name e.g. index.json => index
- $object_called = preg_replace('/^(.*)\.(?:' . implode('|', array_keys($this->_supported_formats)) . ')$/', '$1', $object_called);
-
- //$controller_method = $object_called . '_' . $this->request->method;
- // CamelCase compliant
- $controller_method = $this->request->method.ucfirst($object_called);
-
- // Do we want to log this method (if allowed by config)?
- $log_method = !(isset($this->methods[$controller_method]['log']) && $this->methods[$controller_method]['log'] === FALSE);
-
- // Use keys for this method?
- $use_key = !(isset($this->methods[$controller_method]['key']) && $this->methods[$controller_method]['key'] === FALSE);
-
- // They provided a key, but it wasn't valid, so get them out of here
- if ($this->config->item('rest_enable_keys') && $use_key && $this->_allow === FALSE)
- {
- if ($this->config->item('rest_enable_logging') && $log_method)
- {
- $this->_log_request();
- }
-
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => sprintf($this->lang->line('text_rest_invalid_api_key'), $this->rest->key)
- ], self::HTTP_FORBIDDEN);
- }
-
- // Check to see if this key has access to the requested controller
- if ($this->config->item('rest_enable_keys') && $use_key && empty($this->rest->key) === FALSE && $this->_check_access() === FALSE)
- {
- if ($this->config->item('rest_enable_logging') && $log_method)
- {
- $this->_log_request();
- }
-
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_unauthorized')
- ], self::HTTP_UNAUTHORIZED);
- }
-
- // Sure it exists, but can they do anything with it?
- if (method_exists($this, $controller_method) === FALSE)
- {
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unknown_method')
- ], self::HTTP_NOT_FOUND);
- }
-
- // Doing key related stuff? Can only do it if they have a key right?
- if ($this->config->item('rest_enable_keys') && empty($this->rest->key) === FALSE)
- {
- // Check the limit
- if ($this->config->item('rest_enable_limits') && $this->_check_limit($controller_method) === FALSE)
- {
- $response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_time_limit')];
- $this->response($response, self::HTTP_UNAUTHORIZED);
- }
-
- // If no level is set use 0, they probably aren't using permissions
- $level = isset($this->methods[$controller_method]['level']) ? $this->methods[$controller_method]['level'] : 0;
-
- // If no level is set, or it is lower than/equal to the key's level
- $authorized = $level <= $this->rest->level;
-
- // IM TELLIN!
- if ($this->config->item('rest_enable_logging') && $log_method)
- {
- $this->_log_request($authorized);
- }
-
- // They don't have good enough perms
- $response = [$this->config->item('rest_status_field_name') => FALSE, $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_api_key_permissions')];
- $authorized || $this->response($response, self::HTTP_UNAUTHORIZED);
- }
-
- // No key stuff, but record that stuff is happening
- elseif ($this->config->item('rest_enable_logging') && $log_method)
- {
- $this->_log_request($authorized = TRUE);
- }
-
- // Call the controller method and passed arguments
- try
- {
- call_user_func_array([$this, $controller_method], $arguments);
- }
- catch (Exception $ex)
- {
- // If the method doesn't exist, then the error will be caught and an error response shown
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => [
- 'classname' => get_class($ex),
- 'message' => $ex->getMessage()
- ]
- ], self::HTTP_INTERNAL_SERVER_ERROR);
- }
- }
-
- /**
- * Takes mixed data and optionally a status code, then creates the response
- *
- * @access public
- * @param array|NULL $data Data to output to the user
- * @param int|NULL $http_code HTTP status code
- * @param bool $continue TRUE to flush the response to the client and continue
- * running the script; otherwise, exit
- */
- public function response($data = NULL, $http_code = NULL, $continue = FALSE)
- {
- // If the HTTP status is not NULL, then cast as an integer
- if ($http_code !== NULL)
- {
- // So as to be safe later on in the process
- $http_code = (int) $http_code;
- }
-
- // Set the output as NULL by default
- $output = NULL;
- // If data is NULL and no HTTP status code provided, then display, error and exit
- if ($data === NULL && $http_code === NULL)
- {
- $http_code = self::HTTP_NOT_FOUND;
- }
-
- // If data is not NULL and a HTTP status code provided, then continue
- elseif ($data !== NULL)
- {
- // If the format method exists, call and return the output in that format
- if (method_exists($this->format, 'to_' . $this->response->format))
- {
- // Set the format header
- $this->output->set_content_type($this->_supported_formats[$this->response->format], strtolower($this->config->item('charset')));
- $output = $this->format->factory($data)->{'to_' . $this->response->format}();
-
- // An array must be parsed as a string, so as not to cause an array to string error
- // Json is the most appropriate form for such a datatype
- if ($this->response->format === 'array')
- {
- $output = $this->format->factory($output)->{'to_json'}();
- }
- }
- else
- {
- // If an array or object, then parse as a json, so as to be a 'string'
- if (is_array($data) || is_object($data))
- {
- $data = $this->format->factory($data)->{'to_json'}();
- }
- // Format is not supported, so output the raw data as a string
- $output = $data;
- }
- }
-
- // If not greater than zero, then set the HTTP status code as 200 by default
- // Though perhaps 500 should be set instead, for the developer not passing a
- // correct HTTP status code
- $http_code > 0 || $http_code = self::HTTP_OK;
-
- $this->output->set_status_header($http_code);
-
- // JC: Log response code only if rest logging enabled
- if ($this->config->item('rest_enable_logging') === TRUE)
- {
- $this->_log_response_code($http_code);
- }
-
- // Output the data
- $this->output->set_output($output);
-
- if ($continue === FALSE)
- {
- // Display the data and exit execution
- $this->output->_display();
- exit;
- }
-
- // Otherwise dump the output automatically
- }
-
- /**
- * Takes mixed data and optionally a status code, then creates the response
- * within the buffers of the Output class. The response is sent to the client
- * lately by the framework, after the current controller's method termination.
- * All the hooks after the controller's method termination are executable
- *
- * @access public
- * @param array|NULL $data Data to output to the user
- * @param int|NULL $http_code HTTP status code
- */
- public function set_response($data = NULL, $http_code = NULL)
- {
- $this->response($data, $http_code, TRUE);
- }
-
- /**
- * Get the input format e.g. json or xml
- *
- * @access protected
- * @return string|NULL Supported input format; otherwise, NULL
- */
- protected function _detect_input_format()
- {
- // Get the CONTENT-TYPE value from the SERVER variable
- $content_type = $this->input->server('CONTENT_TYPE');
-
- if (empty($content_type) === FALSE)
- {
- // Check all formats against the HTTP_ACCEPT header
- foreach ($this->_supported_formats as $key => $value)
- {
- // $key = format e.g. csv
- // $value = mime type e.g. application/csv
-
- // If a semi-colon exists in the string, then explode by ; and get the value of where
- // the current array pointer resides. This will generally be the first element of the array
- $content_type = (strpos($content_type, ';') !== FALSE ? current(explode(';', $content_type)) : $content_type);
-
- // If both the mime types match, then return the format
- if ($content_type === $value)
- {
- return $key;
- }
- }
- }
-
- return NULL;
- }
-
- /**
- * Gets the default format from the configuration. Fallbacks to 'json'.
- * if the corresponding configuration option $config['rest_default_format']
- * is missing or is empty.
- *
- * @access protected
- * @return string The default supported input format
- */
- protected function _get_default_output_format()
- {
- $default_format = (string) $this->config->item('rest_default_format');
- return $default_format === '' ? 'json' : $default_format;
- }
-
- /**
- * Detect which format should be used to output the data
- *
- * @access protected
- * @return mixed|NULL|string Output format
- */
- protected function _detect_output_format()
- {
- // Concatenate formats to a regex pattern e.g. \.(csv|json|xml)
- $pattern = '/\.(' . implode('|', array_keys($this->_supported_formats)) . ')($|\/)/';
- $matches = [];
-
- // Check if a file extension is used e.g. http://example.com/api/index.json?param1=param2
- if (preg_match($pattern, $this->uri->uri_string(), $matches))
- {
- return $matches[1];
- }
-
- // Get the format parameter named as 'format'
- if (isset($this->_get_args['format']))
- {
- $format = strtolower($this->_get_args['format']);
-
- if (isset($this->_supported_formats[$format]) === TRUE)
- {
- return $format;
- }
- }
-
- // Get the HTTP_ACCEPT server variable
- $http_accept = $this->input->server('HTTP_ACCEPT');
-
- // Otherwise, check the HTTP_ACCEPT server variable
- if ($this->config->item('rest_ignore_http_accept') === FALSE && $http_accept !== NULL)
- {
- // Check all formats against the HTTP_ACCEPT header
- foreach (array_keys($this->_supported_formats) as $format)
- {
- // Has this format been requested?
- if (strpos($http_accept, $format) !== FALSE)
- {
- if ($format !== 'html' && $format !== 'xml')
- {
- // If not HTML or XML assume it's correct
- return $format;
- }
- elseif ($format === 'html' && strpos($http_accept, 'xml') === FALSE)
- {
- // HTML or XML have shown up as a match
- // If it is truly HTML, it wont want any XML
- return $format;
- }
- else if ($format === 'xml' && strpos($http_accept, 'html') === FALSE)
- {
- // If it is truly XML, it wont want any HTML
- return $format;
- }
- }
- }
- }
-
- // Check if the controller has a default format
- if (empty($this->rest_format) === FALSE)
- {
- return $this->rest_format;
- }
-
- // Obtain the default format from the configuration
- return $this->_get_default_output_format();
- }
-
- /**
- * Get the HTTP request string e.g. get or post
- *
- * @access protected
- * @return string|NULL Supported request method as a lowercase string; otherwise, NULL if not supported
- */
- protected function _detect_method()
- {
- // Declare a variable to store the method
- $method = NULL;
-
- // Determine whether the 'enable_emulate_request' setting is enabled
- if ($this->config->item('enable_emulate_request') === TRUE)
- {
- $method = $this->input->post('_method');
- if ($method === NULL)
- {
- $method = $this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE');
- }
-
- $method = strtolower($method);
- }
-
- if (empty($method))
- {
- // Get the request method as a lowercase string
- $method = $this->input->method();
- }
-
- return in_array($method, $this->allowed_http_methods) && method_exists($this, '_parse_' . $method) ? $method : 'get';
- }
-
- /**
- * See if the user has provided an API key
- *
- * @access protected
- * @return bool
- */
- protected function _detect_api_key()
- {
- // Get the api key name variable set in the rest config file
- $api_key_variable = $this->config->item('rest_key_name');
-
- // Work out the name of the SERVER entry based on config
- $key_name = 'HTTP_' . strtoupper(str_replace('-', '_', $api_key_variable));
-
- $this->rest->key = NULL;
- $this->rest->level = NULL;
- $this->rest->user_id = NULL;
- $this->rest->ignore_limits = FALSE;
-
- // Find the key from server or arguments
- if (($key = isset($this->_args[$api_key_variable]) ? $this->_args[$api_key_variable] : $this->input->server($key_name)))
- {
- if (!($row = $this->rest->db->where($this->config->item('rest_key_column'), $key)->get($this->config->item('rest_keys_table'))->row()))
- {
- return FALSE;
- }
-
- $this->rest->key = $row->{$this->config->item('rest_key_column')};
-
- isset($row->user_id) && $this->rest->user_id = $row->user_id;
- isset($row->level) && $this->rest->level = $row->level;
- isset($row->ignore_limits) && $this->rest->ignore_limits = $row->ignore_limits;
-
- $this->_apiuser = $row;
-
- /*
- * If "is private key" is enabled, compare the ip address with the list
- * of valid ip addresses stored in the database
- */
- if (empty($row->is_private_key) === FALSE)
- {
- // Check for a list of valid ip addresses
- if (isset($row->ip_addresses))
- {
- // multiple ip addresses must be separated using a comma, explode and loop
- $list_ip_addresses = explode(',', $row->ip_addresses);
- $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 TRUE;
- }
-
- // No key has been sent
- return FALSE;
- }
-
- /**
- * Preferred return language
- *
- * @access protected
- * @return string|NULL The language code
- */
- protected function _detect_lang()
- {
- $lang = $this->input->server('HTTP_ACCEPT_LANGUAGE');
- if ($lang === NULL)
- {
- return NULL;
- }
-
- // It appears more than one language has been sent using a comma delimiter
- if (strpos($lang, ',') !== FALSE)
- {
- $langs = explode(',', $lang);
-
- $return_langs = [];
- foreach ($langs as $lang)
- {
- // Remove weight and trim leading and trailing whitespace
- list($lang) = explode(';', $lang);
- $return_langs[] = trim($lang);
- }
-
- return $return_langs;
- }
-
- // Otherwise simply return as a string
- return $lang;
- }
-
- /**
- * Add the request to the log table
- *
- * @access protected
- * @param bool $authorized TRUE the user is authorized; otherwise, FALSE
- * @return bool TRUE the data was inserted; otherwise, FALSE
- */
- protected function _log_request($authorized = FALSE)
- {
- // Insert the request into the log table
- $is_inserted = $this->rest->db
- ->insert(
- $this->config->item('rest_logs_table'), [
- 'uri' => $this->uri->uri_string(),
- 'method' => $this->request->method,
- 'params' => $this->_args ? ($this->config->item('rest_logs_json_params') === TRUE ? json_encode($this->_args) : serialize($this->_args)) : NULL,
- 'api_key' => isset($this->rest->key) ? $this->rest->key : '',
- 'ip_address' => $this->input->ip_address(),
- 'time' => time(),
- 'authorized' => $authorized
- ]);
-
- // Get the last insert id to update at a later stage of the request
- $this->_insert_id = $this->rest->db->insert_id();
-
- return $is_inserted;
- }
-
- /**
- * Check if the requests to a controller method exceed a limit
- *
- * @access protected
- * @param string $controller_method The method being called
- * @return bool TRUE the call limit is below the threshold; otherwise, FALSE
- */
- protected function _check_limit($controller_method)
- {
- // They are special, or it might not even have a limit
- if (empty($this->rest->ignore_limits) === FALSE)
- {
- // Everything is fine
- return TRUE;
- }
-
- switch ($this->config->item('rest_limits_method'))
- {
- case 'API_KEY':
- $limited_uri = 'api-key:' . (isset($this->rest->key) ? $this->rest->key : '');
- $limited_method_name = isset($this->rest->key) ? $this->rest->key : '';
- break;
-
- case 'METHOD_NAME':
- $limited_uri = 'method-name:' . $controller_method;
- $limited_method_name = $controller_method;
- break;
-
- case 'ROUTED_URL':
- default:
- $limited_uri = $this->uri->ruri_string();
- if (strpos(strrev($limited_uri), strrev($this->response->format)) === 0)
- {
- $limited_uri = substr($limited_uri,0, -strlen($this->response->format) - 1);
- }
- $limited_uri = 'uri:' . $limited_uri . ':' . $this->request->method; // It's good to differentiate GET from PUT
- $limited_method_name = $controller_method;
- break;
- }
-
- if (isset($this->methods[$limited_method_name]['limit']) === FALSE )
- {
- // Everything is fine
- return TRUE;
- }
-
- // How many times can you get to this method in a defined time_limit (default: 1 hour)?
- $limit = $this->methods[$limited_method_name]['limit'];
-
- $time_limit = (isset($this->methods[$limited_method_name]['time']) ? $this->methods[$limited_method_name]['time'] : 3600); // 3600 = 60 * 60
-
- // Get data about a keys' usage and limit to one row
- $result = $this->rest->db
- ->where('uri', $limited_uri)
- ->where('api_key', $this->rest->key)
- ->get($this->config->item('rest_limits_table'))
- ->row();
-
- // No calls have been made for this key
- if ($result === NULL)
- {
- // Create a new row for the following key
- $this->rest->db->insert($this->config->item('rest_limits_table'), [
- 'uri' => $limited_uri,
- 'api_key' => isset($this->rest->key) ? $this->rest->key : '',
- 'count' => 1,
- 'hour_started' => time()
- ]);
- }
-
- // Been a time limit (or by default an hour) since they called
- elseif ($result->hour_started < (time() - $time_limit))
- {
- // Reset the started period and count
- $this->rest->db
- ->where('uri', $limited_uri)
- ->where('api_key', isset($this->rest->key) ? $this->rest->key : '')
- ->set('hour_started', time())
- ->set('count', 1)
- ->update($this->config->item('rest_limits_table'));
- }
-
- // They have called within the hour, so lets update
- else
- {
- // The limit has been exceeded
- if ($result->count >= $limit)
- {
- return FALSE;
- }
-
- // Increase the count by one
- $this->rest->db
- ->where('uri', $limited_uri)
- ->where('api_key', $this->rest->key)
- ->set('count', 'count + 1', FALSE)
- ->update($this->config->item('rest_limits_table'));
- }
-
- return TRUE;
- }
-
- /**
- * Check if there is a specific auth type set for the current class/method/HTTP-method being called
- *
- * @access protected
- * @return bool
- */
- protected function _auth_override_check()
- {
- // Assign the class/method auth type override array from the config
- $auth_override_class_method = $this->config->item('auth_override_class_method');
-
- // Check to see if the override array is even populated
- if (!empty($auth_override_class_method))
- {
- // check for wildcard flag for rules for classes
- if (!empty($auth_override_class_method[$this->router->class]['*'])) // Check for class overrides
- {
- // None auth override found, prepare nothing but send back a TRUE override flag
- if ($auth_override_class_method[$this->router->class]['*'] === 'none')
- {
- return TRUE;
- }
-
- // Basic auth override found, prepare basic
- if ($auth_override_class_method[$this->router->class]['*'] === 'basic')
- {
- $this->_prepare_basic_auth();
-
- return TRUE;
- }
-
- // Digest auth override found, prepare digest
- if ($auth_override_class_method[$this->router->class]['*'] === 'digest')
- {
- $this->_prepare_digest_auth();
-
- return TRUE;
- }
-
- // Session auth override found, check session
- if ($auth_override_class_method[$this->router->class]['*'] === 'session')
- {
- $this->_check_php_session();
-
- return TRUE;
- }
-
- // Whitelist auth override found, check client's ip against config whitelist
- if ($auth_override_class_method[$this->router->class]['*'] === 'whitelist')
- {
- $this->_check_whitelist_auth();
-
- return TRUE;
- }
- }
-
- // Check to see if there's an override value set for the current class/method being called
- if (!empty($auth_override_class_method[$this->router->class][$this->router->method]))
- {
- // None auth override found, prepare nothing but send back a TRUE override flag
- if ($auth_override_class_method[$this->router->class][$this->router->method] === 'none')
- {
- return TRUE;
- }
-
- // Basic auth override found, prepare basic
- if ($auth_override_class_method[$this->router->class][$this->router->method] === 'basic')
- {
- $this->_prepare_basic_auth();
-
- return TRUE;
- }
-
- // Digest auth override found, prepare digest
- if ($auth_override_class_method[$this->router->class][$this->router->method] === 'digest')
- {
- $this->_prepare_digest_auth();
-
- return TRUE;
- }
-
- // Session auth override found, check session
- if ($auth_override_class_method[$this->router->class][$this->router->method] === 'session')
- {
- $this->_check_php_session();
-
- return TRUE;
- }
-
- // Whitelist auth override found, check client's ip against config whitelist
- if ($auth_override_class_method[$this->router->class][$this->router->method] === 'whitelist')
- {
- $this->_check_whitelist_auth();
-
- return TRUE;
- }
- }
- }
-
- // Assign the class/method/HTTP-method auth type override array from the config
- $auth_override_class_method_http = $this->config->item('auth_override_class_method_http');
-
- // Check to see if the override array is even populated
- if (!empty($auth_override_class_method_http))
- {
- // check for wildcard flag for rules for classes
- if (!empty($auth_override_class_method_http[$this->router->class]['*'][$this->request->method]))
- {
- // None auth override found, prepare nothing but send back a TRUE override flag
- if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'none')
- {
- return TRUE;
- }
-
- // Basic auth override found, prepare basic
- if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'basic')
- {
- $this->_prepare_basic_auth();
-
- return TRUE;
- }
-
- // Digest auth override found, prepare digest
- if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'digest')
- {
- $this->_prepare_digest_auth();
-
- return TRUE;
- }
-
- // Session auth override found, check session
- if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'session')
- {
- $this->_check_php_session();
-
- return TRUE;
- }
-
- // Whitelist auth override found, check client's ip against config whitelist
- if ($auth_override_class_method_http[$this->router->class]['*'][$this->request->method] === 'whitelist')
- {
- $this->_check_whitelist_auth();
-
- return TRUE;
- }
- }
-
- // Check to see if there's an override value set for the current class/method/HTTP-method being called
- if (!empty($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method]))
- {
- // None auth override found, prepare nothing but send back a TRUE override flag
- if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'none')
- {
- return TRUE;
- }
-
- // Basic auth override found, prepare basic
- if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'basic')
- {
- $this->_prepare_basic_auth();
-
- return TRUE;
- }
-
- // Digest auth override found, prepare digest
- if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'digest')
- {
- $this->_prepare_digest_auth();
-
- return TRUE;
- }
-
- // Session auth override found, check session
- if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'session')
- {
- $this->_check_php_session();
-
- return TRUE;
- }
-
- // Whitelist auth override found, check client's ip against config whitelist
- if ($auth_override_class_method_http[$this->router->class][$this->router->method][$this->request->method] === 'whitelist')
- {
- $this->_check_whitelist_auth();
-
- return TRUE;
- }
- }
- }
- return FALSE;
- }
-
- /**
- * Parse the GET request arguments
- *
- * @access protected
- * @return void
- */
- protected function _parse_get()
- {
- // Merge both the URI segments and query parameters
- $this->_get_args = array_merge($this->_get_args, $this->_query_args);
- }
-
- /**
- * Parse the POST request arguments
- *
- * @access protected
- * @return void
- */
- protected function _parse_post()
- {
- $this->_post_args = $_POST;
-
- if ($this->request->format)
- {
- $this->request->body = $this->input->raw_input_stream;
- }
- }
-
- /**
- * Parse the PUT request arguments
- *
- * @access protected
- * @return void
- */
- protected function _parse_put()
- {
- if ($this->request->format)
- {
- $this->request->body = $this->input->raw_input_stream;
- }
- else if ($this->input->method() === 'put')
- {
- // If no filetype is provided, then there are probably just arguments
- $this->_put_args = $this->input->input_stream();
- }
- }
-
- /**
- * Parse the HEAD request arguments
- *
- * @access protected
- * @return void
- */
- protected function _parse_head()
- {
- // Parse the HEAD variables
- parse_str(parse_url($this->input->server('REQUEST_URI'), PHP_URL_QUERY), $head);
-
- // Merge both the URI segments and HEAD params
- $this->_head_args = array_merge($this->_head_args, $head);
- }
-
- /**
- * Parse the OPTIONS request arguments
- *
- * @access protected
- * @return void
- */
- protected function _parse_options()
- {
- // Parse the OPTIONS variables
- parse_str(parse_url($this->input->server('REQUEST_URI'), PHP_URL_QUERY), $options);
-
- // Merge both the URI segments and OPTIONS params
- $this->_options_args = array_merge($this->_options_args, $options);
- }
-
- /**
- * Parse the PATCH request arguments
- *
- * @access protected
- * @return void
- */
- protected function _parse_patch()
- {
- // It might be a HTTP body
- if ($this->request->format)
- {
- $this->request->body = $this->input->raw_input_stream;
- }
- else if ($this->input->method() === 'patch')
- {
- // If no filetype is provided, then there are probably just arguments
- $this->_patch_args = $this->input->input_stream();
- }
- }
-
- /**
- * Parse the DELETE request arguments
- *
- * @access protected
- * @return void
- */
- protected function _parse_delete()
- {
- // These should exist if a DELETE request
- if ($this->input->method() === 'delete')
- {
- $this->_delete_args = $this->input->input_stream();
- }
- }
-
- /**
- * Parse the query parameters
- *
- * @access protected
- * @return void
- */
- protected function _parse_query()
- {
- $this->_query_args = $this->input->get();
- }
-
- // INPUT FUNCTION --------------------------------------------------------------
-
- /**
- * Retrieve a value from a GET request
- *
- * @access public
- * @param NULL $key Key to retrieve from the GET request
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the GET request; otherwise, NULL
- */
- public function get($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_get_args;
- }
-
- return isset($this->_get_args[$key]) ? $this->_xss_clean($this->_get_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Retrieve a value from a OPTIONS request
- *
- * @access public
- * @param NULL $key Key to retrieve from the OPTIONS request.
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the OPTIONS request; otherwise, NULL
- */
- public function options($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_options_args;
- }
-
- return isset($this->_options_args[$key]) ? $this->_xss_clean($this->_options_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Retrieve a value from a HEAD request
- *
- * @access public
- * @param NULL $key Key to retrieve from the HEAD request
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the HEAD request; otherwise, NULL
- */
- public function head($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_head_args;
- }
-
- return isset($this->_head_args[$key]) ? $this->_xss_clean($this->_head_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Retrieve a value from a POST request
- *
- * @access public
- * @param NULL $key Key to retrieve from the POST request
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the POST request; otherwise, NULL
- */
- public function post($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_post_args;
- }
-
- return isset($this->_post_args[$key]) ? $this->_xss_clean($this->_post_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Retrieve a value from a PUT request
- *
- * @access public
- * @param NULL $key Key to retrieve from the PUT request
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the PUT request; otherwise, NULL
- */
- public function put($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_put_args;
- }
-
- return isset($this->_put_args[$key]) ? $this->_xss_clean($this->_put_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Retrieve a value from a DELETE request
- *
- * @access public
- * @param NULL $key Key to retrieve from the DELETE request
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the DELETE request; otherwise, NULL
- */
- public function delete($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_delete_args;
- }
-
- return isset($this->_delete_args[$key]) ? $this->_xss_clean($this->_delete_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Retrieve a value from a PATCH request
- *
- * @access public
- * @param NULL $key Key to retrieve from the PATCH request
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the PATCH request; otherwise, NULL
- */
- public function patch($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_patch_args;
- }
-
- return isset($this->_patch_args[$key]) ? $this->_xss_clean($this->_patch_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Retrieve a value from the query parameters
- *
- * @access public
- * @param NULL $key Key to retrieve from the query parameters
- * If NULL an array of arguments is returned
- * @param NULL $xss_clean Whether to apply XSS filtering
- * @return array|string|NULL Value from the query parameters; otherwise, NULL
- */
- public function query($key = NULL, $xss_clean = NULL)
- {
- if ($key === NULL)
- {
- return $this->_query_args;
- }
-
- return isset($this->_query_args[$key]) ? $this->_xss_clean($this->_query_args[$key], $xss_clean) : NULL;
- }
-
- /**
- * Sanitizes data so that Cross Site Scripting Hacks can be
- * prevented
- *
- * @access protected
- * @param string $value Input data
- * @param bool $xss_clean Whether to apply XSS filtering
- * @return string
- */
- protected function _xss_clean($value, $xss_clean)
- {
- is_bool($xss_clean) || $xss_clean = $this->_enable_xss;
-
- return $xss_clean === TRUE ? $this->security->xss_clean($value) : $value;
- }
-
- /**
- * Retrieve the validation errors
- *
- * @access public
- * @return array
- */
- public function validation_errors()
- {
- $string = strip_tags($this->form_validation->error_string());
-
- return explode(PHP_EOL, trim($string, PHP_EOL));
- }
-
- // SECURITY FUNCTIONS ---------------------------------------------------------
-
- /**
- * Perform LDAP Authentication
- *
- * @access protected
- * @param string $username The username to validate
- * @param string $password The password to validate
- * @return bool
- */
- protected function _perform_ldap_auth($username = '', $password = NULL)
- {
- if (empty($username))
- {
- log_message('debug', 'LDAP Auth: failure, empty username');
- return FALSE;
- }
-
- log_message('debug', 'LDAP Auth: Loading configuration');
-
- $this->config->load('ldap.php', TRUE);
-
- $ldap = [
- 'timeout' => $this->config->item('timeout', 'ldap'),
- 'host' => $this->config->item('server', 'ldap'),
- 'port' => $this->config->item('port', 'ldap'),
- 'rdn' => $this->config->item('binduser', 'ldap'),
- 'pass' => $this->config->item('bindpw', 'ldap'),
- 'basedn' => $this->config->item('basedn', 'ldap'),
- ];
-
- log_message('debug', 'LDAP Auth: Connect to ' . (isset($ldaphost) ? $ldaphost : '[ldap not configured]'));
-
- // Connect to the ldap server
- $ldapconn = ldap_connect($ldap['host'], $ldap['port']);
- if ($ldapconn)
- {
- log_message('debug', 'Setting timeout to ' . $ldap['timeout'] . ' seconds');
-
- ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, $ldap['timeout']);
-
- log_message('debug', 'LDAP Auth: Binding to ' . $ldap['host'] . ' with dn ' . $ldap['rdn']);
-
- // Binding to the ldap server
- $ldapbind = ldap_bind($ldapconn, $ldap['rdn'], $ldap['pass']);
-
- // Verify the binding
- if ($ldapbind === FALSE)
- {
- log_message('error', 'LDAP Auth: bind was unsuccessful');
- return FALSE;
- }
-
- log_message('debug', 'LDAP Auth: bind successful');
- }
-
- // Search for user
- if (($res_id = ldap_search($ldapconn, $ldap['basedn'], "uid=$username")) === FALSE)
- {
- log_message('error', 'LDAP Auth: User ' . $username . ' not found in search');
- return FALSE;
- }
-
- if (ldap_count_entries($ldapconn, $res_id) !== 1)
- {
- log_message('error', 'LDAP Auth: Failure, username ' . $username . 'found more than once');
- return FALSE;
- }
-
- if (($entry_id = ldap_first_entry($ldapconn, $res_id)) === FALSE)
- {
- log_message('error', 'LDAP Auth: Failure, entry of search result could not be fetched');
- return FALSE;
- }
-
- if (($user_dn = ldap_get_dn($ldapconn, $entry_id)) === FALSE)
- {
- log_message('error', 'LDAP Auth: Failure, user-dn could not be fetched');
- return FALSE;
- }
-
- // User found, could not authenticate as user
- if (($link_id = ldap_bind($ldapconn, $user_dn, $password)) === FALSE)
- {
- log_message('error', 'LDAP Auth: Failure, username/password did not match: ' . $user_dn);
- return FALSE;
- }
-
- log_message('debug', 'LDAP Auth: Success ' . $user_dn . ' authenticated successfully');
-
- $this->_user_ldap_dn = $user_dn;
-
- ldap_close($ldapconn);
-
- return TRUE;
- }
-
- /**
- * Perform Library Authentication - Override this function to change the way the library is called
- *
- * @access protected
- * @param string $username The username to validate
- * @param string $password The password to validate
- * @return bool
- */
- protected function _perform_library_auth($username = '', $password = NULL)
- {
- if (empty($username))
- {
- log_message('error', 'Library Auth: Failure, empty username');
- return FALSE;
- }
-
- $auth_library_class = $this->config->item('auth_library_class');
- $auth_library_function = $this->config->item('auth_library_function');
-
- if (empty($auth_library_class))
- {
- log_message('debug', 'Library Auth: Failure, empty auth_library_class');
- return FALSE;
- }
-
- if (empty($auth_library_function))
- {
- log_message('debug', 'Library Auth: Failure, empty auth_library_function');
- return FALSE;
- }
-
- if (is_callable([$auth_library_class, $auth_library_function]) === FALSE)
- {
- $this->load->library($auth_library_class, array(false));
- }
-
- return $this->{strtolower($auth_library_class)}->$auth_library_function($username, $password);
- }
-
- /**
- * Check if the user is logged in
- *
- * @access protected
- * @param string $username The user's name
- * @param bool|string $password The user's password
- * @return bool
- */
- protected function _check_login($username = NULL, $password = FALSE)
- {
- if (empty($username))
- {
- return FALSE;
- }
-
- $auth_source = strtolower($this->config->item('auth_source'));
- $rest_auth = strtolower($this->config->item('rest_auth'));
- $valid_logins = $this->config->item('rest_valid_logins');
-
- if (!$this->config->item('auth_source') && $rest_auth === 'digest')
- {
- // For digest we do not have a password passed as argument
- return md5($username . ':' . $this->config->item('rest_realm') . ':' . (isset($valid_logins[$username]) ? $valid_logins[$username] : ''));
- }
-
- if ($password === FALSE)
- {
- return FALSE;
- }
-
- if ($auth_source === 'ldap')
- {
- log_message('debug', "Performing LDAP authentication for $username");
-
- return $this->_perform_ldap_auth($username, $password);
- }
-
- if ($auth_source === 'library')
- {
- log_message('debug', "Performing Library authentication for $username");
-
- return $this->_perform_library_auth($username, $password);
- }
-
- if (array_key_exists($username, $valid_logins) === FALSE)
- {
- return FALSE;
- }
-
- if ($valid_logins[$username] !== $password)
- {
- return FALSE;
- }
-
- return TRUE;
- }
-
- /**
- * Check to see if the user is logged in with a PHP session key
- *
- * @access protected
- * @return void
- */
- protected function _check_php_session()
- {
- // Get the auth_source config item
- $key = $this->config->item('auth_source');
-
- // If falsy, then the user isn't logged in
- if (!$this->session->userdata($key))
- {
- // Display an error response
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized')
- ], self::HTTP_UNAUTHORIZED);
- }
- }
-
- /**
- * Prepares for basic authentication
- *
- * @access protected
- * @return void
- */
- protected function _prepare_basic_auth()
- {
- // If whitelist is enabled it has the first chance to kick them out
- if ($this->config->item('rest_ip_whitelist_enabled'))
- {
- $this->_check_whitelist_auth();
- }
-
- // Returns NULL if the SERVER variables PHP_AUTH_USER and HTTP_AUTHENTICATION don't exist
- $username = $this->input->server('PHP_AUTH_USER');
- $http_auth = $this->input->server('HTTP_AUTHENTICATION');
-
- $password = NULL;
- if ($username !== NULL)
- {
- $password = $this->input->server('PHP_AUTH_PW');
- }
- elseif ($http_auth !== NULL)
- {
- // If the authentication header is set as basic, then extract the username and password from
- // HTTP_AUTHORIZATION e.g. my_username:my_password. This is passed in the .htaccess file
- if (strpos(strtolower($http_auth), 'basic') === 0)
- {
- // Search online for HTTP_AUTHORIZATION workaround to explain what this is doing
- list($username, $password) = explode(':', base64_decode(substr($this->input->server('HTTP_AUTHORIZATION'), 6)));
- }
- }
-
- // Check if the user is logged into the system
- if ($this->_check_login($username, $password) === FALSE)
- {
- $this->_force_login();
- }
- }
-
- /**
- * Prepares for digest authentication
- *
- * @access protected
- * @return void
- */
- protected function _prepare_digest_auth()
- {
- // If whitelist is enabled it has the first chance to kick them out
- if ($this->config->item('rest_ip_whitelist_enabled'))
- {
- $this->_check_whitelist_auth();
- }
-
- // We need to test which server authentication variable to use,
- // because the PHP ISAPI module in IIS acts different from CGI
- $digest_string = $this->input->server('PHP_AUTH_DIGEST');
- if ($digest_string === NULL)
- {
- $digest_string = $this->input->server('HTTP_AUTHORIZATION');
- }
-
- $unique_id = uniqid();
-
- // The $_SESSION['error_prompted'] variable is used to ask the password
- // again if none given or if the user enters wrong auth information
- if (empty($digest_string))
- {
- $this->_force_login($unique_id);
- }
-
- // We need to retrieve authentication data from the $digest_string variable
- $matches = [];
- preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches);
- $digest = (empty($matches[1]) || empty($matches[2])) ? [] : array_combine($matches[1], $matches[2]);
-
- // For digest authentication the library function should return
- // already stored password for that username, even if it is hashed
- $username = $this->_check_login($digest['username'], TRUE);
- // If there no password
- if (array_key_exists('username', $digest) === FALSE || $username === FALSE || $username === NULL)
- {
- $this->_force_login($unique_id);
- }
- // If the password was found for this username, generete the string md5('USERNAME:REALM:PASSWORD')
- else
- {
- $username = md5($digest['username'].":".$this->config->item('rest_realm').":".$username);
- }
-
- $md5 = md5(strtoupper($this->request->method) . ':' . $digest['uri']);
- $valid_response = md5($username . ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' . $md5);
-
- // Check if the string don't compare (case-insensitive)
- if (strcasecmp($digest['response'], $valid_response) !== 0)
- {
- // Display an error response
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_invalid_credentials')
- ], self::HTTP_UNAUTHORIZED);
- }
- }
-
- /**
- * Checks if the client's ip is in the 'rest_ip_blacklist' config and generates a 401 response
- *
- * @access protected
- * @return void
- */
- protected function _check_blacklist_auth()
- {
- // Match an ip address in a blacklist e.g. 127.0.0.0, 0.0.0.0
- $pattern = sprintf('/(?:,\s*|^)\Q%s\E(?=,\s*|$)/m', $this->input->ip_address());
-
- // Returns 1, 0 or FALSE (on error only). Therefore implicitly convert 1 to TRUE
- if (preg_match($pattern, $this->config->item('rest_ip_blacklist')))
- {
- // Display an error response
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_denied')
- ], self::HTTP_UNAUTHORIZED);
- }
- }
-
- /**
- * Check if the client's ip is in the 'rest_ip_whitelist' config and generates a 401 response
- *
- * @access protected
- * @return void
- */
- protected function _check_whitelist_auth()
- {
- $whitelist = explode(',', $this->config->item('rest_ip_whitelist'));
-
- array_push($whitelist, '127.0.0.1', '0.0.0.0');
-
- foreach ($whitelist as &$ip)
- {
- // As $ip is a reference, trim leading and trailing whitespace, then store the new value
- // using the reference
- $ip = trim($ip);
- }
-
- if (in_array($this->input->ip_address(), $whitelist) === FALSE)
- {
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_ip_unauthorized')
- ], self::HTTP_UNAUTHORIZED);
- }
- }
-
- /**
- * Force logging in by setting the WWW-Authenticate header
- *
- * @access protected
- * @param string $nonce A server-specified data string which should be uniquely generated
- * each time
- * @return void
- */
- protected function _force_login($nonce = '')
- {
- $rest_auth = $this->config->item('rest_auth');
- $rest_realm = $this->config->item('rest_realm');
- if (strtolower($rest_auth) === 'basic')
- {
- // See http://tools.ietf.org/html/rfc2617#page-5
- header('WWW-Authenticate: Basic realm="' . $rest_realm . '"');
- }
- elseif (strtolower($rest_auth) === 'digest')
- {
- // See http://tools.ietf.org/html/rfc2617#page-18
- header(
- 'WWW-Authenticate: Digest realm="' . $rest_realm
- . '", qop="auth", nonce="' . $nonce
- . '", opaque="' . md5($rest_realm) . '"');
- }
-
- // Display an error response
- $this->response([
- $this->config->item('rest_status_field_name') => FALSE,
- $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized')
- ], self::HTTP_UNAUTHORIZED);
- }
-
- /**
- * Updates the log table with the total access time
- *
- * @access protected
- * @author Chris Kacerguis
- * @return bool TRUE log table updated; otherwise, FALSE
- */
- protected function _log_access_time()
- {
- $payload['rtime'] = $this->_end_rtime - $this->_start_rtime;
-
- return $this->rest->db->update(
- $this->config->item('rest_logs_table'), $payload, [
- 'id' => $this->_insert_id
- ]);
- }
-
- /**
- * Updates the log table with HTTP response code
- *
- * @access protected
- * @author Justin Chen
- * @param $http_code int HTTP status code
- * @return bool TRUE log table updated; otherwise, FALSE
- */
- protected function _log_response_code($http_code)
- {
- $payload['response_code'] = $http_code;
-
- return $this->rest->db->update(
- $this->config->item('rest_logs_table'), $payload, [
- 'id' => $this->_insert_id
- ]);
- }
-
- /**
- * Check to see if the API key has access to the controller and methods
- *
- * @access protected
- * @return bool TRUE the API key has access; otherwise, FALSE
- */
- protected function _check_access()
- {
- // If we don't want to check access, just return TRUE
- if ($this->config->item('rest_enable_access') === FALSE)
- {
- return TRUE;
- }
-
- // Fetch controller based on path and controller name
- $controller = implode(
- '/', [
- $this->router->directory,
- $this->router->class
- ]);
-
- // Remove any double slashes for safety
- $controller = str_replace('//', '/', $controller);
-
- // Query the access table and get the number of results
- return $this->rest->db
- ->where('key', $this->rest->key)
- ->where('controller', $controller)
- ->get($this->config->item('rest_access_table'))
- ->num_rows() > 0;
- }
-}
diff --git a/application/helpers/hlp_authentication_helper.php b/application/helpers/hlp_authentication_helper.php
index 740823ff9..194f0b249 100644
--- a/application/helpers/hlp_authentication_helper.php
+++ b/application/helpers/hlp_authentication_helper.php
@@ -34,3 +34,31 @@ function getAuthUID()
return isLogged() ? ($ci->authlib->getAuthObj())->{AuthLib::AO_USERNAME} : null;
}
+
+/**
+ * If the user is NOT logged then a null value is returned.
+ * If the user is alredy logged, then it is possible to access to the authentication object
+ * that contains the firstname of the logged user
+ * NOTE: if the user is logged with a "foreign" method (ex. Bewerbungstool),
+ * then it is possible that the firstname is null!
+ */
+function getAuthFirstname()
+{
+ $ci =& get_instance(); // get CI instance
+
+ return isLogged() ? ($ci->authlib->getAuthObj())->{AuthLib::AO_NAME} : null;
+}
+
+/**
+ * If the user is NOT logged then a null value is returned.
+ * If the user is alredy logged, then it is possible to access to the authentication object
+ * that contains the surname of the logged user
+ * NOTE: if the user is logged with a "foreign" method (ex. Bewerbungstool),
+ * then it is possible that the surname is null!
+ */
+function getAuthSurname()
+{
+ $ci =& get_instance(); // get CI instance
+
+ return isLogged() ? ($ci->authlib->getAuthObj())->{AuthLib::AO_SURNAME} : null;
+}
diff --git a/application/helpers/hlp_header_helper.php b/application/helpers/hlp_header_helper.php
index 611325722..1a0d9dc49 100644
--- a/application/helpers/hlp_header_helper.php
+++ b/application/helpers/hlp_header_helper.php
@@ -46,13 +46,16 @@ function generateCSSsInclude($CSSs)
{
$cssLink = '';
+ $ci =& get_instance();
+ $cachetoken = '?'.$ci->config->item('fhcomplete_build_version');
+
if (isset($CSSs))
{
$tmpCSSs = is_array($CSSs) ? $CSSs : array($CSSs);
for ($tmpCSSsCounter = 0; $tmpCSSsCounter < count($tmpCSSs); $tmpCSSsCounter++)
{
- $toPrint = sprintf($cssLink, base_url($tmpCSSs[$tmpCSSsCounter])).PHP_EOL;
+ $toPrint = sprintf($cssLink, base_url($tmpCSSs[$tmpCSSsCounter]).$cachetoken).PHP_EOL;
if ($tmpCSSsCounter > 0) $toPrint = "\t\t".$toPrint;
@@ -108,13 +111,16 @@ function generateJSsInclude($JSs)
{
$jsInclude = '';
+ $ci =& get_instance();
+ $cachetoken = '?'.$ci->config->item('fhcomplete_build_version');
+
if (isset($JSs))
{
$tmpJSs = is_array($JSs) ? $JSs : array($JSs);
for ($tmpJSsCounter = 0; $tmpJSsCounter < count($tmpJSs); $tmpJSsCounter++)
{
- $toPrint = sprintf($jsInclude, base_url($tmpJSs[$tmpJSsCounter])).PHP_EOL;
+ $toPrint = sprintf($jsInclude, base_url($tmpJSs[$tmpJSsCounter].$cachetoken)).PHP_EOL;
if ($tmpJSsCounter > 0) $toPrint = "\t\t".$toPrint;
diff --git a/application/language/english/rest_controller_lang.php b/application/language/english/rest_controller_lang.php
deleted file mode 100644
index 1c665bdc5..000000000
--- a/application/language/english/rest_controller_lang.php
+++ /dev/null
@@ -1,17 +0,0 @@
-_ci =& get_instance(); // Gets CI instance
- }
-
- /**
- * Wrapper method for _call
- */
- public function callLibrary($callParameters)
- {
- return $this->_call($callParameters);
- }
-
- /**
- * Wrapper method for _call
- */
- public function callModel($callParameters)
- {
- return $this->_call($callParameters);
- }
-
- /**
- * Everything starts here...
- */
- private function _call($callParameters)
- {
- $result = null;
- $parameters = $this->_getParameters($callParameters);
- $validation = $this->_validateCall($parameters);
-
- // If the validation was passed
- if (isSuccess($validation))
- {
- $loaded = null;
- // If the given resource is a model
- if (strpos($parameters->resourceName, CallerLib::MODEL_PREFIX) !== false)
- {
- // Try to load the model
- $result = $this->_loadModel($parameters->resourcePath, $parameters->resourceName);
- if (isSuccess($result))
- {
- $loaded = $result->retval;
- }
- }
- // If the given resource is a library
- elseif (strpos($parameters->resourceName, CallerLib::LIB_PREFIX) !== false)
- {
- // Check if the resource is already loaded, it works only with libraries and drivers
- $isLoaded = $this->_ci->load->is_loaded($parameters->resourceName);
- // If not loaded then load it
- if ($isLoaded === false)
- {
- // Try to load the library
- $result = $this->_loadLibrary($parameters->resourcePath, $parameters->resourceName);
- if (isSuccess($result))
- {
- $loaded = $result->retval;
- }
- }
- // If it is already loaded $isLoaded contains the instance of the library
- else
- {
- $loaded = $isLoaded;
- }
- }
- // Wrong selection!
- else
- {
- $result = error('Neither a lib nor model: '.$parameters->resourcePath.$parameters->resourceName);
- }
-
- // If the resource was found and loaded
- if (!is_null($loaded))
- {
- $result = $this->_callThis($parameters->resourceName, $parameters->function, $parameters->parameters);
- }
- else
- {
- // Resource not loaded
- }
- }
- else
- {
- $result = $validation;
- }
-
- return $result;
- }
-
- /**
- * Gets the parameters from the http call
- * Search for parameters and
- * is the name of the model or of the library
- * is the name of the method present in the model/library
- * All the others parameters will be given to the method in the same order that
- * they are present in the HTTP call
- * EX:
- * URL: ../system/CallerLibrary/Call?resource=&function=&=&=&=
- * will call .(par1, par2, par3)
- */
- private function _getParameters($parametersArray)
- {
- $parameters = new stdClass();
- $parameters->parameters = array();
- $count = 0;
-
- foreach ($parametersArray as $parameterName => $parameterValue)
- {
- // The name of the resource, path included
- if ($parameterName == CallerLib::RESOURCE_PARAMETER)
- {
- // Separates the resource path from the resource name
- $splittedResource = preg_split(CallerLib::REG_SPLIT_EXPR, $parameterValue);
- $parameters->resourceName = $splittedResource[count($splittedResource) - 1];
- $parameters->resourcePath = str_replace($parameters->resourceName, '', $parameterValue);
- }
- // The name of the function
- elseif ($parameterName == CallerLib::FUNCTION_PARAMETER)
- {
- $parameters->function = $parameterValue;
- }
- // It is assumed that all other parameters are the parameters to be passed to the function
- // They will be passed to the function in the same order in which they are passed to
- // this controller
- else
- {
- $parameters->parameters[$count++] = $parameterValue;
- }
- }
-
- return $parameters;
- }
-
- /**
- * Validate the given parameters
- */
- private function _validateCall($parameters)
- {
- if (!is_object($parameters))
- {
- return error('Parameter is not an object');
- }
- if (!isset($parameters->resourcePath))
- {
- return error('Resource path is not specified');
- }
- if (!isset($parameters->resourceName))
- {
- return error('Resource name is not specified');
- }
- if (!isset($parameters->function))
- {
- return error('Function is not specified');
- }
- if (!is_array($parameters->parameters))
- {
- return error('Parameters are not specified');
- }
- if (in_array($parameters->resourceName, CallerLib::$RESOURCES_BLACK_LIST))
- {
- return error('You are trying to access to unauthorized resources');
- }
-
- return success('Input data are valid');
- }
-
- /**
- * Loads a model using the given path and name
- *
- * NOTE: the models automatically handle the permissions
- */
- private function _loadModel($resourcePath, $resourceName)
- {
- $loaded = null;
- $result = null;
-
- try
- {
- $loaded = $this->_ci->load->model($resourcePath.$resourceName);
- }
- catch (Exception $e)
- {
- // Errors while loading the model
- $result = error('Errors while loading the model: '.$e->getMessage());
- }
-
- if (!is_null($loaded))
- {
- $result = success($loaded);
- }
-
- return $result;
- }
-
- /**
- * Loads a library using the given path and name
- *
- * The method 'library' of the class CI_Loader provided by CI has some limitations,
- * so to be able to check errors was used a workaround.
- * It consists in:
- * - Checking if the file (identified by parameters $resourcePath and $resourceName) exists
- * - If exists it will be loaded using the method 'file' from CI_Loader
- * - Checks if the loaded file contains a class identified by parameter $resourceName
- *
- * If one of the previous tests fails, it will be returned a null value
- */
- private function _loadLibrary($resourcePath, $resourceName)
- {
- $loaded = null;
-
- try
- {
- // Gets all the configured resources paths
- $packagePaths = $this->_ci->load->get_package_paths();
- // Looking for a file in every paths with the same name of the resource
- $found = null;
- for ($i = 0; $i < count($packagePaths) && is_null($found); $i++)
- {
- $file = $packagePaths[$i].CallerLib::LIBS_PATH.DIRECTORY_SEPARATOR.
- $resourcePath.$resourceName.CallerLib::LIB_FILE_EXTENSION;
- if (file_exists($file))
- {
- $found = $file;
- }
- }
-
- // If the file was found
- if (!is_null($found))
- {
- // Load the file
- $loaded = $this->_ci->load->file($found);
- // If the resource is not present inside the file
- if (!class_exists($resourceName))
- {
- $loaded = null;
- // Same phrase error as load->model() provided by CI
- $result = error($found.' exists, but doesn\'t declare class '.$resourceName);
- }
- }
- else
- {
- $loaded = null;
- // Same phrase error as load->model() provided by CI
- $result = error('Unable to load the requested class: '.$resourceName);
- }
- }
- catch (Exception $e)
- {
- // Errors while loading the library
- $result = error('Errors while loading the library: '.$e->getMessage());
- }
-
- if (!is_null($loaded))
- {
- $result = success($loaded);
- }
-
- return $result;
- }
-
- /**
- * Calls a method of a class with the given parameters and returns its result
- *
- * @param string $resourceName identifies the class name
- * @param string $function identifies the method name
- * @param array $parameters contains the parameters to be passed to the method
- */
- private function _callThis($resourceName, $function, $parameters)
- {
- $result = null;
-
- try
- {
- // Get informations about the function
- $reflectionMethod = new ReflectionMethod($resourceName, $function);
- // If the number of given parameters is greater or equal to the number of
- // parameters required by the function
- if (count($parameters) >= $reflectionMethod->getNumberOfRequiredParameters())
- {
- // If the function is static
- if ($reflectionMethod->isStatic() === true)
- {
- $classMethod = $resourceName.'::'.$function;
- }
- // If the function is not static
- else
- {
- $classMethod = array(new $resourceName(), $function);
- }
-
- // If the resource's function is callable
- if (is_callable($classMethod))
- {
- // Call resource->function()
- // @ was applied to prevent really ugly and unmanageable errors
- $resultCall = @call_user_func_array($classMethod, $parameters);
- // If errors occurred while running it
- // NOTE: if the called function via call_user_func_array returns a boolean set as false,
- // it will be recognized like a running error. A little bit tricky ;)
- if ($resultCall === false)
- {
- $result = error('Error running '.$resourceName.'->'.$function.'()');
- }
- // Returns the result of resource->function()
- else
- {
- $result = success($resultCall);
- }
- }
- else
- {
- $result = error($resourceName.'->'.$function.'() is not callable!');
- }
- }
- else
- {
- $result = error(
- 'Number of required parameters: '.$reflectionMethod->getNumberOfRequiredParameters().'. Given: '.count($parameters)
- );
- }
- }
- catch (Exception $e)
- {
- $result = error($e->getMessage());
- }
-
- return $result;
- }
-}
diff --git a/application/libraries/FilterWidgetLib.php b/application/libraries/FilterWidgetLib.php
index 23453a56f..0117377a5 100644
--- a/application/libraries/FilterWidgetLib.php
+++ b/application/libraries/FilterWidgetLib.php
@@ -532,6 +532,14 @@ class FilterWidgetLib
return $applyFilters;
}
+ /**
+ * Reloads dataset by setting session variable to true
+ */
+ public function reloadDataset()
+ {
+ $this->setSessionElement(self::SESSION_RELOAD_DATASET, true);
+ }
+
/**
* Add a filter (SQL where clause) to be applied to the current filter
*/
@@ -795,32 +803,7 @@ class FilterWidgetLib
$filterUniqueId = $this->_ci->router->directory.$this->_ci->router->class.'/'.$this->_ci->router->method;
}
- if ($params != null
- && is_array($params)
- && (isset($params[self::APP_PARAMETER]) || isset($params[self::DATASET_NAME_PARAMETER]) || isset($params[self::FILTER_ID])))
- {
- $app = '';
- $dataset = '';
- $filterid = '';
-
- if (isset($params[self::APP_PARAMETER])) $app = $params[self::APP_PARAMETER];
- if (isset($params[self::DATASET_NAME_PARAMETER])) $dataset = $params[self::DATASET_NAME_PARAMETER];
- if (isset($params[self::FILTER_ID])) $filterid = $params[self::FILTER_ID];
-
- $filterUniqueId .= '/'.$app.':'.$dataset.':'.$filterid;
- }
-
- // If the FHC_CONTROLLER_ID parameter is present in the HTTP GET
- if (isset($_GET[self::FHC_CONTROLLER_ID]))
- {
- $filterUniqueId .= '/'.$this->_ci->input->get(self::FHC_CONTROLLER_ID); // then use it
- }
- elseif (isset($_POST[self::FHC_CONTROLLER_ID])) // else if the FHC_CONTROLLER_ID parameter is present in the HTTP POST
- {
- $filterUniqueId .= '/'.$this->_ci->input->post(self::FHC_CONTROLLER_ID); // then use it
- }
-
- $this->_filterUniqueId = $filterUniqueId;
+ $this->setFilterUniqueId($filterUniqueId);
}
/**
diff --git a/application/libraries/Format.php b/application/libraries/Format.php
deleted file mode 100644
index 0f7ea4a87..000000000
--- a/application/libraries/Format.php
+++ /dev/null
@@ -1,531 +0,0 @@
-_CI = &get_instance();
-
- // Load the inflector helper
- $this->_CI->load->helper('inflector');
-
- // If the provided data is already formatted we should probably convert it to an array
- if ($from_type !== NULL)
- {
- if (method_exists($this, '_from_' . $from_type))
- {
- $data = call_user_func([$this, '_from_' . $from_type], $data);
- }
- else
- {
- throw new Exception('Format class does not support conversion from "' . $from_type . '".');
- }
- }
-
- // Set the member variable to the data passed
- $this->_data = $data;
- }
-
- /**
- * Create an instance of the format class
- * e.g: echo $this->format->factory(['foo' => 'bar'])->to_csv();
- *
- * @param mixed $data Data to convert/parse
- * @param string $from_type Type to convert from e.g. json, csv, html
- *
- * @return object Instance of the format class
- */
- public function factory($data, $from_type = NULL)
- {
- // $class = __CLASS__;
- // return new $class();
-
- return new static($data, $from_type);
- }
-
- // FORMATTING OUTPUT ---------------------------------------------------------
-
- /**
- * Format data as an array
- *
- * @param mixed|NULL $data Optional data to pass, so as to override the data passed
- * to the constructor
- * @return array Data parsed as an array; otherwise, an empty array
- */
- public function to_array($data = NULL)
- {
- // If no data is passed as a parameter, then use the data passed
- // via the constructor
- if ($data === NULL && func_num_args() === 0)
- {
- $data = $this->_data;
- }
-
- // Cast as an array if not already
- if (is_array($data) === FALSE)
- {
- $data = (array) $data;
- }
-
- $array = [];
- foreach ((array) $data as $key => $value)
- {
- if (is_object($value) === TRUE || is_array($value) === TRUE)
- {
- $array[$key] = $this->to_array($value);
- }
- else
- {
- $array[$key] = $value;
- }
- }
-
- return $array;
- }
-
- /**
- * Format data as XML
- *
- * @param mixed|NULL $data Optional data to pass, so as to override the data passed
- * to the constructor
- * @param NULL $structure
- * @param string $basenode
- * @return mixed
- */
- public function to_xml($data = NULL, $structure = NULL, $basenode = 'xml')
- {
- if ($data === NULL && func_num_args() === 0)
- {
- $data = $this->_data;
- }
-
- // 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) === FALSE && is_object($data) === FALSE)
- {
- $data = (array) $data;
- }
-
- foreach ($data as $key => $value)
- {
-
- //change false/true to 0/1
- if (is_bool($value))
- {
- $value = (int) $value;
- }
-
- // no numeric keys in our xml please!
- if (is_numeric($key))
- {
- // make string key...
- $key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
- }
-
- // replace anything not alpha numeric
- $key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
-
- if ($key === '_attributes' && (is_array($value) || is_object($value)))
- {
- $attributes = $value;
- if (is_object($attributes))
- {
- $attributes = get_object_vars($attributes);
- }
-
- foreach ($attributes as $attribute_name => $attribute_value)
- {
- $structure->addAttribute($attribute_name, $attribute_value);
- }
- }
- // if there is another array found recursively call this function
- elseif (is_array($value) || is_object($value))
- {
- $node = $structure->addChild($key);
-
- // recursive call.
- $this->to_xml($value, $node, $key);
- }
- else
- {
- // add single node.
- $value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
-
- $structure->addChild($key, $value);
- }
- }
-
- return $structure->asXML();
- }
-
- /**
- * Format data as HTML
- *
- * @param mixed|NULL $data Optional data to pass, so as to override the data passed
- * to the constructor
- * @return mixed
- */
- public function to_html($data = NULL)
- {
- // If no data is passed as a parameter, then use the data passed
- // via the constructor
- if ($data === NULL && func_num_args() === 0)
- {
- $data = $this->_data;
- }
-
- // Cast as an array if not already
- if (is_array($data) === FALSE)
- {
- $data = (array) $data;
- }
-
- // Check if it's a multi-dimensional array
- if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE))
- {
- // Multi-dimensional array
- $headings = array_keys($data[0]);
- }
- else
- {
- // Single array
- $headings = array_keys($data);
- $data = [$data];
- }
-
- // Load the table library
- $this->_CI->load->library('table');
-
- $this->_CI->table->set_heading($headings);
-
- foreach ($data as $row)
- {
- // Suppressing the "array to string conversion" notice
- // Keep the "evil" @ here
- $row = @array_map('strval', $row);
-
- $this->_CI->table->add_row($row);
- }
-
- return $this->_CI->table->generate();
- }
-
- /**
- * @link http://www.metashock.de/2014/02/create-csv-file-in-memory-php/
- * @param mixed|NULL $data Optional data to pass, so as to override the data passed
- * to the constructor
- * @param string $delimiter The optional delimiter parameter sets the field
- * delimiter (one character only). NULL will use the default value (,)
- * @param string $enclosure The optional enclosure parameter sets the field
- * enclosure (one character only). NULL will use the default value (")
- * @return string A csv string
- */
- public function to_csv($data = NULL, $delimiter = ',', $enclosure = '"')
- {
- // Use a threshold of 1 MB (1024 * 1024)
- $handle = fopen('php://temp/maxmemory:1048576', 'w');
- if ($handle === FALSE)
- {
- return NULL;
- }
-
- // If no data is passed as a parameter, then use the data passed
- // via the constructor
- if ($data === NULL && func_num_args() === 0)
- {
- $data = $this->_data;
- }
-
- // If NULL, then set as the default delimiter
- if ($delimiter === NULL)
- {
- $delimiter = ',';
- }
-
- // If NULL, then set as the default enclosure
- if ($enclosure === NULL)
- {
- $enclosure = '"';
- }
-
- // Cast as an array if not already
- if (is_array($data) === FALSE)
- {
- $data = (array) $data;
- }
-
- // Check if it's a multi-dimensional array
- if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE))
- {
- // Multi-dimensional array
- $headings = array_keys($data[0]);
- }
- else
- {
- // Single array
- $headings = array_keys($data);
- $data = [$data];
- }
-
- // Apply the headings
- fputcsv($handle, $headings, $delimiter, $enclosure);
-
- foreach ($data as $record)
- {
- // If the record is not an array, then break. This is because the 2nd param of
- // fputcsv() should be an array
- if (is_array($record) === FALSE)
- {
- break;
- }
-
- // Suppressing the "array to string conversion" notice.
- // Keep the "evil" @ here.
- $record = @ array_map('strval', $record);
-
- // Returns the length of the string written or FALSE
- fputcsv($handle, $record, $delimiter, $enclosure);
- }
-
- // Reset the file pointer
- rewind($handle);
-
- // Retrieve the csv contents
- $csv = stream_get_contents($handle);
-
- // Close the handle
- fclose($handle);
-
- return $csv;
- }
-
- /**
- * Encode data as json
- *
- * @param mixed|NULL $data Optional data to pass, so as to override the data passed
- * to the constructor
- * @return string Json representation of a value
- */
- public function to_json($data = NULL)
- {
- // If no data is passed as a parameter, then use the data passed
- // via the constructor
- if ($data === NULL && func_num_args() === 0)
- {
- $data = $this->_data;
- }
-
- // Get the callback parameter (if set)
- $callback = $this->_CI->input->get('callback');
-
- if (empty($callback) === TRUE)
- {
- return json_encode($data);
- }
-
- // We only honour a jsonp callback which are valid javascript identifiers
- elseif (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback))
- {
- // Return the data as encoded json with a callback
- return $callback . '(' . json_encode($data) . ');';
- }
-
- // An invalid jsonp callback function provided.
- // Though I don't believe this should be hardcoded here
- $data['warning'] = 'INVALID JSONP CALLBACK: ' . $callback;
-
- return json_encode($data);
- }
-
- /**
- * Encode data as a serialized array
- *
- * @param mixed|NULL $data Optional data to pass, so as to override the data passed
- * to the constructor
- * @return string Serialized data
- */
- public function to_serialized($data = NULL)
- {
- // If no data is passed as a parameter, then use the data passed
- // via the constructor
- if ($data === NULL && func_num_args() === 0)
- {
- $data = $this->_data;
- }
-
- return serialize($data);
- }
-
- /**
- * Format data using a PHP structure
- *
- * @param mixed|NULL $data Optional data to pass, so as to override the data passed
- * to the constructor
- * @return mixed String representation of a variable
- */
- public function to_php($data = NULL)
- {
- // If no data is passed as a parameter, then use the data passed
- // via the constructor
- if ($data === NULL && func_num_args() === 0)
- {
- $data = $this->_data;
- }
-
- return var_export($data, TRUE);
- }
-
- // INTERNAL FUNCTIONS
-
- /**
- * @param $data XML string
- * @return SimpleXMLElement XML element object; otherwise, empty array
- */
- protected function _from_xml($data)
- {
- return $data ? (array) simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA) : [];
- }
-
- /**
- * @param string $data CSV string
- * @param string $delimiter The optional delimiter parameter sets the field
- * delimiter (one character only). NULL will use the default value (,)
- * @param string $enclosure The optional enclosure parameter sets the field
- * enclosure (one character only). NULL will use the default value (")
- * @return array A multi-dimensional array with the outer array being the number of rows
- * and the inner arrays the individual fields
- */
- protected function _from_csv($data, $delimiter = ',', $enclosure = '"')
- {
- // If NULL, then set as the default delimiter
- if ($delimiter === NULL)
- {
- $delimiter = ',';
- }
-
- // If NULL, then set as the default enclosure
- if ($enclosure === NULL)
- {
- $enclosure = '"';
- }
-
- return str_getcsv($data, $delimiter, $enclosure);
- }
-
- /**
- * @param $data Encoded json string
- * @return mixed Decoded json string with leading and trailing whitespace removed
- */
- protected function _from_json($data)
- {
- return json_decode(trim($data));
- }
-
- /**
- * @param string Data to unserialized
- * @return mixed Unserialized data
- */
- protected function _from_serialize($data)
- {
- return unserialize(trim($data));
- }
-
- /**
- * @param $data Data to trim leading and trailing whitespace
- * @return string Data with leading and trailing whitespace removed
- */
- protected function _from_php($data)
- {
- return trim($data);
- }
-
-}
diff --git a/application/libraries/LogLib.php b/application/libraries/LogLib.php
index cb0541003..b98575150 100644
--- a/application/libraries/LogLib.php
+++ b/application/libraries/LogLib.php
@@ -1,102 +1,252 @@
';
const LINE_SEPARATOR = ':';
- // --------------------------------------------------------------------------------------------------------------
- // Public methods
+ // CodeIgniter configuration log entry name and log debug value
+ const CI_LOG_THRESHOLD_NAME = 'log_threshold';
+ const CI_LOG_THRESHOLD_DEBUG = 2;
+
+ // LogLib parameters names
+ const P_NAME_CLASS_INDEX = 'classIndex';
+ const P_NAME_FUNCTION_INDEX = 'functionIndex';
+ const P_NAME_LINE_INDEX = 'lineIndex';
+ const P_NAME_DB_LOG_TYPE = 'dbLogType';
+ const P_NAME_DB_EXECUTE_USER = 'dbExecuteUser';
+
+ // Properties used to retrieve caller data
+ private $_classIndex;
+ private $_functionIndex;
+ private $_lineIndex;
+
+ // Properties used when logging to database
+ private $_dbLogType;
+ private $_dbExecuteUser;
/**
- * logDebug
+ * Set properties to a default value or overwrites them with the given parameters
+ */
+ public function __construct($params = null)
+ {
+ // Properties default values
+ $this->_classIndex = self::CLASS_INDEX;
+ $this->_functionIndex = self::FUNCTION_INDEX;
+ $this->_lineIndex = self::LINE_INDEX;
+ $this->_dbLogType = null;
+ $this->_dbExecuteUser = self::DB_EXECUTE_USER;
+
+ // If parameters are given then overwrite the default values
+ if (!isEmptyArray($params))
+ {
+ if (isset($params[self::P_NAME_CLASS_INDEX])) $this->_classIndex = $params[self::P_NAME_CLASS_INDEX];
+ if (isset($params[self::P_NAME_FUNCTION_INDEX])) $this->_functionIndex = $params[self::P_NAME_FUNCTION_INDEX];
+ if (isset($params[self::P_NAME_LINE_INDEX])) $this->_lineIndex = $params[self::P_NAME_LINE_INDEX];
+ if (isset($params[self::P_NAME_DB_LOG_TYPE])) $this->_dbLogType = $params[self::P_NAME_DB_LOG_TYPE];
+ if (isset($params[self::P_NAME_DB_EXECUTE_USER])) $this->_dbExecuteUser = $params[self::P_NAME_DB_EXECUTE_USER];
+ }
+ }
+
+ // --------------------------------------------------------------------------------------------------------------
+ // Public methods based on CodeIgniter log system
+
+ /**
+ * Writes a debug log to CodeIgniter log
*/
public function logDebug($message)
{
- $this->_log(LogLib::DEBUG, $message);
+ $this->_log(self::DEBUG, $message);
}
/**
- * logInfo
+ * Writes an info log to CodeIgniter log
*/
public function logInfo($message)
{
- $this->_log(LogLib::INFO, $message);
+ $this->_log(self::INFO, $message);
}
/**
- * logError
+ * Writes an error log to CodeIgniter log
*/
public function logError($message)
{
- $this->_log(LogLib::ERROR, $message);
+ $this->_log(self::ERROR, $message);
+ }
+
+ // --------------------------------------------------------------------------------------------------------------
+ // Public methods based on database
+
+ /**
+ * Writes an info log to database
+ */
+ public function logInfoDB($requestId, $data)
+ {
+ $this->_logDB(self::INFO, $requestId, $data);
+ }
+
+ /**
+ * Writes a debug log to database
+ */
+ public function logDebugDB($requestId, $data)
+ {
+ $this->_logDB(self::DEBUG, $requestId, $data);
+ }
+
+ /**
+ * Writes an warning log to database
+ */
+ public function logWarningDB($requestId, $data)
+ {
+ $this->_logDB(self::WARNING, $requestId, $data);
+ }
+
+ /**
+ * Writes an error log to database
+ */
+ public function logErrorDB($requestId, $data)
+ {
+ $this->_logDB(self::ERROR, $requestId, $data);
}
// --------------------------------------------------------------------------------------------------------------
// Private methods
/**
- * log
+ * Writes using CodeIgniter log system (file system)
*/
private function _log($level, $message)
{
- log_message($level, $this->_getCaller().$message);
+ log_message($level, $this->_getPrefix($this->_getCaller()).$message);
}
/**
- * _getCaller
+ * Writes logs to database
+ */
+ private function _logDB($level, $requestId, $data)
+ {
+ // If the _dbLogType parameter was not given when this library was loaded
+ // NOTE: this message will be displayed only to the developer AND stops the execution
+ if ($this->_dbLogType == null)
+ {
+ show_error('To log to database you need to specify the "'.self::P_NAME_DB_LOG_TYPE.'" parameter when the LogLib is loaded');
+ }
+
+ $ci =& get_instance(); // get code igniter instance
+
+ // If only debug log is enabed then is possible to write a debug log, otherwise...
+ if ($level == self::DEBUG && $ci->config->item(self::CI_LOG_THRESHOLD_NAME) != self::CI_LOG_THRESHOLD_DEBUG)
+ {
+ // ...do nothing
+ }
+ else
+ {
+ // Loads WebservicelogModel
+ $ci->load->model('system/Webservicelog_model', 'WebservicelogModel');
+
+ // Get caller data
+ $callerData = $this->_getCaller();
+
+ // Writes a log to database
+ $ci->WebservicelogModel->insert(array(
+ 'webservicetyp_kurzbz' => $this->_dbLogType,
+ 'request_id' => $requestId,
+ 'beschreibung' => $this->_getDatabaseDescription($callerData),
+ 'request_data' => $data,
+ 'execute_user' => $this->_dbExecuteUser,
+ 'execute_time' => 'NOW()' // current time
+ ));
+ }
+ }
+
+ /**
+ * Retrieves caller's data
*/
private function _getCaller()
{
- $classIndex = 3;
- $functionIndex = 3;
- $lineIndex = 2;
$class = '';
$function = '';
$line = '';
$backtrace_arr = debug_backtrace();
- if (isset($backtrace_arr[$classIndex]['class']) && $backtrace_arr[$classIndex]['class'] != '')
+
+ if (isset($backtrace_arr[$this->_classIndex]['class']) && $backtrace_arr[$this->_classIndex]['class'] != '')
{
- $class = $backtrace_arr[$classIndex]['class'];
+ $class = $backtrace_arr[$this->_classIndex]['class'];
}
- if (isset($backtrace_arr[$functionIndex]['function']) && $backtrace_arr[$functionIndex]['function'] != '')
+ if (isset($backtrace_arr[$this->_functionIndex]['function']) && $backtrace_arr[$this->_functionIndex]['function'] != '')
{
- $function = $backtrace_arr[$functionIndex]['function'];
+ $function = $backtrace_arr[$this->_functionIndex]['function'];
}
- if (isset($backtrace_arr[$lineIndex]['line']) && $backtrace_arr[$lineIndex]['line'] != '')
+ if (isset($backtrace_arr[$this->_lineIndex]['line']) && $backtrace_arr[$this->_lineIndex]['line'] != '')
{
- $line = $backtrace_arr[$lineIndex]['line'];
+ $line = $backtrace_arr[$this->_lineIndex]['line'];
}
- return $this->_format($class, $function, $line);
+ return array(
+ self::CLASS_NAME => $class,
+ self::FUNCTION_NAME => $function,
+ self::CODE_LINE => $line
+ );
}
/**
- * format
+ * Formats the log message prefix (file system based)
*/
- private function _format($class, $function, $line)
+ private function _getPrefix($callerData)
{
- $formatted = LogLib::CALLER_PREFIX;
+ $formatted = self::CALLER_PREFIX;
- if (!is_null($class) && $class != '')
+ if (!isEmptyString($callerData[self::CLASS_NAME]))
{
- $formatted .= $class.LogLib::CLASS_POSTFIX;
+ $formatted .= $callerData[self::CLASS_NAME].self::CLASS_POSTFIX;
}
- $formatted .= $function.LogLib::LINE_SEPARATOR.$line.LogLib::CALLER_POSTFIX.' ';
+ $formatted .= $callerData[self::FUNCTION_NAME].self::LINE_SEPARATOR.$callerData[self::CODE_LINE].self::CALLER_POSTFIX.' ';
+
+ return $formatted;
+ }
+
+ /**
+ * Formats the database description for a log
+ */
+ private function _getDatabaseDescription($callerData)
+ {
+ $formatted = $callerData[self::FUNCTION_NAME].self::LINE_SEPARATOR.$callerData[self::CODE_LINE];
+
+ if (!isEmptyString($callerData[self::CLASS_NAME]))
+ {
+ $formatted = $callerData[self::CLASS_NAME].self::CLASS_POSTFIX.$formatted;
+ }
return $formatted;
}
diff --git a/application/libraries/MigrationLib.php b/application/libraries/MigrationLib.php
deleted file mode 100644
index a461d7a82..000000000
--- a/application/libraries/MigrationLib.php
+++ /dev/null
@@ -1,466 +0,0 @@
-load->library('EPrintfLib');
- }
-
- /**
- * Check if a column exists in a table and schema
- */
- private function columnExists($name, $schema, $table)
- {
- $query = sprintf("SELECT %s FROM %s.%s LIMIT 1", $name, $schema, $table);
-
- if (@$this->db->simple_query($query))
- {
- return true;
- }
-
- return false;
- }
-
- /**
- * Print an info about the starting of method up
- */
- protected function startUP()
- {
- $this->eprintflib->printInfo(
- sprintf("%s Start method up of class %s %s", EPrintfLib::SEPARATOR, get_called_class(), EPrintfLib::SEPARATOR)
- );
- }
-
- /**
- * Print an info about the ending of method up
- */
- protected function endUP()
- {
- $this->eprintflib->printInfo(
- sprintf("%s End method up of class %s %s", EPrintfLib::SEPARATOR, get_called_class(), EPrintfLib::SEPARATOR)
- );
- }
-
- /**
- * Print an info about the starting of method down
- */
- protected function startDown()
- {
- $this->eprintflib->printInfo(
- sprintf("%s Start method down of class %s %s", EPrintfLib::SEPARATOR, get_called_class(), EPrintfLib::SEPARATOR)
- );
- }
-
- /**
- * Print an info about the ending of method down
- */
- protected function endDown()
- {
- $this->eprintflib->printInfo(
- sprintf("%s End method down of class %s %s", EPrintfLib::SEPARATOR, get_called_class(), EPrintfLib::SEPARATOR)
- );
- }
-
- /**
- * Adds a column, with attributes, to a table and schema
- */
- protected function addColumn($schema, $table, $fields)
- {
- foreach ($fields as $name => $definition)
- {
- if (!$this->columnExists($name, $schema, $table))
- {
- if ($this->dbforge->add_column($schema.'.'.$table, array($name => $definition)))
- {
- $this->eprintflib->printMessage(sprintf("Column %s.%s.%s of type %s added", $schema, $table, $name, $definition["type"]));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Error while adding column %s.%s.%s of type %s", $schema, $table, $name, $definition["type"]));
- }
- }
- else
- {
- $this->eprintflib->printInfo(sprintf("Column %s.%s.%s already exists", $schema, $table, $name));
- }
- }
- }
-
- /**
- * Modifies a column, and its attributes, of a table and schema
- */
- protected function modifyColumn($schema, $table, $fields)
- {
- foreach ($fields as $name => $definition)
- {
- if ($this->columnExists($name, $schema, $table))
- {
- if ($this->dbforge->modify_column($schema.'.'.$table, array($name => $definition)))
- {
- $this->eprintflib->printMessage(sprintf("Column %s.%s.%s has been modified", $schema, $table, $name));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Error while modifying column %s.%s.%s", $schema, $table, $name));
- }
- }
- else
- {
- $this->eprintflib->printInfo(sprintf("Column %s.%s.%s doesn't exist", $schema, $table, $name));
- }
- }
- }
-
- /**
- * Drops a column from a table and schema
- */
- protected function dropColumn($schema, $table, $field)
- {
- if ($this->columnExists($field, $schema, $table))
- {
- if ($this->dbforge->drop_column($schema.'.'.$table, $field))
- {
- $this->eprintflib->printMessage(sprintf("Column %s.%s.%s has been dropped", $schema, $table, $field));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Error while dropping column %s.%s.%s", $schema, $table, $field));
- }
- }
- else
- {
- $this->eprintflib->printInfo(sprintf("Column %s.%s.%s doesn't exist", $schema, $table, $field));
- }
- }
-
- /**
- * Sets a column as primary key of a table and schema
- */
- protected function addPrimaryKey($schema, $table, $name, $fields)
- {
- $stringFields = null;
-
- if (is_array($fields))
- {
- if (count($fields) > 0)
- {
- $stringFields = "";
- for ($i = 0; $i < count($fields); $i++)
- {
- $stringFields .= $fields[$i];
- if ($i != count($fields) - 1)
- {
- $stringFields .= ", ";
- }
- }
- $query = sprintf("ALTER TABLE %s.%s ADD CONSTRAINT %s PRIMARY KEY (%s)", $schema, $table, $name, $stringFields);
- }
- }
- else
- {
- $query = sprintf("ALTER TABLE %s.%s ADD CONSTRAINT %s PRIMARY KEY (%s)", $schema, $table, $name, $fields);
- }
-
- if (@$this->db->simple_query($query))
- {
- $this->eprintflib->printMessage(sprintf("Added primary key %s on table %s.%s", $name, $schema, $table));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Adding primary key %s on table %s.%s", $name, $schema, $table));
- }
- }
-
- /**
- * Sets a column as foreign key of a table and schema
- */
- protected function addForeingKey($schema, $table, $name, $field, $schemaDest, $tableDest, $fieldDest, $attributes)
- {
- $query = sprintf(
- "ALTER TABLE %s.%s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s.%s (%s) %s",
- $schema,
- $table,
- $name,
- $field,
- $schemaDest,
- $tableDest,
- $fieldDest,
- $attributes
- );
-
- if (@$this->db->simple_query($query))
- {
- $this->eprintflib->printMessage(sprintf("Added foreign key %s on table %s.%s", $name, $schema, $table));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Adding foreign key %s on table %s.%s", $name, $schema, $table));
- }
- }
-
- /**
- * Sets a column as unique key of a table and schema
- */
- protected function addUniqueKey($schema, $table, $name, $fields)
- {
- $stringFields = null;
-
- if (is_array($fields))
- {
- if (count($fields) > 0)
- {
- $stringFields = "";
- for ($i = 0; $i < count($fields); $i++)
- {
- $stringFields .= $fields[$i];
- if ($i != count($fields) - 1)
- {
- $stringFields .= ", ";
- }
- }
- $query = sprintf("CREATE UNIQUE INDEX %s ON %s.%s (%s)", $name, $schema, $table, $stringFields);
- }
- }
- else
- {
- $query = sprintf("CREATE UNIQUE INDEX %s ON %s.%s (%s)", $name, $schema, $table, $fields);
- }
-
- if (@$this->db->simple_query($query))
- {
- $this->eprintflib->printMessage(sprintf("Added unique key %s on table %s.%s", $name, $schema, $table));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Adding unique key %s on table %s.%s", $name, $schema, $table));
- }
- }
-
- /**
- * Grants permissions to a user on a table and schema
- */
- protected function grantTable($permissions, $schema, $table, $user)
- {
- $stringPermission = null;
-
- if (is_array($permissions))
- {
- if (count($permissions) > 0)
- {
- $stringPermission = "";
- for ($i = 0; $i < count($permissions); $i++)
- {
- $stringPermission .= $permissions[$i];
- if ($i != count($permissions) - 1)
- {
- $stringPermission .= ", ";
- }
- }
- $query = sprintf("GRANT %s ON TABLE %s.%s TO %s", $stringPermission, $schema, $table, $user);
- }
- }
- else
- {
- $query = sprintf("GRANT %s ON TABLE %s.%s TO %s", $permissions, $schema, $table, $user);
- }
-
- if (@$this->db->simple_query($query))
- {
- $this->eprintflib->printMessage(
- sprintf(
- "Granted permissions %s on table %s.%s to user %s",
- is_null($stringPermission) ? $permissions : $stringPermission,
- $schema,
- $table,
- $user
- )
- );
- }
- else
- {
- $this->eprintflib->printError(
- sprintf(
- "Granting permissions %s on table %s.%s to user %s",
- is_null($stringPermission) ? $permissions : $stringPermission,
- $schema,
- $table,
- $user
- )
- );
- }
- }
-
- /**
- * Creates a table in a schema with columns
- */
- protected function createTable($schema, $table, $fields)
- {
- $this->dbforge->add_field($fields);
-
- if ($this->dbforge->create_table($schema.'.'.$table, true))
- {
- $this->eprintflib->printMessage(sprintf("Table %s.%s created or existing", $schema, $table));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Creating table %s.%s", $schema, $table));
- }
- }
-
- /**
- * Drops a table from a schema
- */
- protected function dropTable($schema, $table)
- {
- if ($this->dbforge->drop_table($schema.".".$table))
- {
- $this->eprintflib->printMessage(sprintf("Table %s.%s has been dropped", $schema, $table));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Dropping table %s.%s", $schema, $table));
- }
- }
-
- /**
- * Initializes a sequence with the max value of a column
- */
- protected function initializeSequence($schemaSrc, $sequence, $schemaDst, $table, $field)
- {
- $query = sprintf("SELECT SETVAL('%s.%s', (SELECT MAX(%s) FROM %s.%s))", $schemaSrc, $sequence, $field, $schemaDst, $table);
-
- if (@$this->db->simple_query($query))
- {
- $this->eprintflib->printMessage(sprintf("Sequence %s.%s has been initialized", $schemaSrc, $sequence));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Initializing sequence %s.%s", $schemaSrc, $sequence));
- }
- }
-
- /**
- * Add comment to a column
- */
- protected function addCommentToColumn($schema, $table, $field, $comment)
- {
- $query = sprintf("COMMENT ON COLUMN %s.%s.%s IS ?", $schema, $table, $field);
-
- if (@$this->db->query($query, array($comment)))
- {
- $this->eprintflib->printMessage(sprintf("Comment added to %s.%s.%s", $schema, $table, $field));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Error while adding comment to %s.%s.%s", $schema, $table, $field));
- }
- }
-
- /**
- * Add comment to a table
- */
- protected function addCommentToTable($schema, $table, $comment)
- {
- $query = sprintf("COMMENT ON TABLE %s.%s IS ?", $schema, $table, $field);
-
- if (@$this->db->query($query, array($comment)))
- {
- $this->eprintflib->printMessage(sprintf("Comment added to %s.%s", $schema, $table));
- }
- else
- {
- $this->eprintflib->printError(sprintf("Error while adding comment to %s.%s", $schema, $table));
- }
- }
- /**
- * Grants permissions to a user on a sequence
- */
- protected function grantSequence($permissions, $schema, $sequence, $user)
- {
- $stringPermission = null;
-
- if (is_array($permissions))
- {
- if (count($permissions) > 0)
- {
- $stringPermission = "";
- for ($i = 0; $i < count($permissions); $i++)
- {
- $stringPermission .= $permissions[$i];
- if ($i != count($permissions) - 1)
- {
- $stringPermission .= ", ";
- }
- }
- $query = sprintf("GRANT %s ON SEQUENCE %s.%s TO %s", $stringPermission, $schema, $sequence, $user);
- }
- }
- else
- {
- $query = sprintf("GRANT %s ON SEQUENCE %s.%s TO %s", $permissions, $schema, $sequence, $user);
- }
-
- if (@$this->db->simple_query($query))
- {
- $this->eprintflib->printMessage(
- sprintf(
- "Granted permissions %s on sequence %s.%s to user %s",
- is_null($stringPermission) ? $permissions : $stringPermission,
- $schema,
- $sequence,
- $user
- )
- );
- }
- else
- {
- $this->eprintflib->printError(
- sprintf(
- "Granting permissions %s on sequence %s.%s to user %s",
- is_null($stringPermission) ? $permissions : $stringPermission,
- $schema,
- $sequence,
- $user
- )
- );
- }
- }
-
- /**
- * Executes the given query
- */
- protected function execQuery($query)
- {
- if (! @$this->db->simple_query($query))
- {
- $error = $this->db->error();
-
- if (is_array($error) && isset($error["message"]))
- {
- $this->eprintflib->printError($error["message"]);
- }
- else
- {
- $this->eprintflib->printError("Error while executing a query");
- }
- }
-
- $this->eprintflib->printInfo(
- "Query correctly executed: ".
- substr(preg_replace("/\s+/", " ", trim($query)), 0, EPrintfLib::PRINT_QUERY_LEN).
- (strlen($query) > EPrintfLib::PRINT_QUERY_LEN ? "..." : "")
- );
- }
-}
diff --git a/application/libraries/PersonLogLib.php b/application/libraries/PersonLogLib.php
index b56937dfe..299fc8ce2 100644
--- a/application/libraries/PersonLogLib.php
+++ b/application/libraries/PersonLogLib.php
@@ -8,6 +8,7 @@ if (! defined('BASEPATH')) exit('No direct script access allowed');
class PersonLogLib
{
const PARKED_LOGNAME = 'Parked';
+ const ONHOLD_LOGNAME = 'Onhold';
/**
* Constructor
@@ -91,26 +92,20 @@ class PersonLogLib
*/
public function park($person_id, $date, $taetigkeit_kurzbz, $app = 'core', $oe_kurzbz = null, $user = null)
{
- $logdata = array(
+ $onhold = $this->getOnHoldDate($person_id);
+
+ if (hasData($onhold))
+ return error("Person already on hold");
+
+ $logjson = array(
'name' => self::PARKED_LOGNAME
);
- $data = array(
- 'person_id' => $person_id,
- 'zeitpunkt' => $date,
- 'taetigkeit_kurzbz' => $taetigkeit_kurzbz,
- 'app' => $app,
- 'oe_kurzbz' => $oe_kurzbz,
- 'logtype_kurzbz' => 'Processstate',
- 'logdata' => json_encode($logdata),
- 'insertvon' => $user
- );
-
- return $this->ci->PersonLogModel->insert($data);
+ return $this->_savePsLog($person_id, $date, $taetigkeit_kurzbz, $logjson, $app, $oe_kurzbz, $user);
}
/**
- * Unparks a person, i.e. removes all log entries in the future
+ * Unparks a person, i.e. removes all log entries in the future with logname for parking
* @param $person_id
* @return array with deleted logids
*/
@@ -131,17 +126,9 @@ class PersonLogLib
{
$deleted[] = $log->log_id;
}
- else
- {
- return $delresult;
- }
}
}
}
- else
- {
- return $result;
- }
return success($deleted);
}
@@ -172,4 +159,111 @@ class PersonLogLib
return $parkeddate;
}
+
+ /**
+ * Sets person on hold, i.e. marks a person so no actions are expected for the person (e.g. as a prestudent).
+ * Done by adding a logentry with a special name. can be undone only manually by clicking button.
+ * @param $person_id
+ * @param $date
+ * @param $taetigkeit_kurzbz
+ * @param string $app
+ * @param null $oe_kurzbz
+ * @param null $user
+ * @return array
+ */
+ public function setOnHold($person_id, $date, $taetigkeit_kurzbz, $app = 'core', $oe_kurzbz = null, $user = null)
+ {
+ $parked = $this->getParkedDate($person_id);
+
+ if (hasData($parked))
+ return error("Person already parked");
+
+ $logjson = array(
+ 'name' => self::ONHOLD_LOGNAME
+ );
+
+ return $this->_savePsLog($person_id, $date, $taetigkeit_kurzbz, $logjson, $app, $oe_kurzbz, $user);
+ }
+
+ /**
+ * Removes on hold status, i.e. removes all log entries with logname for on hold
+ * @param $person_id
+ * @return array
+ */
+ public function removeOnHold($person_id)
+ {
+ $deleted = array();
+
+ $result = $this->ci->PersonLogModel->filterLog($person_id);
+ if (hasData($result))
+ {
+ foreach ($result->retval as $log)
+ {
+ $logdata = json_decode($log->logdata);
+ if (isset($logdata->name) && $logdata->name === self::ONHOLD_LOGNAME)
+ {
+ $delresult = $this->ci->PersonLogModel->deleteLog($log->log_id);
+ if (isSuccess($delresult))
+ {
+ $deleted[] = $log->log_id;
+ }
+ }
+ }
+ }
+ return success($deleted);
+ }
+
+ /**
+ * Gets date until which a person is on hold
+ * @param $person_id
+ * @return the date if person is on hold, null otherwise
+ */
+ public function getOnHoldDate($person_id)
+ {
+ $result = $this->ci->PersonLogModel->filterLog($person_id);
+
+ $onholddate = null;
+
+ if (hasData($result))
+ {
+ foreach ($result->retval as $log)
+ {
+ $logdata = json_decode($log->logdata);
+ if (isset($logdata->name) && $logdata->name === self::ONHOLD_LOGNAME)
+ {
+ $onholddate = $log->zeitpunkt;
+ break;
+ }
+ }
+ }
+
+ return $onholddate;
+ }
+
+ /**
+ * Saves a processstate log with specified parameters, including a specified log date.
+ * @param $person_id
+ * @param $date
+ * @param $taetigkeit_kurzbz
+ * @param $logjson
+ * @param string $app
+ * @param null $oe_kurzbz
+ * @param null $user
+ * @return mixed
+ */
+ private function _savePsLog($person_id, $date, $taetigkeit_kurzbz, $logjson, $app = 'core', $oe_kurzbz = null, $user = null)
+ {
+ $data = array(
+ 'person_id' => $person_id,
+ 'zeitpunkt' => $date,
+ 'taetigkeit_kurzbz' => $taetigkeit_kurzbz,
+ 'app' => $app,
+ 'oe_kurzbz' => $oe_kurzbz,
+ 'logtype_kurzbz' => 'Processstate',
+ 'logdata' => json_encode($logjson),
+ 'insertvon' => $user
+ );
+
+ return $this->ci->PersonLogModel->insert($data);
+ }
}
diff --git a/application/libraries/TableWidgetLib.php b/application/libraries/TableWidgetLib.php
new file mode 100644
index 000000000..009103e68
--- /dev/null
+++ b/application/libraries/TableWidgetLib.php
@@ -0,0 +1,206 @@
+_ci =& get_instance(); // get code igniter instance
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // Public methods
+
+ /**
+ * Checks if at least one of the permissions given as parameter (requiredPermissions) belongs
+ * to the authenticated user, if confirmed then is allowed to use this FilterWidget.
+ * If the parameter requiredPermissions is NOT given or is not present in the session,
+ * then NO one is allow to use this FilterWidget
+ * Wrapper method to permissionlib->hasAtLeastOne
+ */
+ public function isAllowed($requiredPermissions = null)
+ {
+ $this->_ci->load->library('PermissionLib'); // Load permission library
+
+ // Gets the required permissions from the session if they are not provided as parameter
+ $rq = $requiredPermissions;
+ if ($rq == null) $rq = $this->getSessionElement(self::REQUIRED_PERMISSIONS_PARAMETER);
+
+ return $this->_ci->permissionlib->hasAtLeastOne($rq, self::PERMISSION_TABLE_METHOD, self::PERMISSION_TYPE);
+ }
+
+ /**
+ * Wrapper method to the session helper funtions to retrieve the whole session for this filter
+ */
+ public function getSession()
+ {
+ return getSessionElement(self::SESSION_NAME, $this->_tableUniqueId);
+ }
+
+ /**
+ * Wrapper method to the session helper funtions to retrieve one element from the session of this filter
+ */
+ public function getSessionElement($name)
+ {
+ $session = getSessionElement(self::SESSION_NAME, $this->_tableUniqueId);
+
+ if (isset($session[$name]))
+ {
+ return $session[$name];
+ }
+
+ return null;
+ }
+
+ /**
+ * Wrapper method to the session helper funtions to set the whole session for this filter
+ */
+ public function setSession($data)
+ {
+ setSessionElement(self::SESSION_NAME, $this->_tableUniqueId, $data);
+ }
+
+ /**
+ * Wrapper method to the session helper funtions to set one element in the session for this filter
+ */
+ public function setSessionElement($name, $value)
+ {
+ $session = getSessionElement(self::SESSION_NAME, $this->_tableUniqueId);
+
+ $session[$name] = $value;
+
+ setSessionElement(self::SESSION_NAME, $this->_tableUniqueId, $session); // stores the single value
+ }
+
+ /**
+ * Generate the query to retrieve the dataset for a filter
+ */
+ public function generateDatasetQuery($query)
+ {
+ return 'SELECT * FROM ('.$query.') '.self::DATASET_TABLE_ALIAS;
+ }
+
+ /**
+ * Retrieves the dataset from the DB
+ */
+ public function getDataset($datasetQuery)
+ {
+ $dataset = null;
+
+ if ($datasetQuery != null)
+ {
+ $this->_ci->load->model('system/Filters_model', 'FiltersModel');
+
+ // Execute the given SQL statement suppressing error messages
+ $dataset = @$this->_ci->FiltersModel->execReadOnlyQuery($datasetQuery);
+ }
+
+ return $dataset;
+ }
+
+ /**
+ * Retrieves metadata from the last executed query
+ */
+ public function getExecutedQueryMetaData()
+ {
+ return $this->_ci->FiltersModel->getExecutedQueryMetaData();
+ }
+
+ /**
+ * Retrieves the list of fields from the last executed query
+ */
+ public function getExecutedQueryListFields()
+ {
+ return $this->_ci->FiltersModel->getExecutedQueryListFields();
+ }
+
+ /**
+ * Return an unique string that identify this filter widget
+ * NOTE: The default value is the URI where the FilterWidget is called
+ * If the fhc_controller_id is present then is also used
+ */
+ public function setTableUniqueIdByParams($params)
+ {
+ if ($params != null
+ && is_array($params)
+ && isset($params[self::TABLE_UNIQUE_ID])
+ && !isEmptyString($params[self::TABLE_UNIQUE_ID]))
+ {
+ $tableUniqueId = $this->_ci->router->directory.$this->_ci->router->class.'/'.
+ $this->_ci->router->method.'/'.
+ $params[self::TABLE_UNIQUE_ID];
+
+ $this->setTableUniqueId($tableUniqueId);
+ }
+ }
+
+ /**
+ * Set the _tableUniqueId property
+ */
+ public function setTableUniqueId($tableUniqueId)
+ {
+ $this->_tableUniqueId = $tableUniqueId;
+ }
+}
diff --git a/application/libraries/VariableLib.php b/application/libraries/VariableLib.php
new file mode 100644
index 000000000..3d732984f
--- /dev/null
+++ b/application/libraries/VariableLib.php
@@ -0,0 +1,131 @@
+_ci =& get_instance();
+
+ $this->_variables = null;
+
+ $this->_ci->load->model('system/Variable_model', 'VariableModel');
+ $this->_ci->load->model('organisation/studiensemester_model', 'StudiensemesterModel');
+
+ if (isset($loggeduid['uid']) && !isEmptyString($loggeduid['uid']))
+ $this->_setVariables($loggeduid['uid']);
+ else
+ {
+ show_error('uid of logged user not passed!');
+ }
+ }
+
+ /**
+ * Gets an already loaded user variable by variable name.
+ * @param $name
+ * @return mixed|null
+ */
+ public function getVar($name)
+ {
+ return isset($this->_variables[$name]) ? $this->_variables[$name] : null;
+ }
+
+ /**
+ * Changes variables having Studiensemester as value. Sets variable value to next or previous Semester.
+ * @param $uid variable is set for this user
+ * @param $name variable name
+ * @param $change if positive, variable value is set to next semester, negative - previous semester
+ * @return array if change was successfull, uid and variable name. Infotext otherwise.
+ */
+ public function changeStudiensemesterVar($uid, $name, $change)
+ {
+ $result = error('error when setting variable!');
+ $notchangedtext = "Studiensemester variable not changed.";
+
+ if (!isEmptyString($uid) && !isEmptyString($name) && is_numeric($change))
+ {
+ $change = (int) $change;
+ $varres = $this->_ci->VariableModel->getVariables($uid, array($name));
+
+ if (isSuccess($varres))
+ {
+ if (hasData($varres))
+ {
+ $currStudiensemester = getData($varres);
+
+ if ($change === 0)
+ {
+ $result = success($notchangedtext);
+ }
+ else
+ {
+ if ($change > 0)
+ {
+ $changedsem = $this->_ci->StudiensemesterModel->getNextFrom($currStudiensemester[$name]);
+ }
+ elseif ($change < 0)
+ {
+ $changedsem = $this->_ci->StudiensemesterModel->getPreviousFrom($currStudiensemester[$name]);
+ }
+
+ if (hasData($changedsem))
+ {
+ $changedsem = getData($changedsem);
+
+ $result = $this->_ci->VariableModel->setVariable($uid, $name, $changedsem[0]->studiensemester_kurzbz);
+ //update property
+ $this->_setVariable($uid, $name);
+ }
+ else
+ {
+ $result = success($notchangedtext);
+ }
+ }
+ }
+ }
+ }
+ return $result;
+ }
+
+ /**
+ * "Refreshes" variable value with given name by retrieving current value from db and saving it.
+ * @param $uid
+ * @param $name
+ */
+ private function _setVariable($uid, $name)
+ {
+ $variable = $this->_ci->VariableModel->getVariables($uid, array($name));
+
+ if (hasData($variable))
+ {
+ $variable = getData($variable);
+ $this->_variables[$name] = $variable[$name];
+ }
+ }
+
+ /**
+ * "Refreshes" all variable values by retrieving current values from db and saving them.
+ * @param $uid
+ */
+ private function _setVariables($uid)
+ {
+ $variables = $this->_ci->VariableModel->getVariables($uid);
+ if (hasData($variables))
+ {
+ $this->_variables = getData($variables);
+ }
+ }
+}
diff --git a/application/models/codex/Bisiozweck_model.php b/application/models/codex/Bisiozweck_model.php
new file mode 100644
index 000000000..b456f412d
--- /dev/null
+++ b/application/models/codex/Bisiozweck_model.php
@@ -0,0 +1,15 @@
+dbTable = 'bis.tbl_bisio_zweck';
+ $this->pk = array('bisio_id', 'zweck_code');
+ $this->hasSequence = false;
+ }
+}
diff --git a/application/models/crm/Prestudent_model.php b/application/models/crm/Prestudent_model.php
index ffc6afb0e..32673d10d 100644
--- a/application/models/crm/Prestudent_model.php
+++ b/application/models/crm/Prestudent_model.php
@@ -10,6 +10,8 @@ class Prestudent_model extends DB_Model
parent::__construct();
$this->dbTable = 'public.tbl_prestudent';
$this->pk = 'prestudent_id';
+
+ $this->load->model('crm/prestudentstatus_model', 'PrestudentstatusModel');
}
/**
@@ -208,7 +210,6 @@ class Prestudent_model extends DB_Model
return error('prestudent could not be loaded');
//Prestudentstatus
- $this->load->model('crm/prestudentstatus_model', 'PrestudentstatusModel');
$lastStatus = $this->PrestudentstatusModel->getLastStatus($prestudent_id);
if ($lastStatus->error)
@@ -310,8 +311,6 @@ class Prestudent_model extends DB_Model
if (!hasData($prestudents))
return $bewerbungen;
- $this->load->model('crm/prestudentstatus_model', 'PrestudentstatusModel');
-
foreach ($prestudents->retval as $prestudent)
{
$lastStatus = $this->PrestudentstatusModel->getLastStatus($prestudent->prestudent_id, $studiensemester_kurzbz);
@@ -424,7 +423,6 @@ class Prestudent_model extends DB_Model
if (!hasData($prestudent))
return false;
- $this->load->model('prestudentstatus_model', 'PrestudentstatusModel');
$lastStatus = $this->PrestudentstatusModel->getLastStatus($prestudent_id, null, 'Interessent');
if (!hasData($lastStatus))
diff --git a/application/models/education/Lehreinheitgruppe_model.php b/application/models/education/Lehreinheitgruppe_model.php
index 796ae574b..2a6f9571a 100644
--- a/application/models/education/Lehreinheitgruppe_model.php
+++ b/application/models/education/Lehreinheitgruppe_model.php
@@ -98,8 +98,8 @@ class Lehreinheitgruppe_model extends DB_Model
'semester' => $lvadata->semester,
'bezeichnung' => $bezeichnung,
'aktiv' => true,
- 'mailgrp' => false,
- 'sichtbar' => true,
+ 'mailgrp' => true,
+ 'sichtbar' => false,
'generiert' => false,
'insertamum' => date('Y-m-d H:i:s'),
'insertvon' => $loggedInUser,
diff --git a/application/models/education/Lehrveranstaltung_model.php b/application/models/education/Lehrveranstaltung_model.php
index 1685ddf81..1235769ac 100644
--- a/application/models/education/Lehrveranstaltung_model.php
+++ b/application/models/education/Lehrveranstaltung_model.php
@@ -10,6 +10,9 @@ class Lehrveranstaltung_model extends DB_Model
parent::__construct();
$this->dbTable = 'lehre.tbl_lehrveranstaltung';
$this->pk = 'lehrveranstaltung_id';
+
+ $this->load->model('organisation/studiengang_model', 'StudiengangModel');
+ $this->load->model('organisation/studiensemester_model', 'StudiensemesterModel');
}
/**
@@ -22,8 +25,6 @@ class Lehrveranstaltung_model extends DB_Model
*/
public function getLehrveranstaltungGroupNames($studiensemester_kurzbz, $ausbildungssemester = null, $studiengang_kz = null, $lehrveranstaltung_ids = null)
{
- $this->load->model('organisation/studiengang_model', 'StudiengangModel');
-
$studiengang_kz_arr = array();
$ausbildungssemester_arr = array();
$lehrveranstaltung_id_arr = array();
@@ -59,7 +60,6 @@ class Lehrveranstaltung_model extends DB_Model
}
else
{
- $this->load->model('organisation/studiensemester_model', 'StudiensemesterModel');
foreach ($studiengang_kz_arr as $studiengang_kz_item)
{
$result = $this->StudiensemesterModel->getAusbildungssemesterByStudiensemesterAndStudiengang($studiensemester_kurzbz, $studiengang_kz_item);
@@ -214,8 +214,6 @@ class Lehrveranstaltung_model extends DB_Model
*/
public function getLvsWithIncomingPlaces($studiensemester_kurzbz)
{
- $this->load->model('organisation/Studiensemester_model', 'StudiensemesterModel');
-
$studsemres = $this->StudiensemesterModel->load($studiensemester_kurzbz);
if (!hasData($studsemres))
diff --git a/application/models/organisation/Studienplan_model.php b/application/models/organisation/Studienplan_model.php
index 2c3b36c03..0cc23b85d 100644
--- a/application/models/organisation/Studienplan_model.php
+++ b/application/models/organisation/Studienplan_model.php
@@ -19,7 +19,7 @@ class Studienplan_model extends DB_Model
return $this->loadWhere(array("studiengang_kz" => $studiengang_kz));
}
- public function getStudienplaeneBySemester($studiengang_kz, $studiensemester_kurzbz, $ausbildungssemester = null, $orgform_kurzbz = null)
+ public function getStudienplaeneBySemester($studiengang_kz, $studiensemester_kurzbz, $ausbildungssemester = null, $orgform_kurzbz = null, $sprache = null)
{
$this->addJoin("lehre.tbl_studienordnung", "studienordnung_id");
$this->addJoin("lehre.tbl_studienplan_semester", "studienplan_id");
@@ -40,6 +40,11 @@ class Studienplan_model extends DB_Model
$whereArray["orgform_kurzbz"] = $orgform_kurzbz;
}
+ if(!is_null($sprache))
+ {
+ $whereArray["tbl_studienplan.sprache"] = $sprache;
+ }
+
return $this->StudienplanModel->loadWhere($whereArray);
}
diff --git a/application/models/organisation/Studiensemester_model.php b/application/models/organisation/Studiensemester_model.php
index efe244746..9cdde7a52 100644
--- a/application/models/organisation/Studiensemester_model.php
+++ b/application/models/organisation/Studiensemester_model.php
@@ -77,7 +77,7 @@ class Studiensemester_model extends DB_Model
start,
ende
FROM public.tbl_studiensemester
- WHERE start > (
+ WHERE start >= (
SELECT ende
FROM public.tbl_studiensemester
WHERE studiensemester_kurzbz = ?
@@ -88,6 +88,26 @@ class Studiensemester_model extends DB_Model
return $this->execQuery($query, array($studiensemester_kurzbz));
}
+ /**
+ * getPreviousFrom
+ */
+ public function getPreviousFrom($studiensemester_kurzbz)
+ {
+ $query = 'SELECT studiensemester_kurzbz,
+ start,
+ ende
+ FROM public.tbl_studiensemester
+ WHERE ende <= (
+ SELECT start
+ FROM public.tbl_studiensemester
+ WHERE studiensemester_kurzbz = ?
+ )
+ ORDER BY start DESC
+ LIMIT 1';
+
+ return $this->execQuery($query, array($studiensemester_kurzbz));
+ }
+
/**
* getNearest
*/
diff --git a/application/models/person/Person_model.php b/application/models/person/Person_model.php
index b689f4fcb..1291427b6 100644
--- a/application/models/person/Person_model.php
+++ b/application/models/person/Person_model.php
@@ -10,6 +10,9 @@ class Person_model extends DB_Model
parent::__construct();
$this->dbTable = 'public.tbl_person';
$this->pk = 'person_id';
+
+ $this->load->model('person/kontakt_model', 'KontaktModel');
+ $this->load->model('person/adresse_model', 'AdresseModel');
}
/**
@@ -162,9 +165,6 @@ class Person_model extends DB_Model
if(count($person->retval) < 1)
return success(null);
- $this->load->model('person/kontakt_model', 'KontaktModel');
- $this->load->model('person/adresse_model', 'AdresseModel');
-
$this->KontaktModel->addDistinct();
$this->KontaktModel->addSelect('kontakttyp, anmerkung, kontakt, zustellung');
$this->KontaktModel->addOrder('kontakttyp');
diff --git a/application/models/system/FAS_UDF_model.php b/application/models/system/FAS_UDF_model.php
new file mode 100644
index 000000000..aee49d431
--- /dev/null
+++ b/application/models/system/FAS_UDF_model.php
@@ -0,0 +1,169 @@
+load->model('person/Person_model', 'PersonModel');
+
+ $result = $this->load(array('public', 'tbl_person'));
+ if (isSuccess($result) && count($result->retval) == 1)
+ {
+ $jsons = json_decode($result->retval[0]->jsons);
+ }
+
+ $udfs = $this->_fillMissingTextUDF($udfs, $jsons);
+ $udfs = $this->_fillMissingChkboxUDF($udfs, $jsons);
+ $udfs = $this->_fillMissingDropdownUDF($udfs, $jsons);
+
+ $resultPerson = $this->PersonModel->update($person_id, $udfs);
+ }
+
+ //
+ if (isset($prestudent_id))
+ {
+ // Load model Prestudent_model
+ $this->load->model('crm/Prestudent_model', 'PrestudentModel');
+
+ $result = $this->load(array('public', 'tbl_prestudent'));
+ if (isSuccess($result) && count($result->retval) == 1)
+ {
+ $jsons = json_decode($result->retval[0]->jsons);
+ }
+
+ $udfs = $this->_fillMissingTextUDF($udfs, $jsons);
+ $udfs = $this->_fillMissingChkboxUDF($udfs, $jsons);
+ $udfs = $this->_fillMissingDropdownUDF($udfs, $jsons);
+
+ $resultPrestudent = $this->PrestudentModel->update($prestudent_id, $udfs);
+ }
+
+ if (isSuccess($resultPerson) && isSuccess($resultPrestudent))
+ {
+ $result = success(array($resultPerson->retval, $resultPrestudent->retval));
+ }
+ else if(isError($resultPerson))
+ {
+ $result = $resultPerson;
+ }
+ else if(isError($resultPrestudent))
+ {
+ $result = $resultPrestudent;
+ }
+
+ return $result;
+ }
+
+ /**
+ *
+ */
+ private function _fillMissingChkboxUDF($udfs, $jsons)
+ {
+ $_fillMissingChkboxUDF = $udfs;
+
+ foreach($jsons as $udfDescription)
+ {
+ if ($udfDescription->{UDFLib::TYPE} == UDFLib::CHKBOX_TYPE)
+ {
+ if (!isset($_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}]))
+ {
+ $_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] = false;
+ }
+ else
+ {
+ if ($_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] == UDF_model::STRING_FALSE)
+ {
+ $_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] = false;
+ }
+ else if ($_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] == UDF_model::STRING_TRUE)
+ {
+ $_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] = true;
+ }
+ }
+ }
+ }
+
+ return $_fillMissingChkboxUDF;
+ }
+
+ /**
+ *
+ */
+ private function _fillMissingDropdownUDF($udfs, $jsons)
+ {
+ $_fillMissingDropdownUDF = $udfs;
+
+ foreach($jsons as $udfDescription)
+ {
+ if ($udfDescription->{UDFLib::TYPE} == UDF_model::UDF_DROPDOWN_TYPE
+ || $udfDescription->{UDFLib::TYPE} == UDF_model::UDF_MULTIPLEDROPDOWN_TYPE)
+ {
+ if (!isset($_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}]))
+ {
+ $_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}] = null;
+ }
+ else if($_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}] == UDF_model::STRING_NULL)
+ {
+ $_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}] = null;
+ }
+ }
+ }
+
+ return $_fillMissingDropdownUDF;
+ }
+
+ /**
+ *
+ */
+ private function _fillMissingTextUDF($udfs, $jsons)
+ {
+ $_fillMissingTextUDF = $udfs;
+
+ foreach($jsons as $udfDescription)
+ {
+ if ($udfDescription->{UDFLib::TYPE} == 'textarea'
+ || $udfDescription->{UDFLib::TYPE} == 'textfield')
+ {
+ if (!isset($_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}]))
+ {
+ $_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}] = null;
+ }
+ else if(trim($_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}]) == '')
+ {
+ $_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}] = null;
+ }
+ }
+ }
+
+ return $_fillMissingTextUDF;
+ }
+}
diff --git a/application/models/system/UDF_model.php b/application/models/system/UDF_model.php
index 5efb061d1..6923d1733 100644
--- a/application/models/system/UDF_model.php
+++ b/application/models/system/UDF_model.php
@@ -2,14 +2,6 @@
class UDF_model extends DB_Model
{
- // String values of booleans
- const STRING_NULL = 'null';
- const STRING_TRUE = 'true';
- const STRING_FALSE = 'false';
-
- const UDF_DROPDOWN_TYPE = 'dropdown';
- const UDF_MULTIPLEDROPDOWN_TYPE = 'multipledropdown';
-
/**
* Constructor
*/
@@ -38,164 +30,4 @@ class UDF_model extends DB_Model
return $udfResults;
}
-
- // ------------------------------------------------------------------------------------
- // These methods work only with the this version of FAS, not with the future versions
-
- /**
- * Methods to save data from FAS
- */
- public function saveUDFs($udfs)
- {
- $result = error('No way man!');
- $resultPerson = success('person');
- $resultPrestudent = success('prestudent');
-
- $person_id = null;
- if (isset($udfs['person_id'])) $person_id = $udfs['person_id'];
- unset($udfs['person_id']);
-
- $prestudent_id = null;
- if (isset($udfs['prestudent_id'])) $prestudent_id = $udfs['prestudent_id'];
- unset($udfs['prestudent_id']);
-
- $jsons = array();
-
- //
- if (isset($person_id))
- {
- // Load model Person_model
- $this->load->model('person/Person_model', 'PersonModel');
-
- $result = $this->load(array('public', 'tbl_person'));
- if (isSuccess($result) && count($result->retval) == 1)
- {
- $jsons = json_decode($result->retval[0]->jsons);
- }
-
- $udfs = $this->_fillMissingTextUDF($udfs, $jsons);
- $udfs = $this->_fillMissingChkboxUDF($udfs, $jsons);
- $udfs = $this->_fillMissingDropdownUDF($udfs, $jsons);
-
- $resultPerson = $this->PersonModel->update($person_id, $udfs);
- }
-
- //
- if (isset($prestudent_id))
- {
- // Load model Prestudent_model
- $this->load->model('crm/Prestudent_model', 'PrestudentModel');
-
- $result = $this->load(array('public', 'tbl_prestudent'));
- if (isSuccess($result) && count($result->retval) == 1)
- {
- $jsons = json_decode($result->retval[0]->jsons);
- }
-
- $udfs = $this->_fillMissingTextUDF($udfs, $jsons);
- $udfs = $this->_fillMissingChkboxUDF($udfs, $jsons);
- $udfs = $this->_fillMissingDropdownUDF($udfs, $jsons);
-
- $resultPrestudent = $this->PrestudentModel->update($prestudent_id, $udfs);
- }
-
- if (isSuccess($resultPerson) && isSuccess($resultPrestudent))
- {
- $result = success(array($resultPerson->retval, $resultPrestudent->retval));
- }
- else if(isError($resultPerson))
- {
- $result = $resultPerson;
- }
- else if(isError($resultPrestudent))
- {
- $result = $resultPrestudent;
- }
-
- return $result;
- }
-
- /**
- *
- */
- private function _fillMissingChkboxUDF($udfs, $jsons)
- {
- $_fillMissingChkboxUDF = $udfs;
-
- foreach($jsons as $udfDescription)
- {
- if ($udfDescription->{UDFLib::TYPE} == UDFLib::CHKBOX_TYPE)
- {
- if (!isset($_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}]))
- {
- $_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] = false;
- }
- else
- {
- if ($_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] == UDF_model::STRING_FALSE)
- {
- $_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] = false;
- }
- else if ($_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] == UDF_model::STRING_TRUE)
- {
- $_fillMissingChkboxUDF[$udfDescription->{UDFLib::NAME}] = true;
- }
- }
- }
- }
-
- return $_fillMissingChkboxUDF;
- }
-
- /**
- *
- */
- private function _fillMissingDropdownUDF($udfs, $jsons)
- {
- $_fillMissingDropdownUDF = $udfs;
-
- foreach($jsons as $udfDescription)
- {
- if ($udfDescription->{UDFLib::TYPE} == UDF_model::UDF_DROPDOWN_TYPE
- || $udfDescription->{UDFLib::TYPE} == UDF_model::UDF_MULTIPLEDROPDOWN_TYPE)
- {
- if (!isset($_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}]))
- {
- $_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}] = null;
- }
- else if($_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}] == UDF_model::STRING_NULL)
- {
- $_fillMissingDropdownUDF[$udfDescription->{UDFLib::NAME}] = null;
- }
- }
- }
-
- return $_fillMissingDropdownUDF;
- }
-
- /**
- *
- */
- private function _fillMissingTextUDF($udfs, $jsons)
- {
- $_fillMissingTextUDF = $udfs;
-
- foreach($jsons as $udfDescription)
- {
- if ($udfDescription->{UDFLib::TYPE} == 'textarea'
- || $udfDescription->{UDFLib::TYPE} == 'textfield')
- {
- if (!isset($_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}]))
- {
- $_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}] = null;
- }
- else if(trim($_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}]) == '')
- {
- $_fillMissingTextUDF[$udfDescription->{UDFLib::NAME}] = null;
- }
- }
- }
-
- return $_fillMissingTextUDF;
- }
}
diff --git a/application/models/system/Variable_model.php b/application/models/system/Variable_model.php
index 9800999fe..1fcb5b274 100644
--- a/application/models/system/Variable_model.php
+++ b/application/models/system/Variable_model.php
@@ -10,5 +10,92 @@ class Variable_model extends DB_Model
parent::__construct();
$this->dbTable = 'public.tbl_variable';
$this->pk = array('uid', 'name');
+ $this->hasSequence = false;
+
+ $this->load->model('system/Variablenname_model', 'VariablennameModel');
+ }
+
+ /**
+ * Gets user variables and values for a uid.
+ * If no value found in tbl_variable, default as defined in variablename_model is retrieved.
+ * @param $uid
+ * @param null $names optionally get only certain variables
+ * @return array
+ */
+ public function getVariables($uid, $names = null)
+ {
+ if (isEmptyString($uid) || (isset($names) && !is_array($names)))
+ $result = error('wrong parameters passed');
+ else
+ {
+ $vardata = array();
+
+ $qry = "SELECT name, wert FROM public.tbl_variable WHERE uid = ?";
+
+ if (isset($names))
+ {
+ $qry .= " AND name IN ('".implode(',', $names)."')";
+ }
+ $qry .= ";";
+
+ $varresults = $this->execQuery($qry, array($uid));
+
+ if (hasData($varresults))
+ {
+ $varresults = getData($varresults);
+ foreach ($varresults as $varresult)
+ {
+ if (isset($varresult->wert))
+ $vardata[$varresult->name] = $varresult->wert;
+ }
+ }
+
+ $vardefaults = $this->VariablennameModel->getDefaults($names);
+
+ if (hasData($vardefaults))
+ {
+ $vardefaults = getData($vardefaults);
+
+
+ foreach ($vardefaults as $vardefault)
+ {
+ if (!isset($vardata[$vardefault->name]) && isset($vardefault->defaultwert))
+ {
+ $vardata[$vardefault->name] = $vardefault->defaultwert;
+ }
+ }
+ }
+ $result = success($vardata);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Sets a variable value for a uid. Adds new entry if not present, updates entry otherwise.
+ * @param $uid
+ * @param $name
+ * @param $wert
+ * @return array
+ */
+ public function setVariable($uid, $name, $wert)
+ {
+ $result = error('error when setting variable!');
+ if (!isEmptyString($uid) && !isEmptyString($name) && !isEmptyString($wert))
+ {
+ $varres = $this->loadWhere(array('uid' => $uid, 'name' => $name));
+
+ if (isSuccess($varres))
+ {
+ if (hasData($varres))
+ {
+ $result = $this->VariableModel->update(array('uid' => $uid, 'name' => $name), array('wert' => $wert));
+ }
+ else
+ $result = $this->VariableModel->insert(array('uid' => $uid, 'name' => $name, 'wert' => $wert));
+ }
+ }
+
+ return $result;
}
}
diff --git a/application/models/system/Variablenname_model.php b/application/models/system/Variablenname_model.php
new file mode 100644
index 000000000..ada1d330c
--- /dev/null
+++ b/application/models/system/Variablenname_model.php
@@ -0,0 +1,78 @@
+ 'SELECT studiensemester_kurzbz FROM public.tbl_studiensemester WHERE ende>now() ORDER BY start LIMIT 1',
+ 'infocenter_studiensemester' => 'SELECT studiensemester_kurzbz FROM (
+ SELECT DISTINCT ON (studienjahr_kurzbz) start, studiensemester_kurzbz
+ FROM public.tbl_studiensemester
+ ORDER BY studienjahr_kurzbz, start
+ ) sem
+ WHERE start > now()
+ LIMIT 1;'
+ );
+
+ /**
+ * Constructor
+ */
+ public function __construct()
+ {
+ parent::__construct();
+ $this->dbTable = 'public.tbl_variablenname';
+ $this->pk ='name';
+ }
+
+ /**
+ * Gets defaults for user variables.
+ * If no default value present in table, SQL can be executed for retrieving the value.
+ * @param null $names optionally get only defaults for certain variables
+ * @return array
+ */
+ public function getDefaults($names = null)
+ {
+ $defaults = array();
+
+ $qry = "SELECT name, defaultwert FROM public.tbl_variablenname";
+
+ if (isset($names) && is_array($names))
+ {
+ $qry .= " WHERE name IN ('".implode(',', $names)."')";
+ }
+ $qry .= ";";
+
+ $defaultsres = $this->execQuery($qry);
+
+ if (hasData($defaultsres))
+ {
+ $defaults = getData($defaultsres);
+
+ foreach ($defaults as $default)
+ {
+ if (!isset($default->defaultwert))
+ {
+ if (isset($this->_dynamic_defaults[$default->name]))
+ {
+ $dyndefault = $this->execQuery($this->_dynamic_defaults[$default->name]);
+ if (hasData($dyndefault))
+ {
+ $dyndefault = getData($dyndefault);
+
+ if (count($dyndefault) === 1)
+ {
+ foreach ($dyndefault[0] as $value)
+ {
+ $default->defaultwert = $value;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return success($defaults);
+ }
+}
diff --git a/application/models/system/Webservicelog_model.php b/application/models/system/Webservicelog_model.php
index dc45b13a7..a5b23a396 100644
--- a/application/models/system/Webservicelog_model.php
+++ b/application/models/system/Webservicelog_model.php
@@ -1,13 +1,14 @@
dbTable = 'system.tbl_webservicelog';
$this->pk = 'webservicelog_id';
}
diff --git a/application/views/home.php b/application/views/home.php
index d00b98f81..79669dd88 100644
--- a/application/views/home.php
+++ b/application/views/home.php
@@ -3,6 +3,7 @@ $this->load->view('templates/FHC-Header',
array(
'title' => 'FH-Complete',
'jquery' => true,
+ 'jqueryui' => true,
'bootstrap' => true,
'fontawesome' => true,
'sbadmintemplate' => true,
diff --git a/application/views/lehre/lehrauftrag/acceptLehrauftrag.php b/application/views/lehre/lehrauftrag/acceptLehrauftrag.php
index 0d0b8aee4..887e01ffa 100644
--- a/application/views/lehre/lehrauftrag/acceptLehrauftrag.php
+++ b/application/views/lehre/lehrauftrag/acceptLehrauftrag.php
@@ -100,4 +100,3 @@ $this->load->view(