# Parameters
collection=NUMBER
- ID of a collection
+ ID of a collection
p=list
- Get the latest 10 for given collection
+ Get the latest 10 for given collection
p=add&collection=NUMBER&authKey=API_AUTH_TOKEN
- POST call to add a new entry to given collection.
- See p=addInfo for the details which info is needed in the add call
- More information can be found in import.txt
+ POST call to add a new entry to given collection.
+ See p=addInfo for the details which info is needed in the add call
+ More information can be found in import.txt
p=addInfo&collection=NUMBER
- Describes how the data in the POST add call should be formatted.
- The JSON info in the data field, tells which fields are available and in which format the value
- is accepted.
- Expected is a curl call with an array as payload
+ Describes how the data in the POST add call should be formatted.
+ The JSON info in the data field, tells which fields are available and in which format the value
+ is accepted.
+ Expected is a curl call with an array as payload
# Response
The result is json
{
- "message": "Message as string",
- "status": INTEGER based on HTTP_STATUS CODE
- "data": {}
+ "message": "Message as string",
+ "status": INTEGER based on HTTP_STATUS CODE
+ "data": {}
}
$_requestMode = "default";
if(isset($_GET['p']) && !empty($_GET['p'])) {
- $_requestMode = trim($_GET['p']);
- $_requestMode = Summoner::validate($_requestMode,'nospace') ? $_requestMode : "default";
+ $_requestMode = trim($_GET['p']);
+ $_requestMode = Summoner::validate($_requestMode,'nospace') ? $_requestMode : "default";
- if(!$Spectre->allowedRequests($_requestMode)) $_requestMode = "default";
+ if(!$Spectre->allowedRequests($_requestMode)) $_requestMode = "default";
}
$_authKey = false;
if(isset($_GET['authKey']) && !empty($_GET['authKey'])) {
- $_authKey = trim($_GET['authKey']);
- $_authKey = Summoner::validate($_authKey,'nospace') ? $_authKey : false;
+ $_authKey = trim($_GET['authKey']);
+ $_authKey = Summoner::validate($_authKey,'nospace') ? $_authKey : false;
}
$_apiResult = array(
- 'message' => 'Nothing to see here.',
- 'status' => 200,
- 'data' => array()
+ 'message' => 'Nothing to see here.',
+ 'status' => 200,
+ 'data' => array()
);
switch ($_requestMode) {
- case 'list':
- # get the latest 10 entris for given collection
- $_msg = 'Missing parameter with value: collection';
- $_status = 404;
- $_data = array();
-
- $_collection = false;
- if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
- }
-
- if(!empty($_collection)) {
- $_msg = 'Invalid collection.';
- $Mancubus = new Mancubus($DB,$Doomguy);
- $Trite = new Trite($DB,$Doomguy);
- $collectionInfo = $Trite->load($_collection);
-
- $Mancubus->setCollection($Trite->param('id'));
- $Mancubus->setQueryOptions(array('limit' => 10));
-
- $entries = $Mancubus->getEntries();
- if(!empty($entries)) {
- $_msg = 'Latest entries for collection: '.$collectionInfo['name'];
- $_status = 200;
- $_data = $entries;
- }
- }
-
- $_apiResult = array(
- 'message' => $_msg,
- 'status' => $_status,
- 'data' => $_data
- );
- break;
-
- case 'add':
- # add a single new entry to given collection
- # authenticated by api token
- $_msg = 'Missing parameter with value: collection';
- $_status = 400;
- $_data = array();
-
- $Doomguy->authByApiToken($_authKey);
- if(!$Doomguy->isSignedIn()) {
- $_apiResult = array(
- 'message' => "Missing API token.",
- 'status' => 401,
- 'data' => $_data
- );
- break;
- }
-
- $_collection = false;
- if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
- }
-
- if(!empty($_collection)) {
- $_msg = 'Invalid POST data.';
-
- $Mancubus = new Mancubus($DB,$Doomguy);
- $ManangeEntry = new Manageentry($DB,$Doomguy);
-
- $ManangeEntry->setCollection($_collection);
- $editFields = $ManangeEntry->getEditFields();
-
- if(!empty($_POST) && !empty($editFields)) {
- $fdata = $_POST;
- if(!empty($_FILES)) {
- $fupload = $Spectre->prepareFilesArray($_FILES);
- }
-
- $_owner = $Doomguy->param('id');
- $_group = $Doomguy->param('baseGroupId');
- $_rights = 'rwxrwxr--';
-
- foreach ($editFields as $fieldId=>$fieldData) {
- if(isset($fupload['name'][$fieldData['identifier']])) {
- $fieldData['uploadData'] = $fupload;
- $_fieldsToSave[$fieldData['identifier']] = $fieldData;
- }
- elseif(isset($fdata[$fieldData['identifier']])) {
- $_value = trim($fdata[$fieldData['identifier']]);
- if(!empty($_value)) {
- $fieldData['valueToSave'] = trim($fdata[$fieldData['identifier']]);
-
- $_fieldsToSave[$fieldData['identifier']] = $fieldData;
- }
- }
- }
-
- // special case. Title field should be always available.
- if(!empty($_fieldsToSave) && isset($_fieldsToSave['title'])) {
- $do = $ManangeEntry->create($_fieldsToSave, $_owner, $_group, $_rights);
- if(!empty($do)) {
- $_msg = 'Added entry: '.$_fieldsToSave['title']['valueToSave'];
- $_status = 200;
- $_data = array();
- }
- }
- }
- }
-
- $_apiResult = array(
- 'message' => $_msg,
- 'status' => $_status,
- 'data' => $_data
- );
- break;
-
- case 'addInfo':
- # return information about the given collection to create an ad call.
- $_msg = 'Missing parameter with value: collection';
- $_status = 404;
- $_data = array();
-
- $_collection = false;
- if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
- }
-
- if(!empty($_collection)) {
- $_msg = 'Invalid collection.';
- $Mancubus = new Mancubus($DB,$Doomguy);
- $Trite = new Trite($DB,$Doomguy);
- $collectionInfo = $Trite->load($_collection);
-
- $Mancubus->setCollection($Trite->param('id'));
-
- // just get one entry fpr given collection and then build the
- // json information about adding structure
- $entryStructure = $Mancubus->getEntryStructure();
- $structure = $Spectre->buildAddStructure($entryStructure['fields']);
-
- if(!empty($structure)) {
- $_msg = 'API POST and FILES data information for collection: '.$collectionInfo['name'];
- $_status = 200;
- $_data = $structure;
- }
- }
-
- $_apiResult = array(
- 'message' => $_msg,
- 'status' => $_status,
- 'data' => $_data
- );
- break;
-
- case 'default':
- default:
- // do nothing
+ case 'list':
+ # get the latest 10 entris for given collection
+ $_msg = 'Missing parameter with value: collection';
+ $_status = 404;
+ $_data = array();
+
+ $_collection = false;
+ if(isset($_GET['collection']) && !empty($_GET['collection'])) {
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ }
+
+ if(!empty($_collection)) {
+ $_msg = 'Invalid collection.';
+ $Mancubus = new Mancubus($DB,$Doomguy);
+ $Trite = new Trite($DB,$Doomguy);
+ $collectionInfo = $Trite->load($_collection);
+
+ $Mancubus->setCollection($Trite->param('id'));
+ $Mancubus->setQueryOptions(array('limit' => 10));
+
+ $entries = $Mancubus->getEntries();
+ if(!empty($entries)) {
+ $_msg = 'Latest entries for collection: '.$collectionInfo['name'];
+ $_status = 200;
+ $_data = $entries;
+ }
+ }
+
+ $_apiResult = array(
+ 'message' => $_msg,
+ 'status' => $_status,
+ 'data' => $_data
+ );
+ break;
+
+ case 'add':
+ # add a single new entry to given collection
+ # authenticated by api token
+ $_msg = 'Missing parameter with value: collection';
+ $_status = 400;
+ $_data = array();
+
+ $Doomguy->authByApiToken($_authKey);
+ if(!$Doomguy->isSignedIn()) {
+ $_apiResult = array(
+ 'message' => "Missing API token.",
+ 'status' => 401,
+ 'data' => $_data
+ );
+ break;
+ }
+
+ $_collection = false;
+ if(isset($_GET['collection']) && !empty($_GET['collection'])) {
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ }
+
+ if(!empty($_collection)) {
+ $_msg = 'Invalid POST data.';
+
+ $Mancubus = new Mancubus($DB,$Doomguy);
+ $ManangeEntry = new Manageentry($DB,$Doomguy);
+
+ $ManangeEntry->setCollection($_collection);
+ $editFields = $ManangeEntry->getEditFields();
+
+ if(!empty($_POST) && !empty($editFields)) {
+ $fdata = $_POST;
+ if(!empty($_FILES)) {
+ $fupload = $Spectre->prepareFilesArray($_FILES);
+ }
+
+ $_owner = $Doomguy->param('id');
+ $_group = $Doomguy->param('baseGroupId');
+ $_rights = 'rwxrwxr--';
+
+ foreach ($editFields as $fieldId=>$fieldData) {
+ if(isset($fupload['name'][$fieldData['identifier']])) {
+ $fieldData['uploadData'] = $fupload;
+ $_fieldsToSave[$fieldData['identifier']] = $fieldData;
+ }
+ elseif(isset($fdata[$fieldData['identifier']])) {
+ $_value = trim($fdata[$fieldData['identifier']]);
+ if(!empty($_value)) {
+ $fieldData['valueToSave'] = trim($fdata[$fieldData['identifier']]);
+
+ $_fieldsToSave[$fieldData['identifier']] = $fieldData;
+ }
+ }
+ }
+
+ // special case. Title field should be always available.
+ if(!empty($_fieldsToSave) && isset($_fieldsToSave['title'])) {
+ $do = $ManangeEntry->create($_fieldsToSave, $_owner, $_group, $_rights);
+ if(!empty($do)) {
+ $_msg = 'Added entry: '.$_fieldsToSave['title']['valueToSave'];
+ $_status = 200;
+ $_data = array();
+ }
+ }
+ }
+ }
+
+ $_apiResult = array(
+ 'message' => $_msg,
+ 'status' => $_status,
+ 'data' => $_data
+ );
+ break;
+
+ case 'addInfo':
+ # return information about the given collection to create an ad call.
+ $_msg = 'Missing parameter with value: collection';
+ $_status = 404;
+ $_data = array();
+
+ $_collection = false;
+ if(isset($_GET['collection']) && !empty($_GET['collection'])) {
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ }
+
+ if(!empty($_collection)) {
+ $_msg = 'Invalid collection.';
+ $Mancubus = new Mancubus($DB,$Doomguy);
+ $Trite = new Trite($DB,$Doomguy);
+ $collectionInfo = $Trite->load($_collection);
+
+ $Mancubus->setCollection($Trite->param('id'));
+
+ // just get one entry fpr given collection and then build the
+ // json information about adding structure
+ $entryStructure = $Mancubus->getEntryStructure();
+ $structure = $Spectre->buildAddStructure($entryStructure['fields']);
+
+ if(!empty($structure)) {
+ $_msg = 'API POST and FILES data information for collection: '.$collectionInfo['name'];
+ $_status = 200;
+ $_data = $structure;
+ }
+ }
+
+ $_apiResult = array(
+ 'message' => $_msg,
+ 'status' => $_status,
+ 'data' => $_data
+ );
+ break;
+
+ case 'default':
+ default:
+ // do nothing
}
# header information
$_requestMode = false;
if(isset($_GET['p']) && !empty($_GET['p'])) {
- $_requestMode = trim($_GET['p']);
- $_requestMode = Summoner::validate($_requestMode,'nospace') ? $_requestMode : "dashboard";
+ $_requestMode = trim($_GET['p']);
+ $_requestMode = Summoner::validate($_requestMode,'nospace') ? $_requestMode : "dashboard";
- $_validPages = $Gorenest->allowedPageRequests();
- $_validPages["dashboard"] = "dashboard";
- if(!isset($_validPages[$_requestMode])) $_requestMode = "dashboard";
+ $_validPages = $Gorenest->allowedPageRequests();
+ $_validPages["dashboard"] = "dashboard";
+ if(!isset($_validPages[$_requestMode])) $_requestMode = "dashboard";
- $ViewScript = Summoner::themefile($_requestMode.'/'.$_requestMode.'.php', UI_THEME);
- $View = Summoner::themefile($_requestMode.'/'.$_requestMode.'.html', UI_THEME);
+ $ViewScript = Summoner::themefile($_requestMode.'/'.$_requestMode.'.php', UI_THEME);
+ $View = Summoner::themefile($_requestMode.'/'.$_requestMode.'.html', UI_THEME);
}
# now inlcude the script
# this sets information into $Data and can overwrite $View
if(!empty($ViewScript)) {
- require_once $ViewScript;
+ require_once $ViewScript;
}
if(!empty($TemplateData['refresh'])) {
- header("Location: ".$TemplateData['refresh']);
+ header("Location: ".$TemplateData['refresh']);
}
# header information
*/
class Doomguy {
- /**
- * the global DB object
- * @var object
- */
- private $_DB;
-
- /**
- * if the user is logged in or not
- * @var boolean
- */
- protected $isSignedIn = false;
-
- /**
- * the data from the current user
- * @var array
- */
- protected $userData = false;
-
- /**
- * the user ID from user management or default
- * @var Int
- */
- protected $userID = 0;
-
- /**
- * the rights string defined the mysql query !
- * the syntax is for mysql only
- *
- * @var array
- */
- protected $_rightsArray = array(
- 'user' => array(
- 'read' => 'r________',
- 'write' => 'rw_______',
- 'delete' => 'rwx______'
- ),
- 'group' => array(
- 'read' => '___r_____',
- 'write' => '___rw____',
- 'delete' => '___rwx___'
- ),
- 'world' => array(
- 'read' => '______r__',
- 'write' => '______rw_',
- 'delete' => '______rwx'
- )
- );
-
- public function __construct($db) {
- $this->_DB = $db;
-
- if($this->_checkSession() === true) {
- $this->isSignedIn = true;
- $this->_loadUser();
- }
- else {
- # anonymoose ;-)
- $this->userID = ANON_USER_ID;
- $this->_loadUser();
- }
- }
-
- /**
- * get the value of the specified param from the user data array
- * @param string $param
- * @return bool|mixed
- */
- public function param($param) {
- $ret = false;
-
- $param = trim($param);
-
- if(!empty($param) && isset($this->userData[$param])) {
- $ret = $this->userData[$param];
- }
-
- return $ret;
- }
-
- /**
- * return the isSignedIn status.
- * @return boolean
- */
- public function isSignedIn() {
- return $this->isSignedIn;
- }
-
- /**
- * get the data from the userSession table
- * @param string $param
- * @return bool
- */
- public function getSessionInfo($param) {
- $ret = false;
-
- $query = $this->_DB->query("SELECT `".$param."`
+ /**
+ * the global DB object
+ * @var object
+ */
+ private $_DB;
+
+ /**
+ * if the user is logged in or not
+ * @var boolean
+ */
+ protected $isSignedIn = false;
+
+ /**
+ * the data from the current user
+ * @var array
+ */
+ protected $userData = false;
+
+ /**
+ * the user ID from user management or default
+ * @var Int
+ */
+ protected $userID = 0;
+
+ /**
+ * the rights string defined the mysql query !
+ * the syntax is for mysql only
+ *
+ * @var array
+ */
+ protected $_rightsArray = array(
+ 'user' => array(
+ 'read' => 'r________',
+ 'write' => 'rw_______',
+ 'delete' => 'rwx______'
+ ),
+ 'group' => array(
+ 'read' => '___r_____',
+ 'write' => '___rw____',
+ 'delete' => '___rwx___'
+ ),
+ 'world' => array(
+ 'read' => '______r__',
+ 'write' => '______rw_',
+ 'delete' => '______rwx'
+ )
+ );
+
+ public function __construct($db) {
+ $this->_DB = $db;
+
+ if($this->_checkSession() === true) {
+ $this->isSignedIn = true;
+ $this->_loadUser();
+ }
+ else {
+ # anonymoose ;-)
+ $this->userID = ANON_USER_ID;
+ $this->_loadUser();
+ }
+ }
+
+ /**
+ * get the value of the specified param from the user data array
+ * @param string $param
+ * @return bool|mixed
+ */
+ public function param($param) {
+ $ret = false;
+
+ $param = trim($param);
+
+ if(!empty($param) && isset($this->userData[$param])) {
+ $ret = $this->userData[$param];
+ }
+
+ return $ret;
+ }
+
+ /**
+ * return the isSignedIn status.
+ * @return boolean
+ */
+ public function isSignedIn() {
+ return $this->isSignedIn;
+ }
+
+ /**
+ * get the data from the userSession table
+ * @param string $param
+ * @return bool
+ */
+ public function getSessionInfo($param) {
+ $ret = false;
+
+ $query = $this->_DB->query("SELECT `".$param."`
FROM `".DB_PREFIX."_userSession`
WHERE `fk_user_id` = '".$this->_DB->real_escape_string($this->userID)."'");
- if($query !== false && $query->num_rows > 0) {
- $result = $query->fetch_assoc();
- $ret = $result[$param];
- }
-
- return $ret;
- }
-
- /**
- * Log out the current loaded user
- * @return boolean
- */
- public function logOut () {
- $ret = false;
-
- if($this->_checkAgainstSessionTable() === true) {
- $this->_destroySession();
- $ret = true;
- }
-
- return $ret;
- }
-
- /**
- * check if the loaded user is in this group
- * if the user is in ADMIN_GROUP_ID, the he is automatically "in" every group
- * @param int $groupID
- * @return bool
- */
- public function isInGroup($groupID) {
- $ret = false;
-
- if($this->userData['isRoot'] === true) {
- $ret = true;
- }
- elseif(in_array($groupID, array_keys($this->userData['group']))) {
- $ret = true;
- }
-
- return $ret;
- }
-
- /**
- * authenticate the user. Create session and db entries
- * @param string $username
- * @param string $password
- * @return boolean
- */
- public function authenticate($username,$password) {
- $ret = false;
-
- if(!empty($username) && !empty($password)) {
- $do = $this->_checkAgainstUserTable($username);
- if($do === true) {
- # valid user now load the user data and compare password etc.
- $this->_loadUser();
- if(password_verify($password,$this->userData['password'])) {
- # everything ok
-
- # create the session info
- $tokenInfo = $this->_createToken();
- $_SESSION[SESSION_NAME]['bibliothecatoken'] = $tokenInfo['token'];
-
- $this->_DB->query("INSERT INTO `".DB_PREFIX."_userSession`
+ if($query !== false && $query->num_rows > 0) {
+ $result = $query->fetch_assoc();
+ $ret = $result[$param];
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Log out the current loaded user
+ * @return boolean
+ */
+ public function logOut () {
+ $ret = false;
+
+ if($this->_checkAgainstSessionTable() === true) {
+ $this->_destroySession();
+ $ret = true;
+ }
+
+ return $ret;
+ }
+
+ /**
+ * check if the loaded user is in this group
+ * if the user is in ADMIN_GROUP_ID, the he is automatically "in" every group
+ * @param int $groupID
+ * @return bool
+ */
+ public function isInGroup($groupID) {
+ $ret = false;
+
+ if($this->userData['isRoot'] === true) {
+ $ret = true;
+ }
+ elseif(in_array($groupID, array_keys($this->userData['group']))) {
+ $ret = true;
+ }
+
+ return $ret;
+ }
+
+ /**
+ * authenticate the user. Create session and db entries
+ * @param string $username
+ * @param string $password
+ * @return boolean
+ */
+ public function authenticate($username,$password) {
+ $ret = false;
+
+ if(!empty($username) && !empty($password)) {
+ $do = $this->_checkAgainstUserTable($username);
+ if($do === true) {
+ # valid user now load the user data and compare password etc.
+ $this->_loadUser();
+ if(password_verify($password,$this->userData['password'])) {
+ # everything ok
+
+ # create the session info
+ $tokenInfo = $this->_createToken();
+ $_SESSION[SESSION_NAME]['bibliothecatoken'] = $tokenInfo['token'];
+
+ $this->_DB->query("INSERT INTO `".DB_PREFIX."_userSession`
SET `token` = '".$this->_DB->real_escape_string($tokenInfo['token'])."',
`loginTime` = NOW(),
`area` = '".$this->_DB->real_escape_string(SESSION_NAME)."',
`fk_user_id` = '".$this->_DB->real_escape_string($this->userID)."',
- `salt` = '".$this->_DB->real_escape_string($tokenInfo['salt'])."'
+ `salt` = '".$this->_DB->real_escape_string($tokenInfo['salt'])."'
ON DUPLICATE KEY UPDATE
- `token` = '".$this->_DB->real_escape_string($tokenInfo['token'])."',
- `salt` = '".$this->_DB->real_escape_string($tokenInfo['salt'])."',
+ `token` = '".$this->_DB->real_escape_string($tokenInfo['token'])."',
+ `salt` = '".$this->_DB->real_escape_string($tokenInfo['salt'])."',
`loginTime` = NOW()");
- # do some actions
- $this->_loginActions();
+ # do some actions
+ $this->_loginActions();
- $ret = true;
- }
- }
- }
+ $ret = true;
+ }
+ }
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * Use the user identified by apitoken
- * @param $token string
- */
- public function authByApiToken($token) {
- if(!empty($token)) {
- $queryStr = "SELECT `id`
+ /**
+ * Use the user identified by apitoken
+ * @param $token string
+ */
+ public function authByApiToken($token) {
+ if(!empty($token)) {
+ $queryStr = "SELECT `id`
FROM `".DB_PREFIX."_user`
WHERE `apiToken` = '".$this->_DB->real_escape_string($token)."'
AND `apiTokenValidDate` > NOW()";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- $result = $query->fetch_assoc();
- $this->userID = $result['id'];
- $this->isSignedIn = true;
- $this->_loadUser();
- $this->_loginActions();
- }
- }
- }
-
- /**
- * create the sql string for rights sql
- *
- * @param string $mode
- * @param bool $tableName
- * @return string $str
- * @throws Exception
- */
- public function getSQLRightsString($mode = "read", $tableName=false) {
- $prefix = '';
- if(!empty($tableName)) {
- $prefix = "`".$tableName."`.";
- }
- if(isset($this->_rightsArray['user'][$mode]) && isset($this->_rightsArray['group'][$mode]) && isset($this->_rightsArray['world'][$mode])) {
- $uid = $this->userID;
- $gids = implode("','", array_keys($this->userData['groups']));
-
- if($this->userData['isRoot'] === true) {
- $str = "( ($prefix`rights` LIKE '".$this->_rightsArray['user'][$mode]."') ";
- $str .= "OR ($prefix`rights` LIKE '".$this->_rightsArray['group'][$mode]."') ";
- $str .= "OR ($prefix`rights` LIKE '".$this->_rightsArray['world'][$mode]."') )";
- }
- else {
- $str = "( ($prefix`owner` = ".$uid." AND $prefix`rights` LIKE '".$this->_rightsArray['user'][$mode]."') ";
- $str .= "OR ($prefix`group` IN ('".$gids."') AND $prefix`rights` LIKE '".$this->_rightsArray['group'][$mode]."') ";
- $str .= "OR ($prefix`rights` LIKE '".$this->_rightsArray['world'][$mode]."') )";
- }
- }
- else {
- throw new Exception("Site User: invalid rights string.");
- }
-
- return $str;
- }
-
- /**
- * check if we can use session
- * we only use session if we can use cookies with the session
- * THIS DOES NOT CHECK IF THE USER HAS COOKIES ACTIVATED !
- */
- protected function _checkSession() {
-
- if(ini_set('session.use_only_cookies',true) === false ||
- ini_set('session.cookie_httponly',true) === false ||
- ini_set('session.use_cookies',true) === false) {
-
- return false;
- }
-
-
- $garbage_timeout = SESSION_LIFETIME + 300;
- ini_set('session.gc_maxlifetime', $garbage_timeout);
- # the % rate how often the session.gc is run
- # http://de.php.net/manual/en/session.configuration.php#ini.session.gc-probability
- ini_set('session.gc_probability',10); // 100 = everytime = 100%
-
- session_save_path(SESSION_SAVE_PATH);
- session_set_cookie_params(SESSION_LIFETIME);
- session_name(SESSION_NAME);
- session_start();
- # produce problems
- # multiple request at once will confuse the script and loose session information
- #session_regenerate_id(true);
-
- if(isset($_SESSION[SESSION_NAME]['bibliothecatoken']) && !empty($_SESSION[SESSION_NAME]['bibliothecatoken'])) {
- return $this->_checkAgainstSessionTable();
- }
-
- return false;
- }
-
- /**
- * we have session data available. Now check if those data is valid
- */
- protected function _checkAgainstSessionTable() {
- $ret = false;
-
- $timeframe = date("Y-m-d H:i:s",time()-SESSION_LIFETIME);
-
- $queryStr = "SELECT s.fk_user_id, s.salt, s.token FROM `".DB_PREFIX."_userSession` AS s
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ $result = $query->fetch_assoc();
+ $this->userID = $result['id'];
+ $this->isSignedIn = true;
+ $this->_loadUser();
+ $this->_loginActions();
+ }
+ }
+ }
+
+ /**
+ * create the sql string for rights sql
+ *
+ * @param string $mode
+ * @param bool $tableName
+ * @return string $str
+ * @throws Exception
+ */
+ public function getSQLRightsString($mode = "read", $tableName=false) {
+ $prefix = '';
+ if(!empty($tableName)) {
+ $prefix = "`".$tableName."`.";
+ }
+ if(isset($this->_rightsArray['user'][$mode]) && isset($this->_rightsArray['group'][$mode]) && isset($this->_rightsArray['world'][$mode])) {
+ $uid = $this->userID;
+ $gids = implode("','", array_keys($this->userData['groups']));
+
+ if($this->userData['isRoot'] === true) {
+ $str = "( ($prefix`rights` LIKE '".$this->_rightsArray['user'][$mode]."') ";
+ $str .= "OR ($prefix`rights` LIKE '".$this->_rightsArray['group'][$mode]."') ";
+ $str .= "OR ($prefix`rights` LIKE '".$this->_rightsArray['world'][$mode]."') )";
+ }
+ else {
+ $str = "( ($prefix`owner` = ".$uid." AND $prefix`rights` LIKE '".$this->_rightsArray['user'][$mode]."') ";
+ $str .= "OR ($prefix`group` IN ('".$gids."') AND $prefix`rights` LIKE '".$this->_rightsArray['group'][$mode]."') ";
+ $str .= "OR ($prefix`rights` LIKE '".$this->_rightsArray['world'][$mode]."') )";
+ }
+ }
+ else {
+ throw new Exception("Site User: invalid rights string.");
+ }
+
+ return $str;
+ }
+
+ /**
+ * check if we can use session
+ * we only use session if we can use cookies with the session
+ * THIS DOES NOT CHECK IF THE USER HAS COOKIES ACTIVATED !
+ */
+ protected function _checkSession() {
+
+ if(ini_set('session.use_only_cookies',true) === false ||
+ ini_set('session.cookie_httponly',true) === false ||
+ ini_set('session.use_cookies',true) === false) {
+
+ return false;
+ }
+
+
+ $garbage_timeout = SESSION_LIFETIME + 300;
+ ini_set('session.gc_maxlifetime', $garbage_timeout);
+ # the % rate how often the session.gc is run
+ # http://de.php.net/manual/en/session.configuration.php#ini.session.gc-probability
+ ini_set('session.gc_probability',10); // 100 = everytime = 100%
+
+ session_save_path(SESSION_SAVE_PATH);
+ session_set_cookie_params(SESSION_LIFETIME);
+ session_name(SESSION_NAME);
+ session_start();
+ # produce problems
+ # multiple request at once will confuse the script and loose session information
+ #session_regenerate_id(true);
+
+ if(isset($_SESSION[SESSION_NAME]['bibliothecatoken']) && !empty($_SESSION[SESSION_NAME]['bibliothecatoken'])) {
+ return $this->_checkAgainstSessionTable();
+ }
+
+ return false;
+ }
+
+ /**
+ * we have session data available. Now check if those data is valid
+ */
+ protected function _checkAgainstSessionTable() {
+ $ret = false;
+
+ $timeframe = date("Y-m-d H:i:s",time()-SESSION_LIFETIME);
+
+ $queryStr = "SELECT s.fk_user_id, s.salt, s.token FROM `".DB_PREFIX."_userSession` AS s
INNER JOIN `".DB_PREFIX."_user` AS u ON s.fk_user_id = u.id
WHERE s.token = '".$this->_DB->real_escape_string($_SESSION[SESSION_NAME]['bibliothecatoken'])."'
- AND s.salt <> ''
+ AND s.salt <> ''
AND s.loginTime >= '".$timeframe."'";
- $query = $this->_DB->query($queryStr);
-
- if($query !== false && $query->num_rows > 0) {
- # existing session info
- $result = $query->fetch_assoc();
-
- # valide the token
- $_check = $this->_createToken($result['salt']);
- if(!empty($_check) && $result['token'] === $_check['token']) {
- $this->userID = $result['fk_user_id'];
-
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * check if the given username is set in user table
- * if so load the user data
- * @param string $u
- * @return boolean
- */
- protected function _checkAgainstUserTable($u) {
- $ret = false;
-
- if(!empty($u)) {
- $query = $this->_DB->query("SELECT `id`
+ $query = $this->_DB->query($queryStr);
+
+ if($query !== false && $query->num_rows > 0) {
+ # existing session info
+ $result = $query->fetch_assoc();
+
+ # valide the token
+ $_check = $this->_createToken($result['salt']);
+ if(!empty($_check) && $result['token'] === $_check['token']) {
+ $this->userID = $result['fk_user_id'];
+
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * check if the given username is set in user table
+ * if so load the user data
+ * @param string $u
+ * @return boolean
+ */
+ protected function _checkAgainstUserTable($u) {
+ $ret = false;
+
+ if(!empty($u)) {
+ $query = $this->_DB->query("SELECT `id`
FROM `".DB_PREFIX."_user`
WHERE `login` = '". $this->_DB->real_escape_string($u)."'
AND `active` = '1'");
- if($query !== false && $query->num_rows > 0) {
- $result = $query->fetch_assoc();
- $this->userID = $result['id'];
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * if we have to run some at login
- */
- protected function _loginActions() {
- # @todo:
- # garbage collection for error files
-
- # clean old sessions on session table
- $timeframe = date("Y-m-d H:i:s",time()-SESSION_LIFETIME);
- $query = $this->_DB->query("DELETE FROM `".DB_PREFIX."_userSession`
+ if($query !== false && $query->num_rows > 0) {
+ $result = $query->fetch_assoc();
+ $this->userID = $result['id'];
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * if we have to run some at login
+ */
+ protected function _loginActions() {
+ # @todo:
+ # garbage collection for error files
+
+ # clean old sessions on session table
+ $timeframe = date("Y-m-d H:i:s",time()-SESSION_LIFETIME);
+ $query = $this->_DB->query("DELETE FROM `".DB_PREFIX."_userSession`
WHERE `loginTime` <= '".$timeframe."'");
- }
-
- /**
- * load the user and groups
- */
- protected function _loadUser() {
- if(!empty($this->userID)) {
- $queryStr = "SELECT `id`, `baseGroupId`,`protected`,`password`,`login`
+ }
+
+ /**
+ * load the user and groups
+ */
+ protected function _loadUser() {
+ if(!empty($this->userID)) {
+ $queryStr = "SELECT `id`, `baseGroupId`,`protected`,`password`,`login`
FROM `".DB_PREFIX."_user`
WHERE `id` = '".$this->_DB->real_escape_string($this->userID)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- $result = $query->fetch_assoc();
- $this->userData = $result;
- }
-
- # now the groups
- $queryStr = "SELECT g.name AS groupName,
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ $result = $query->fetch_assoc();
+ $this->userData = $result;
+ }
+
+ # now the groups
+ $queryStr = "SELECT g.name AS groupName,
g.description AS groupDescription,
g.id AS groupId
FROM `".DB_PREFIX."_user2group` AS u2g,
`".DB_PREFIX."_group` AS g
WHERE u2g.fk_user_id = '".$this->_DB->real_escape_string($this->userID)."'
AND u2g.fk_group_id = g.id";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $this->userData['groups'][$result['groupId']] = array(
- 'groupName' => $result['groupName'],
- 'groupDescription' => $result['groupDescription']
- );
- }
- }
-
- $this->userData['isRoot'] = false;
- $grIds = array_keys($this->userData['groups']);
- if(in_array(ADMIN_GROUP_ID,$grIds)) {
- $this->userData['isRoot'] = true;
- }
- }
- }
-
- /**
- * destroy and remove the current session from SESSION and session table
- * @return boolean
- */
- protected function _destroySession() {
- $timeframe = date("Y-m-d H:i:s",time()-SESSION_LIFETIME);
- $query = $this->_DB->query("DELETE FROM `".DB_PREFIX."_userSession`
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $this->userData['groups'][$result['groupId']] = array(
+ 'groupName' => $result['groupName'],
+ 'groupDescription' => $result['groupDescription']
+ );
+ }
+ }
+
+ $this->userData['isRoot'] = false;
+ $grIds = array_keys($this->userData['groups']);
+ if(in_array(ADMIN_GROUP_ID,$grIds)) {
+ $this->userData['isRoot'] = true;
+ }
+ }
+ }
+
+ /**
+ * destroy and remove the current session from SESSION and session table
+ * @return boolean
+ */
+ protected function _destroySession() {
+ $timeframe = date("Y-m-d H:i:s",time()-SESSION_LIFETIME);
+ $query = $this->_DB->query("DELETE FROM `".DB_PREFIX."_userSession`
WHERE `fk_user_id` = '".$this->_DB->real_escape_string($this->userID)."'
OR `loginTime` <= '".$timeframe."'");
- unset($_SESSION);
- unset($_COOKIE);
- session_destroy();
-
- return true;
- }
-
- /**
- * create the usertoken based on the HEADER information:
- * HTTP_USER_AGENT, REMOTE_ADDR, HTTP_ACCEPT, HTTP_ACCEPT_LANGUAGE
- * HTTP_ACCEPT_ENCODING, HTTP_VIA
- * and a salt
- *
- * @param bool $salt
- * @return bool
- */
- protected function _createToken($salt=false) {
- $ret = false;
-
- $defaultStr = "unknown";
-
- if(!isset($_SERVER['HTTP_USER_AGENT'])) $_SERVER['HTTP_USER_AGENT'] = $defaultStr;
- if(!isset($_SERVER['REMOTE_ADDR'])) $_SERVER['REMOTE_ADDR'] = $defaultStr;
- if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $defaultStr;
- if(!isset($_SERVER['HTTP_VIA'])) $_SERVER['HTTP_VIA'] = $defaultStr;
- if(!isset($_SERVER['HTTP_DNT'])) $_SERVER['HTTP_DNT'] = $defaultStr;
-
- // cli info
- if(!isset($_SERVER['PATH'])) $_SERVER['PATH'] = $defaultStr;
- if(!isset($_SERVER['SHELL'])) $_SERVER['SHELL'] = $defaultStr;
- if(!isset($_SERVER['SESSION_MANAGER'])) $_SERVER['SESSION_MANAGER'] = $defaultStr;
- if(!isset($_SERVER['USER'])) $_SERVER['USER'] = $defaultStr;
-
- $finalString = $_SERVER['HTTP_USER_AGENT']
- .$_SERVER['REMOTE_ADDR']
- .$_SERVER['HTTP_ACCEPT_LANGUAGE']
- .$_SERVER['HTTP_DNT']
- .$_SERVER['HTTP_VIA']
- .$_SERVER['PATH']
- .$_SERVER['SHELL']
- .$_SERVER['SESSION_MANAGER']
- .$_SERVER['USER'];
-
- # check how often we have unknown in it
- # the more the less secure...
- $_count = substr_count($finalString, $defaultStr);
- if($_count < 5) {
- if(empty($salt)) {
- # 8 chars
- $salt = bin2hex(openssl_random_pseudo_bytes(4));
- }
- $ret['token'] = sha1($finalString.$salt);
- $ret['salt'] = $salt;
- }
-
- return $ret;
- }
+ unset($_SESSION);
+ unset($_COOKIE);
+ session_destroy();
+
+ return true;
+ }
+
+ /**
+ * create the usertoken based on the HEADER information:
+ * HTTP_USER_AGENT, REMOTE_ADDR, HTTP_ACCEPT, HTTP_ACCEPT_LANGUAGE
+ * HTTP_ACCEPT_ENCODING, HTTP_VIA
+ * and a salt
+ *
+ * @param bool $salt
+ * @return bool
+ */
+ protected function _createToken($salt=false) {
+ $ret = false;
+
+ $defaultStr = "unknown";
+
+ if(!isset($_SERVER['HTTP_USER_AGENT'])) $_SERVER['HTTP_USER_AGENT'] = $defaultStr;
+ if(!isset($_SERVER['REMOTE_ADDR'])) $_SERVER['REMOTE_ADDR'] = $defaultStr;
+ if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $defaultStr;
+ if(!isset($_SERVER['HTTP_VIA'])) $_SERVER['HTTP_VIA'] = $defaultStr;
+ if(!isset($_SERVER['HTTP_DNT'])) $_SERVER['HTTP_DNT'] = $defaultStr;
+
+ // cli info
+ if(!isset($_SERVER['PATH'])) $_SERVER['PATH'] = $defaultStr;
+ if(!isset($_SERVER['SHELL'])) $_SERVER['SHELL'] = $defaultStr;
+ if(!isset($_SERVER['SESSION_MANAGER'])) $_SERVER['SESSION_MANAGER'] = $defaultStr;
+ if(!isset($_SERVER['USER'])) $_SERVER['USER'] = $defaultStr;
+
+ $finalString = $_SERVER['HTTP_USER_AGENT']
+ .$_SERVER['REMOTE_ADDR']
+ .$_SERVER['HTTP_ACCEPT_LANGUAGE']
+ .$_SERVER['HTTP_DNT']
+ .$_SERVER['HTTP_VIA']
+ .$_SERVER['PATH']
+ .$_SERVER['SHELL']
+ .$_SERVER['SESSION_MANAGER']
+ .$_SERVER['USER'];
+
+ # check how often we have unknown in it
+ # the more the less secure...
+ $_count = substr_count($finalString, $defaultStr);
+ if($_count < 5) {
+ if(empty($salt)) {
+ # 8 chars
+ $salt = bin2hex(openssl_random_pseudo_bytes(4));
+ }
+ $ret['token'] = sha1($finalString.$salt);
+ $ret['salt'] = $salt;
+ }
+
+ return $ret;
+ }
}
*/
class GoreNest {
- /**
- * the global DB object
- * @var object
- */
- private $_DB;
+ /**
+ * the global DB object
+ * @var object
+ */
+ private $_DB;
- /**
- * the current loaded user
- * @var object
- */
- private $_User;
+ /**
+ * the current loaded user
+ * @var object
+ */
+ private $_User;
- /**
- * the already loaded menu information
- * to avoid multiple calls to the DB
- * @var array
- */
- private $_menuData = array();
+ /**
+ * the already loaded menu information
+ * to avoid multiple calls to the DB
+ * @var array
+ */
+ private $_menuData = array();
- /**
- * GoreNest constructor.
- * @param $db
- * @param $user
- */
- public function __construct($db, $user) {
- $this->_DB = $db;
- $this->_User = $user;
- }
+ /**
+ * GoreNest constructor.
+ * @param $db
+ * @param $user
+ */
+ public function __construct($db, $user) {
+ $this->_DB = $db;
+ $this->_User = $user;
+ }
- /**
- * Get the menu data for given area and category.
- * This shows only entries which have a category set.
- * No category can be used for hidden entries.
- *
- * @param $category
- * @param bool $reload
- * @return array
- */
- public function get($category,$reload=false) {
+ /**
+ * Get the menu data for given area and category.
+ * This shows only entries which have a category set.
+ * No category can be used for hidden entries.
+ *
+ * @param $category
+ * @param bool $reload
+ * @return array
+ */
+ public function get($category,$reload=false) {
- if(empty($category)) return false;
+ if(empty($category)) return false;
- if(empty($reload) && isset($this->_menuData[$category])) {
- return $this->_menuData[$category];
- }
+ if(empty($reload) && isset($this->_menuData[$category])) {
+ return $this->_menuData[$category];
+ }
- # reset the menu
- $this->_menuData[$category] = array();
+ # reset the menu
+ $this->_menuData[$category] = array();
- $queryStr = "SELECT id, text, action, icon, category
+ $queryStr = "SELECT id, text, action, icon, category
FROM `".DB_PREFIX."_menu`
WHERE ".$this->_User->getSQLRightsString()."
AND `category` = '".$this->_DB->real_escape_string($category)."'
- ORDER BY position";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $this->_menuData[$result['category']][$result['id']] = $result;
- }
- }
+ ORDER BY position";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $this->_menuData[$result['category']][$result['id']] = $result;
+ }
+ }
- return $this->_menuData[$category];
- }
+ return $this->_menuData[$category];
+ }
- /**
- * Allowed page requests based on the menu entries and user
- * @return array
- */
- public function allowedPageRequests() {
- $ret = array();
- $queryStr = "SELECT id, action
+ /**
+ * Allowed page requests based on the menu entries and user
+ * @return array
+ */
+ public function allowedPageRequests() {
+ $ret = array();
+ $queryStr = "SELECT id, action
FROM `".DB_PREFIX."_menu`
WHERE ".$this->_User->getSQLRightsString()."";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['action']] = $result['action'];
- }
- }
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['action']] = $result['action'];
+ }
+ }
- return $ret;
- }
+ return $ret;
+ }
}
*/
class IMDB
{
- /**
- * Set this to true if you run into problems.
- */
- private $IMDB_DEBUG = false;
-
- /**
- * Set the preferred language for the User Agent.
- */
- private $IMDB_LANG = 'en-US,en;q=0.9';
-
- /**
- * Define the timeout for cURL requests.
- */
- private $IMDB_TIMEOUT = 15;
-
- /**
- * These are the regular expressions used to extract the data.
- * If you don’t know what you’re doing, you shouldn’t touch them.
- */
- const IMDB_AKA = '~<td[^>]*>\s*Also\s*Known\s*As\s*</td>\s*<td>(.+)</td>~Uis';
- const IMDB_ASPECT_RATIO = '~<td[^>]*>Aspect\s*Ratio</td>\s*<td>(.+)</td>~Uis';
- const IMDB_AWARDS = '~<div\s*class="titlereference-overview-section">\s*Awards:(.+)</div>~Uis';
- const IMDB_BUDGET = '~<td[^>]*>Budget<\/td>\s*<td>\s*(.*)(?:\(estimated\))\s*<\/td>~Ui';
- const IMDB_CAST = '~<td[^>]*itemprop="actor"[^>]*>\s*<a\s*href="/name/([^/]*)/\?[^"]*"[^>]*>\s*<span.+>(.+)</span~Ui';
- const IMDB_CAST_IMAGE = '~(loadlate="(.*)"[^>]*><\/a>\s+<\/td>\s+)?<td[^>]*itemprop="actor"[^>]*>\s*<a\s*href="\/name\/([^/]*)\/\?[^"]*"[^>]*>\s*<span.+>(.+)<\/span+~Uis';
- const IMDB_CERTIFICATION = '~<td[^>]*>\s*Certification\s*</td>\s*<td>(.+)</td>~Ui';
- const IMDB_CHAR = '~<td class="character">(?:\s+)<div>(.*)(?:\s+)(?: /| \(.*\)|<\/div>)~Ui';
- const IMDB_COLOR = '~<a href="\/search\/title\?colors=(?:.*)">(.*)<\/a>~Ui';
- const IMDB_COMPANY = '~href="[^"]*update=[t0-9]+:production_companies[^"]*">Edit</a>\s*</header>\s*<ul\s*class="simpleList">.+<a href="\/company\/(.*)\/">(.*)</a>~Ui';
- const IMDB_COUNTRY = '~<a href="/country/(\w+)">(.*)</a>~Ui';
- const IMDB_CREATOR = '~<div[^>]*>\s*(?:Creator|Creators)\s*:\s*<ul[^>]*>(.+)</ul>~Uxsi';
- const IMDB_DIRECTOR = '~<div[^>]*>\s*(?:Director|Directors)\s*:\s*<ul[^>]*>(.+)</ul>~Uxsi';
- const IMDB_GENRE = '~href="/genre/([a-zA-Z_-]*)/?">([a-zA-Z_ -]*)</a>~Ui';
- const IMDB_GROSS = '~pl-zebra-list__label">Cumulative Worldwide Gross<\/td>\s+<td>\s+(.*)\s+<~Uxsi';
- const IMDB_ID = '~((?:tt\d{6,})|(?:itle\?\d{6,}))~';
- const IMDB_LANGUAGE = '~<a href="\/language\/(\w+)">(.*)<\/a>~Ui';
- const IMDB_LOCATION = '~href="\/search\/title\?locations=(.*)">(.*)<\/a>~Ui';
- const IMDB_LOCATIONS = '~href="\/search\/title\?locations=[^>]*>\s?(.*)\s?<\/a>[^"]*<dd>\s?(.*)\s<\/dd>~Ui';
- const IMDB_MPAA = '~<li class="ipl-inline-list__item">(?:\s+)(TV-Y|TV-Y7|TV-G|TV-PG|TV-14|TV-MA|G|PG|PG-13|R|NC-17|NR|UR)(?:\s+)<\/li>~Ui';
- const IMDB_NAME = '~href="/name/(.+)/?(?:\?[^"]*)?"[^>]*>(.+)</a>~Ui';
- const IMDB_DESCRIPTION = '~<section class="titlereference-section-overview">\s+<div>(.*)</div>\s+<hr>~Ui';
- const IMDB_NOT_FOUND = '~<h1 class="findHeader">No results found for ~Ui';
- const IMDB_PLOT = '~<td[^>]*>\s*Plot\s*Summary\s*</td>\s*<td>\s*<p>(.+)</p>~Ui';
- const IMDB_PLOT_KEYWORDS = '~<td[^>]*>Plot\s*Keywords</td>\s*<td>(.+)(?:<a\s*href="/title/[^>]*>[^<]*</a>\s*</li>\s*</ul>\s*)?</td>~Ui';
- const IMDB_POSTER = '~<link\s*rel=\'image_src\'\s*href="(.*)">~Ui';
- const IMDB_RATING = '~class="ipl-rating-star__rating">(.*)<~Ui';
- const IMDB_RATING_COUNT = '~class="ipl-rating-star__total-votes">\((.*)\)<~Ui';
- const IMDB_RELEASE_DATE = '~href="/title/[t0-9]*/releaseinfo">(.*)<~Ui';
- const IMDB_RUNTIME = '~<td[^>]*>\s*Runtime\s*</td>\s*<td>(.+)</td>~Ui';
- const IMDB_SEARCH = '~<td class="result_text"> <a href="\/title\/(tt\d{6,})\/(?:.*)"(?:\s*)>(?:.*)<\/a>~Ui';
- const IMDB_SEASONS = '~episodes\?season=(?:\d+)">(\d+)<~Ui';
- const IMDB_SOUND_MIX = '~<td[^>]*>\s*Sound\s*Mix\s*</td>\s*<td>(.+)</td>~Ui';
- const IMDB_TAGLINE = '~<td[^>]*>\s*Taglines\s*</td>\s*<td>(.+)</td>~Ui';
- const IMDB_TITLE = '~itemprop="name">(.*)(<\/h3>|<span)~Ui';
- const IMDB_TITLE_ORIG = '~</h3>(?:\s+)(.*)(?:\s+)<span class=\"titlereference-original-title-label~Ui';
- const IMDB_TRAILER = '~href="videoplayer/(vi[0-9]*)"~Ui';
- const IMDB_URL = '~https?://(?:.*\.|.*)imdb.com/(?:t|T)itle(?:\?|/)(..\d+)~i';
- const IMDB_USER_REVIEW = '~href="/title/[t0-9]*/reviews"[^>]*>([^<]*)\s*User~Ui';
- const IMDB_VOTES = '~"ipl-rating-star__total-votes">\s*\((.*)\)\s*<~Ui';
- const IMDB_WRITER = '~<div[^>]*>\s*(?:Writer|Writers)\s*:\s*<ul[^>]*>(.+)</ul>~Ui';
- const IMDB_YEAR = '~og:title\' content="(?:.*)\((?:.*)(\d{4})(?:.*)\)~Ui';
-
- /**
- * @var string The string returned, if nothing is found.
- */
- public $sNotFound = 'n/A';
-
- /**
- * @var null|int The ID of the movie.
- */
- public $iId = null;
-
- /**
- * @var bool Is the content ready?
- */
- public $isReady = false;
-
- /**
- * @var string Char that separates multiple entries.
- */
- public $sSeparator = ' / ';
-
- /**
- * @var null|string The URL to the movie.
- */
- public $sUrl = null;
-
- /**
- * @var bool Return responses enclosed in array
- */
- public $bArrayOutput = false;
-
- /**
- * @var int Maximum cache time.
- */
- private $iCache = 1440;
-
- /**
- * @var null|string The root of the script.
- */
- private $sRoot = null;
-
- /**
- * @var null|string Holds the source.
- */
- private $sSource = null;
-
- /**
- * @var string What to search for?
- */
- private $sSearchFor = 'all';
-
- /**
- * IMDB constructor. Can now set some options
- *
- * @param $options array with the following options
- * int iCache Custom cache time in minutes.
- * string sSearchFor What type to search for?
- * string storage Where to store data. Absolute path
- * boolean debug Show depubg messages or not
- */
- public function __construct($options) {
-
- if(isset($options['debug']) && !empty($options['debug'])) {
- $this->IMDB_DEBUG = true;
- }
-
- if(isset($options['iCache']) && !empty($options['iCache'])) $this->iCache = (int) $options['iCache'];
-
- $this->sRoot = dirname(__FILE__);
- if(isset($options['storage']) && !empty($options['storage'])) {
- $this->sRoot = $options['storage'];
- }
-
- if(isset($options['sSearchFor']) && !empty($options['sSearchFor'])) {
- if (in_array(
- $options['sSearchFor'],
- [
- 'movie',
- 'tv',
- 'episode',
- 'game',
- 'all',
- ]
- )) {
- $this->sSearchFor = $options['sSearchFor'];
- }
- }
- }
-
-
- /**
- * @param $sSearch
- * @throws Exception
- */
- public function search($sSearch) {
-
- $sSearch = trim($sSearch);
- if(empty($sSearch)) {
- throw new Exception('Missing search term');
- }
-
- if ( ! is_writable($this->sRoot . '/posters') && ! mkdir($this->sRoot . '/posters')) {
- throw new Exception('The directory “' . $this->sRoot . '/posters” isn’t writable.');
- }
- if ( ! is_writable($this->sRoot . '/cache') && ! mkdir($this->sRoot . '/cache')) {
- throw new Exception('The directory “' . $this->sRoot . '/cache” isn’t writable.');
- }
- if ( ! is_writable($this->sRoot . '/cast') && ! mkdir($this->sRoot . '/cast')) {
- throw new Exception('The directory “' . $this->sRoot . '/cast” isn’t writable.');
- }
-
- if ( ! function_exists('curl_init')) {
- throw new Exception('You need to enable the PHP cURL extension.');
- }
-
- $this->fetchUrl($sSearch);
- }
-
- /**
- * @param string $sSearch IMDb URL or movie title to search for.
- *
- * @return bool True on success, false on failure.
- */
- private function fetchUrl($sSearch)
- {
-
-
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>Running:</b> fetchUrl("' . $sSearch . '")</pre>';
- }
-
- // Try to find a valid URL.
- $sId = $this->matchRegex($sSearch, self::IMDB_ID, 1);
- if (false !== $sId) {
- $this->iId = preg_replace('~[\D]~', '', $sId);
- $this->sUrl = 'https://www.imdb.com/title/tt' . $this->iId . '/reference';
- $bSearch = false;
- } else {
- switch (strtolower($this->sSearchFor)) {
- case 'movie':
- $sParameters = '&s=tt&ttype=ft';
- break;
- case 'tv':
- $sParameters = '&s=tt&ttype=tv';
- break;
- case 'episode':
- $sParameters = '&s=tt&ttype=ep';
- break;
- case 'game':
- $sParameters = '&s=tt&ttype=vg';
- break;
- default:
- $sParameters = '&s=tt';
- }
-
- $this->sUrl = 'https://www.imdb.com/find?q=' . rawurlencode(str_replace(' ', '+', $sSearch)) . $sParameters;
- $bSearch = true;
-
- // Was this search already performed and cached?
- $sRedirectFile = $this->sRoot . '/cache/' . sha1($this->sUrl) . '.redir';
- if (is_readable($sRedirectFile)) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>Using redirect:</b> ' . basename($sRedirectFile) . '</pre>';
- }
- $sRedirect = file_get_contents($sRedirectFile);
- $this->sUrl = trim($sRedirect);
- $this->iId = preg_replace('~[\D]~', '', $this->matchRegex($sRedirect, self::IMDB_ID, 1));
- $bSearch = false;
- }
- }
-
- // Does a cache of this movie exist?
- $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '.cache';
- if (is_readable($sCacheFile)) {
- $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
- if ($iDiff < $this->iCache) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>Using cache:</b> ' . basename($sCacheFile) . '</pre>';
- }
- $this->sSource = file_get_contents($sCacheFile);
- $this->isReady = true;
-
- return true;
- }
- }
-
- // Run cURL on the URL.
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>Running cURL:</b> ' . $this->sUrl . '</pre>';
- }
-
- $aCurlInfo = $this->runCurl($this->sUrl);
- $sSource = $aCurlInfo['contents'];
-
- if (false === $sSource) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
- }
-
- return false;
- }
-
- // Was the movie found?
- $sMatch = $this->matchRegex($sSource, self::IMDB_SEARCH, 1);
- if (false !== $sMatch) {
- $sUrl = 'https://www.imdb.com/title/' . $sMatch . '/reference';
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>New redirect saved:</b> ' . basename($sRedirectFile) . ' => ' . $sUrl . '</pre>';
- }
- file_put_contents($sRedirectFile, $sUrl);
- $this->sSource = null;
- $this->fetchUrl($sUrl);
-
- return true;
- }
- $sMatch = $this->matchRegex($sSource, self::IMDB_NOT_FOUND, 0);
- if (false !== $sMatch) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>Movie not found:</b> ' . $sSearch . '</pre>';
- }
-
- return false;
- }
-
- $this->sSource = str_replace(
- [
- "\n",
- "\r\n",
- "\r",
- ],
- '',
- $sSource
- );
- $this->isReady = true;
-
- // Save cache.
- if (false === $bSearch) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>Cache created:</b> ' . basename($sCacheFile) . '</pre>';
- }
- file_put_contents($sCacheFile, $this->sSource);
- }
-
- return true;
- }
-
- /**
- * @return array All data.
- */
- public function getAll()
- {
- $aData = [];
- foreach (get_class_methods(__CLASS__) as $method) {
- if (substr($method, 0, 3) === 'get' && $method !== 'getAll' && $method !== 'getCastImages') {
- $aData[$method] = [
- 'name' => ltrim($method, 'get'),
- 'value' => $this->{$method}(),
- ];
- }
- }
- array_multisort($aData);
-
- return $aData;
- }
-
- /**
- * @return string “Also Known As” or $sNotFound.
- */
- public function getAka()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_AKA, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * Returns all local names
- *
- * @return string All local names.
- */
- public function getAkas()
- {
- if (true === $this->isReady) {
- // Does a cache of this movie exist?
- $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '_akas.cache';
- $bUseCache = false;
-
- if (is_readable($sCacheFile)) {
- $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
- if ($iDiff < $this->iCache || false) {
- $bUseCache = true;
- }
- }
-
- if ($bUseCache) {
- $aRawReturn = file_get_contents($sCacheFile);
- $aReturn = unserialize($aRawReturn);
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- } else {
- $fullAkas = sprintf('https://www.imdb.com/title/tt%s/releaseinfo', $this->iId);
- $aCurlInfo = $this->runCurl($fullAkas);
- $sSource = $aCurlInfo['contents'];
-
- if (false === $sSource) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
- }
-
- return false;
- }
-
- $aReturned = $this->matchRegex($sSource, "~<td>(.*?)<\/td>\s+<td>(.*?)<\/td>~");
-
- if ($aReturned) {
- $aReturn = [];
- foreach ($aReturned[1] as $i => $strName) {
- if (strpos($strName, '(') === false) {
- $aReturn[] = [
- 'title' => $this->cleanString($aReturned[2][$i]),
- 'country' => $this->cleanString($strName),
- ];
- }
- }
-
- file_put_contents($sCacheFile, serialize($aReturn));
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string “Aspect Ratio” or $sNotFound.
- */
- public function getAspectRatio()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_ASPECT_RATIO, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The awards of the movie or $sNotFound
- */
- public function getAwards()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_AWARDS, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param int $iLimit How many cast members should be returned?
- * @param bool $bMore Add … if there are more cast members than printed.
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with linked cast members or $sNotFound.
- */
- public function getCastAsUrl($iLimit = 0, $bMore = true, $sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- if (0 !== $iLimit && $i >= $iLimit) {
- break;
- }
- $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
- $aMatch[1][$i]
- ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
-
- return $this->arrayOutput(
- $this->bArrayOutput,
- $this->sSeparator,
- $this->sNotFound,
- $aReturn,
- $bHaveMore
- );
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param int $iLimit How many cast members should be returned?
- * @param bool $bMore Add … if there are more cast members than printed.
- *
- * @return string A list with cast members or $sNotFound.
- */
- public function getCast($iLimit = 0, $bMore = true)
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- if (0 !== $iLimit && $i >= $iLimit) {
- break;
- }
- $aReturn[] = $this->cleanString($sName);
- }
-
- $bMore = (0 !== $iLimit && $bMore && (count($aMatch[2]) > $iLimit) ? '…' : '');
-
- $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
-
- return $this->arrayOutput(
- $this->bArrayOutput,
- $this->sSeparator,
- $this->sNotFound,
- $aReturn,
- $bHaveMore
- );
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @param int $iLimit How many cast images should be returned?
- * @param bool $bMore Add … if there are more cast members than printed.
- * @param string $sSize small, mid or big cast images
- * @param bool $bDownload Return URL or Download
- *
- * @return array Array with cast name as key, and image as value.
- */
- public function getCastImages($iLimit = 0, $bMore = true, $sSize = 'small', $bDownload = false)
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST_IMAGE);
- $aReturn = [];
- if (count($aMatch[4])) {
- foreach ($aMatch[4] as $i => $sName) {
- if (0 !== $iLimit && $i >= $iLimit) {
- break;
- }
- $sMatch = $aMatch[2][$i];
-
- if ('big' === strtolower($sSize) && false !== strstr($aMatch[2][$i], '@._')) {
- $sMatch = substr($aMatch[2][$i], 0, strpos($aMatch[2][$i], '@._')) . '@.jpg';
- } elseif ('mid' === strtolower($sSize) && false !== strstr($aMatch[2][$i], '@._')) {
- $sMatch = substr($aMatch[2][$i], 0, strpos($aMatch[2][$i], '@._')) . '@._V1_UX214_AL_.jpg';
- }
-
- if (false === $bDownload) {
- $sMatch = $this->cleanString($sMatch);
- } else {
- $sLocal = $this->saveImageCast($sMatch, $aMatch[3][$i]);
- if (file_exists(dirname(__FILE__) . '/' . $sLocal)) {
- $sMatch = $sLocal;
- } else {
- //the 'big' image isn't available, try the 'mid' one (vice versa)
- if ('big' === strtolower($sSize) && false !== strstr($aMatch[2][$i], '@._')) {
- //trying the 'mid' one
- $sMatch = substr(
- $aMatch[2][$i],
- 0,
- strpos($aMatch[2][$i], '@._')
- ) . '@._V1_UX214_AL_.jpg';
- } else {
- //trying the 'big' one
- $sMatch = substr($aMatch[2][$i], 0, strpos($aMatch[2][$i], '@._')) . '@.jpg';
- }
-
- $sLocal = $this->saveImageCast($sMatch, $aMatch[3][$i]);
- if (file_exists(dirname(__FILE__) . '/' . $sLocal)) {
- $sMatch = $sLocal;
- } else {
- $sMatch = $this->cleanString($aMatch[2][$i]);
- }
- }
- }
-
- $aReturn[$this->cleanString($aMatch[4][$i])] = $sMatch;
- }
-
- $bMore = (0 !== $iLimit && $bMore && (count($aMatch[4]) > $iLimit) ? '…' : '');
-
- $bHaveMore = ($bMore && (count($aMatch[4]) > $iLimit));
-
- $aReturn = array_replace(
- $aReturn,
- array_fill_keys(
- array_keys($aReturn, $this->sNotFound),
- 'cast/not-found.jpg'
- )
- );
-
- return $aReturn;
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @param int $iLimit How many cast members should be returned?
- * @param bool $bMore Add … if there are more cast members than
- * printed.
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with linked cast members and their character or
- * $sNotFound.
- */
- public function getCastAndCharacterAsUrl($iLimit = 0, $bMore = true, $sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
- $aMatchChar = $this->matchRegex($this->sSource, self::IMDB_CHAR);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- if (0 !== $iLimit && $i >= $iLimit) {
- break;
- }
- $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
- $aMatch[1][$i]
- ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a> as ' . $this->cleanString($aMatchChar[1][$i]);
- }
-
- $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
-
- return $this->arrayOutput(
- $this->bArrayOutput,
- $this->sSeparator,
- $this->sNotFound,
- $aReturn,
- $bHaveMore
- );
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @param int $iLimit How many cast members should be returned?
- * @param bool $bMore Add … if there are more cast members than printed.
- *
- * @return string A list with cast members and their character or
- * $sNotFound.
- */
- public function getCastAndCharacter($iLimit = 0, $bMore = true)
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
- $aMatchChar = $this->matchRegex($this->sSource, self::IMDB_CHAR);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- if (0 !== $iLimit && $i >= $iLimit) {
- break;
- }
- $aReturn[] = $this->cleanString($sName) . ' as ' . $this->cleanString($aMatchChar[1][$i]);
- }
-
- $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
-
- return $this->arrayOutput(
- $this->bArrayOutput,
- $this->sSeparator,
- $this->sNotFound,
- $aReturn,
- $bHaveMore
- );
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string The certification of the movie or $sNotFound.
- */
- public function getCertification()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_CERTIFICATION, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string Color or $sNotFound.
- */
- public function getColor()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_COLOR, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The company producing the movie or $sNotFound.
- */
- public function getCompany()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getCompanyAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string The linked company producing the movie or $sNotFound.
- */
- public function getCompanyAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_COMPANY);
- if (isset($aMatch[2][0])) {
- return '<a href="https://www.imdb.com/company/' . $this->cleanString(
- $aMatch[1][0]
- ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $aMatch[2][0]
- ) . '</a>';
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string A list with countries or $sNotFound.
- */
- public function getCountry()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getCountryAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with linked countries or $sNotFound.
- */
- public function getCountryAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_COUNTRY);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/country/' . trim(
- $aMatch[1][$i]
- ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string A list with the creators or $sNotFound.
- */
- public function getCreator()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getCreatorAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with the linked creators or $sNotFound.
- */
- public function getCreatorAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_CREATOR, 1);
- $aMatch = $this->matchRegex($sMatch, self::IMDB_NAME);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
- $aMatch[1][$i]
- ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string The description of the movie or $sNotFound.
- */
- public function getDescription()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_DESCRIPTION, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string A list with the directors or $sNotFound.
- */
- public function getDirector()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getDirectorAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with the linked directors or $sNotFound.
- */
- public function getDirectorAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_DIRECTOR, 1);
- $aMatch = $this->matchRegex($sMatch, self::IMDB_NAME);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
- $aMatch[1][$i]
- ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string A list with the genres or $sNotFound.
- */
- public function getGenre()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getGenreAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with the linked genres or $sNotFound.
- */
- public function getGenreAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_GENRE);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach (array_unique($aMatch[2]) as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/search/title?genres=' . $this->cleanString(
- $aMatch[1][$i]
- ) . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string cumulative worldwide gross or $sNotFound.
- */
- public function getGross()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_GROSS, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string A list with the languages or $sNotFound.
- */
- public function getLanguage()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getLanguageAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with the linked languages or $sNotFound.
- */
- public function getLanguageAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_LANGUAGE);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/language/' . $this->cleanString(
- $aMatch[1][$i]
- ) . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string A list with the location or $sNotFound.
- */
- public function getLocation()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getLocationAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with the linked location or $sNotFound.
- */
- public function getLocationAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_LOCATION);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/search/title?locations=' . $this->cleanString(
- $aMatch[1][$i]
- ) . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * Returns all locations
- *
- * @return string location
- * @return string specification
- */
- public function getLocations()
- {
- if (true === $this->isReady) {
- // Does a cache of this movie exist?
- $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '_locations.cache';
- $bUseCache = false;
-
- if (is_readable($sCacheFile)) {
- $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
- if ($iDiff < $this->iCache || false) {
- $bUseCache = true;
- }
- }
-
- if ($bUseCache) {
- $aRawReturn = file_get_contents($sCacheFile);
- $aReturn = unserialize($aRawReturn);
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- } else {
- $fullLocations = sprintf('https://www.imdb.com/title/tt%s/locations', $this->iId);
- $aCurlInfo = $this->runCurl($fullLocations);
- $sSource = $aCurlInfo['contents'];
-
- if (false === $sSource) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
- }
-
- return false;
- }
-
- $aReturned = $this->matchRegex($sSource, self::IMDB_LOCATIONS);
-
- if ($aReturned) {
- $aReturn = [];
- foreach ($aReturned[1] as $i => $strName) {
- if (strpos($strName, '(') === false) {
- $aReturn[] = [
- 'location' => $this->cleanString($strName),
- ];
- }
- if (strpos($aReturned[2][$i], '(') !== false) {
- $aReturn[] = [
- 'specification' => $this->cleanString($aReturned[2][$i]),
- ];
- }
- }
-
- file_put_contents($sCacheFile, serialize($aReturn));
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string The MPAA of the movie or $sNotFound.
- */
- public function getMpaa()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_MPAA, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string A list with the plot keywords or $sNotFound.
- */
- public function getPlotKeywords()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_PLOT_KEYWORDS, 1);
- if (false !== $sMatch) {
- $aReturn = explode('|', $this->cleanString($sMatch));
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @param int $iLimit The limit.
- *
- * @return string The plot of the movie or $sNotFound.
- */
- public function getPlot($iLimit = 0)
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_PLOT, 1);
- if (false !== $sMatch) {
- if ($iLimit !== 0) {
- return $this->shortText($this->cleanString($sMatch), $iLimit);
- }
-
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sSize Small, big, xxs, xs, s poster?
- * @param bool $bDownload Return URL to the poster or download it?
- *
- * @return bool|string Path to the poster.
- */
- public function getPoster($sSize = 'small', $bDownload = false)
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_POSTER, 1);
- if (false !== $sMatch) {
- if ('big' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
- $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@.jpg';
- }
- if ('xxs' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
- $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@._V1_UY67_CR0,0,45,67_AL_.jpg';
- }
- if ('xs' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
- $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@._V1_UY113_CR0,0,76,113_AL_.jpg';
- }
- if ('s' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
- $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@._V1_UX182_CR0,0,182,268_AL_.jpg';
- }
- if (false === $bDownload) {
- return $this->cleanString($sMatch);
- } else {
- $sLocal = $this->saveImage($sMatch, $this->iId);
- if (file_exists(dirname(__FILE__) . '/' . $sLocal)) {
- return $sLocal;
- } else {
- return $sMatch;
- }
- }
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The rating of the movie or $sNotFound.
- */
- public function getRating()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_RATING, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The rating count of the movie or $sNotFound.
- */
- public function getRatingCount()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_RATING_COUNT, 1);
- if (false !== $sMatch) {
- return str_replace(',', '', $this->cleanString($sMatch));
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * Release date doesn't contain all the information we need to create a media and
- * we need this function that checks if users can vote target media (if can, it's released).
- *
- * @return true If the media is released
- */
- public function isReleased()
- {
- $strReturn = $this->getReleaseDate();
- if ($strReturn == $this->sNotFound || $strReturn == 'Not yet released') {
- return false;
- }
-
- return true;
- }
-
- /**
- * @return string The release date of the movie or $sNotFound.
- */
- public function getReleaseDate()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_RELEASE_DATE, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * Returns all local names
- *
- * @return string country
- * @return string release date
- */
- public function getReleaseDates()
- {
- if (true === $this->isReady) {
- // Does a cache of this movie exist?
- $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '_akas.cache';
- $bUseCache = false;
-
- if (is_readable($sCacheFile)) {
- $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
- if ($iDiff < $this->iCache || false) {
- $bUseCache = true;
- }
- }
-
- if ($bUseCache) {
- $aRawReturn = file_get_contents($sCacheFile);
- $aReturn = unserialize($aRawReturn);
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- } else {
- $fullAkas = sprintf('https://www.imdb.com/title/tt%s/releaseinfo', $this->iId);
- $aCurlInfo = $this->runCurl($fullAkas);
- $sSource = $aCurlInfo['contents'];
-
- if (false === $sSource) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
- }
-
- return false;
- }
-
- $aReturned = $this->matchRegex(
- $sSource,
- '~>(.*)<\/a><\/td>\s+<td class="release_date">(.*)<\/td>~'
- );
-
- if ($aReturned) {
- $aReturn = [];
- foreach ($aReturned[1] as $i => $strName) {
- if (strpos($strName, '(') === false) {
- $aReturn[] = [
- 'country' => $this->cleanString($strName),
- 'releasedate' => $this->cleanString($aReturned[2][$i]),
- ];
- }
- }
-
- file_put_contents($sCacheFile, serialize($aReturn));
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string The runtime of the movie or $sNotFound.
- */
- public function getRuntime()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_RUNTIME, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string A list with the seasons or $sNotFound.
- */
- public function getSeasons()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getSeasonsAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with the linked seasons or $sNotFound.
- */
- public function getSeasonsAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $aMatch = $this->matchRegex($this->sSource, self::IMDB_SEASONS);
- $aReturn = [];
- if (count($aMatch[1])) {
- foreach (range(1, max($aMatch[1])) as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/title/tt' . $this->iId . '/episodes?season=' . $sName . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $sName . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
- }
-
- /**
- * @return string The sound mix of the movie or $sNotFound.
- */
- public function getSoundMix()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_SOUND_MIX, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The tagline of the movie or $sNotFound.
- */
- public function getTagline()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_TAGLINE, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param bool $bForceLocal Try to return the original name of the movie.
- *
- * @return string The title of the movie or $sNotFound.
- */
- public function getTitle($bForceLocal = false)
- {
- if (true === $this->isReady) {
- if (true === $bForceLocal) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_TITLE_ORIG, 1);
- if (false !== $sMatch && "" !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_TITLE, 1);
- $sMatch = preg_replace('~\(\d{4}\)$~Ui', '', $sMatch);
- if (false !== $sMatch && "" !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param bool $bEmbed Link to player directly?
- *
- * @return string The URL to the trailer of the movie or $sNotFound.
- */
- public function getTrailerAsUrl($bEmbed = false)
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_TRAILER, 1);
- if (false !== $sMatch) {
- $sUrl = 'https://www.imdb.com/video/imdb/' . $sMatch . '/' . ($bEmbed ? 'player' : '');
-
- return $this->cleanString($sUrl);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The IMDb URL.
- */
- public function getUrl()
- {
- if (true === $this->isReady) {
- return $this->cleanString(str_replace('reference', '', $this->sUrl));
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The user review of the movie or $sNotFound.
- */
- public function getUserReview()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_USER_REVIEW, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The votes of the movie or $sNotFound.
- */
- public function getVotes()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_VOTES, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string A list with the writers or $sNotFound.
- */
- public function getWriter()
- {
- if (true === $this->isReady) {
- $sMatch = $this->getWriterAsUrl();
- if ($this->sNotFound !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @param string $sTarget Add a target to the links?
- *
- * @return string A list with the linked writers or $sNotFound.
- */
- public function getWriterAsUrl($sTarget = '')
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_WRITER, 1);
- $aMatch = $this->matchRegex($sMatch, self::IMDB_NAME);
- $aReturn = [];
- if (count($aMatch[2])) {
- foreach ($aMatch[2] as $i => $sName) {
- $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
- $aMatch[1][$i]
- ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
- $sName
- ) . '</a>';
- }
-
- return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The year of the movie or $sNotFound.
- */
- public function getYear()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_YEAR, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
- /**
- * @return string The budget of the movie or $sNotFound.
- */
- public function getBudget()
- {
- if (true === $this->isReady) {
- $sMatch = $this->matchRegex($this->sSource, self::IMDB_BUDGET, 1);
- if (false !== $sMatch) {
- return $this->cleanString($sMatch);
- }
- }
-
- return $this->sNotFound;
- }
-
-
- /**
- * Regular expression helper.
- *
- * @param string $sContent The content to search in.
- * @param string $sPattern The regular expression.
- * @param null $iIndex The index to return.
- *
- * @return bool If no match was found.
- * @return string If one match was found.
- * @return array If more than one match was found.
- */
- private function matchRegex($sContent, $sPattern, $iIndex = null)
- {
- preg_match_all($sPattern, $sContent, $aMatches);
- if ($aMatches === false) {
- return false;
- }
- if ($iIndex !== null && is_int($iIndex)) {
- if (isset($aMatches[$iIndex][0])) {
- return $aMatches[$iIndex][0];
- }
-
- return false;
- }
-
- return $aMatches;
- }
-
- /**
- * Preferred output in responses with multiple elements
- *
- * @param bool $bArrayOutput Native array or string with separators.
- * @param string $sSeparator String separator.
- * @param string $sNotFound Not found text.
- * @param array $aReturn Original input.
- * @param bool $bHaveMore Have more elements indicator.
- *
- * @return string|array Multiple results separated by selected separator string, or enclosed into native array.
- */
- private function arrayOutput($bArrayOutput, $sSeparator, $sNotFound, $aReturn = null, $bHaveMore = false)
- {
- if ($bArrayOutput) {
- if ($aReturn == null || ! is_array($aReturn)) {
- return [];
- }
-
- if ($bHaveMore) {
- $aReturn[] = '…';
- }
-
- return $aReturn;
- } else {
- if ($aReturn == null || ! is_array($aReturn)) {
- return $sNotFound;
- }
-
- foreach ($aReturn as $i => $value) {
- if (is_array($value)) {
- $aReturn[$i] = implode($sSeparator, $value);
- }
- }
-
- return implode($sSeparator, $aReturn) . (($bHaveMore) ? '…' : '');
- }
- }
-
- /**
- * @param string $sInput Input (eg. HTML).
- *
- * @return string Cleaned string.
- */
- private function cleanString($sInput)
- {
- $aSearch = [
- 'Full summary »',
- 'Full synopsis »',
- 'Add summary »',
- 'Add synopsis »',
- 'See more »',
- 'See why on IMDbPro.',
- "\n",
- "\r",
- ];
- $aReplace = [
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- ];
- $sInput = str_replace('</li>', ' | ', $sInput);
- $sInput = strip_tags($sInput);
- $sInput = str_replace(' ', ' ', $sInput);
- $sInput = str_replace($aSearch, $aReplace, $sInput);
- $sInput = html_entity_decode($sInput, ENT_QUOTES | ENT_HTML5);
- $sInput = preg_replace('/\s+/', ' ', $sInput);
- $sInput = trim($sInput);
- $sInput = rtrim($sInput, ' |');
-
- return ($sInput ? trim($sInput) : $this->sNotFound);
- }
-
- /**
- * @param string $sText The long text.
- * @param int $iLength The maximum length of the text.
- *
- * @return string The shortened text.
- */
- private function shortText($sText, $iLength = 100)
- {
- if (mb_strlen($sText) <= $iLength) {
- return $sText;
- }
-
- list($sShort) = explode("\n", wordwrap($sText, $iLength - 1));
-
- if (substr($sShort, -1) !== '.') {
- return $sShort . '…';
- }
-
- return $sShort;
- }
-
- /**
- * @param string $sUrl The URL to the image to download.
- * @param int $iId The ID of the movie.
- *
- * @return string Local path.
- */
- private function saveImage($sUrl, $iId)
- {
- if (preg_match('~title_addposter.jpg|imdb-share-logo.png~', $sUrl)) {
- return 'posters/not-found.jpg';
- }
-
- $sFilename = $this->sRoot . '/posters/' . $iId . '.jpg';
- if (file_exists($sFilename)) {
- return 'posters/' . $iId . '.jpg';
- }
-
- $aCurlInfo = $this->runCurl($sUrl, true);
- $sData = $aCurlInfo['contents'];
- if (false === $sData) {
- return 'posters/not-found.jpg';
- }
-
- $oFile = fopen($sFilename, 'x');
- fwrite($oFile, $sData);
- fclose($oFile);
-
- return 'posters/' . $iId . '.jpg';
- }
-
- /**
- * @param string $sUrl The URL to fetch.
- * @param bool $bDownload Download?
- *
- * @return bool|mixed Array on success, false on failure.
- */
- private function runCurl($sUrl, $bDownload = false)
- {
- $oCurl = curl_init($sUrl);
- curl_setopt_array(
- $oCurl,
- [
- CURLOPT_BINARYTRANSFER => ($bDownload ? true : false),
- CURLOPT_CONNECTTIMEOUT => $this->IMDB_TIMEOUT,
- CURLOPT_ENCODING => '',
- CURLOPT_FOLLOWLOCATION => 0,
- CURLOPT_FRESH_CONNECT => 0,
- CURLOPT_HEADER => ($bDownload ? false : true),
- CURLOPT_HTTPHEADER => [
- 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
- 'Accept-Charset: utf-8, iso-8859-1;q=0.5',
- 'Accept-Language: ' . $this->IMDB_LANG,
- ],
- CURLOPT_REFERER => 'https://www.imdb.com',
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_SSL_VERIFYHOST => 0,
- CURLOPT_SSL_VERIFYPEER => 0,
- CURLOPT_TIMEOUT => $this->IMDB_TIMEOUT,
- CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0',
- CURLOPT_VERBOSE => 0,
- ]
- );
- $sOutput = curl_exec($oCurl);
- $aCurlInfo = curl_getinfo($oCurl);
- curl_close($oCurl);
- $aCurlInfo['contents'] = $sOutput;
-
- if (200 !== $aCurlInfo['http_code'] && 302 !== $aCurlInfo['http_code']) {
- if ($this->IMDB_DEBUG) {
- echo '<pre><b>cURL returned wrong HTTP code “' . $aCurlInfo['http_code'] . '”, aborting.</b></pre>';
- }
-
- return false;
- }
-
- return $aCurlInfo;
- }
-
- /**
- * @param string $sUrl The URL to the image to download.
- * @param int $cId The cast ID of the actor.
- *
- * @return string Local path.
- */
- private function saveImageCast($sUrl, $cId)
- {
- if ( ! preg_match('~http~', $sUrl)) {
- return 'cast/not-found.jpg';
- }
-
- $sFilename = $this->sRoot . '/cast/' . $cId . '.jpg';
- if (file_exists($sFilename)) {
- return 'cast/' . $cId . '.jpg';
- }
-
- $aCurlInfo = $this->runCurl($sUrl, true);
- $sData = $aCurlInfo['contents'];
- if (false === $sData) {
- return 'cast/not-found.jpg';
- }
-
- $oFile = fopen($sFilename, 'x');
- fwrite($oFile, $sData);
- fclose($oFile);
-
- return 'cast/' . $cId . '.jpg';
- }
-
- /**
- * Makes strings with $this->sSeparator as separator result in an array
- *
- * @param $string
- * @return array|string
- */
- public function slashStringAsArray($string) {
- $ret = $string;
-
- if(strstr($string, $this->sSeparator)) {
- $ret = array();
- $_t = explode($this->sSeparator, $string);
- foreach ($_t as $v) {
- $v = trim($v);
- if(!empty($v)) {
- $ret[] = $v;
- }
- }
- }
-
- return $ret;
- }
+ /**
+ * Set this to true if you run into problems.
+ */
+ private $IMDB_DEBUG = false;
+
+ /**
+ * Set the preferred language for the User Agent.
+ */
+ private $IMDB_LANG = 'en-US,en;q=0.9';
+
+ /**
+ * Define the timeout for cURL requests.
+ */
+ private $IMDB_TIMEOUT = 15;
+
+ /**
+ * These are the regular expressions used to extract the data.
+ * If you don’t know what you’re doing, you shouldn’t touch them.
+ */
+ const IMDB_AKA = '~<td[^>]*>\s*Also\s*Known\s*As\s*</td>\s*<td>(.+)</td>~Uis';
+ const IMDB_ASPECT_RATIO = '~<td[^>]*>Aspect\s*Ratio</td>\s*<td>(.+)</td>~Uis';
+ const IMDB_AWARDS = '~<div\s*class="titlereference-overview-section">\s*Awards:(.+)</div>~Uis';
+ const IMDB_BUDGET = '~<td[^>]*>Budget<\/td>\s*<td>\s*(.*)(?:\(estimated\))\s*<\/td>~Ui';
+ const IMDB_CAST = '~<td[^>]*itemprop="actor"[^>]*>\s*<a\s*href="/name/([^/]*)/\?[^"]*"[^>]*>\s*<span.+>(.+)</span~Ui';
+ const IMDB_CAST_IMAGE = '~(loadlate="(.*)"[^>]*><\/a>\s+<\/td>\s+)?<td[^>]*itemprop="actor"[^>]*>\s*<a\s*href="\/name\/([^/]*)\/\?[^"]*"[^>]*>\s*<span.+>(.+)<\/span+~Uis';
+ const IMDB_CERTIFICATION = '~<td[^>]*>\s*Certification\s*</td>\s*<td>(.+)</td>~Ui';
+ const IMDB_CHAR = '~<td class="character">(?:\s+)<div>(.*)(?:\s+)(?: /| \(.*\)|<\/div>)~Ui';
+ const IMDB_COLOR = '~<a href="\/search\/title\?colors=(?:.*)">(.*)<\/a>~Ui';
+ const IMDB_COMPANY = '~href="[^"]*update=[t0-9]+:production_companies[^"]*">Edit</a>\s*</header>\s*<ul\s*class="simpleList">.+<a href="\/company\/(.*)\/">(.*)</a>~Ui';
+ const IMDB_COUNTRY = '~<a href="/country/(\w+)">(.*)</a>~Ui';
+ const IMDB_CREATOR = '~<div[^>]*>\s*(?:Creator|Creators)\s*:\s*<ul[^>]*>(.+)</ul>~Uxsi';
+ const IMDB_DIRECTOR = '~<div[^>]*>\s*(?:Director|Directors)\s*:\s*<ul[^>]*>(.+)</ul>~Uxsi';
+ const IMDB_GENRE = '~href="/genre/([a-zA-Z_-]*)/?">([a-zA-Z_ -]*)</a>~Ui';
+ const IMDB_GROSS = '~pl-zebra-list__label">Cumulative Worldwide Gross<\/td>\s+<td>\s+(.*)\s+<~Uxsi';
+ const IMDB_ID = '~((?:tt\d{6,})|(?:itle\?\d{6,}))~';
+ const IMDB_LANGUAGE = '~<a href="\/language\/(\w+)">(.*)<\/a>~Ui';
+ const IMDB_LOCATION = '~href="\/search\/title\?locations=(.*)">(.*)<\/a>~Ui';
+ const IMDB_LOCATIONS = '~href="\/search\/title\?locations=[^>]*>\s?(.*)\s?<\/a>[^"]*<dd>\s?(.*)\s<\/dd>~Ui';
+ const IMDB_MPAA = '~<li class="ipl-inline-list__item">(?:\s+)(TV-Y|TV-Y7|TV-G|TV-PG|TV-14|TV-MA|G|PG|PG-13|R|NC-17|NR|UR)(?:\s+)<\/li>~Ui';
+ const IMDB_NAME = '~href="/name/(.+)/?(?:\?[^"]*)?"[^>]*>(.+)</a>~Ui';
+ const IMDB_DESCRIPTION = '~<section class="titlereference-section-overview">\s+<div>(.*)</div>\s+<hr>~Ui';
+ const IMDB_NOT_FOUND = '~<h1 class="findHeader">No results found for ~Ui';
+ const IMDB_PLOT = '~<td[^>]*>\s*Plot\s*Summary\s*</td>\s*<td>\s*<p>(.+)</p>~Ui';
+ const IMDB_PLOT_KEYWORDS = '~<td[^>]*>Plot\s*Keywords</td>\s*<td>(.+)(?:<a\s*href="/title/[^>]*>[^<]*</a>\s*</li>\s*</ul>\s*)?</td>~Ui';
+ const IMDB_POSTER = '~<link\s*rel=\'image_src\'\s*href="(.*)">~Ui';
+ const IMDB_RATING = '~class="ipl-rating-star__rating">(.*)<~Ui';
+ const IMDB_RATING_COUNT = '~class="ipl-rating-star__total-votes">\((.*)\)<~Ui';
+ const IMDB_RELEASE_DATE = '~href="/title/[t0-9]*/releaseinfo">(.*)<~Ui';
+ const IMDB_RUNTIME = '~<td[^>]*>\s*Runtime\s*</td>\s*<td>(.+)</td>~Ui';
+ const IMDB_SEARCH = '~<td class="result_text"> <a href="\/title\/(tt\d{6,})\/(?:.*)"(?:\s*)>(?:.*)<\/a>~Ui';
+ const IMDB_SEASONS = '~episodes\?season=(?:\d+)">(\d+)<~Ui';
+ const IMDB_SOUND_MIX = '~<td[^>]*>\s*Sound\s*Mix\s*</td>\s*<td>(.+)</td>~Ui';
+ const IMDB_TAGLINE = '~<td[^>]*>\s*Taglines\s*</td>\s*<td>(.+)</td>~Ui';
+ const IMDB_TITLE = '~itemprop="name">(.*)(<\/h3>|<span)~Ui';
+ const IMDB_TITLE_ORIG = '~</h3>(?:\s+)(.*)(?:\s+)<span class=\"titlereference-original-title-label~Ui';
+ const IMDB_TRAILER = '~href="videoplayer/(vi[0-9]*)"~Ui';
+ const IMDB_URL = '~https?://(?:.*\.|.*)imdb.com/(?:t|T)itle(?:\?|/)(..\d+)~i';
+ const IMDB_USER_REVIEW = '~href="/title/[t0-9]*/reviews"[^>]*>([^<]*)\s*User~Ui';
+ const IMDB_VOTES = '~"ipl-rating-star__total-votes">\s*\((.*)\)\s*<~Ui';
+ const IMDB_WRITER = '~<div[^>]*>\s*(?:Writer|Writers)\s*:\s*<ul[^>]*>(.+)</ul>~Ui';
+ const IMDB_YEAR = '~og:title\' content="(?:.*)\((?:.*)(\d{4})(?:.*)\)~Ui';
+
+ /**
+ * @var string The string returned, if nothing is found.
+ */
+ public $sNotFound = 'n/A';
+
+ /**
+ * @var null|int The ID of the movie.
+ */
+ public $iId = null;
+
+ /**
+ * @var bool Is the content ready?
+ */
+ public $isReady = false;
+
+ /**
+ * @var string Char that separates multiple entries.
+ */
+ public $sSeparator = ' / ';
+
+ /**
+ * @var null|string The URL to the movie.
+ */
+ public $sUrl = null;
+
+ /**
+ * @var bool Return responses enclosed in array
+ */
+ public $bArrayOutput = false;
+
+ /**
+ * @var int Maximum cache time.
+ */
+ private $iCache = 1440;
+
+ /**
+ * @var null|string The root of the script.
+ */
+ private $sRoot = null;
+
+ /**
+ * @var null|string Holds the source.
+ */
+ private $sSource = null;
+
+ /**
+ * @var string What to search for?
+ */
+ private $sSearchFor = 'all';
+
+ /**
+ * IMDB constructor. Can now set some options
+ *
+ * @param $options array with the following options
+ * int iCache Custom cache time in minutes.
+ * string sSearchFor What type to search for?
+ * string storage Where to store data. Absolute path
+ * boolean debug Show depubg messages or not
+ */
+ public function __construct($options) {
+
+ if(isset($options['debug']) && !empty($options['debug'])) {
+ $this->IMDB_DEBUG = true;
+ }
+
+ if(isset($options['iCache']) && !empty($options['iCache'])) $this->iCache = (int) $options['iCache'];
+
+ $this->sRoot = dirname(__FILE__);
+ if(isset($options['storage']) && !empty($options['storage'])) {
+ $this->sRoot = $options['storage'];
+ }
+
+ if(isset($options['sSearchFor']) && !empty($options['sSearchFor'])) {
+ if (in_array(
+ $options['sSearchFor'],
+ [
+ 'movie',
+ 'tv',
+ 'episode',
+ 'game',
+ 'all',
+ ]
+ )) {
+ $this->sSearchFor = $options['sSearchFor'];
+ }
+ }
+ }
+
+
+ /**
+ * @param $sSearch
+ * @throws Exception
+ */
+ public function search($sSearch) {
+
+ $sSearch = trim($sSearch);
+ if(empty($sSearch)) {
+ throw new Exception('Missing search term');
+ }
+
+ if ( ! is_writable($this->sRoot . '/posters') && ! mkdir($this->sRoot . '/posters')) {
+ throw new Exception('The directory “' . $this->sRoot . '/posters” isn’t writable.');
+ }
+ if ( ! is_writable($this->sRoot . '/cache') && ! mkdir($this->sRoot . '/cache')) {
+ throw new Exception('The directory “' . $this->sRoot . '/cache” isn’t writable.');
+ }
+ if ( ! is_writable($this->sRoot . '/cast') && ! mkdir($this->sRoot . '/cast')) {
+ throw new Exception('The directory “' . $this->sRoot . '/cast” isn’t writable.');
+ }
+
+ if ( ! function_exists('curl_init')) {
+ throw new Exception('You need to enable the PHP cURL extension.');
+ }
+
+ $this->fetchUrl($sSearch);
+ }
+
+ /**
+ * @param string $sSearch IMDb URL or movie title to search for.
+ *
+ * @return bool True on success, false on failure.
+ */
+ private function fetchUrl($sSearch)
+ {
+
+
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>Running:</b> fetchUrl("' . $sSearch . '")</pre>';
+ }
+
+ // Try to find a valid URL.
+ $sId = $this->matchRegex($sSearch, self::IMDB_ID, 1);
+ if (false !== $sId) {
+ $this->iId = preg_replace('~[\D]~', '', $sId);
+ $this->sUrl = 'https://www.imdb.com/title/tt' . $this->iId . '/reference';
+ $bSearch = false;
+ } else {
+ switch (strtolower($this->sSearchFor)) {
+ case 'movie':
+ $sParameters = '&s=tt&ttype=ft';
+ break;
+ case 'tv':
+ $sParameters = '&s=tt&ttype=tv';
+ break;
+ case 'episode':
+ $sParameters = '&s=tt&ttype=ep';
+ break;
+ case 'game':
+ $sParameters = '&s=tt&ttype=vg';
+ break;
+ default:
+ $sParameters = '&s=tt';
+ }
+
+ $this->sUrl = 'https://www.imdb.com/find?q=' . rawurlencode(str_replace(' ', '+', $sSearch)) . $sParameters;
+ $bSearch = true;
+
+ // Was this search already performed and cached?
+ $sRedirectFile = $this->sRoot . '/cache/' . sha1($this->sUrl) . '.redir';
+ if (is_readable($sRedirectFile)) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>Using redirect:</b> ' . basename($sRedirectFile) . '</pre>';
+ }
+ $sRedirect = file_get_contents($sRedirectFile);
+ $this->sUrl = trim($sRedirect);
+ $this->iId = preg_replace('~[\D]~', '', $this->matchRegex($sRedirect, self::IMDB_ID, 1));
+ $bSearch = false;
+ }
+ }
+
+ // Does a cache of this movie exist?
+ $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '.cache';
+ if (is_readable($sCacheFile)) {
+ $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
+ if ($iDiff < $this->iCache) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>Using cache:</b> ' . basename($sCacheFile) . '</pre>';
+ }
+ $this->sSource = file_get_contents($sCacheFile);
+ $this->isReady = true;
+
+ return true;
+ }
+ }
+
+ // Run cURL on the URL.
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>Running cURL:</b> ' . $this->sUrl . '</pre>';
+ }
+
+ $aCurlInfo = $this->runCurl($this->sUrl);
+ $sSource = $aCurlInfo['contents'];
+
+ if (false === $sSource) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
+ }
+
+ return false;
+ }
+
+ // Was the movie found?
+ $sMatch = $this->matchRegex($sSource, self::IMDB_SEARCH, 1);
+ if (false !== $sMatch) {
+ $sUrl = 'https://www.imdb.com/title/' . $sMatch . '/reference';
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>New redirect saved:</b> ' . basename($sRedirectFile) . ' => ' . $sUrl . '</pre>';
+ }
+ file_put_contents($sRedirectFile, $sUrl);
+ $this->sSource = null;
+ $this->fetchUrl($sUrl);
+
+ return true;
+ }
+ $sMatch = $this->matchRegex($sSource, self::IMDB_NOT_FOUND, 0);
+ if (false !== $sMatch) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>Movie not found:</b> ' . $sSearch . '</pre>';
+ }
+
+ return false;
+ }
+
+ $this->sSource = str_replace(
+ [
+ "\n",
+ "\r\n",
+ "\r",
+ ],
+ '',
+ $sSource
+ );
+ $this->isReady = true;
+
+ // Save cache.
+ if (false === $bSearch) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>Cache created:</b> ' . basename($sCacheFile) . '</pre>';
+ }
+ file_put_contents($sCacheFile, $this->sSource);
+ }
+
+ return true;
+ }
+
+ /**
+ * @return array All data.
+ */
+ public function getAll()
+ {
+ $aData = [];
+ foreach (get_class_methods(__CLASS__) as $method) {
+ if (substr($method, 0, 3) === 'get' && $method !== 'getAll' && $method !== 'getCastImages') {
+ $aData[$method] = [
+ 'name' => ltrim($method, 'get'),
+ 'value' => $this->{$method}(),
+ ];
+ }
+ }
+ array_multisort($aData);
+
+ return $aData;
+ }
+
+ /**
+ * @return string “Also Known As” or $sNotFound.
+ */
+ public function getAka()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_AKA, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * Returns all local names
+ *
+ * @return string All local names.
+ */
+ public function getAkas()
+ {
+ if (true === $this->isReady) {
+ // Does a cache of this movie exist?
+ $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '_akas.cache';
+ $bUseCache = false;
+
+ if (is_readable($sCacheFile)) {
+ $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
+ if ($iDiff < $this->iCache || false) {
+ $bUseCache = true;
+ }
+ }
+
+ if ($bUseCache) {
+ $aRawReturn = file_get_contents($sCacheFile);
+ $aReturn = unserialize($aRawReturn);
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ } else {
+ $fullAkas = sprintf('https://www.imdb.com/title/tt%s/releaseinfo', $this->iId);
+ $aCurlInfo = $this->runCurl($fullAkas);
+ $sSource = $aCurlInfo['contents'];
+
+ if (false === $sSource) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
+ }
+
+ return false;
+ }
+
+ $aReturned = $this->matchRegex($sSource, "~<td>(.*?)<\/td>\s+<td>(.*?)<\/td>~");
+
+ if ($aReturned) {
+ $aReturn = [];
+ foreach ($aReturned[1] as $i => $strName) {
+ if (strpos($strName, '(') === false) {
+ $aReturn[] = [
+ 'title' => $this->cleanString($aReturned[2][$i]),
+ 'country' => $this->cleanString($strName),
+ ];
+ }
+ }
+
+ file_put_contents($sCacheFile, serialize($aReturn));
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string “Aspect Ratio” or $sNotFound.
+ */
+ public function getAspectRatio()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_ASPECT_RATIO, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The awards of the movie or $sNotFound
+ */
+ public function getAwards()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_AWARDS, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param int $iLimit How many cast members should be returned?
+ * @param bool $bMore Add … if there are more cast members than printed.
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with linked cast members or $sNotFound.
+ */
+ public function getCastAsUrl($iLimit = 0, $bMore = true, $sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ if (0 !== $iLimit && $i >= $iLimit) {
+ break;
+ }
+ $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
+
+ return $this->arrayOutput(
+ $this->bArrayOutput,
+ $this->sSeparator,
+ $this->sNotFound,
+ $aReturn,
+ $bHaveMore
+ );
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param int $iLimit How many cast members should be returned?
+ * @param bool $bMore Add … if there are more cast members than printed.
+ *
+ * @return string A list with cast members or $sNotFound.
+ */
+ public function getCast($iLimit = 0, $bMore = true)
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ if (0 !== $iLimit && $i >= $iLimit) {
+ break;
+ }
+ $aReturn[] = $this->cleanString($sName);
+ }
+
+ $bMore = (0 !== $iLimit && $bMore && (count($aMatch[2]) > $iLimit) ? '…' : '');
+
+ $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
+
+ return $this->arrayOutput(
+ $this->bArrayOutput,
+ $this->sSeparator,
+ $this->sNotFound,
+ $aReturn,
+ $bHaveMore
+ );
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @param int $iLimit How many cast images should be returned?
+ * @param bool $bMore Add … if there are more cast members than printed.
+ * @param string $sSize small, mid or big cast images
+ * @param bool $bDownload Return URL or Download
+ *
+ * @return array Array with cast name as key, and image as value.
+ */
+ public function getCastImages($iLimit = 0, $bMore = true, $sSize = 'small', $bDownload = false)
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST_IMAGE);
+ $aReturn = [];
+ if (count($aMatch[4])) {
+ foreach ($aMatch[4] as $i => $sName) {
+ if (0 !== $iLimit && $i >= $iLimit) {
+ break;
+ }
+ $sMatch = $aMatch[2][$i];
+
+ if ('big' === strtolower($sSize) && false !== strstr($aMatch[2][$i], '@._')) {
+ $sMatch = substr($aMatch[2][$i], 0, strpos($aMatch[2][$i], '@._')) . '@.jpg';
+ } elseif ('mid' === strtolower($sSize) && false !== strstr($aMatch[2][$i], '@._')) {
+ $sMatch = substr($aMatch[2][$i], 0, strpos($aMatch[2][$i], '@._')) . '@._V1_UX214_AL_.jpg';
+ }
+
+ if (false === $bDownload) {
+ $sMatch = $this->cleanString($sMatch);
+ } else {
+ $sLocal = $this->saveImageCast($sMatch, $aMatch[3][$i]);
+ if (file_exists(dirname(__FILE__) . '/' . $sLocal)) {
+ $sMatch = $sLocal;
+ } else {
+ //the 'big' image isn't available, try the 'mid' one (vice versa)
+ if ('big' === strtolower($sSize) && false !== strstr($aMatch[2][$i], '@._')) {
+ //trying the 'mid' one
+ $sMatch = substr(
+ $aMatch[2][$i],
+ 0,
+ strpos($aMatch[2][$i], '@._')
+ ) . '@._V1_UX214_AL_.jpg';
+ } else {
+ //trying the 'big' one
+ $sMatch = substr($aMatch[2][$i], 0, strpos($aMatch[2][$i], '@._')) . '@.jpg';
+ }
+
+ $sLocal = $this->saveImageCast($sMatch, $aMatch[3][$i]);
+ if (file_exists(dirname(__FILE__) . '/' . $sLocal)) {
+ $sMatch = $sLocal;
+ } else {
+ $sMatch = $this->cleanString($aMatch[2][$i]);
+ }
+ }
+ }
+
+ $aReturn[$this->cleanString($aMatch[4][$i])] = $sMatch;
+ }
+
+ $bMore = (0 !== $iLimit && $bMore && (count($aMatch[4]) > $iLimit) ? '…' : '');
+
+ $bHaveMore = ($bMore && (count($aMatch[4]) > $iLimit));
+
+ $aReturn = array_replace(
+ $aReturn,
+ array_fill_keys(
+ array_keys($aReturn, $this->sNotFound),
+ 'cast/not-found.jpg'
+ )
+ );
+
+ return $aReturn;
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @param int $iLimit How many cast members should be returned?
+ * @param bool $bMore Add … if there are more cast members than
+ * printed.
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with linked cast members and their character or
+ * $sNotFound.
+ */
+ public function getCastAndCharacterAsUrl($iLimit = 0, $bMore = true, $sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
+ $aMatchChar = $this->matchRegex($this->sSource, self::IMDB_CHAR);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ if (0 !== $iLimit && $i >= $iLimit) {
+ break;
+ }
+ $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a> as ' . $this->cleanString($aMatchChar[1][$i]);
+ }
+
+ $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
+
+ return $this->arrayOutput(
+ $this->bArrayOutput,
+ $this->sSeparator,
+ $this->sNotFound,
+ $aReturn,
+ $bHaveMore
+ );
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @param int $iLimit How many cast members should be returned?
+ * @param bool $bMore Add … if there are more cast members than printed.
+ *
+ * @return string A list with cast members and their character or
+ * $sNotFound.
+ */
+ public function getCastAndCharacter($iLimit = 0, $bMore = true)
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_CAST);
+ $aMatchChar = $this->matchRegex($this->sSource, self::IMDB_CHAR);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ if (0 !== $iLimit && $i >= $iLimit) {
+ break;
+ }
+ $aReturn[] = $this->cleanString($sName) . ' as ' . $this->cleanString($aMatchChar[1][$i]);
+ }
+
+ $bHaveMore = ($bMore && (count($aMatch[2]) > $iLimit));
+
+ return $this->arrayOutput(
+ $this->bArrayOutput,
+ $this->sSeparator,
+ $this->sNotFound,
+ $aReturn,
+ $bHaveMore
+ );
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string The certification of the movie or $sNotFound.
+ */
+ public function getCertification()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_CERTIFICATION, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string Color or $sNotFound.
+ */
+ public function getColor()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_COLOR, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The company producing the movie or $sNotFound.
+ */
+ public function getCompany()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getCompanyAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string The linked company producing the movie or $sNotFound.
+ */
+ public function getCompanyAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_COMPANY);
+ if (isset($aMatch[2][0])) {
+ return '<a href="https://www.imdb.com/company/' . $this->cleanString(
+ $aMatch[1][0]
+ ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $aMatch[2][0]
+ ) . '</a>';
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string A list with countries or $sNotFound.
+ */
+ public function getCountry()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getCountryAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with linked countries or $sNotFound.
+ */
+ public function getCountryAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_COUNTRY);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/country/' . trim(
+ $aMatch[1][$i]
+ ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string A list with the creators or $sNotFound.
+ */
+ public function getCreator()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getCreatorAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with the linked creators or $sNotFound.
+ */
+ public function getCreatorAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_CREATOR, 1);
+ $aMatch = $this->matchRegex($sMatch, self::IMDB_NAME);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string The description of the movie or $sNotFound.
+ */
+ public function getDescription()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_DESCRIPTION, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string A list with the directors or $sNotFound.
+ */
+ public function getDirector()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getDirectorAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with the linked directors or $sNotFound.
+ */
+ public function getDirectorAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_DIRECTOR, 1);
+ $aMatch = $this->matchRegex($sMatch, self::IMDB_NAME);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string A list with the genres or $sNotFound.
+ */
+ public function getGenre()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getGenreAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with the linked genres or $sNotFound.
+ */
+ public function getGenreAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_GENRE);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach (array_unique($aMatch[2]) as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/search/title?genres=' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string cumulative worldwide gross or $sNotFound.
+ */
+ public function getGross()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_GROSS, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string A list with the languages or $sNotFound.
+ */
+ public function getLanguage()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getLanguageAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with the linked languages or $sNotFound.
+ */
+ public function getLanguageAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_LANGUAGE);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/language/' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string A list with the location or $sNotFound.
+ */
+ public function getLocation()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getLocationAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with the linked location or $sNotFound.
+ */
+ public function getLocationAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_LOCATION);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/search/title?locations=' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * Returns all locations
+ *
+ * @return string location
+ * @return string specification
+ */
+ public function getLocations()
+ {
+ if (true === $this->isReady) {
+ // Does a cache of this movie exist?
+ $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '_locations.cache';
+ $bUseCache = false;
+
+ if (is_readable($sCacheFile)) {
+ $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
+ if ($iDiff < $this->iCache || false) {
+ $bUseCache = true;
+ }
+ }
+
+ if ($bUseCache) {
+ $aRawReturn = file_get_contents($sCacheFile);
+ $aReturn = unserialize($aRawReturn);
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ } else {
+ $fullLocations = sprintf('https://www.imdb.com/title/tt%s/locations', $this->iId);
+ $aCurlInfo = $this->runCurl($fullLocations);
+ $sSource = $aCurlInfo['contents'];
+
+ if (false === $sSource) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
+ }
+
+ return false;
+ }
+
+ $aReturned = $this->matchRegex($sSource, self::IMDB_LOCATIONS);
+
+ if ($aReturned) {
+ $aReturn = [];
+ foreach ($aReturned[1] as $i => $strName) {
+ if (strpos($strName, '(') === false) {
+ $aReturn[] = [
+ 'location' => $this->cleanString($strName),
+ ];
+ }
+ if (strpos($aReturned[2][$i], '(') !== false) {
+ $aReturn[] = [
+ 'specification' => $this->cleanString($aReturned[2][$i]),
+ ];
+ }
+ }
+
+ file_put_contents($sCacheFile, serialize($aReturn));
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string The MPAA of the movie or $sNotFound.
+ */
+ public function getMpaa()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_MPAA, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string A list with the plot keywords or $sNotFound.
+ */
+ public function getPlotKeywords()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_PLOT_KEYWORDS, 1);
+ if (false !== $sMatch) {
+ $aReturn = explode('|', $this->cleanString($sMatch));
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @param int $iLimit The limit.
+ *
+ * @return string The plot of the movie or $sNotFound.
+ */
+ public function getPlot($iLimit = 0)
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_PLOT, 1);
+ if (false !== $sMatch) {
+ if ($iLimit !== 0) {
+ return $this->shortText($this->cleanString($sMatch), $iLimit);
+ }
+
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sSize Small, big, xxs, xs, s poster?
+ * @param bool $bDownload Return URL to the poster or download it?
+ *
+ * @return bool|string Path to the poster.
+ */
+ public function getPoster($sSize = 'small', $bDownload = false)
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_POSTER, 1);
+ if (false !== $sMatch) {
+ if ('big' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
+ $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@.jpg';
+ }
+ if ('xxs' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
+ $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@._V1_UY67_CR0,0,45,67_AL_.jpg';
+ }
+ if ('xs' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
+ $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@._V1_UY113_CR0,0,76,113_AL_.jpg';
+ }
+ if ('s' === strtolower($sSize) && false !== strstr($sMatch, '@._')) {
+ $sMatch = substr($sMatch, 0, strpos($sMatch, '@._')) . '@._V1_UX182_CR0,0,182,268_AL_.jpg';
+ }
+ if (false === $bDownload) {
+ return $this->cleanString($sMatch);
+ } else {
+ $sLocal = $this->saveImage($sMatch, $this->iId);
+ if (file_exists(dirname(__FILE__) . '/' . $sLocal)) {
+ return $sLocal;
+ } else {
+ return $sMatch;
+ }
+ }
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The rating of the movie or $sNotFound.
+ */
+ public function getRating()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_RATING, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The rating count of the movie or $sNotFound.
+ */
+ public function getRatingCount()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_RATING_COUNT, 1);
+ if (false !== $sMatch) {
+ return str_replace(',', '', $this->cleanString($sMatch));
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * Release date doesn't contain all the information we need to create a media and
+ * we need this function that checks if users can vote target media (if can, it's released).
+ *
+ * @return true If the media is released
+ */
+ public function isReleased()
+ {
+ $strReturn = $this->getReleaseDate();
+ if ($strReturn == $this->sNotFound || $strReturn == 'Not yet released') {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * @return string The release date of the movie or $sNotFound.
+ */
+ public function getReleaseDate()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_RELEASE_DATE, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * Returns all local names
+ *
+ * @return string country
+ * @return string release date
+ */
+ public function getReleaseDates()
+ {
+ if (true === $this->isReady) {
+ // Does a cache of this movie exist?
+ $sCacheFile = $this->sRoot . '/cache/' . sha1($this->iId) . '_akas.cache';
+ $bUseCache = false;
+
+ if (is_readable($sCacheFile)) {
+ $iDiff = round(abs(time() - filemtime($sCacheFile)) / 60);
+ if ($iDiff < $this->iCache || false) {
+ $bUseCache = true;
+ }
+ }
+
+ if ($bUseCache) {
+ $aRawReturn = file_get_contents($sCacheFile);
+ $aReturn = unserialize($aRawReturn);
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ } else {
+ $fullAkas = sprintf('https://www.imdb.com/title/tt%s/releaseinfo', $this->iId);
+ $aCurlInfo = $this->runCurl($fullAkas);
+ $sSource = $aCurlInfo['contents'];
+
+ if (false === $sSource) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>cURL error:</b> ' . var_dump($aCurlInfo) . '</pre>';
+ }
+
+ return false;
+ }
+
+ $aReturned = $this->matchRegex(
+ $sSource,
+ '~>(.*)<\/a><\/td>\s+<td class="release_date">(.*)<\/td>~'
+ );
+
+ if ($aReturned) {
+ $aReturn = [];
+ foreach ($aReturned[1] as $i => $strName) {
+ if (strpos($strName, '(') === false) {
+ $aReturn[] = [
+ 'country' => $this->cleanString($strName),
+ 'releasedate' => $this->cleanString($aReturned[2][$i]),
+ ];
+ }
+ }
+
+ file_put_contents($sCacheFile, serialize($aReturn));
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string The runtime of the movie or $sNotFound.
+ */
+ public function getRuntime()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_RUNTIME, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string A list with the seasons or $sNotFound.
+ */
+ public function getSeasons()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getSeasonsAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with the linked seasons or $sNotFound.
+ */
+ public function getSeasonsAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $aMatch = $this->matchRegex($this->sSource, self::IMDB_SEASONS);
+ $aReturn = [];
+ if (count($aMatch[1])) {
+ foreach (range(1, max($aMatch[1])) as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/title/tt' . $this->iId . '/episodes?season=' . $sName . '"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $sName . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound);
+ }
+
+ /**
+ * @return string The sound mix of the movie or $sNotFound.
+ */
+ public function getSoundMix()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_SOUND_MIX, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The tagline of the movie or $sNotFound.
+ */
+ public function getTagline()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_TAGLINE, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param bool $bForceLocal Try to return the original name of the movie.
+ *
+ * @return string The title of the movie or $sNotFound.
+ */
+ public function getTitle($bForceLocal = false)
+ {
+ if (true === $this->isReady) {
+ if (true === $bForceLocal) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_TITLE_ORIG, 1);
+ if (false !== $sMatch && "" !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_TITLE, 1);
+ $sMatch = preg_replace('~\(\d{4}\)$~Ui', '', $sMatch);
+ if (false !== $sMatch && "" !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param bool $bEmbed Link to player directly?
+ *
+ * @return string The URL to the trailer of the movie or $sNotFound.
+ */
+ public function getTrailerAsUrl($bEmbed = false)
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_TRAILER, 1);
+ if (false !== $sMatch) {
+ $sUrl = 'https://www.imdb.com/video/imdb/' . $sMatch . '/' . ($bEmbed ? 'player' : '');
+
+ return $this->cleanString($sUrl);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The IMDb URL.
+ */
+ public function getUrl()
+ {
+ if (true === $this->isReady) {
+ return $this->cleanString(str_replace('reference', '', $this->sUrl));
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The user review of the movie or $sNotFound.
+ */
+ public function getUserReview()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_USER_REVIEW, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The votes of the movie or $sNotFound.
+ */
+ public function getVotes()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_VOTES, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string A list with the writers or $sNotFound.
+ */
+ public function getWriter()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->getWriterAsUrl();
+ if ($this->sNotFound !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @param string $sTarget Add a target to the links?
+ *
+ * @return string A list with the linked writers or $sNotFound.
+ */
+ public function getWriterAsUrl($sTarget = '')
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_WRITER, 1);
+ $aMatch = $this->matchRegex($sMatch, self::IMDB_NAME);
+ $aReturn = [];
+ if (count($aMatch[2])) {
+ foreach ($aMatch[2] as $i => $sName) {
+ $aReturn[] = '<a href="https://www.imdb.com/name/' . $this->cleanString(
+ $aMatch[1][$i]
+ ) . '/"' . ($sTarget ? ' target="' . $sTarget . '"' : '') . '>' . $this->cleanString(
+ $sName
+ ) . '</a>';
+ }
+
+ return $this->arrayOutput($this->bArrayOutput, $this->sSeparator, $this->sNotFound, $aReturn);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The year of the movie or $sNotFound.
+ */
+ public function getYear()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_YEAR, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+ /**
+ * @return string The budget of the movie or $sNotFound.
+ */
+ public function getBudget()
+ {
+ if (true === $this->isReady) {
+ $sMatch = $this->matchRegex($this->sSource, self::IMDB_BUDGET, 1);
+ if (false !== $sMatch) {
+ return $this->cleanString($sMatch);
+ }
+ }
+
+ return $this->sNotFound;
+ }
+
+
+ /**
+ * Regular expression helper.
+ *
+ * @param string $sContent The content to search in.
+ * @param string $sPattern The regular expression.
+ * @param null $iIndex The index to return.
+ *
+ * @return bool If no match was found.
+ * @return string If one match was found.
+ * @return array If more than one match was found.
+ */
+ private function matchRegex($sContent, $sPattern, $iIndex = null)
+ {
+ preg_match_all($sPattern, $sContent, $aMatches);
+ if ($aMatches === false) {
+ return false;
+ }
+ if ($iIndex !== null && is_int($iIndex)) {
+ if (isset($aMatches[$iIndex][0])) {
+ return $aMatches[$iIndex][0];
+ }
+
+ return false;
+ }
+
+ return $aMatches;
+ }
+
+ /**
+ * Preferred output in responses with multiple elements
+ *
+ * @param bool $bArrayOutput Native array or string with separators.
+ * @param string $sSeparator String separator.
+ * @param string $sNotFound Not found text.
+ * @param array $aReturn Original input.
+ * @param bool $bHaveMore Have more elements indicator.
+ *
+ * @return string|array Multiple results separated by selected separator string, or enclosed into native array.
+ */
+ private function arrayOutput($bArrayOutput, $sSeparator, $sNotFound, $aReturn = null, $bHaveMore = false)
+ {
+ if ($bArrayOutput) {
+ if ($aReturn == null || ! is_array($aReturn)) {
+ return [];
+ }
+
+ if ($bHaveMore) {
+ $aReturn[] = '…';
+ }
+
+ return $aReturn;
+ } else {
+ if ($aReturn == null || ! is_array($aReturn)) {
+ return $sNotFound;
+ }
+
+ foreach ($aReturn as $i => $value) {
+ if (is_array($value)) {
+ $aReturn[$i] = implode($sSeparator, $value);
+ }
+ }
+
+ return implode($sSeparator, $aReturn) . (($bHaveMore) ? '…' : '');
+ }
+ }
+
+ /**
+ * @param string $sInput Input (eg. HTML).
+ *
+ * @return string Cleaned string.
+ */
+ private function cleanString($sInput)
+ {
+ $aSearch = [
+ 'Full summary »',
+ 'Full synopsis »',
+ 'Add summary »',
+ 'Add synopsis »',
+ 'See more »',
+ 'See why on IMDbPro.',
+ "\n",
+ "\r",
+ ];
+ $aReplace = [
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ ];
+ $sInput = str_replace('</li>', ' | ', $sInput);
+ $sInput = strip_tags($sInput);
+ $sInput = str_replace(' ', ' ', $sInput);
+ $sInput = str_replace($aSearch, $aReplace, $sInput);
+ $sInput = html_entity_decode($sInput, ENT_QUOTES | ENT_HTML5);
+ $sInput = preg_replace('/\s+/', ' ', $sInput);
+ $sInput = trim($sInput);
+ $sInput = rtrim($sInput, ' |');
+
+ return ($sInput ? trim($sInput) : $this->sNotFound);
+ }
+
+ /**
+ * @param string $sText The long text.
+ * @param int $iLength The maximum length of the text.
+ *
+ * @return string The shortened text.
+ */
+ private function shortText($sText, $iLength = 100)
+ {
+ if (mb_strlen($sText) <= $iLength) {
+ return $sText;
+ }
+
+ list($sShort) = explode("\n", wordwrap($sText, $iLength - 1));
+
+ if (substr($sShort, -1) !== '.') {
+ return $sShort . '…';
+ }
+
+ return $sShort;
+ }
+
+ /**
+ * @param string $sUrl The URL to the image to download.
+ * @param int $iId The ID of the movie.
+ *
+ * @return string Local path.
+ */
+ private function saveImage($sUrl, $iId)
+ {
+ if (preg_match('~title_addposter.jpg|imdb-share-logo.png~', $sUrl)) {
+ return 'posters/not-found.jpg';
+ }
+
+ $sFilename = $this->sRoot . '/posters/' . $iId . '.jpg';
+ if (file_exists($sFilename)) {
+ return 'posters/' . $iId . '.jpg';
+ }
+
+ $aCurlInfo = $this->runCurl($sUrl, true);
+ $sData = $aCurlInfo['contents'];
+ if (false === $sData) {
+ return 'posters/not-found.jpg';
+ }
+
+ $oFile = fopen($sFilename, 'x');
+ fwrite($oFile, $sData);
+ fclose($oFile);
+
+ return 'posters/' . $iId . '.jpg';
+ }
+
+ /**
+ * @param string $sUrl The URL to fetch.
+ * @param bool $bDownload Download?
+ *
+ * @return bool|mixed Array on success, false on failure.
+ */
+ private function runCurl($sUrl, $bDownload = false)
+ {
+ $oCurl = curl_init($sUrl);
+ curl_setopt_array(
+ $oCurl,
+ [
+ CURLOPT_BINARYTRANSFER => ($bDownload ? true : false),
+ CURLOPT_CONNECTTIMEOUT => $this->IMDB_TIMEOUT,
+ CURLOPT_ENCODING => '',
+ CURLOPT_FOLLOWLOCATION => 0,
+ CURLOPT_FRESH_CONNECT => 0,
+ CURLOPT_HEADER => ($bDownload ? false : true),
+ CURLOPT_HTTPHEADER => [
+ 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
+ 'Accept-Charset: utf-8, iso-8859-1;q=0.5',
+ 'Accept-Language: ' . $this->IMDB_LANG,
+ ],
+ CURLOPT_REFERER => 'https://www.imdb.com',
+ CURLOPT_RETURNTRANSFER => 1,
+ CURLOPT_SSL_VERIFYHOST => 0,
+ CURLOPT_SSL_VERIFYPEER => 0,
+ CURLOPT_TIMEOUT => $this->IMDB_TIMEOUT,
+ CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0',
+ CURLOPT_VERBOSE => 0,
+ ]
+ );
+ $sOutput = curl_exec($oCurl);
+ $aCurlInfo = curl_getinfo($oCurl);
+ curl_close($oCurl);
+ $aCurlInfo['contents'] = $sOutput;
+
+ if (200 !== $aCurlInfo['http_code'] && 302 !== $aCurlInfo['http_code']) {
+ if ($this->IMDB_DEBUG) {
+ echo '<pre><b>cURL returned wrong HTTP code “' . $aCurlInfo['http_code'] . '”, aborting.</b></pre>';
+ }
+
+ return false;
+ }
+
+ return $aCurlInfo;
+ }
+
+ /**
+ * @param string $sUrl The URL to the image to download.
+ * @param int $cId The cast ID of the actor.
+ *
+ * @return string Local path.
+ */
+ private function saveImageCast($sUrl, $cId)
+ {
+ if ( ! preg_match('~http~', $sUrl)) {
+ return 'cast/not-found.jpg';
+ }
+
+ $sFilename = $this->sRoot . '/cast/' . $cId . '.jpg';
+ if (file_exists($sFilename)) {
+ return 'cast/' . $cId . '.jpg';
+ }
+
+ $aCurlInfo = $this->runCurl($sUrl, true);
+ $sData = $aCurlInfo['contents'];
+ if (false === $sData) {
+ return 'cast/not-found.jpg';
+ }
+
+ $oFile = fopen($sFilename, 'x');
+ fwrite($oFile, $sData);
+ fclose($oFile);
+
+ return 'cast/' . $cId . '.jpg';
+ }
+
+ /**
+ * Makes strings with $this->sSeparator as separator result in an array
+ *
+ * @param $string
+ * @return array|string
+ */
+ public function slashStringAsArray($string) {
+ $ret = $string;
+
+ if(strstr($string, $this->sSeparator)) {
+ $ret = array();
+ $_t = explode($this->sSeparator, $string);
+ foreach ($_t as $v) {
+ $v = trim($v);
+ if(!empty($v)) {
+ $ret[] = $v;
+ }
+ }
+ }
+
+ return $ret;
+ }
}
*/
class ManageCollectionFields {
- /**
- * The database object
- *
- * @var object
- */
- private $_DB;
+ /**
+ * The database object
+ *
+ * @var object
+ */
+ private $_DB;
- /**
- * The user object to query with
- *
- * @var object
- */
- private $_User;
+ /**
+ * The user object to query with
+ *
+ * @var object
+ */
+ private $_User;
- /**
- * The collection we are working with
- *
- * @var integer
- */
- private $_collectionId;
+ /**
+ * The collection we are working with
+ *
+ * @var integer
+ */
+ private $_collectionId;
- /**
- * Which db cols should not be removed
- *
- * @var array
- */
- private $_protectedDBCols = array(
- 'id','created','modified','modificationuser','owner','group','rights'
- );
+ /**
+ * Which db cols should not be removed
+ *
+ * @var array
+ */
+ private $_protectedDBCols = array(
+ 'id','created','modified','modificationuser','owner','group','rights'
+ );
- /**
- * Store existing fileds info for runtime
- *
- * @var array
- */
- private $_cacheExistingSysFields = array();
+ /**
+ * Store existing fileds info for runtime
+ *
+ * @var array
+ */
+ private $_cacheExistingSysFields = array();
- /**
- * ManageCollections constructor
- *
- * @param $databaseConnectionObject
- * @param $userObj
- */
- public function __construct($databaseConnectionObject, $userObj) {
- $this->_DB = $databaseConnectionObject;
- $this->_User = $userObj;
- }
+ /**
+ * ManageCollections constructor
+ *
+ * @param $databaseConnectionObject
+ * @param $userObj
+ */
+ public function __construct($databaseConnectionObject, $userObj) {
+ $this->_DB = $databaseConnectionObject;
+ $this->_User = $userObj;
+ }
- /**
- * The id from the collection we are working with
- *
- * @param $id integer
- */
- public function setCollection($id) {
- if(!empty($id)) {
- $this->_collectionId = $id;
- }
- }
+ /**
+ * The id from the collection we are working with
+ *
+ * @param $id integer
+ */
+ public function setCollection($id) {
+ if(!empty($id)) {
+ $this->_collectionId = $id;
+ }
+ }
- /**
- * Get available fields based on user
- *
- * @return array
- * @todo No rights implemented yet. Maybe not needed. Management done by hand directly on DB
- */
- public function getAvailableFields() {
- $ret = array();
+ /**
+ * Get available fields based on user
+ *
+ * @return array
+ * @todo No rights implemented yet. Maybe not needed. Management done by hand directly on DB
+ */
+ public function getAvailableFields() {
+ $ret = array();
- $queryStr = "SELECT `id`, `identifier`, `displayname`, `type`,
- `createstring`, `value`
- FROM `".DB_PREFIX."_sys_fields`
- ORDER BY `displayname`";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
+ $queryStr = "SELECT `id`, `identifier`, `displayname`, `type`,
+ `createstring`, `value`
+ FROM `".DB_PREFIX."_sys_fields`
+ ORDER BY `displayname`";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * Simple comma seperated number string
- *
- * @param $string string
- * @return bool
- */
- public function validateFieldSortString($string) {
- $ret = false;
+ /**
+ * Simple comma seperated number string
+ *
+ * @param $string string
+ * @return bool
+ */
+ public function validateFieldSortString($string) {
+ $ret = false;
- $_t = str_replace(",","",$string);
- if(Summoner::validate($_t, 'digit')) {
- $ret = true;
- }
+ $_t = str_replace(",","",$string);
+ if(Summoner::validate($_t, 'digit')) {
+ $ret = true;
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * $fieldsSortString have to valided already
- *
- * @todo remove non existing ones from table
- *
- * @param $fieldsSortString string
- * @return bool
- */
- public function updateFields($fieldsSortString) {
- $ret = false;
- $ids = array();
+ /**
+ * $fieldsSortString have to valided already
+ *
+ * @todo remove non existing ones from table
+ *
+ * @param $fieldsSortString string
+ * @return bool
+ */
+ public function updateFields($fieldsSortString) {
+ $ret = false;
+ $ids = array();
- $fieldsSortString = trim($fieldsSortString, ", ");
- if(strstr($fieldsSortString, ",")) {
- $ids = explode(",", $fieldsSortString);
- }
- else {
- $ids[] = $fieldsSortString;
- }
+ $fieldsSortString = trim($fieldsSortString, ", ");
+ if(strstr($fieldsSortString, ",")) {
+ $ids = explode(",", $fieldsSortString);
+ }
+ else {
+ $ids[] = $fieldsSortString;
+ }
- if(!empty($ids)) {
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+ if(!empty($ids)) {
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
- $queryStr1 = "DELETE FROM `".DB_PREFIX."_collection_fields_".$this->_collectionId."`
- WHERE `fk_field_id` NOT IN (".implode(",",$ids).")";
- $q1 = $this->_DB->query($queryStr1);
- if($q1 !== false) {
- // https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
- $queryStr = "INSERT INTO `".DB_PREFIX."_collection_fields_".$this->_collectionId."` (`fk_field_id`,`sort`) VALUES ";
- foreach ($ids as $k => $v) {
- $queryStr .= "($v,$k),";
- }
- $queryStr = trim($queryStr, ",");
- $queryStr .= " AS newEntry(fid,s) ON DUPLICATE KEY UPDATE `sort`=s";
+ $queryStr1 = "DELETE FROM `".DB_PREFIX."_collection_fields_".$this->_collectionId."`
+ WHERE `fk_field_id` NOT IN (".implode(",",$ids).")";
+ $q1 = $this->_DB->query($queryStr1);
+ if($q1 !== false) {
+ // https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
+ $queryStr = "INSERT INTO `".DB_PREFIX."_collection_fields_".$this->_collectionId."` (`fk_field_id`,`sort`) VALUES ";
+ foreach ($ids as $k => $v) {
+ $queryStr .= "($v,$k),";
+ }
+ $queryStr = trim($queryStr, ",");
+ $queryStr .= " AS newEntry(fid,s) ON DUPLICATE KEY UPDATE `sort`=s";
- $q2 = $this->_DB->query($queryStr);
- if($q2 !== false) {
- $_newColumns = $this->_getSQLForCollectionColumns($ids);
- $alterQuery = false;
- if(!empty($_newColumns)) {
- $alterString = "ALTER TABLE `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
- foreach($_newColumns as $k=>$v) {
- $alterString .= " ADD ".$v['createstring'].",";
- }
- $alterString = trim($alterString, ",");
- $alterQuery = $this->_DB->query($alterString);
- }
- if(!empty($_newColumns) && $alterQuery == false) {
- $this->_DB->rollback();
- error_log('ERROR Failed to update entry table: '.var_export($alterString, true));
- }
- else {
- $this->_DB->commit();
- $ret = true;
- }
- }
- else {
- $this->_DB->rollback();
- error_log('ERROR Failed to update collection fields: '.var_export($queryStr1, true));
- error_log('ERROR Failed to update collection fields: '.var_export($queryStr, true));
- }
- }
- }
+ $q2 = $this->_DB->query($queryStr);
+ if($q2 !== false) {
+ $_newColumns = $this->_getSQLForCollectionColumns($ids);
+ $alterQuery = false;
+ if(!empty($_newColumns)) {
+ $alterString = "ALTER TABLE `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
+ foreach($_newColumns as $k=>$v) {
+ $alterString .= " ADD ".$v['createstring'].",";
+ }
+ $alterString = trim($alterString, ",");
+ $alterQuery = $this->_DB->query($alterString);
+ }
+ if(!empty($_newColumns) && $alterQuery == false) {
+ $this->_DB->rollback();
+ error_log('ERROR Failed to update entry table: '.var_export($alterString, true));
+ }
+ else {
+ $this->_DB->commit();
+ $ret = true;
+ }
+ }
+ else {
+ $this->_DB->rollback();
+ error_log('ERROR Failed to update collection fields: '.var_export($queryStr1, true));
+ error_log('ERROR Failed to update collection fields: '.var_export($queryStr, true));
+ }
+ }
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * Get the fields for currently loaded collection.
- *
- * @param bool $refresh True to reload from DB
- * @return array
- */
- public function getExistingFields($refresh=false) {
- if($refresh === false && !empty($this->_cacheExistingSysFields)) {
- return $this->_cacheExistingSysFields;
- }
+ /**
+ * Get the fields for currently loaded collection.
+ *
+ * @param bool $refresh True to reload from DB
+ * @return array
+ */
+ public function getExistingFields($refresh=false) {
+ if($refresh === false && !empty($this->_cacheExistingSysFields)) {
+ return $this->_cacheExistingSysFields;
+ }
- $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`
- FROM `".DB_PREFIX."_collection_fields_".$this->_collectionId."` AS cf
- LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
- ORDER BY `cf`.`sort`";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $this->_cacheExistingSysFields[$result['id']] = $result;
- }
- }
+ $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`
+ FROM `".DB_PREFIX."_collection_fields_".$this->_collectionId."` AS cf
+ LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
+ ORDER BY `cf`.`sort`";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $this->_cacheExistingSysFields[$result['id']] = $result;
+ }
+ }
- return $this->_cacheExistingSysFields;
- }
+ return $this->_cacheExistingSysFields;
+ }
- /**
- * Get the column names from current collection entry table
- *
- * @return array
- */
- private function _getExistingCollectionColumns() {
- $ret = array();
+ /**
+ * Get the column names from current collection entry table
+ *
+ * @return array
+ */
+ private function _getExistingCollectionColumns() {
+ $ret = array();
- $queryStr = "SHOW COLUMNS FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- if(!in_array($result['Field'], $this->_protectedDBCols, true)) {
- $ret[$result['Field']] = $result['Field'];
- }
- }
- }
+ $queryStr = "SHOW COLUMNS FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ if(!in_array($result['Field'], $this->_protectedDBCols, true)) {
+ $ret[$result['Field']] = $result['Field'];
+ }
+ }
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * Get the required SQL information from given field ids
- * to create columns in entry table.
- *
- * @param $columnIds array sort=>fk_field_id
- * @return array
- */
- private function _getSQLForCollectionColumns($columnIds) {
- $_fields = array();
- // enrich with information
- $_sysFields = $this->getAvailableFields();
- $_existingDBColumns = $this->_getExistingCollectionColumns();
- if(!empty($columnIds)) {
- foreach($columnIds as $sort=>$fieldId) {
- if(isset($_sysFields[$fieldId])) {
- $_fd = $_sysFields[$fieldId];
- if(isset($_existingDBColumns[$_fd['identifier']])) continue;
- if(empty($_fd['createstring'])) continue;
- $_fields[$fieldId] = $_fd;
- }
- }
- }
- return $_fields;
- }
+ /**
+ * Get the required SQL information from given field ids
+ * to create columns in entry table.
+ *
+ * @param $columnIds array sort=>fk_field_id
+ * @return array
+ */
+ private function _getSQLForCollectionColumns($columnIds) {
+ $_fields = array();
+ // enrich with information
+ $_sysFields = $this->getAvailableFields();
+ $_existingDBColumns = $this->_getExistingCollectionColumns();
+ if(!empty($columnIds)) {
+ foreach($columnIds as $sort=>$fieldId) {
+ if(isset($_sysFields[$fieldId])) {
+ $_fd = $_sysFields[$fieldId];
+ if(isset($_existingDBColumns[$_fd['identifier']])) continue;
+ if(empty($_fd['createstring'])) continue;
+ $_fields[$fieldId] = $_fd;
+ }
+ }
+ }
+ return $_fields;
+ }
}
class ManageCollections {
/**
* The database object
- *
+ *
* @var object
*/
private $_DB;
- /**
- * The user object to query with
- *
- * @var object
- */
+ /**
+ * The user object to query with
+ *
+ * @var object
+ */
private $_User;
- /**
- * ManageCollections constructor.
- *
- * @param $databaseConnectionObject
- * @param $userObj
- */
- public function __construct($databaseConnectionObject, $userObj) {
+ /**
+ * ManageCollections constructor.
+ *
+ * @param $databaseConnectionObject
+ * @param $userObj
+ */
+ public function __construct($databaseConnectionObject, $userObj) {
$this->_DB = $databaseConnectionObject;
$this->_User = $userObj;
}
- /**
- * Load collection info from table. Checks user rights
- *
- * @param $id
- * @param string $ritghsMode
- * @return array
- */
+ /**
+ * Load collection info from table. Checks user rights
+ *
+ * @param $id
+ * @param string $ritghsMode
+ * @return array
+ */
public function getCollection($id,$ritghsMode="read") {
- $ret = array();
-
- if (Summoner::validate($id, 'digit')) {
- $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`
- FROM `".DB_PREFIX."_collection` AS c
- WHERE ".$this->_User->getSQLRightsString($ritghsMode, "c")."
- AND `c`.`id` = '".$this->_DB->real_escape_string($id)."'";
- try {
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows > 0) {
- $ret = $query->fetch_assoc();
- }
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- }
- }
-
- return $ret;
- }
-
- /**
- * Get all available collections for display based on current user
- *
- * @return array
- */
+ $ret = array();
+
+ if (Summoner::validate($id, 'digit')) {
+ $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`
+ FROM `".DB_PREFIX."_collection` AS c
+ WHERE ".$this->_User->getSQLRightsString($ritghsMode, "c")."
+ AND `c`.`id` = '".$this->_DB->real_escape_string($id)."'";
+ try {
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows > 0) {
+ $ret = $query->fetch_assoc();
+ }
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Get all available collections for display based on current user
+ *
+ * @return array
+ */
public function getCollections() {
- $ret = array();
-
- $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
- `c`.`owner`, `c`.`group`, `c`.`rights`,
- `u`.`name` AS username, `g`.`name` AS groupname
- FROM `".DB_PREFIX."_collection` AS c
- LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
- LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
- WHERE ".$this->_User->getSQLRightsString("read", "c")."
- ORDER BY `c`.`name`";
- try {
- $query = $this->_DB->query($queryStr);
-
- if ($query !== false && $query->num_rows > 0) {
- while (($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- }
-
- return $ret;
- }
-
- /**
- * Retrieve the groups for selection based on user rights
- *
- * @return array
- */
- public function getGroupsForSelection() {
- $ret = array();
-
- $queryStr = "SELECT `id`, `name`, `description`
- FROM `".DB_PREFIX."_group`
- WHERE ".$this->_User->getSQLRightsString()."
- ORDER BY `name`";
- try {
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- }
-
- return $ret;
- }
-
- /**
- * Fetch all available users for selection based on current user rights
- *
- * @return array
- */
- public function getUsersForSelection() {
- $ret = array();
-
- $queryStr = "SELECT `id`, `name`, `login`
- FROM `".DB_PREFIX."_user`
- WHERE ".$this->_User->getSQLRightsString()."";
- try {
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- }
-
- return $ret;
- }
-
- /**
- * Fetch all availbale tools based on current user rights
- *
- * @return array
- */
- public function getToolsForSelection() {
- $ret = array();
-
- $queryStr = "SELECT `id`, `name`, `description`
- FROM `".DB_PREFIX."_tool`
- WHERE ".$this->_User->getSQLRightsString()."";
- try {
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- }
-
- return $ret;
- }
-
- /**
- * Create new collection entry in collection table. Provide valid data
- * only $name will be checked again
- *
- * @param array $data
- * @return bool
- */
- public function createCollection($data) {
- $ret = false;
-
- if(!empty($data['name']) === true
- && $this->_validNewCollectionName($data['name']) === true
- ) {
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
- try {
- $queryStr = "INSERT INTO `".DB_PREFIX."_collection`
- SET `name` = '".$this->_DB->real_escape_string($data['name'])."',
- `description` = '".$this->_DB->real_escape_string($data['description'])."',
- `owner` = '".$this->_DB->real_escape_string($data['owner'])."',
- `group` = '".$this->_DB->real_escape_string($data['group'])."',
- `rights` = '".$this->_DB->real_escape_string($data['rights'])."',
- `defaultSearchField` = '".$this->_DB->real_escape_string($data['defaultSearchField'])."'";
- $this->_DB->query($queryStr);
- $newId = $this->_DB->insert_id;
-
-
- $queryEntry2lookup = "CREATE TABLE `".DB_PREFIX."_collection_entry2lookup_".$newId."` (
- `fk_field` int NOT NULL,
- `fk_entry` int NOT NULL,
- `value` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
- FULLTEXT KEY `value` (`value`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";
- $this->_DB->query($queryEntry2lookup);
-
- $queryCollectionFields = "CREATE TABLE `".DB_PREFIX."_collection_fields_".$newId."` (
- `fk_field_id` int NOT NULL,
- `sort` int NOT NULL,
- UNIQUE KEY `fk_field_id` (`fk_field_id`),
- KEY `sort` (`sort`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";
- $this->_DB->query($queryCollectionFields);
-
- $queryCollectionEntry = "CREATE TABLE `".DB_PREFIX."_collection_entry_".$newId."` (
- `id` int NOT NULL AUTO_INCREMENT,
- `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
- `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- `modificationuser` int NOT NULL,
- `owner` int NOT NULL,
- `group` int NOT NULL,
- `rights` char(9) COLLATE utf8mb4_bin NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";
- $this->_DB->query($queryCollectionEntry);
-
- $this->_updateToolRelation($newId,$data['tool']);
-
- $this->_DB->commit();
- $ret = true;
- }
- catch (Exception $e) {
- if(DEBUG) var_dump($e->getMessage());
- error_log('ERROR Failed to create entry: '.var_export($e->getMessage(),true));
- $this->_DB->rollback();
- }
- }
-
- return $ret;
- }
-
- /**
- * Load the information from collection table for given $id
- *
- * @param string $id Number
- * @return array
- */
- public function getEditData($id) {
- $ret = array();
-
- if (Summoner::validate($id, 'digit')) {
- $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
- `c`.`owner`, `c`.`group`, `c`.`rights`, `c`.`defaultSearchField`,
- `u`.`name` AS username, `g`.`name` AS groupname
- FROM `".DB_PREFIX."_collection` AS c
- LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
- LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
- WHERE ".$this->_User->getSQLRightsString("read", "c")."
- AND `c`.`id` = '".$this->_DB->real_escape_string($id)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- $ret = $query->fetch_assoc();
- $ret['rights'] = Summoner::prepareRightsArray($ret['rights']);
- $ret['tool'] = $this->getAvailableTools($id);
- }
- }
-
- return $ret;
- }
-
- /**
- * Update collection with given data identified by given id
- * See method for the fields
- *
- * @param array $data
- * @return bool
- */
- public function updateCollection($data) {
- $ret = false;
-
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." data: ".var_export($data,true));
-
- if(!empty($data['name']) === true
- && $this->_validUpdateCollectionName($data['name'], $data['id']) === true
- && Summoner::validate($data['id'], 'digit')
- ) {
- $queryStr = "UPDATE `".DB_PREFIX."_collection`
- SET `name` = '".$this->_DB->real_escape_string($data['name'])."',
- `description` = '".$this->_DB->real_escape_string($data['description'])."',
- `owner` = '".$this->_DB->real_escape_string($data['owner'])."',
- `group` = '".$this->_DB->real_escape_string($data['group'])."',
- `rights` = '".$this->_DB->real_escape_string($data['rights'])."',
- `defaultSearchField` = '".$this->_DB->real_escape_string($data['defaultSearchField'])."'
- WHERE `id` = '".$this->_DB->real_escape_string($data['id'])."'";
- try {
- $this->_DB->query($queryStr);
- $this->_updateToolRelation($data['id'],$data['tool']);
- $ret = true;
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- }
-
- // update the search field if it is a field from the collection entry table
- // and add the index. The lookup table has already a fulltext index on value
- $queryCheck = "SHOW COLUMNS FROM `".DB_PREFIX."_collection_entry_".$data['id']."`
- LIKE '".$this->_DB->real_escape_string($data['defaultSearchField'])."'";
- $queryStr = "CREATE FULLTEXT INDEX ".$this->_DB->real_escape_string($data['defaultSearchField'])."
- ON `".DB_PREFIX."_collection_entry_".$data['id']."`
- (`".$this->_DB->real_escape_string($data['defaultSearchField'])."`)";
- try {
- $query = $this->_DB->query($queryCheck);
- if($query !== false && $query->num_rows > 0) {
- $this->_DB->query($queryStr);
- // altering or adding an index while data exists
- // ignores the collation (?)
- // optimize does a recreation and the column collation
- // is considered
- $this->_DB->query("OPTIMIZE TABLE `".DB_PREFIX."_collection_entry_".$data['id']."`");
- }
- } catch (Exception $e) {
- if($e->getCode() == "1061") {
- // duplicate key
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$e->getMessage());
- }
- else {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryCheck);
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- error_log("[ERROR] ".__METHOD__." mysql query: ".$e->getMessage());
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Delete collection identified by given id
- *
- * @param $id string Number
- * @return bool
- */
- public function deleteCollection($id) {
- $ret = false;
-
- // @todo Implement list deletion
- // what to do with the entries?
- exit('No implemented yet.');
-
- if(!empty($id) && Summoner::validate($id, 'digit')) {
- $queryStr = "DELETE FROM `".DB_PREFIX."_collection`
- WHERE `id` = '".$this->_DB->real_escape_string($id)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false) {
-
- var_dump("Implement list deletion");
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * Load the tools configured to the given collection
- *
- * @param $id
- * @return array
- */
- public function getAvailableTools($id) {
- $ret = array();
-
- $queryStr = "SELECT `t`.`id`, `t`.`name`, `t`.`description`, `t`.`action`, `t`.`target`
- FROM `".DB_PREFIX."_tool2collection` AS t2c
- LEFT JOIN `".DB_PREFIX."_tool` AS t ON t2c.fk_collection_id = t.id
- WHERE t2c.fk_collection_id = '".$this->_DB->real_escape_string($id)."'";
- try {
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- }
-
- return $ret;
- }
-
- /**
- * Check if given name can be used as a new one
- *
- * @param $name string
- * @return bool
- */
- private function _validNewCollectionName($name) {
- $ret = false;
- if (Summoner::validate($name, 'nospace')) {
- $queryStr = "SELECT `id` FROM `".DB_PREFIX."_collection`
- WHERE `name` = '".$this->_DB->real_escape_string($name)."'";
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows < 1) {
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * Check if given name can be used as a new name for id
- *
- * @param $name string
- * @param $id string Number
- * @return bool
- */
- private function _validUpdateCollectionName($name, $id) {
- $ret = false;
-
- if (Summoner::validate($name, 'nospace')
- && Summoner::validate($id,'digit')
- ) {
- $queryStr = "SELECT `id` FROM `".DB_PREFIX."_collection`
- WHERE `name` = '".$this->_DB->real_escape_string($name)."'
- AND `id` != '".$this->_DB->real_escape_string($id)."'";
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows < 1) {
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * Update the given colletion ($id) with the given tool array
- *
- * @param $id
- * @param $tool
- * @return bool
- */
- private function _updateToolRelation($id,$tool) {
- $ret = false;
-
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
- try {
- $this->_DB->query("DELETE FROM `".DB_PREFIX."_tool2collection`
- WHERE `fk_collection_id` = '".$this->_DB->real_escape_string($id)."'");
- if(!empty($tool)) {
- foreach($tool as $k=>$v) {
- if(!empty($v)) {
- $this->_DB->query("INSERT IGNORE INTO `".DB_PREFIX."_tool2collection`
- SET `fk_tool_id` = '".$this->_DB->real_escape_string($v)."',
- `fk_collection_id` = '".$this->_DB->real_escape_string($id)."'");
- }
- }
- }
- $this->_DB->commit();
- $ret = true;
- } catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- $this->_DB->rollback();
- }
-
- return $ret;
- }
+ $ret = array();
+
+ $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
+ `c`.`owner`, `c`.`group`, `c`.`rights`,
+ `u`.`name` AS username, `g`.`name` AS groupname
+ FROM `".DB_PREFIX."_collection` AS c
+ LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
+ LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
+ WHERE ".$this->_User->getSQLRightsString("read", "c")."
+ ORDER BY `c`.`name`";
+ try {
+ $query = $this->_DB->query($queryStr);
+
+ if ($query !== false && $query->num_rows > 0) {
+ while (($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve the groups for selection based on user rights
+ *
+ * @return array
+ */
+ public function getGroupsForSelection() {
+ $ret = array();
+
+ $queryStr = "SELECT `id`, `name`, `description`
+ FROM `".DB_PREFIX."_group`
+ WHERE ".$this->_User->getSQLRightsString()."
+ ORDER BY `name`";
+ try {
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Fetch all available users for selection based on current user rights
+ *
+ * @return array
+ */
+ public function getUsersForSelection() {
+ $ret = array();
+
+ $queryStr = "SELECT `id`, `name`, `login`
+ FROM `".DB_PREFIX."_user`
+ WHERE ".$this->_User->getSQLRightsString()."";
+ try {
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Fetch all availbale tools based on current user rights
+ *
+ * @return array
+ */
+ public function getToolsForSelection() {
+ $ret = array();
+
+ $queryStr = "SELECT `id`, `name`, `description`
+ FROM `".DB_PREFIX."_tool`
+ WHERE ".$this->_User->getSQLRightsString()."";
+ try {
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Create new collection entry in collection table. Provide valid data
+ * only $name will be checked again
+ *
+ * @param array $data
+ * @return bool
+ */
+ public function createCollection($data) {
+ $ret = false;
+
+ if(!empty($data['name']) === true
+ && $this->_validNewCollectionName($data['name']) === true
+ ) {
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+ try {
+ $queryStr = "INSERT INTO `".DB_PREFIX."_collection`
+ SET `name` = '".$this->_DB->real_escape_string($data['name'])."',
+ `description` = '".$this->_DB->real_escape_string($data['description'])."',
+ `owner` = '".$this->_DB->real_escape_string($data['owner'])."',
+ `group` = '".$this->_DB->real_escape_string($data['group'])."',
+ `rights` = '".$this->_DB->real_escape_string($data['rights'])."',
+ `defaultSearchField` = '".$this->_DB->real_escape_string($data['defaultSearchField'])."'";
+ $this->_DB->query($queryStr);
+ $newId = $this->_DB->insert_id;
+
+
+ $queryEntry2lookup = "CREATE TABLE `".DB_PREFIX."_collection_entry2lookup_".$newId."` (
+ `fk_field` int NOT NULL,
+ `fk_entry` int NOT NULL,
+ `value` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
+ FULLTEXT KEY `value` (`value`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";
+ $this->_DB->query($queryEntry2lookup);
+
+ $queryCollectionFields = "CREATE TABLE `".DB_PREFIX."_collection_fields_".$newId."` (
+ `fk_field_id` int NOT NULL,
+ `sort` int NOT NULL,
+ UNIQUE KEY `fk_field_id` (`fk_field_id`),
+ KEY `sort` (`sort`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";
+ $this->_DB->query($queryCollectionFields);
+
+ $queryCollectionEntry = "CREATE TABLE `".DB_PREFIX."_collection_entry_".$newId."` (
+ `id` int NOT NULL AUTO_INCREMENT,
+ `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+ `modificationuser` int NOT NULL,
+ `owner` int NOT NULL,
+ `group` int NOT NULL,
+ `rights` char(9) COLLATE utf8mb4_bin NOT NULL,
+ PRIMARY KEY (`id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";
+ $this->_DB->query($queryCollectionEntry);
+
+ $this->_updateToolRelation($newId,$data['tool']);
+
+ $this->_DB->commit();
+ $ret = true;
+ }
+ catch (Exception $e) {
+ if(DEBUG) var_dump($e->getMessage());
+ error_log('ERROR Failed to create entry: '.var_export($e->getMessage(),true));
+ $this->_DB->rollback();
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load the information from collection table for given $id
+ *
+ * @param string $id Number
+ * @return array
+ */
+ public function getEditData($id) {
+ $ret = array();
+
+ if (Summoner::validate($id, 'digit')) {
+ $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
+ `c`.`owner`, `c`.`group`, `c`.`rights`, `c`.`defaultSearchField`,
+ `u`.`name` AS username, `g`.`name` AS groupname
+ FROM `".DB_PREFIX."_collection` AS c
+ LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
+ LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
+ WHERE ".$this->_User->getSQLRightsString("read", "c")."
+ AND `c`.`id` = '".$this->_DB->real_escape_string($id)."'";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ $ret = $query->fetch_assoc();
+ $ret['rights'] = Summoner::prepareRightsArray($ret['rights']);
+ $ret['tool'] = $this->getAvailableTools($id);
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Update collection with given data identified by given id
+ * See method for the fields
+ *
+ * @param array $data
+ * @return bool
+ */
+ public function updateCollection($data) {
+ $ret = false;
+
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." data: ".var_export($data,true));
+
+ if(!empty($data['name']) === true
+ && $this->_validUpdateCollectionName($data['name'], $data['id']) === true
+ && Summoner::validate($data['id'], 'digit')
+ ) {
+ $queryStr = "UPDATE `".DB_PREFIX."_collection`
+ SET `name` = '".$this->_DB->real_escape_string($data['name'])."',
+ `description` = '".$this->_DB->real_escape_string($data['description'])."',
+ `owner` = '".$this->_DB->real_escape_string($data['owner'])."',
+ `group` = '".$this->_DB->real_escape_string($data['group'])."',
+ `rights` = '".$this->_DB->real_escape_string($data['rights'])."',
+ `defaultSearchField` = '".$this->_DB->real_escape_string($data['defaultSearchField'])."'
+ WHERE `id` = '".$this->_DB->real_escape_string($data['id'])."'";
+ try {
+ $this->_DB->query($queryStr);
+ $this->_updateToolRelation($data['id'],$data['tool']);
+ $ret = true;
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ }
+
+ // update the search field if it is a field from the collection entry table
+ // and add the index. The lookup table has already a fulltext index on value
+ $queryCheck = "SHOW COLUMNS FROM `".DB_PREFIX."_collection_entry_".$data['id']."`
+ LIKE '".$this->_DB->real_escape_string($data['defaultSearchField'])."'";
+ $queryStr = "CREATE FULLTEXT INDEX ".$this->_DB->real_escape_string($data['defaultSearchField'])."
+ ON `".DB_PREFIX."_collection_entry_".$data['id']."`
+ (`".$this->_DB->real_escape_string($data['defaultSearchField'])."`)";
+ try {
+ $query = $this->_DB->query($queryCheck);
+ if($query !== false && $query->num_rows > 0) {
+ $this->_DB->query($queryStr);
+ // altering or adding an index while data exists
+ // ignores the collation (?)
+ // optimize does a recreation and the column collation
+ // is considered
+ $this->_DB->query("OPTIMIZE TABLE `".DB_PREFIX."_collection_entry_".$data['id']."`");
+ }
+ } catch (Exception $e) {
+ if($e->getCode() == "1061") {
+ // duplicate key
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$e->getMessage());
+ }
+ else {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryCheck);
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ error_log("[ERROR] ".__METHOD__." mysql query: ".$e->getMessage());
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Delete collection identified by given id
+ *
+ * @param $id string Number
+ * @return bool
+ */
+ public function deleteCollection($id) {
+ $ret = false;
+
+ // @todo Implement list deletion
+ // what to do with the entries?
+ exit('No implemented yet.');
+
+ if(!empty($id) && Summoner::validate($id, 'digit')) {
+ $queryStr = "DELETE FROM `".DB_PREFIX."_collection`
+ WHERE `id` = '".$this->_DB->real_escape_string($id)."'";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false) {
+
+ var_dump("Implement list deletion");
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load the tools configured to the given collection
+ *
+ * @param $id
+ * @return array
+ */
+ public function getAvailableTools($id) {
+ $ret = array();
+
+ $queryStr = "SELECT `t`.`id`, `t`.`name`, `t`.`description`, `t`.`action`, `t`.`target`
+ FROM `".DB_PREFIX."_tool2collection` AS t2c
+ LEFT JOIN `".DB_PREFIX."_tool` AS t ON t2c.fk_collection_id = t.id
+ WHERE t2c.fk_collection_id = '".$this->_DB->real_escape_string($id)."'";
+ try {
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Check if given name can be used as a new one
+ *
+ * @param $name string
+ * @return bool
+ */
+ private function _validNewCollectionName($name) {
+ $ret = false;
+ if (Summoner::validate($name, 'nospace')) {
+ $queryStr = "SELECT `id` FROM `".DB_PREFIX."_collection`
+ WHERE `name` = '".$this->_DB->real_escape_string($name)."'";
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows < 1) {
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Check if given name can be used as a new name for id
+ *
+ * @param $name string
+ * @param $id string Number
+ * @return bool
+ */
+ private function _validUpdateCollectionName($name, $id) {
+ $ret = false;
+
+ if (Summoner::validate($name, 'nospace')
+ && Summoner::validate($id,'digit')
+ ) {
+ $queryStr = "SELECT `id` FROM `".DB_PREFIX."_collection`
+ WHERE `name` = '".$this->_DB->real_escape_string($name)."'
+ AND `id` != '".$this->_DB->real_escape_string($id)."'";
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows < 1) {
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Update the given colletion ($id) with the given tool array
+ *
+ * @param $id
+ * @param $tool
+ * @return bool
+ */
+ private function _updateToolRelation($id,$tool) {
+ $ret = false;
+
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+ try {
+ $this->_DB->query("DELETE FROM `".DB_PREFIX."_tool2collection`
+ WHERE `fk_collection_id` = '".$this->_DB->real_escape_string($id)."'");
+ if(!empty($tool)) {
+ foreach($tool as $k=>$v) {
+ if(!empty($v)) {
+ $this->_DB->query("INSERT IGNORE INTO `".DB_PREFIX."_tool2collection`
+ SET `fk_tool_id` = '".$this->_DB->real_escape_string($v)."',
+ `fk_collection_id` = '".$this->_DB->real_escape_string($id)."'");
+ }
+ }
+ }
+ $this->_DB->commit();
+ $ret = true;
+ } catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ $this->_DB->rollback();
+ }
+
+ return $ret;
+ }
}
*/
class Manageentry {
- /**
- * The database object
- *
- * @var object
- */
- private $_DB;
-
- /**
- * The user object to query with
- *
- * @var object
- */
- private $_User;
-
- /**
- * Currently loaded collection to manage entries from
- *
- * @var string Number
- */
- private $_collectionId;
-
- /**
- * Placeholder in query strings for inserted DB id
- *
- * @var string
- */
- private $_replaceEntryString = 'REPLACE_ENTERY';
-
- /**
- * ManageCollections constructor.
- *
- * @param $databaseConnectionObject
- * @param $userObj
- */
- public function __construct($databaseConnectionObject, $userObj) {
- $this->_DB = $databaseConnectionObject;
- $this->_User = $userObj;
- }
-
- /**
- * Set the collection to manage entries from
- *
- * @param $collectionId
- */
- public function setCollection($collectionId) {
- if(!empty($collectionId)) {
- $this->_collectionId = $collectionId;
- }
- }
-
- /**
- * Load the fields for the loaded collection
- * Also load additional data based on fieldtype and _loadField_ method
- *
- * @return array
- */
- public function getEditFields() {
- $ret = array();
-
- if(!empty($this->_collectionId)) {
- $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`,
- `sf`.`value`
- FROM `".DB_PREFIX."_collection_fields_".$this->_DB->real_escape_string($this->_collectionId)."` AS cf
- LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
- ORDER BY `cf`.`sort`";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $_mn = '_loadField_'.$result['type'];
- if(method_exists($this, $_mn)) {
- $result = $this->$_mn($result);
- }
- $ret[$result['id']] = $result;
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Load required data for edit. Uses some functions from Mancubus but has
- * different data layout. Checks write edit too
- *
- * @param $entryId
- * @return array
- */
- public function getEditData($entryId) {
- $ret = array();
-
- if(!empty($this->_collectionId) && !empty($entryId)) {
- $queryStr = "SELECT *
- FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`
- WHERE ".$this->_User->getSQLRightsString("write")."
- AND `id` = '".$this->_DB->real_escape_string($entryId)."'";
- $query = $this->_DB->query($queryStr);
-
- if($query !== false && $query->num_rows > 0) {
- $_entryFields = $this->getEditFields();
-
- if(($result = $query->fetch_assoc()) != false) {
- $ret = $this->_mergeEntryWithFields($result, $_entryFields);
- $ret['_canDelete'] = $this->_canDelete($entryId);
- }
-
- }
- }
-
- return $ret;
- }
-
- /**
- * Create an entry with given data
- *
- * @param array $data
- * @param number $owner
- * @param number $group
- * @param string $rights
- * @param mixed $update Either false for no update or the ID to update
- * @return mixed
- */
- public function create($data, $owner, $group, $rights, $update=false) {
- $ret = false;
-
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." data: ".var_export($data,true));
-
- //@todo there is no setting for individual rights available yet
- if(!empty($data) && !empty($owner) && !empty($group) && !empty($rights)) {
-
- // create the queryData array
- // init is the entry in the table. Needed for after stuff
- // after returns query and upload which then calls the extra methods
- $queryData['init'] = array();
- $queryData['after'] = array();
- foreach ($data as $i=>$d) {
- $_mn = '_saveField_'.$d['type'];
- if(method_exists($this, $_mn)) {
- $queryData = $this->$_mn($d, $queryData);
- }
- else {
- if(DEBUG)error_log("[DEBUG] ".__METHOD__." Missing query function for: ".var_export($d, true));
- }
- }
-
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." queryData: ".var_export($queryData,true));
-
- if(!empty($queryData['init'])) {
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
-
- try {
- $queryStr = "INSERT INTO `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
- if($update !== false && is_numeric($update)) {
- $queryStr = "UPDATE `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
- }
- $queryStr .= " SET
- `modificationuser` = '".$this->_DB->real_escape_string($owner)."',
- `owner` = '".$this->_DB->real_escape_string($owner)."',
- `group` = '".$this->_DB->real_escape_string($group)."',
- `rights`= '".$this->_DB->real_escape_string($rights)."',";
- $queryStr .= implode(", ",$queryData['init']);
- if($update !== false && is_numeric($update)) {
- $queryStr .= " WHERE `id` = '".$this->_DB->real_escape_string($update)."'";
- }
-
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." init queryStr: ".var_export($queryStr,true));
-
- $this->_DB->query($queryStr);
-
- if($update !== false && is_numeric($update)) {
- $newId = $update;
- }
- else {
- $newId = $this->_DB->insert_id;
- }
-
- if(!empty($newId)) {
- if(!empty($queryData['after']) && isset($queryData['after']['query'])) {
- foreach ($queryData['after']['query'] as $q) {
- $this->_runAfter_query($q, $newId);
- }
- }
-
- if(!empty($queryData['after']) && isset($queryData['after']['upload'])) {
- foreach ($queryData['after']['upload'] as $q) {
- $this->_runAfter_upload($q, $newId);
- }
- }
-
- $this->_DB->commit();
- $ret = $newId;
- }
- else {
- $this->_DB->rollback();
- }
- } catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- $this->_DB->rollback();
- }
- }
- else {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." empty init in: ".var_export($queryData,true));
- }
- }
-
- return $ret;
- }
-
- /**
- * Delete given entryId from currently loaded collection
- * Checks userrights too.
- *
- * @param $entryId
- * @return bool
- */
- public function delete($entryId) {
- $ret = false;
-
- if(!empty($entryId) && !empty($this->_collectionId)) {
-
- if ($this->_canDelete($entryId)) {
-
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
-
- try {
- // remove assets
- $_path = PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId;
- if(is_dir($_path) && is_readable($_path)) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove assets :".$_path);
- $rmDir = Summoner::recursive_remove_directory($_path);
- if($rmDir === false) {
- throw new Exception("Failed to delete path: ".$_path);
- }
- }
-
- // delete data from lookup fields
- $queryStr = "DELETE
- FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
- WHERE `fk_entry` = '".$this->_DB->real_escape_string($entryId)."'";
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove lookup queryStr: ".var_export($queryStr,true));
- $this->_DB->query($queryStr);
-
- // delete entry
- $queryStr = "DELETE
- FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`
- WHERE `id` = '".$this->_DB->real_escape_string($entryId)."'
- AND " . $this->_User->getSQLRightsString("delete") . "";
- $this->_DB->query($queryStr);
-
- $this->_DB->commit();
- $ret = true;
- } catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- $this->_DB->rollback();
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Validates that current use can write the given Entry
- *
- * @param $entryId
- * @return bool
- */
- public function canEditEntry($entryId) {
- $ret = false;
-
- if(!empty($entryId) && !empty($this->_collectionId)) {
-
- $queryStr = "SELECT `id`
- FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`
- WHERE `id` = '".$this->_DB->real_escape_string($entryId)."'
- AND " . $this->_User->getSQLRightsString("write") . "";
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows > 0) {
- if (($result = $query->fetch_assoc()) != false) {
- $ret = true;
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Check if given entryid can be deleted from current collection
- * and user
- *
- * @param $entryId
- * @return bool
- */
- private function _canDelete($entryId) {
- $ret = false;
-
- if(!empty($entryId) && !empty($this->_collectionId)) {
-
- $queryStr = "SELECT `id`
- FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`
- WHERE `id` = '".$this->_DB->real_escape_string($entryId)."'
- AND " . $this->_User->getSQLRightsString("delete") . "";
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows > 0) {
- if (($result = $query->fetch_assoc()) != false) {
- $ret = true;
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Merge the loaded entryData with the to look up entryFields data
- * In this case only the fields which have a _loadFieldValue_ method
- * are loaded. More is not needed here.
- *
- * @param $entryData array
- * @param $entryFields array
- * @return array
- */
- private function _mergeEntryWithFields($entryData, $entryFields) {
- if(!empty($entryFields)) {
- foreach($entryFields as $f) {
- $_mnValue = '_loadFieldValue_'.$f['type'];
-
- if(!isset($entryData[$f['identifier']]) && method_exists($this, $_mnValue) && isset($entryData['id']) ) {
- $entryData[$f['identifier']] = $this->$_mnValue($entryData['id'], $f);
- }
- }
- }
- return $entryData;
- }
-
- /**
- * Load the values for given $entryId for $fieldData
- * lookup function for field type lookupmultiple
- *
- * @see Mancubus
- * @param Number $entryId
- * @param array $fieldData
- * @return array
- */
- private function _loadFieldValue_lookupmultiple($entryId, $fieldData) {
- $ret = array();
-
- if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
- $queryStr = "SELECT `value`
- FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
- WHERE `fk_field` = '".$this->_DB->real_escape_string($fieldData['id'])."'
- AND `fk_entry` = '".$this->_DB->real_escape_string($entryId)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[] = $result['value'];
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Get the single upload file from storage location
- * lookup function for field type upload
- *
- * @see Mancubus
- * @param $entryId
- * @param $fieldData
- * @return string
- */
- private function _loadFieldValue_upload($entryId, $fieldData) {
- $ret = "";
- if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
-
- $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
- if(!empty($uploadedFile)) {
- foreach ($uploadedFile as $f) {
- $ret = basename($f);
- break;
- }
- }
- }
- return $ret;
- }
-
- /**
- * Get the multiple upload files from storage location
- * lookup function for field type upload_multiple
- *
- * @see Mancubus
- * @param $entryId
- * @param $fieldData
- * @return array
- */
- private function _loadFieldValue_upload_multiple($entryId, $fieldData) {
- $ret = array();
- if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
-
- $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
- if(!empty($uploadedFile)) {
- foreach ($uploadedFile as $f) {
- $ret[] = basename($f);
- }
- }
- }
- return $ret;
- }
-
- /**
- * Provide the options for a selection field by processing the $data['value']
- * since the values are stored in the entry DB as a list
- *
- * @param $data array
- * @return array
- */
- private function _loadField_selection($data) {
- if(!empty($data) && isset($data['value']) && !empty($data['value'])) {
- if(strstr($data['value'], ",")) {
- $data['options'] = explode(",", $data['value']);
- }
- }
- return $data;
- }
-
- /**
- * Load suggestions based on the existing data for this field
- *
- * @param $data array Field data
- * @return array
- */
- private function _loadField_lookupmultiple($data) {
- if(!empty($data) && isset($data['id']) && !empty($data['id'])) {
- $queryStr = "SELECT DISTINCT(`value`)
- FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
- WHERE `fk_field` = '".$this->_DB->real_escape_string($data['id'])."'";
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows > 0) {
- while (($result = $query->fetch_assoc()) != false) {
- $data['suggestion'][] = $result['value'];
- }
- }
- }
- return $data;
- }
-
- /**
- * Create part of the insert statement for field type text
- *
- * @param $data array Field data
- * @param $queryData array Query data array
- * @return array
- */
- private function _saveField_text($data, $queryData) {
- $queryData['init'][] = "`".$data['identifier']."` = '".$this->_DB->real_escape_string($data['valueToSave'])."'";
- return $queryData;
- }
-
- /**
- * Create part of the insert statement for field type text3
- *
- * @param $data array Field data
- * @param $queryData array Query data array
- * @return array
- */
- private function _saveField_text3($data, $queryData) {
- return $this->_saveField_text($data, $queryData);
- }
-
- /**
- * Create part of the insert statement for field type textarea
- *
- * @param $data array Field data
- * @param $queryData array Query data array
- * @return array
- */
- private function _saveField_textarea($data, $queryData) {
- return $this->_saveField_text($data, $queryData);
- }
-
- /**
- * Create part of the insert statement for field type selection
- *
- * @param $data array Field data
- * @param $queryData array Query data array
- * @return array
- */
- private function _saveField_selection($data, $queryData) {
- return $this->_saveField_text($data, $queryData);
- }
- /**
- * Create part of the insert statement for field type year
- *
- * @param $data array Field data
- * @param $queryData array Query data array
- * @return array
- */
- private function _saveField_year($data, $queryData) {
- return $this->_saveField_text($data, $queryData);
- }
-
- /**
- * Create part of the insert statement for field type lookupmultiple
- *
- * @param $data array Field data
- * @param $queryData array Query data array
- * @return array
- */
- private function _saveField_lookupmultiple($data, $queryData) {
- $_d = trim($data['valueToSave']);
- $_d = trim($_d, ",");
-
- // first clean since the new data is everything
- $queryData['after']['query'][] = "DELETE FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_collectionId."`
- WHERE `fk_field` = '".$this->_DB->real_escape_string($data['id'])."'
- AND `fk_entry` = '".$this->_replaceEntryString."'";
- if(!empty($_d)) {
- $_process = array($_d);
- if (strstr($data['valueToSave'], ",")) {
- $_process = explode(",", $data['valueToSave']);
- }
- foreach ($_process as $p) {
- $queryData['after']['query'][] = "INSERT IGNORE INTO `".DB_PREFIX."_collection_entry2lookup_".$this->_collectionId."`
- SET `fk_field` = '".$this->_DB->real_escape_string($data['id'])."',
- `fk_entry` = '".$this->_replaceEntryString."',
- `value` = '".$this->_DB->real_escape_string($p)."'";
- }
- }
-
- return $queryData;
- }
-
- /**
- * Single upload field
- *
- * @param $data array The data from _FILES
- * @param $queryData array
- * @return array
- */
- private function _saveField_upload($data, $queryData) {
- $_up = $data['uploadData'];
-
- // delete the single upload
- // this way the after query method is triggered without any upload
- if(isset($data['deleteData'])) {
- $queryData['after']['upload'][] = array(
- 'identifier' => $data['identifier'],
- 'multiple' => false,
- 'deleteData' => $data['deleteData']
- );
- }
-
- if($_up['error'][$data['identifier']] === 0) {
- $_ext = pathinfo($_up['name'][$data['identifier']],PATHINFO_EXTENSION);
- $newFilename = sha1($_up['name'][$data['identifier']]).".".$_ext;
-
- $queryData['after']['upload'][] = array(
- 'identifier' => $data['identifier'],
- 'name' => $newFilename,
- 'tmp_name' => $_up['tmp_name'][$data['identifier']],
- 'multiple' => false
- );
- }
- return $queryData;
- }
-
- /**
- * Multiple upload field
- *
- * @param $data array The data from _FILES
- * @param $queryData array
- * @return array
- */
- private function _saveField_upload_multiple($data, $queryData) {
- $_up = $data['uploadData'];
-
- if(isset($data['deleteData'])) {
- $queryData['after']['upload'][] = array(
- 'identifier' => $data['identifier'],
- 'multiple' => true,
- 'deleteData' => $data['deleteData']
- );
- }
-
- foreach ($_up['error'][$data['identifier']] as $k=>$v) {
- if($v === 0) {
- $_ext = pathinfo($_up['name'][$data['identifier']][$k],PATHINFO_EXTENSION);
- $newFilename = sha1($_up['name'][$data['identifier']][$k]).".".$_ext;
-
- $queryData['after']['upload'][] = array(
- 'identifier' => $data['identifier'],
- 'name' => $newFilename,
- 'tmp_name' => $_up['tmp_name'][$data['identifier']][$k],
- 'multiple' => true
- );
- }
- }
-
- return $queryData;
- }
-
- /**
- * runs the query and throws query execption if false
- *
- * @param $queryString
- * @param $insertId
- */
- private function _runAfter_query($queryString, $insertId) {
- if(!empty($queryString) && !empty($insertId)) {
- // replace only once to avoid replacing actual data
- $queryStr = Summoner::replaceOnce($queryString,$this->_replaceEntryString, $insertId);
- $this->_DB->query($queryStr);
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." queryStr: ".var_export($queryStr,true));
- }
- }
-
- /**
- * Move uploaded into right directory
- * If single upload (multiple=false) then remove all the files for this type field first. Works the same
- * if you want to remove the upload via edit
- *
- * Also removes the defined uploads from multiple upload field
- *
- * @param $uploadData
- * @param $insertId
- * @throws Exception
- */
- private function _runAfter_upload($uploadData, $insertId) {
- if(!empty($uploadData) && !empty($insertId)) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." uploadata: ".var_export($uploadData,true));
- $_path = PATH_STORAGE.'/'.$this->_collectionId.'/'.$insertId;
- if(!is_dir($_path)) {
- if(!mkdir($_path, 0777, true)) {
- throw new Exception("Failed to create storage path: ".$_path);
- }
- }
-
- if($uploadData['multiple'] === false) {
- // single upload. Delete existing first.
- // also triggered if the single needs to be deleted
- $_existingFiles = glob($_path.'/'.$uploadData['identifier'].'-*');
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove single existing: ".var_export($_existingFiles,true));
- if(!empty($_existingFiles)) {
- foreach ($_existingFiles as $f) {
- unlink($f);
- }
- clearstatcache();
- }
- }
-
- if($uploadData['multiple'] === true && isset($uploadData['deleteData'])) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove multiple existing: ".var_export($uploadData['deleteData'],true));
- foreach ($uploadData['deleteData'] as $k=>$v) {
- $_file = $_path.'/'.$v;
- if(file_exists($_file)) {
- unlink($_file);
- }
- clearstatcache();
- }
- }
-
- if(isset($uploadData['tmp_name']) && isset($uploadData['name'])) {
- if(!move_uploaded_file($uploadData['tmp_name'],$_path.'/'.$uploadData['identifier'].'-'.$uploadData['name'])) {
- throw new Exception("Can not move file to: ".$_path.'/'.$uploadData['identifier'].'-'.$uploadData['name']);
- }
- }
- }
- }
+ /**
+ * The database object
+ *
+ * @var object
+ */
+ private $_DB;
+
+ /**
+ * The user object to query with
+ *
+ * @var object
+ */
+ private $_User;
+
+ /**
+ * Currently loaded collection to manage entries from
+ *
+ * @var string Number
+ */
+ private $_collectionId;
+
+ /**
+ * Placeholder in query strings for inserted DB id
+ *
+ * @var string
+ */
+ private $_replaceEntryString = 'REPLACE_ENTERY';
+
+ /**
+ * ManageCollections constructor.
+ *
+ * @param $databaseConnectionObject
+ * @param $userObj
+ */
+ public function __construct($databaseConnectionObject, $userObj) {
+ $this->_DB = $databaseConnectionObject;
+ $this->_User = $userObj;
+ }
+
+ /**
+ * Set the collection to manage entries from
+ *
+ * @param $collectionId
+ */
+ public function setCollection($collectionId) {
+ if(!empty($collectionId)) {
+ $this->_collectionId = $collectionId;
+ }
+ }
+
+ /**
+ * Load the fields for the loaded collection
+ * Also load additional data based on fieldtype and _loadField_ method
+ *
+ * @return array
+ */
+ public function getEditFields() {
+ $ret = array();
+
+ if(!empty($this->_collectionId)) {
+ $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`,
+ `sf`.`value`
+ FROM `".DB_PREFIX."_collection_fields_".$this->_DB->real_escape_string($this->_collectionId)."` AS cf
+ LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
+ ORDER BY `cf`.`sort`";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $_mn = '_loadField_'.$result['type'];
+ if(method_exists($this, $_mn)) {
+ $result = $this->$_mn($result);
+ }
+ $ret[$result['id']] = $result;
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load required data for edit. Uses some functions from Mancubus but has
+ * different data layout. Checks write edit too
+ *
+ * @param $entryId
+ * @return array
+ */
+ public function getEditData($entryId) {
+ $ret = array();
+
+ if(!empty($this->_collectionId) && !empty($entryId)) {
+ $queryStr = "SELECT *
+ FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`
+ WHERE ".$this->_User->getSQLRightsString("write")."
+ AND `id` = '".$this->_DB->real_escape_string($entryId)."'";
+ $query = $this->_DB->query($queryStr);
+
+ if($query !== false && $query->num_rows > 0) {
+ $_entryFields = $this->getEditFields();
+
+ if(($result = $query->fetch_assoc()) != false) {
+ $ret = $this->_mergeEntryWithFields($result, $_entryFields);
+ $ret['_canDelete'] = $this->_canDelete($entryId);
+ }
+
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Create an entry with given data
+ *
+ * @param array $data
+ * @param number $owner
+ * @param number $group
+ * @param string $rights
+ * @param mixed $update Either false for no update or the ID to update
+ * @return mixed
+ */
+ public function create($data, $owner, $group, $rights, $update=false) {
+ $ret = false;
+
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." data: ".var_export($data,true));
+
+ //@todo there is no setting for individual rights available yet
+ if(!empty($data) && !empty($owner) && !empty($group) && !empty($rights)) {
+
+ // create the queryData array
+ // init is the entry in the table. Needed for after stuff
+ // after returns query and upload which then calls the extra methods
+ $queryData['init'] = array();
+ $queryData['after'] = array();
+ foreach ($data as $i=>$d) {
+ $_mn = '_saveField_'.$d['type'];
+ if(method_exists($this, $_mn)) {
+ $queryData = $this->$_mn($d, $queryData);
+ }
+ else {
+ if(DEBUG)error_log("[DEBUG] ".__METHOD__." Missing query function for: ".var_export($d, true));
+ }
+ }
+
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." queryData: ".var_export($queryData,true));
+
+ if(!empty($queryData['init'])) {
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+
+ try {
+ $queryStr = "INSERT INTO `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
+ if($update !== false && is_numeric($update)) {
+ $queryStr = "UPDATE `".DB_PREFIX."_collection_entry_".$this->_collectionId."`";
+ }
+ $queryStr .= " SET
+ `modificationuser` = '".$this->_DB->real_escape_string($owner)."',
+ `owner` = '".$this->_DB->real_escape_string($owner)."',
+ `group` = '".$this->_DB->real_escape_string($group)."',
+ `rights`= '".$this->_DB->real_escape_string($rights)."',";
+ $queryStr .= implode(", ",$queryData['init']);
+ if($update !== false && is_numeric($update)) {
+ $queryStr .= " WHERE `id` = '".$this->_DB->real_escape_string($update)."'";
+ }
+
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." init queryStr: ".var_export($queryStr,true));
+
+ $this->_DB->query($queryStr);
+
+ if($update !== false && is_numeric($update)) {
+ $newId = $update;
+ }
+ else {
+ $newId = $this->_DB->insert_id;
+ }
+
+ if(!empty($newId)) {
+ if(!empty($queryData['after']) && isset($queryData['after']['query'])) {
+ foreach ($queryData['after']['query'] as $q) {
+ $this->_runAfter_query($q, $newId);
+ }
+ }
+
+ if(!empty($queryData['after']) && isset($queryData['after']['upload'])) {
+ foreach ($queryData['after']['upload'] as $q) {
+ $this->_runAfter_upload($q, $newId);
+ }
+ }
+
+ $this->_DB->commit();
+ $ret = $newId;
+ }
+ else {
+ $this->_DB->rollback();
+ }
+ } catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ $this->_DB->rollback();
+ }
+ }
+ else {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." empty init in: ".var_export($queryData,true));
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Delete given entryId from currently loaded collection
+ * Checks userrights too.
+ *
+ * @param $entryId
+ * @return bool
+ */
+ public function delete($entryId) {
+ $ret = false;
+
+ if(!empty($entryId) && !empty($this->_collectionId)) {
+
+ if ($this->_canDelete($entryId)) {
+
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+
+ try {
+ // remove assets
+ $_path = PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId;
+ if(is_dir($_path) && is_readable($_path)) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove assets :".$_path);
+ $rmDir = Summoner::recursive_remove_directory($_path);
+ if($rmDir === false) {
+ throw new Exception("Failed to delete path: ".$_path);
+ }
+ }
+
+ // delete data from lookup fields
+ $queryStr = "DELETE
+ FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
+ WHERE `fk_entry` = '".$this->_DB->real_escape_string($entryId)."'";
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove lookup queryStr: ".var_export($queryStr,true));
+ $this->_DB->query($queryStr);
+
+ // delete entry
+ $queryStr = "DELETE
+ FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`
+ WHERE `id` = '".$this->_DB->real_escape_string($entryId)."'
+ AND " . $this->_User->getSQLRightsString("delete") . "";
+ $this->_DB->query($queryStr);
+
+ $this->_DB->commit();
+ $ret = true;
+ } catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ $this->_DB->rollback();
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Validates that current use can write the given Entry
+ *
+ * @param $entryId
+ * @return bool
+ */
+ public function canEditEntry($entryId) {
+ $ret = false;
+
+ if(!empty($entryId) && !empty($this->_collectionId)) {
+
+ $queryStr = "SELECT `id`
+ FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`
+ WHERE `id` = '".$this->_DB->real_escape_string($entryId)."'
+ AND " . $this->_User->getSQLRightsString("write") . "";
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows > 0) {
+ if (($result = $query->fetch_assoc()) != false) {
+ $ret = true;
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Check if given entryid can be deleted from current collection
+ * and user
+ *
+ * @param $entryId
+ * @return bool
+ */
+ private function _canDelete($entryId) {
+ $ret = false;
+
+ if(!empty($entryId) && !empty($this->_collectionId)) {
+
+ $queryStr = "SELECT `id`
+ FROM `".DB_PREFIX."_collection_entry_".$this->_collectionId."`
+ WHERE `id` = '".$this->_DB->real_escape_string($entryId)."'
+ AND " . $this->_User->getSQLRightsString("delete") . "";
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows > 0) {
+ if (($result = $query->fetch_assoc()) != false) {
+ $ret = true;
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Merge the loaded entryData with the to look up entryFields data
+ * In this case only the fields which have a _loadFieldValue_ method
+ * are loaded. More is not needed here.
+ *
+ * @param $entryData array
+ * @param $entryFields array
+ * @return array
+ */
+ private function _mergeEntryWithFields($entryData, $entryFields) {
+ if(!empty($entryFields)) {
+ foreach($entryFields as $f) {
+ $_mnValue = '_loadFieldValue_'.$f['type'];
+
+ if(!isset($entryData[$f['identifier']]) && method_exists($this, $_mnValue) && isset($entryData['id']) ) {
+ $entryData[$f['identifier']] = $this->$_mnValue($entryData['id'], $f);
+ }
+ }
+ }
+ return $entryData;
+ }
+
+ /**
+ * Load the values for given $entryId for $fieldData
+ * lookup function for field type lookupmultiple
+ *
+ * @see Mancubus
+ * @param Number $entryId
+ * @param array $fieldData
+ * @return array
+ */
+ private function _loadFieldValue_lookupmultiple($entryId, $fieldData) {
+ $ret = array();
+
+ if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
+ $queryStr = "SELECT `value`
+ FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
+ WHERE `fk_field` = '".$this->_DB->real_escape_string($fieldData['id'])."'
+ AND `fk_entry` = '".$this->_DB->real_escape_string($entryId)."'";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[] = $result['value'];
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Get the single upload file from storage location
+ * lookup function for field type upload
+ *
+ * @see Mancubus
+ * @param $entryId
+ * @param $fieldData
+ * @return string
+ */
+ private function _loadFieldValue_upload($entryId, $fieldData) {
+ $ret = "";
+ if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
+
+ $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
+ if(!empty($uploadedFile)) {
+ foreach ($uploadedFile as $f) {
+ $ret = basename($f);
+ break;
+ }
+ }
+ }
+ return $ret;
+ }
+
+ /**
+ * Get the multiple upload files from storage location
+ * lookup function for field type upload_multiple
+ *
+ * @see Mancubus
+ * @param $entryId
+ * @param $fieldData
+ * @return array
+ */
+ private function _loadFieldValue_upload_multiple($entryId, $fieldData) {
+ $ret = array();
+ if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
+
+ $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
+ if(!empty($uploadedFile)) {
+ foreach ($uploadedFile as $f) {
+ $ret[] = basename($f);
+ }
+ }
+ }
+ return $ret;
+ }
+
+ /**
+ * Provide the options for a selection field by processing the $data['value']
+ * since the values are stored in the entry DB as a list
+ *
+ * @param $data array
+ * @return array
+ */
+ private function _loadField_selection($data) {
+ if(!empty($data) && isset($data['value']) && !empty($data['value'])) {
+ if(strstr($data['value'], ",")) {
+ $data['options'] = explode(",", $data['value']);
+ }
+ }
+ return $data;
+ }
+
+ /**
+ * Load suggestions based on the existing data for this field
+ *
+ * @param $data array Field data
+ * @return array
+ */
+ private function _loadField_lookupmultiple($data) {
+ if(!empty($data) && isset($data['id']) && !empty($data['id'])) {
+ $queryStr = "SELECT DISTINCT(`value`)
+ FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
+ WHERE `fk_field` = '".$this->_DB->real_escape_string($data['id'])."'";
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows > 0) {
+ while (($result = $query->fetch_assoc()) != false) {
+ $data['suggestion'][] = $result['value'];
+ }
+ }
+ }
+ return $data;
+ }
+
+ /**
+ * Create part of the insert statement for field type text
+ *
+ * @param $data array Field data
+ * @param $queryData array Query data array
+ * @return array
+ */
+ private function _saveField_text($data, $queryData) {
+ $queryData['init'][] = "`".$data['identifier']."` = '".$this->_DB->real_escape_string($data['valueToSave'])."'";
+ return $queryData;
+ }
+
+ /**
+ * Create part of the insert statement for field type text3
+ *
+ * @param $data array Field data
+ * @param $queryData array Query data array
+ * @return array
+ */
+ private function _saveField_text3($data, $queryData) {
+ return $this->_saveField_text($data, $queryData);
+ }
+
+ /**
+ * Create part of the insert statement for field type textarea
+ *
+ * @param $data array Field data
+ * @param $queryData array Query data array
+ * @return array
+ */
+ private function _saveField_textarea($data, $queryData) {
+ return $this->_saveField_text($data, $queryData);
+ }
+
+ /**
+ * Create part of the insert statement for field type selection
+ *
+ * @param $data array Field data
+ * @param $queryData array Query data array
+ * @return array
+ */
+ private function _saveField_selection($data, $queryData) {
+ return $this->_saveField_text($data, $queryData);
+ }
+ /**
+ * Create part of the insert statement for field type year
+ *
+ * @param $data array Field data
+ * @param $queryData array Query data array
+ * @return array
+ */
+ private function _saveField_year($data, $queryData) {
+ return $this->_saveField_text($data, $queryData);
+ }
+
+ /**
+ * Create part of the insert statement for field type lookupmultiple
+ *
+ * @param $data array Field data
+ * @param $queryData array Query data array
+ * @return array
+ */
+ private function _saveField_lookupmultiple($data, $queryData) {
+ $_d = trim($data['valueToSave']);
+ $_d = trim($_d, ",");
+
+ // first clean since the new data is everything
+ $queryData['after']['query'][] = "DELETE FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_collectionId."`
+ WHERE `fk_field` = '".$this->_DB->real_escape_string($data['id'])."'
+ AND `fk_entry` = '".$this->_replaceEntryString."'";
+ if(!empty($_d)) {
+ $_process = array($_d);
+ if (strstr($data['valueToSave'], ",")) {
+ $_process = explode(",", $data['valueToSave']);
+ }
+ foreach ($_process as $p) {
+ $queryData['after']['query'][] = "INSERT IGNORE INTO `".DB_PREFIX."_collection_entry2lookup_".$this->_collectionId."`
+ SET `fk_field` = '".$this->_DB->real_escape_string($data['id'])."',
+ `fk_entry` = '".$this->_replaceEntryString."',
+ `value` = '".$this->_DB->real_escape_string($p)."'";
+ }
+ }
+
+ return $queryData;
+ }
+
+ /**
+ * Single upload field
+ *
+ * @param $data array The data from _FILES
+ * @param $queryData array
+ * @return array
+ */
+ private function _saveField_upload($data, $queryData) {
+ $_up = $data['uploadData'];
+
+ // delete the single upload
+ // this way the after query method is triggered without any upload
+ if(isset($data['deleteData'])) {
+ $queryData['after']['upload'][] = array(
+ 'identifier' => $data['identifier'],
+ 'multiple' => false,
+ 'deleteData' => $data['deleteData']
+ );
+ }
+
+ if($_up['error'][$data['identifier']] === 0) {
+ $_ext = pathinfo($_up['name'][$data['identifier']],PATHINFO_EXTENSION);
+ $newFilename = sha1($_up['name'][$data['identifier']]).".".$_ext;
+
+ $queryData['after']['upload'][] = array(
+ 'identifier' => $data['identifier'],
+ 'name' => $newFilename,
+ 'tmp_name' => $_up['tmp_name'][$data['identifier']],
+ 'multiple' => false
+ );
+ }
+ return $queryData;
+ }
+
+ /**
+ * Multiple upload field
+ *
+ * @param $data array The data from _FILES
+ * @param $queryData array
+ * @return array
+ */
+ private function _saveField_upload_multiple($data, $queryData) {
+ $_up = $data['uploadData'];
+
+ if(isset($data['deleteData'])) {
+ $queryData['after']['upload'][] = array(
+ 'identifier' => $data['identifier'],
+ 'multiple' => true,
+ 'deleteData' => $data['deleteData']
+ );
+ }
+
+ foreach ($_up['error'][$data['identifier']] as $k=>$v) {
+ if($v === 0) {
+ $_ext = pathinfo($_up['name'][$data['identifier']][$k],PATHINFO_EXTENSION);
+ $newFilename = sha1($_up['name'][$data['identifier']][$k]).".".$_ext;
+
+ $queryData['after']['upload'][] = array(
+ 'identifier' => $data['identifier'],
+ 'name' => $newFilename,
+ 'tmp_name' => $_up['tmp_name'][$data['identifier']][$k],
+ 'multiple' => true
+ );
+ }
+ }
+
+ return $queryData;
+ }
+
+ /**
+ * runs the query and throws query execption if false
+ *
+ * @param $queryString
+ * @param $insertId
+ */
+ private function _runAfter_query($queryString, $insertId) {
+ if(!empty($queryString) && !empty($insertId)) {
+ // replace only once to avoid replacing actual data
+ $queryStr = Summoner::replaceOnce($queryString,$this->_replaceEntryString, $insertId);
+ $this->_DB->query($queryStr);
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." queryStr: ".var_export($queryStr,true));
+ }
+ }
+
+ /**
+ * Move uploaded into right directory
+ * If single upload (multiple=false) then remove all the files for this type field first. Works the same
+ * if you want to remove the upload via edit
+ *
+ * Also removes the defined uploads from multiple upload field
+ *
+ * @param $uploadData
+ * @param $insertId
+ * @throws Exception
+ */
+ private function _runAfter_upload($uploadData, $insertId) {
+ if(!empty($uploadData) && !empty($insertId)) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." uploadata: ".var_export($uploadData,true));
+ $_path = PATH_STORAGE.'/'.$this->_collectionId.'/'.$insertId;
+ if(!is_dir($_path)) {
+ if(!mkdir($_path, 0777, true)) {
+ throw new Exception("Failed to create storage path: ".$_path);
+ }
+ }
+
+ if($uploadData['multiple'] === false) {
+ // single upload. Delete existing first.
+ // also triggered if the single needs to be deleted
+ $_existingFiles = glob($_path.'/'.$uploadData['identifier'].'-*');
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove single existing: ".var_export($_existingFiles,true));
+ if(!empty($_existingFiles)) {
+ foreach ($_existingFiles as $f) {
+ unlink($f);
+ }
+ clearstatcache();
+ }
+ }
+
+ if($uploadData['multiple'] === true && isset($uploadData['deleteData'])) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." remove multiple existing: ".var_export($uploadData['deleteData'],true));
+ foreach ($uploadData['deleteData'] as $k=>$v) {
+ $_file = $_path.'/'.$v;
+ if(file_exists($_file)) {
+ unlink($_file);
+ }
+ clearstatcache();
+ }
+ }
+
+ if(isset($uploadData['tmp_name']) && isset($uploadData['name'])) {
+ if(!move_uploaded_file($uploadData['tmp_name'],$_path.'/'.$uploadData['identifier'].'-'.$uploadData['name'])) {
+ throw new Exception("Can not move file to: ".$_path.'/'.$uploadData['identifier'].'-'.$uploadData['name']);
+ }
+ }
+ }
+ }
}
* Class Mancubus everything to show an entry
*/
class Mancubus {
- /**
- * The database object
- *
- * @var object
- */
- private $_DB;
-
- /**
- * The user object to query with
- *
- * @var object
- */
- private $_User;
-
- /**
- * Currently loaded collection to work with
- *
- * @var number
- */
- private $_collectionId;
-
- /**
- * Options for db queries
- * 'limit' => int,
- * 'offset' => int,
- * 'orderby' => string,
- * 'sortDirection' => ASC|DESC
- *
- * @var array
- */
- private $_queryOptions;
-
- /**
- * Mancubus constructor.
- *
- * @param $databaseConnectionObject
- * @param $userObj
- */
- public function __construct($databaseConnectionObject, $userObj) {
- $this->_DB = $databaseConnectionObject;
- $this->_User = $userObj;
-
- $this->_setDefaults();
- }
-
- /**
- * Set the to work with collection id
- *
- * @param $collectionId Number
- */
- public function setCollection($collectionId) {
- if(!empty($collectionId)) {
- $this->_collectionId = $collectionId;
- }
- }
-
- /**
- * Set the following options which can be used in DB queries
- * array(
- * 'limit' => RESULTS_PER_PAGE,
- * 'offset' => (RESULTS_PER_PAGE * ($_curPage-1)),
- * 'orderby' => $_sort,
- * 'sortDirection' => $_sortDirection
- * );
- *
- * @param array $options
- */
- public function setQueryOptions($options) {
-
- if(!isset($options['limit'])) $options['limit'] = 5;
- if(!isset($options['offset'])) $options['offset'] = false;
- if(!isset($options['sort'])) $options['sort'] = false;
- if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
-
- $this->_queryOptions = $options;
- }
-
- /**
- * Get all available collections for display based on current user
- *
- * @param int $selections Number of selections
- * @param int $entries Number of entries
- * @param string $search Search string to search for
- * @return array
- */
- public function getLatest($selections, $entries, $search='') {
- $ret = array();
-
- $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
- `c`.`owner`, `c`.`group`, `c`.`rights`,
- `u`.`name` AS username, `g`.`name` AS groupname
- FROM `".DB_PREFIX."_collection` AS c
- LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
- LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
- WHERE ".$this->_User->getSQLRightsString("read", "c")."
- ORDER BY `c`.`name`
- LIMIT $selections";
- $query = $this->_DB->query($queryStr);
-
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $_mObj = new Mancubus($this->_DB,$this->_User);
- $_mObj->setCollection($result['id']);
- $_mObj->setQueryOptions(array('limit' => $entries));
-
- if(!empty($search)) {
- require_once 'lib/trite.class.php';
- $_colObj = new Trite($this->_DB,$this->_User);
- $_colObj->load($result['id']);
-
- $result['entries'] = $_mObj->getEntries($_colObj->param('defaultSearchField'),$search,true);
- }
- else {
- $result['entries'] = $_mObj->getEntries();
- }
- $ret[$result['id']] = $result;
- unset($_mObj);
- }
- }
-
- return $ret;
- }
-
- /**
- * Get entries for loaded collection limited by search in
- * given colName and colValue
- *
- * @param string $colName Table col to search
- * @param string $colValue Value to search in col
- * @param bool $fulltext If col has a fulltext index use it.
- * @return array
- */
- public function getEntries($colName='', $colValue='',$fulltext=false) {
- $ret = array();
-
- if(!empty($this->_collectionId)) {
- // split since part of it is used later
- $querySelect = "SELECT *";
- $queryFrom = " FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."` AS t";
- $queryWhere = " WHERE ".$this->_User->getSQLRightsString("read", "t")."";
-
- if(!empty($colName) && !empty($colValue)) {
- if($fulltext === true) {
- $queryWhere .= " AND MATCH (`t`.`".$this->_DB->real_escape_string($colName)."`)
- AGAINST ('".$this->_DB->real_escape_string($colValue)."' IN BOOLEAN MODE)";
- }
- else {
- $queryWhere .= " AND `t`.`" . $this->_DB->real_escape_string($colName) . "` = '" . $this->_DB->real_escape_string($colValue) . "'";
- }
- }
-
- $queryOrder = " ORDER BY";
- if(!empty($this->_queryOptions['sort'])) {
- $queryOrder .= ' t.'.$this->_queryOptions['sort'];
- }
- else {
- $queryOrder .= " t.created";
- }
- if(!empty($this->_queryOptions['sortDirection'])) {
- $queryOrder .= ' '.$this->_queryOptions['sortDirection'];
- }
- else {
- $queryOrder .= " DESC";
- }
-
- $queryLimit = '';
- if(!empty($this->_queryOptions['limit'])) {
- $queryLimit .= " LIMIT ".$this->_queryOptions['limit'];
- # offset can be 0
- if($this->_queryOptions['offset'] !== false) {
- $queryLimit .= " OFFSET ".$this->_queryOptions['offset'];
- }
- }
-
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." data: ".$querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
-
- $query = $this->_DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
-
- if($query !== false && $query->num_rows > 0) {
- $_entryFields = $this->_getEntryFields();
-
- while(($result = $query->fetch_assoc()) != false) {
- $result = $this->_mergeEntryWithFields($result, $_entryFields);
-
- $ret['results'][$result['id']] = $result;
- }
-
- $query = $this->_DB->query("SELECT COUNT(t.id) AS amount ".$queryFrom.$queryWhere);
- $result = $query->fetch_assoc();
- $ret['amount'] = $result['amount'];
- }
- }
-
- return $ret;
- }
-
- /**
- * Retrive all the data needed to display the entry for given entryId
- * @param $entryId
- * @return array|mixed
- */
- public function getEntry($entryId) {
- $ret = array();
-
- if(!empty($this->_collectionId) && !empty($entryId)) {
- $queryStr = "SELECT *
- FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`
- WHERE ".$this->_User->getSQLRightsString("read")."
- AND `id` = '".$this->_DB->real_escape_string($entryId)."'";
- $query = $this->_DB->query($queryStr);
-
- if($query !== false && $query->num_rows > 0) {
- $_entryFields = $this->_getEntryFields();
-
- if(($result = $query->fetch_assoc()) != false) {
- $ret = $this->_mergeEntryWithFields($result, $_entryFields);
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Get entries for loaded collection by looking for the given value in given field
- *
- * @param Number $fieldId ID of the field to search in
- * @param String $fieldValue Value of the field
- * @return array
- */
- public function getEntriesByFieldValue($fieldId, $fieldValue) {
- $ret = array();
-
- $fieldData = array();
- $queryStr = "SELECT `identifier`, `type` FROM `".DB_PREFIX."_sys_fields`
- WHERE `id` = '".$this->_DB->real_escape_string($fieldId)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- if(($result = $query->fetch_assoc()) != false) {
- $fieldData = $result;
- }
- }
-
- if(empty($fieldData)) return $ret;
-
- if($fieldData['type'] !== "lookupmultiple") {
- return $this->getEntries($fieldData['identifier'], $fieldValue);
- }
-
- $querySelect = "SELECT `fk_entry`";
- $queryFrom = " FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."` AS t";
- $queryWhere = " WHERE t.fk_field = '".$this->_DB->real_escape_string($fieldId)."'
- AND t.value = '".$this->_DB->real_escape_string($fieldValue)."'";
-
- $queryOrder = " ORDER BY";
- if(!empty($this->_queryOptions['sort'])) {
- $queryOrder .= ' t.'.$this->_queryOptions['sort'];
- }
- else {
- $queryOrder .= " t.value";
- }
- if(!empty($this->_queryOptions['sortDirection'])) {
- $queryOrder .= ' '.$this->_queryOptions['sortDirection'];
- }
- else {
- $queryOrder .= " DESC";
- }
-
- $queryLimit = '';
- if(!empty($this->_queryOptions['limit'])) {
- $queryLimit .= " LIMIT ".$this->_queryOptions['limit'];
- # offset can be 0
- if($this->_queryOptions['offset'] !== false) {
- $queryLimit .= " OFFSET ".$this->_queryOptions['offset'];
- }
- }
-
- $query = $this->_DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
-
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $_r = $this->getEntry($result['fk_entry']);
- $ret['results'][$_r['id']] = $_r;
- }
-
- $query = $this->_DB->query("SELECT COUNT(t.value) AS amount ".$queryFrom.$queryWhere);
- $result = $query->fetch_assoc();
- $ret['amount'] = $result['amount'];
- }
-
- return $ret;
- }
-
- /**
- * Get tags for loaded collection. Provide earch term to use match against db search
- *
- * @todo Replace with trite class
- *
- * @param mixed $search Search term
- * @return array
- */
- public function getTags($search=false) {
- $ret = array();
-
- if(!empty($this->_collectionId)) {
- $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`
- FROM `".DB_PREFIX."_collection_fields_".$this->_DB->real_escape_string($this->_collectionId)."` AS cf
- LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
- WHERE `sf`.`searchtype` = 'tag'
- ORDER BY `sf`.`displayname`";
-
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- $ret[$result['id']]['entries'] = array();
-
- $_mn = '_loadTagDistinct_'.$result['type'];
- if(method_exists($this, $_mn)) {
- $ret[$result['id']]['entries'] = $this->$_mn($result,$search);
- }
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Return the storage info for loaded collection
- * Used by API
- * @return array|mixed
- */
- public function getEntryStructure() {
- $ret = array();
-
- $_entryFields = $this->_getEntryFields();
- $ret = $this->_mergeEntryWithFields($ret, $_entryFields);
-
- return $ret;
- }
-
- /**
- * Load the fields from the loaded collection
- * @return array
- */
- private function _getEntryFields() {
- $ret = array();
-
- if(!empty($this->_collectionId)) {
- $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`,
- `sf`.`value` AS preValue, `sf`.`apiinfo`
- FROM `".DB_PREFIX."_collection_fields_".$this->_DB->real_escape_string($this->_collectionId)."` AS cf
- LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
- ORDER BY `cf`.`sort`";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Merge the loaded information from collection_entry with the given
- * configured fields
- * @param array $entryData Loaded entry
- * @param array $entryFields Loaded fields
- * @return mixed
- */
- private function _mergeEntryWithFields($entryData, $entryFields) {
- if(!empty($entryFields)) {
- foreach($entryFields as $f) {
- $_mnValue = '_loadFieldValue_'.$f['type'];
-
- if(isset($entryData[$f['identifier']])) {
- $f['value'] = $entryData[$f['identifier']];
- unset($entryData[$f['identifier']]);
- } elseif(method_exists($this, $_mnValue) && isset($entryData['id'])) {
- $f['value'] = $this->$_mnValue($entryData['id'], $f);
- }
-
- $_mnSelectionValue = '_loadFieldSelection_'.$f['type'];
- if(method_exists($this, $_mnSelectionValue) && isset($f['preValue'])) {
- $f['preValue'] = $this->$_mnSelectionValue($f['preValue']);
- }
-
- $entryData['fields'][$f['identifier']] = $f;
- }
- }
- return $entryData;
- }
-
- /**
- * Load the values for given $entryId for $fieldData
- * lookup function for field type lookupmultiple
- * @param Numer $entryId
- * @param array $fieldData
- * @return array
- */
- private function _loadFieldValue_lookupmultiple($entryId, $fieldData) {
- $ret = array();
-
- if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
- $queryStr = "SELECT `value`
- FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
- WHERE `fk_field` = '".$this->_DB->real_escape_string($fieldData['id'])."'
- AND `fk_entry` = '".$this->_DB->real_escape_string($entryId)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[] = $result['value'];
- }
- }
- }
-
- return $ret;
- }
-
- /**
- * Get the single upload file from storage location
- * lookup function for field type upload
- * @param $entryId
- * @param $fieldData
- * @return string
- */
- private function _loadFieldValue_upload($entryId, $fieldData) {
- $ret = "";
- if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
-
- $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
- if(!empty($uploadedFile)) {
- foreach ($uploadedFile as $f) {
- $ret = basename($f);
- break;
- }
- }
- }
- return $ret;
- }
-
- /**
- * Get the multiple upload files from storage location
- * lookup function for field type upload_multiple
- * @param $entryId
- * @param $fieldData
- * @return array
- */
- private function _loadFieldValue_upload_multiple($entryId, $fieldData) {
- $ret = array();
- if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
-
- $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
- if(!empty($uploadedFile)) {
- foreach ($uploadedFile as $f) {
- $ret[] = basename($f);
- }
- }
- }
- return $ret;
- }
-
- /**
- * Load and prepare the value for a selection field
- *
- * @param $data string
- * @return array
- */
- private function _loadFieldSelection_selection($data) {
- $ret = array();
-
- if(is_string($data)) {
- if(strstr($data, ',')) {
- $ret = explode(',',$data);
- }
- else {
- $ret[] = $data;
- }
- }
-
- return $ret;
- }
-
- /**
- * Load the selection as tag.
- * Search is a 1:1 match
- *
- * @param array $fieldData The sys field data
- * @param mixed $search Searchterm
- * @return array
- */
- private function _loadTagDistinct_selection($fieldData,$search=false) {
- return $this->_loadColAsTagFromEntryTable($fieldData['identifier'],$search);
- }
-
- /**
- * Load the data for lookupmultiple field. Provide field id and optional searchterm.
- * Uses currently loaded collection
- *
- * @param array $fieldData The field data to use
- * @param mixed $search Searchterm to run a match against DB search
- * @return array
- */
- private function _loadTagDistinct_lookupmultiple($fieldData,$search=false) {
- $ret = array();
-
- if(!empty($fieldData) && !empty($this->_collectionId)) {
- $queryStr = "SELECT DISTINCT(`value`)
- FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
- WHERE `fk_field` = '".$this->_DB->real_escape_string($fieldData['id'])."'";
- if(!empty($search)) {
- $queryStr .= " AND MATCH (`value`) AGAINST ('" . $this->_DB->real_escape_string($search) . "' IN BOOLEAN MODE)";
- }
-
- try {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
-
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows > 0) {
- while (($result = $query->fetch_assoc()) != false) {
- $ret[] = $result['value'];
- }
- }
- }
- catch (Exception $e) {
- error_log("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
-
- }
- }
-
- return $ret;
- }
-
- /**
- * Load the data from lookupmultiple field. In this case $fieldata is overwritten
- * and year is used.
- *
- * @param array $fieldData
- * @param bool $search
- * @return array
- */
- private function _loadTagDistinct_year($fieldData,$search=false) {
- return $this->_loadColAsTagFromEntryTable("year",$search);
- }
-
- /**
- * Get the distinct data from a col and optionaml search term
- *
- * @param $colname
- * @param $search
- * @return array
- */
- private function _loadColAsTagFromEntryTable($colname,$search) {
- $ret = array();
-
- if(!empty($colname) && !empty($this->_collectionId)) {
- if(!empty($search)) {
- $queryStr = "SELECT `".$this->_DB->real_escape_string($colname)."`
- FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`";
- $queryStr .= " WHERE `".$colname."` = '".$this->_DB->real_escape_string($search)."'";
- }
- else {
- $queryStr = "SELECT DISTINCT(`".$this->_DB->real_escape_string($colname)."`)
- FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`";
- }
-
- $queryStr .= " ORDER BY `".$this->_DB->real_escape_string($colname)."` DESC";
-
- try {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
-
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- if(!empty($result[$colname])) {
- $ret[] = $result[$colname];
- }
- }
- }
- }
- catch (Exception $e) {
- error_log("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
- }
- }
-
-
- return $ret;
- }
-
- /**
- * set some defaults by init of the class
- */
- private function _setDefaults() {
- // default query options
- $options['limit'] = 5;
- $options['offset'] = false;
- $options['sort'] = false;
- $options['sortDirection'] = false;
- $this->setQueryOptions($options);
- }
+ /**
+ * The database object
+ *
+ * @var object
+ */
+ private $_DB;
+
+ /**
+ * The user object to query with
+ *
+ * @var object
+ */
+ private $_User;
+
+ /**
+ * Currently loaded collection to work with
+ *
+ * @var number
+ */
+ private $_collectionId;
+
+ /**
+ * Options for db queries
+ * 'limit' => int,
+ * 'offset' => int,
+ * 'orderby' => string,
+ * 'sortDirection' => ASC|DESC
+ *
+ * @var array
+ */
+ private $_queryOptions;
+
+ /**
+ * Mancubus constructor.
+ *
+ * @param $databaseConnectionObject
+ * @param $userObj
+ */
+ public function __construct($databaseConnectionObject, $userObj) {
+ $this->_DB = $databaseConnectionObject;
+ $this->_User = $userObj;
+
+ $this->_setDefaults();
+ }
+
+ /**
+ * Set the to work with collection id
+ *
+ * @param $collectionId Number
+ */
+ public function setCollection($collectionId) {
+ if(!empty($collectionId)) {
+ $this->_collectionId = $collectionId;
+ }
+ }
+
+ /**
+ * Set the following options which can be used in DB queries
+ * array(
+ * 'limit' => RESULTS_PER_PAGE,
+ * 'offset' => (RESULTS_PER_PAGE * ($_curPage-1)),
+ * 'orderby' => $_sort,
+ * 'sortDirection' => $_sortDirection
+ * );
+ *
+ * @param array $options
+ */
+ public function setQueryOptions($options) {
+
+ if(!isset($options['limit'])) $options['limit'] = 5;
+ if(!isset($options['offset'])) $options['offset'] = false;
+ if(!isset($options['sort'])) $options['sort'] = false;
+ if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
+
+ $this->_queryOptions = $options;
+ }
+
+ /**
+ * Get all available collections for display based on current user
+ *
+ * @param int $selections Number of selections
+ * @param int $entries Number of entries
+ * @param string $search Search string to search for
+ * @return array
+ */
+ public function getLatest($selections, $entries, $search='') {
+ $ret = array();
+
+ $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
+ `c`.`owner`, `c`.`group`, `c`.`rights`,
+ `u`.`name` AS username, `g`.`name` AS groupname
+ FROM `".DB_PREFIX."_collection` AS c
+ LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
+ LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
+ WHERE ".$this->_User->getSQLRightsString("read", "c")."
+ ORDER BY `c`.`name`
+ LIMIT $selections";
+ $query = $this->_DB->query($queryStr);
+
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $_mObj = new Mancubus($this->_DB,$this->_User);
+ $_mObj->setCollection($result['id']);
+ $_mObj->setQueryOptions(array('limit' => $entries));
+
+ if(!empty($search)) {
+ require_once 'lib/trite.class.php';
+ $_colObj = new Trite($this->_DB,$this->_User);
+ $_colObj->load($result['id']);
+
+ $result['entries'] = $_mObj->getEntries($_colObj->param('defaultSearchField'),$search,true);
+ }
+ else {
+ $result['entries'] = $_mObj->getEntries();
+ }
+ $ret[$result['id']] = $result;
+ unset($_mObj);
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Get entries for loaded collection limited by search in
+ * given colName and colValue
+ *
+ * @param string $colName Table col to search
+ * @param string $colValue Value to search in col
+ * @param bool $fulltext If col has a fulltext index use it.
+ * @return array
+ */
+ public function getEntries($colName='', $colValue='',$fulltext=false) {
+ $ret = array();
+
+ if(!empty($this->_collectionId)) {
+ // split since part of it is used later
+ $querySelect = "SELECT *";
+ $queryFrom = " FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."` AS t";
+ $queryWhere = " WHERE ".$this->_User->getSQLRightsString("read", "t")."";
+
+ if(!empty($colName) && !empty($colValue)) {
+ if($fulltext === true) {
+ $queryWhere .= " AND MATCH (`t`.`".$this->_DB->real_escape_string($colName)."`)
+ AGAINST ('".$this->_DB->real_escape_string($colValue)."' IN BOOLEAN MODE)";
+ }
+ else {
+ $queryWhere .= " AND `t`.`" . $this->_DB->real_escape_string($colName) . "` = '" . $this->_DB->real_escape_string($colValue) . "'";
+ }
+ }
+
+ $queryOrder = " ORDER BY";
+ if(!empty($this->_queryOptions['sort'])) {
+ $queryOrder .= ' t.'.$this->_queryOptions['sort'];
+ }
+ else {
+ $queryOrder .= " t.created";
+ }
+ if(!empty($this->_queryOptions['sortDirection'])) {
+ $queryOrder .= ' '.$this->_queryOptions['sortDirection'];
+ }
+ else {
+ $queryOrder .= " DESC";
+ }
+
+ $queryLimit = '';
+ if(!empty($this->_queryOptions['limit'])) {
+ $queryLimit .= " LIMIT ".$this->_queryOptions['limit'];
+ # offset can be 0
+ if($this->_queryOptions['offset'] !== false) {
+ $queryLimit .= " OFFSET ".$this->_queryOptions['offset'];
+ }
+ }
+
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." data: ".$querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
+
+ $query = $this->_DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
+
+ if($query !== false && $query->num_rows > 0) {
+ $_entryFields = $this->_getEntryFields();
+
+ while(($result = $query->fetch_assoc()) != false) {
+ $result = $this->_mergeEntryWithFields($result, $_entryFields);
+
+ $ret['results'][$result['id']] = $result;
+ }
+
+ $query = $this->_DB->query("SELECT COUNT(t.id) AS amount ".$queryFrom.$queryWhere);
+ $result = $query->fetch_assoc();
+ $ret['amount'] = $result['amount'];
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrive all the data needed to display the entry for given entryId
+ * @param $entryId
+ * @return array|mixed
+ */
+ public function getEntry($entryId) {
+ $ret = array();
+
+ if(!empty($this->_collectionId) && !empty($entryId)) {
+ $queryStr = "SELECT *
+ FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`
+ WHERE ".$this->_User->getSQLRightsString("read")."
+ AND `id` = '".$this->_DB->real_escape_string($entryId)."'";
+ $query = $this->_DB->query($queryStr);
+
+ if($query !== false && $query->num_rows > 0) {
+ $_entryFields = $this->_getEntryFields();
+
+ if(($result = $query->fetch_assoc()) != false) {
+ $ret = $this->_mergeEntryWithFields($result, $_entryFields);
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Get entries for loaded collection by looking for the given value in given field
+ *
+ * @param Number $fieldId ID of the field to search in
+ * @param String $fieldValue Value of the field
+ * @return array
+ */
+ public function getEntriesByFieldValue($fieldId, $fieldValue) {
+ $ret = array();
+
+ $fieldData = array();
+ $queryStr = "SELECT `identifier`, `type` FROM `".DB_PREFIX."_sys_fields`
+ WHERE `id` = '".$this->_DB->real_escape_string($fieldId)."'";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ if(($result = $query->fetch_assoc()) != false) {
+ $fieldData = $result;
+ }
+ }
+
+ if(empty($fieldData)) return $ret;
+
+ if($fieldData['type'] !== "lookupmultiple") {
+ return $this->getEntries($fieldData['identifier'], $fieldValue);
+ }
+
+ $querySelect = "SELECT `fk_entry`";
+ $queryFrom = " FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."` AS t";
+ $queryWhere = " WHERE t.fk_field = '".$this->_DB->real_escape_string($fieldId)."'
+ AND t.value = '".$this->_DB->real_escape_string($fieldValue)."'";
+
+ $queryOrder = " ORDER BY";
+ if(!empty($this->_queryOptions['sort'])) {
+ $queryOrder .= ' t.'.$this->_queryOptions['sort'];
+ }
+ else {
+ $queryOrder .= " t.value";
+ }
+ if(!empty($this->_queryOptions['sortDirection'])) {
+ $queryOrder .= ' '.$this->_queryOptions['sortDirection'];
+ }
+ else {
+ $queryOrder .= " DESC";
+ }
+
+ $queryLimit = '';
+ if(!empty($this->_queryOptions['limit'])) {
+ $queryLimit .= " LIMIT ".$this->_queryOptions['limit'];
+ # offset can be 0
+ if($this->_queryOptions['offset'] !== false) {
+ $queryLimit .= " OFFSET ".$this->_queryOptions['offset'];
+ }
+ }
+
+ $query = $this->_DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
+
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $_r = $this->getEntry($result['fk_entry']);
+ $ret['results'][$_r['id']] = $_r;
+ }
+
+ $query = $this->_DB->query("SELECT COUNT(t.value) AS amount ".$queryFrom.$queryWhere);
+ $result = $query->fetch_assoc();
+ $ret['amount'] = $result['amount'];
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Get tags for loaded collection. Provide earch term to use match against db search
+ *
+ * @todo Replace with trite class
+ *
+ * @param mixed $search Search term
+ * @return array
+ */
+ public function getTags($search=false) {
+ $ret = array();
+
+ if(!empty($this->_collectionId)) {
+ $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`
+ FROM `".DB_PREFIX."_collection_fields_".$this->_DB->real_escape_string($this->_collectionId)."` AS cf
+ LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
+ WHERE `sf`.`searchtype` = 'tag'
+ ORDER BY `sf`.`displayname`";
+
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ $ret[$result['id']]['entries'] = array();
+
+ $_mn = '_loadTagDistinct_'.$result['type'];
+ if(method_exists($this, $_mn)) {
+ $ret[$result['id']]['entries'] = $this->$_mn($result,$search);
+ }
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Return the storage info for loaded collection
+ * Used by API
+ * @return array|mixed
+ */
+ public function getEntryStructure() {
+ $ret = array();
+
+ $_entryFields = $this->_getEntryFields();
+ $ret = $this->_mergeEntryWithFields($ret, $_entryFields);
+
+ return $ret;
+ }
+
+ /**
+ * Load the fields from the loaded collection
+ * @return array
+ */
+ private function _getEntryFields() {
+ $ret = array();
+
+ if(!empty($this->_collectionId)) {
+ $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`,
+ `sf`.`value` AS preValue, `sf`.`apiinfo`
+ FROM `".DB_PREFIX."_collection_fields_".$this->_DB->real_escape_string($this->_collectionId)."` AS cf
+ LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
+ ORDER BY `cf`.`sort`";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Merge the loaded information from collection_entry with the given
+ * configured fields
+ * @param array $entryData Loaded entry
+ * @param array $entryFields Loaded fields
+ * @return mixed
+ */
+ private function _mergeEntryWithFields($entryData, $entryFields) {
+ if(!empty($entryFields)) {
+ foreach($entryFields as $f) {
+ $_mnValue = '_loadFieldValue_'.$f['type'];
+
+ if(isset($entryData[$f['identifier']])) {
+ $f['value'] = $entryData[$f['identifier']];
+ unset($entryData[$f['identifier']]);
+ } elseif(method_exists($this, $_mnValue) && isset($entryData['id'])) {
+ $f['value'] = $this->$_mnValue($entryData['id'], $f);
+ }
+
+ $_mnSelectionValue = '_loadFieldSelection_'.$f['type'];
+ if(method_exists($this, $_mnSelectionValue) && isset($f['preValue'])) {
+ $f['preValue'] = $this->$_mnSelectionValue($f['preValue']);
+ }
+
+ $entryData['fields'][$f['identifier']] = $f;
+ }
+ }
+ return $entryData;
+ }
+
+ /**
+ * Load the values for given $entryId for $fieldData
+ * lookup function for field type lookupmultiple
+ * @param Numer $entryId
+ * @param array $fieldData
+ * @return array
+ */
+ private function _loadFieldValue_lookupmultiple($entryId, $fieldData) {
+ $ret = array();
+
+ if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
+ $queryStr = "SELECT `value`
+ FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
+ WHERE `fk_field` = '".$this->_DB->real_escape_string($fieldData['id'])."'
+ AND `fk_entry` = '".$this->_DB->real_escape_string($entryId)."'";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[] = $result['value'];
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Get the single upload file from storage location
+ * lookup function for field type upload
+ * @param $entryId
+ * @param $fieldData
+ * @return string
+ */
+ private function _loadFieldValue_upload($entryId, $fieldData) {
+ $ret = "";
+ if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
+
+ $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
+ if(!empty($uploadedFile)) {
+ foreach ($uploadedFile as $f) {
+ $ret = basename($f);
+ break;
+ }
+ }
+ }
+ return $ret;
+ }
+
+ /**
+ * Get the multiple upload files from storage location
+ * lookup function for field type upload_multiple
+ * @param $entryId
+ * @param $fieldData
+ * @return array
+ */
+ private function _loadFieldValue_upload_multiple($entryId, $fieldData) {
+ $ret = array();
+ if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
+
+ $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
+ if(!empty($uploadedFile)) {
+ foreach ($uploadedFile as $f) {
+ $ret[] = basename($f);
+ }
+ }
+ }
+ return $ret;
+ }
+
+ /**
+ * Load and prepare the value for a selection field
+ *
+ * @param $data string
+ * @return array
+ */
+ private function _loadFieldSelection_selection($data) {
+ $ret = array();
+
+ if(is_string($data)) {
+ if(strstr($data, ',')) {
+ $ret = explode(',',$data);
+ }
+ else {
+ $ret[] = $data;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load the selection as tag.
+ * Search is a 1:1 match
+ *
+ * @param array $fieldData The sys field data
+ * @param mixed $search Searchterm
+ * @return array
+ */
+ private function _loadTagDistinct_selection($fieldData,$search=false) {
+ return $this->_loadColAsTagFromEntryTable($fieldData['identifier'],$search);
+ }
+
+ /**
+ * Load the data for lookupmultiple field. Provide field id and optional searchterm.
+ * Uses currently loaded collection
+ *
+ * @param array $fieldData The field data to use
+ * @param mixed $search Searchterm to run a match against DB search
+ * @return array
+ */
+ private function _loadTagDistinct_lookupmultiple($fieldData,$search=false) {
+ $ret = array();
+
+ if(!empty($fieldData) && !empty($this->_collectionId)) {
+ $queryStr = "SELECT DISTINCT(`value`)
+ FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`
+ WHERE `fk_field` = '".$this->_DB->real_escape_string($fieldData['id'])."'";
+ if(!empty($search)) {
+ $queryStr .= " AND MATCH (`value`) AGAINST ('" . $this->_DB->real_escape_string($search) . "' IN BOOLEAN MODE)";
+ }
+
+ try {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows > 0) {
+ while (($result = $query->fetch_assoc()) != false) {
+ $ret[] = $result['value'];
+ }
+ }
+ }
+ catch (Exception $e) {
+ error_log("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
+
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load the data from lookupmultiple field. In this case $fieldata is overwritten
+ * and year is used.
+ *
+ * @param array $fieldData
+ * @param bool $search
+ * @return array
+ */
+ private function _loadTagDistinct_year($fieldData,$search=false) {
+ return $this->_loadColAsTagFromEntryTable("year",$search);
+ }
+
+ /**
+ * Get the distinct data from a col and optionaml search term
+ *
+ * @param $colname
+ * @param $search
+ * @return array
+ */
+ private function _loadColAsTagFromEntryTable($colname,$search) {
+ $ret = array();
+
+ if(!empty($colname) && !empty($this->_collectionId)) {
+ if(!empty($search)) {
+ $queryStr = "SELECT `".$this->_DB->real_escape_string($colname)."`
+ FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`";
+ $queryStr .= " WHERE `".$colname."` = '".$this->_DB->real_escape_string($search)."'";
+ }
+ else {
+ $queryStr = "SELECT DISTINCT(`".$this->_DB->real_escape_string($colname)."`)
+ FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`";
+ }
+
+ $queryStr .= " ORDER BY `".$this->_DB->real_escape_string($colname)."` DESC";
+
+ try {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ if(!empty($result[$colname])) {
+ $ret[] = $result[$colname];
+ }
+ }
+ }
+ }
+ catch (Exception $e) {
+ error_log("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
+ }
+ }
+
+
+ return $ret;
+ }
+
+ /**
+ * set some defaults by init of the class
+ */
+ private function _setDefaults() {
+ // default query options
+ $options['limit'] = 5;
+ $options['offset'] = false;
+ $options['sort'] = false;
+ $options['sortDirection'] = false;
+ $this->setQueryOptions($options);
+ }
}
*
*/
class Possessed {
- /**
- * the global DB object
- *
- * @var object
- */
- private $_DB;
-
- public function __construct($db) {
- $this->_DB = $db;
- }
-
- /**
- * Retrieve the groups for selection
- *
- * @return array
- */
- public function getGroups() {
- $ret = array();
-
- $queryStr = "SELECT `id`, `name`, `description` FROM `".DB_PREFIX."_group` ORDER BY `name`";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
-
- return $ret;
- }
-
- /**
- * Fetch all available users for management
- *
- * @return array
- */
- public function getUsers() {
- $ret = array();
-
- $queryStr = "SELECT `id`, `login`, `name`, `active`, `baseGroupId`, `protected`, `created`
- FROM `".DB_PREFIX."_user`";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- $ret[$result['id']]['groups'] = $this->_loadUserGroupInfo($result['id']);
- }
- }
-
- return $ret;
- }
-
- /**
- * Create or update a user and set the required user releations
- *
- * @param $username string
- * @param $login string
- * @param $password string
- * @param $group string Number
- * @param bool $active
- * @return bool
- */
- public function createUser($username, $login, $password, $group, $active=false) {
- $ret = false;
-
- if(!empty($login) === true
- && $this->_validNewLogin($login) == true
- && $this->_validUsergroup($group) == true
- &&(!empty($password))
- ) {
- if ($active === true) {
- $active = "1";
- } else {
- $active = "0";
- }
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
-
- $_password = password_hash($password, PASSWORD_DEFAULT);
-
- $queryStr = "INSERT INTO `".DB_PREFIX . "_user`
- SET `name` = '".$this->_DB->real_escape_string($username)."',
- `login` = '".$this->_DB->real_escape_string($login)."',
- `password` = '".$this->_DB->real_escape_string($_password)."',
- `active` = '".$this->_DB->real_escape_string($active)."',
- `baseGroupId` = '".$this->_DB->real_escape_string($group)."',
- `rights` = 'rwxr--r--',
- `owner` = 0,
- `group` = '".$this->_DB->real_escape_string($group)."'";
- $query = $this->_DB->query($queryStr);
-
- if ($query !== false) {
- $_userid = $this->_DB->insert_id;
- $this->_DB->query("UPDATE `".DB_PREFIX . "_user`
- SET `owner` = '".$this->_DB->real_escape_string($_userid)."'
- WHERE `id` = '".$this->_DB->real_escape_string($_userid)."'");
- $_setGroupRelation = $this->_setGroupReleation($_userid,$group);
- if($_setGroupRelation !== false) {
- $this->_DB->commit();
- $ret = true;
- }
- $this->_DB->rollback();
- error_log('ERROR Failed to insert user releation: '.var_export($queryStr, true));
- } else {
- $this->_DB->rollback();
- error_log('ERROR Failed to insert user: '.var_export($queryStr, true));
- }
- }
-
- return $ret;
- }
-
- /**
- * Update given user id with given data
- *
- * @param $id
- * @param $username
- * @param $login
- * @param $password
- * @param $group
- * @param bool $active
- * @param bool $refreshApiToken
- * @return bool
- */
- public function updateUser($id, $username, $login, $password, $group, $active=false, $refreshApiToken=false) {
- $ret = false;
-
- if(!empty($login) === true
- && $this->_validUpdateLogin($login,$id) == true
- && $this->_validUsergroup($group) == true
- && !empty($id)
- ) {
- if ($active === true) {
- $active = "1";
- } else {
- $active = "0";
- }
-
- $_password = password_hash($password, PASSWORD_DEFAULT);
-
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
-
- $queryStr = "UPDATE `".DB_PREFIX . "_user`
- SET `name` = '".$this->_DB->real_escape_string($username)."',
- `login` = '".$this->_DB->real_escape_string($login)."',
- `active` = '".$this->_DB->real_escape_string($active)."',
- `baseGroupId` = '".$this->_DB->real_escape_string($group)."'";
- if(Summoner::validate($password,'text')) {
- $queryStr .= ", `password` = '".$this->_DB->real_escape_string($_password)."'";
- }
- if($refreshApiToken === true) {
- $queryStr .= ", `apiToken` = '".md5(base64_encode(openssl_random_pseudo_bytes(30)))."'";
- $queryStr .= ", `apiTokenValidDate` = CURRENT_TIMESTAMP() + INTERVAL 1 DAY";
- }
- $queryStr .= " WHERE `id` = '".$this->_DB->real_escape_string($id)."'
- AND `protected` = '0'";
- $query = $this->_DB->query($queryStr);
-
- if ($query !== false) {
- $_setGroupRelation = $this->_setGroupReleation($id,$group, true);
- if($_setGroupRelation !== false) {
- $this->_DB->commit();
- $ret = true;
- }
- $this->_DB->rollback();
- error_log('ERROR Failed to insert user releation: '.var_export($queryStr, true));
- } else {
- $this->_DB->rollback();
- error_log('ERROR Failed to insert user: '.var_export($queryStr, true));
- }
- }
-
- return $ret;
- }
-
- /**
- * Load the userinformation and groups for given id
- *
- * @param $userId string Number
- * @return array
- */
- public function getEditData($userId) {
- $ret = array();
-
- if(Summoner::validate($userId,'digit')) {
- $queryStr = "SELECT `id`, `login`, `name`, `active`, `baseGroupId`, `created`,`apiToken`,`apiTokenValidDate`
- FROM `".DB_PREFIX."_user`
- WHERE `protected` = '0'
- AND `id` = '".$this->_DB->real_escape_string($userId)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows == 1) {
- $ret = $query->fetch_assoc();
- $ret['groups'] = $this->_loadUserGroupInfo($userId);
- }
-
- }
-
- return $ret;
- }
-
- /**
- * Delete user by given user id
- *
- * @param $id string Number
- * @return bool
- */
- public function deleteUser($id) {
- $ret = false;
-
- if(!empty($id)) {
- $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
-
- $d1 = $this->_DB->query("DELETE FROM `".DB_PREFIX."_user`
- WHERE `id` = '".$this->_DB->real_escape_string($id)."'
- AND `protected` = '0'");
- $d2 = $this->_DB->query("DELETE FROM `".DB_PREFIX."_user2group` WHERE `fk_user_id` = '".$this->_DB->real_escape_string($id)."'");
- $d3 = $this->_DB->query("DELETE FROM `".DB_PREFIX."_userSession` WHERE `fk_user_id` = '".$this->_DB->real_escape_string($id)."'");
-
- if($d1 !== false && $d2 !== false && $d3 !== false) {
- $this->_DB->commit();
- $ret = true;
- }
- else {
- $this->_DB->rollback();
- }
- }
-
- return $ret;
- }
-
- /**
- * Check if given login can be used as a new one
- *
- * @param string $login
- * @return bool
- */
- private function _validNewLogin($login) {
- $ret = false;
- if (Summoner::validate($login, 'nospace')) {
- $queryStr = "SELECT `id` FROM `".DB_PREFIX."_user`
- WHERE `login` = '".$this->_DB->real_escape_string($login)."'";
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows < 1) {
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * Check if given $login can be used as a new login for given id
- *
- * @param string $login
- * @param string $id Number
- * @return bool
- */
- private function _validUpdateLogin($login,$id) {
- $ret = false;
- if (Summoner::validate($login, 'nospace')) {
- $queryStr = "SELECT `id` FROM `" . DB_PREFIX . "_user`
- WHERE `login` = '".$this->_DB->real_escape_string($login)."'
- AND `id` != '".$this->_DB->real_escape_string($id)."'";
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows < 1) {
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * check if given group id is present
- *
- * @param string $groupId Number
- * @return bool
- */
- private function _validUsergroup($groupId) {
- $ret = false;
-
- if(Summoner::validate($groupId,'digit')) {
- $queryStr = "SELECT `id` FROM `".DB_PREFIX."_group`
- WHERE `id` = '".$this->_DB->real_escape_string($groupId)."'";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- $ret = true;
- }
- }
-
- return $ret;
- }
-
- /**
- * Set user to group releation in database.
- * clean will delete all existing ones for given userid first.
- *
- * @param string $userid Number
- * @param string $groupid Number
- * @param bool $clean
- * @return bool
- */
- private function _setGroupReleation($userid, $groupid, $clean=false) {
- $ret = false;
-
- if(Summoner::validate($userid,'digit')
- && Summoner::validate($groupid,'digit')) {
-
- if($clean === true) {
- $this->_DB->query("DELETE FROM `".DB_PREFIX."_user2group`
- WHERE `fk_user_id` = '".$this->_DB->real_escape_string($userid)."'");
- }
-
- $queryStr = "INSERT IGNORE INTO `".DB_PREFIX."_user2group`
- SET `fk_user_id` = '".$this->_DB->real_escape_string($userid)."',
- `fk_group_id` = '".$this->_DB->real_escape_string($groupid)."'";
- $ret = $this->_DB->query($queryStr);
- }
-
- return $ret;
- }
-
- /**
- * Load all the groups the user is in and the information of them
- *
- * @param $userId string Number
- * @return array
- */
- private function _loadUserGroupInfo($userId) {
- $ret = array();
-
- $queryStr = "SELECT g.name AS groupName,
+ /**
+ * the global DB object
+ *
+ * @var object
+ */
+ private $_DB;
+
+ public function __construct($db) {
+ $this->_DB = $db;
+ }
+
+ /**
+ * Retrieve the groups for selection
+ *
+ * @return array
+ */
+ public function getGroups() {
+ $ret = array();
+
+ $queryStr = "SELECT `id`, `name`, `description` FROM `".DB_PREFIX."_group` ORDER BY `name`";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Fetch all available users for management
+ *
+ * @return array
+ */
+ public function getUsers() {
+ $ret = array();
+
+ $queryStr = "SELECT `id`, `login`, `name`, `active`, `baseGroupId`, `protected`, `created`
+ FROM `".DB_PREFIX."_user`";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ $ret[$result['id']]['groups'] = $this->_loadUserGroupInfo($result['id']);
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Create or update a user and set the required user releations
+ *
+ * @param $username string
+ * @param $login string
+ * @param $password string
+ * @param $group string Number
+ * @param bool $active
+ * @return bool
+ */
+ public function createUser($username, $login, $password, $group, $active=false) {
+ $ret = false;
+
+ if(!empty($login) === true
+ && $this->_validNewLogin($login) == true
+ && $this->_validUsergroup($group) == true
+ &&(!empty($password))
+ ) {
+ if ($active === true) {
+ $active = "1";
+ } else {
+ $active = "0";
+ }
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+
+ $_password = password_hash($password, PASSWORD_DEFAULT);
+
+ $queryStr = "INSERT INTO `".DB_PREFIX . "_user`
+ SET `name` = '".$this->_DB->real_escape_string($username)."',
+ `login` = '".$this->_DB->real_escape_string($login)."',
+ `password` = '".$this->_DB->real_escape_string($_password)."',
+ `active` = '".$this->_DB->real_escape_string($active)."',
+ `baseGroupId` = '".$this->_DB->real_escape_string($group)."',
+ `rights` = 'rwxr--r--',
+ `owner` = 0,
+ `group` = '".$this->_DB->real_escape_string($group)."'";
+ $query = $this->_DB->query($queryStr);
+
+ if ($query !== false) {
+ $_userid = $this->_DB->insert_id;
+ $this->_DB->query("UPDATE `".DB_PREFIX . "_user`
+ SET `owner` = '".$this->_DB->real_escape_string($_userid)."'
+ WHERE `id` = '".$this->_DB->real_escape_string($_userid)."'");
+ $_setGroupRelation = $this->_setGroupReleation($_userid,$group);
+ if($_setGroupRelation !== false) {
+ $this->_DB->commit();
+ $ret = true;
+ }
+ $this->_DB->rollback();
+ error_log('ERROR Failed to insert user releation: '.var_export($queryStr, true));
+ } else {
+ $this->_DB->rollback();
+ error_log('ERROR Failed to insert user: '.var_export($queryStr, true));
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Update given user id with given data
+ *
+ * @param $id
+ * @param $username
+ * @param $login
+ * @param $password
+ * @param $group
+ * @param bool $active
+ * @param bool $refreshApiToken
+ * @return bool
+ */
+ public function updateUser($id, $username, $login, $password, $group, $active=false, $refreshApiToken=false) {
+ $ret = false;
+
+ if(!empty($login) === true
+ && $this->_validUpdateLogin($login,$id) == true
+ && $this->_validUsergroup($group) == true
+ && !empty($id)
+ ) {
+ if ($active === true) {
+ $active = "1";
+ } else {
+ $active = "0";
+ }
+
+ $_password = password_hash($password, PASSWORD_DEFAULT);
+
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+
+ $queryStr = "UPDATE `".DB_PREFIX . "_user`
+ SET `name` = '".$this->_DB->real_escape_string($username)."',
+ `login` = '".$this->_DB->real_escape_string($login)."',
+ `active` = '".$this->_DB->real_escape_string($active)."',
+ `baseGroupId` = '".$this->_DB->real_escape_string($group)."'";
+ if(Summoner::validate($password,'text')) {
+ $queryStr .= ", `password` = '".$this->_DB->real_escape_string($_password)."'";
+ }
+ if($refreshApiToken === true) {
+ $queryStr .= ", `apiToken` = '".md5(base64_encode(openssl_random_pseudo_bytes(30)))."'";
+ $queryStr .= ", `apiTokenValidDate` = CURRENT_TIMESTAMP() + INTERVAL 1 DAY";
+ }
+ $queryStr .= " WHERE `id` = '".$this->_DB->real_escape_string($id)."'
+ AND `protected` = '0'";
+ $query = $this->_DB->query($queryStr);
+
+ if ($query !== false) {
+ $_setGroupRelation = $this->_setGroupReleation($id,$group, true);
+ if($_setGroupRelation !== false) {
+ $this->_DB->commit();
+ $ret = true;
+ }
+ $this->_DB->rollback();
+ error_log('ERROR Failed to insert user releation: '.var_export($queryStr, true));
+ } else {
+ $this->_DB->rollback();
+ error_log('ERROR Failed to insert user: '.var_export($queryStr, true));
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load the userinformation and groups for given id
+ *
+ * @param $userId string Number
+ * @return array
+ */
+ public function getEditData($userId) {
+ $ret = array();
+
+ if(Summoner::validate($userId,'digit')) {
+ $queryStr = "SELECT `id`, `login`, `name`, `active`, `baseGroupId`, `created`,`apiToken`,`apiTokenValidDate`
+ FROM `".DB_PREFIX."_user`
+ WHERE `protected` = '0'
+ AND `id` = '".$this->_DB->real_escape_string($userId)."'";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows == 1) {
+ $ret = $query->fetch_assoc();
+ $ret['groups'] = $this->_loadUserGroupInfo($userId);
+ }
+
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Delete user by given user id
+ *
+ * @param $id string Number
+ * @return bool
+ */
+ public function deleteUser($id) {
+ $ret = false;
+
+ if(!empty($id)) {
+ $this->_DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
+
+ $d1 = $this->_DB->query("DELETE FROM `".DB_PREFIX."_user`
+ WHERE `id` = '".$this->_DB->real_escape_string($id)."'
+ AND `protected` = '0'");
+ $d2 = $this->_DB->query("DELETE FROM `".DB_PREFIX."_user2group` WHERE `fk_user_id` = '".$this->_DB->real_escape_string($id)."'");
+ $d3 = $this->_DB->query("DELETE FROM `".DB_PREFIX."_userSession` WHERE `fk_user_id` = '".$this->_DB->real_escape_string($id)."'");
+
+ if($d1 !== false && $d2 !== false && $d3 !== false) {
+ $this->_DB->commit();
+ $ret = true;
+ }
+ else {
+ $this->_DB->rollback();
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Check if given login can be used as a new one
+ *
+ * @param string $login
+ * @return bool
+ */
+ private function _validNewLogin($login) {
+ $ret = false;
+ if (Summoner::validate($login, 'nospace')) {
+ $queryStr = "SELECT `id` FROM `".DB_PREFIX."_user`
+ WHERE `login` = '".$this->_DB->real_escape_string($login)."'";
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows < 1) {
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Check if given $login can be used as a new login for given id
+ *
+ * @param string $login
+ * @param string $id Number
+ * @return bool
+ */
+ private function _validUpdateLogin($login,$id) {
+ $ret = false;
+ if (Summoner::validate($login, 'nospace')) {
+ $queryStr = "SELECT `id` FROM `" . DB_PREFIX . "_user`
+ WHERE `login` = '".$this->_DB->real_escape_string($login)."'
+ AND `id` != '".$this->_DB->real_escape_string($id)."'";
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows < 1) {
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * check if given group id is present
+ *
+ * @param string $groupId Number
+ * @return bool
+ */
+ private function _validUsergroup($groupId) {
+ $ret = false;
+
+ if(Summoner::validate($groupId,'digit')) {
+ $queryStr = "SELECT `id` FROM `".DB_PREFIX."_group`
+ WHERE `id` = '".$this->_DB->real_escape_string($groupId)."'";
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ $ret = true;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Set user to group releation in database.
+ * clean will delete all existing ones for given userid first.
+ *
+ * @param string $userid Number
+ * @param string $groupid Number
+ * @param bool $clean
+ * @return bool
+ */
+ private function _setGroupReleation($userid, $groupid, $clean=false) {
+ $ret = false;
+
+ if(Summoner::validate($userid,'digit')
+ && Summoner::validate($groupid,'digit')) {
+
+ if($clean === true) {
+ $this->_DB->query("DELETE FROM `".DB_PREFIX."_user2group`
+ WHERE `fk_user_id` = '".$this->_DB->real_escape_string($userid)."'");
+ }
+
+ $queryStr = "INSERT IGNORE INTO `".DB_PREFIX."_user2group`
+ SET `fk_user_id` = '".$this->_DB->real_escape_string($userid)."',
+ `fk_group_id` = '".$this->_DB->real_escape_string($groupid)."'";
+ $ret = $this->_DB->query($queryStr);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load all the groups the user is in and the information of them
+ *
+ * @param $userId string Number
+ * @return array
+ */
+ private function _loadUserGroupInfo($userId) {
+ $ret = array();
+
+ $queryStr = "SELECT g.name AS groupName,
g.description AS groupDescription,
g.id AS groupId
FROM `".DB_PREFIX."_user2group` AS u2g,
`".DB_PREFIX."_group` AS g
WHERE u2g.fk_user_id = '".$this->_DB->real_escape_string($userId)."'
AND u2g.fk_group_id = g.id";
- $query = $this->_DB->query($queryStr);
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['groupId']] = array(
- 'groupName' => $result['groupName'],
- 'groupDescription' => $result['groupDescription']
- );
- }
- }
-
- return $ret;
- }
+ $query = $this->_DB->query($queryStr);
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['groupId']] = array(
+ 'groupName' => $result['groupName'],
+ 'groupDescription' => $result['groupDescription']
+ );
+ }
+ }
+
+ return $ret;
+ }
}
* API for Bibliotheca
*/
class Spectre {
- /**
- * the global DB object
- *
- * @var object
- */
- private $_DB;
+ /**
+ * the global DB object
+ *
+ * @var object
+ */
+ private $_DB;
- /**
- * The user object to query with
- *
- * @var object
- */
- private $_User;
+ /**
+ * The user object to query with
+ *
+ * @var object
+ */
+ private $_User;
- private $_allowedRequests = array('default','list','add','addInfo');
+ private $_allowedRequests = array('default','list','add','addInfo');
- /**
- * Spectre constructor.
- *
- * @param $databaseConnectionObject
- * @param $userObj
- */
- public function __construct($databaseConnectionObject, $userObj) {
- $this->_DB = $databaseConnectionObject;
- $this->_User = $userObj;
- }
+ /**
+ * Spectre constructor.
+ *
+ * @param $databaseConnectionObject
+ * @param $userObj
+ */
+ public function __construct($databaseConnectionObject, $userObj) {
+ $this->_DB = $databaseConnectionObject;
+ $this->_User = $userObj;
+ }
- /**
- * Validate given request string
- *
- * @param $request string
- * @return bool
- */
- public function allowedRequests($request) {
- $ret = false;
+ /**
+ * Validate given request string
+ *
+ * @param $request string
+ * @return bool
+ */
+ public function allowedRequests($request) {
+ $ret = false;
- if(in_array($request, $this->_allowedRequests)) {
- $ret = true;
- }
+ if(in_array($request, $this->_allowedRequests)) {
+ $ret = true;
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * With given data build the structure to create a add post
- * request
- *
- * @param $data
- * @return array
- */
- public function buildAddStructure($data) {
- $ret = array();
+ /**
+ * With given data build the structure to create a add post
+ * request
+ *
+ * @param $data
+ * @return array
+ */
+ public function buildAddStructure($data) {
+ $ret = array();
- if(!empty($data) && is_array($data)) {
- foreach($data as $k=>$v) {
- $ret[$k] = array('input' => $v['apiinfo']);
- }
- }
+ if(!empty($data) && is_array($data)) {
+ foreach($data as $k=>$v) {
+ $ret[$k] = array('input' => $v['apiinfo']);
+ }
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * rewrite the data from curl into the format the
- * POST via web frontend creates
- * "The problem occurs when you have a form that uses both single file and HTML array feature."
- *
- * @param $data
- * @return array
- */
- public function prepareFilesArray($data) {
- $ret = array();
+ /**
+ * rewrite the data from curl into the format the
+ * POST via web frontend creates
+ * "The problem occurs when you have a form that uses both single file and HTML array feature."
+ *
+ * @param $data
+ * @return array
+ */
+ public function prepareFilesArray($data) {
+ $ret = array();
- if(!empty($data)) {
- foreach($data as $fieldName=>$fdata) {
- foreach($fdata as $k=>$v) {
- $ret[$k][$fieldName] = $v;
- }
+ if(!empty($data)) {
+ foreach($data as $fieldName=>$fdata) {
+ foreach($fdata as $k=>$v) {
+ $ret[$k][$fieldName] = $v;
+ }
- }
- }
+ }
+ }
- return $ret;
- }
+ return $ret;
+ }
}
*/
class Summoner {
- /**
- * Return path to given theme file with fallback to default theme
- *
- * @param string $file relative path from THEME/
- * @param string $theme Theme name
- * @param string $defaultTheme Default theme name can be overwritten
- * @return boolean|string False of nothing is found
- */
- static function themefile($file, $theme, $defaultTheme='default') {
- $ret = false;
-
- if(file_exists('view/'.$theme.'/'.$file)) {
- $ret = 'view/'.$theme.'/'.$file;
- }
- elseif (file_exists('view/'.$defaultTheme.'/'.$file)) {
- $ret = 'view/'.$defaultTheme.'/'.$file;
- }
-
- return $ret;
- }
+ /**
+ * Return path to given theme file with fallback to default theme
+ *
+ * @param string $file relative path from THEME/
+ * @param string $theme Theme name
+ * @param string $defaultTheme Default theme name can be overwritten
+ * @return boolean|string False of nothing is found
+ */
+ static function themefile($file, $theme, $defaultTheme='default') {
+ $ret = false;
+
+ if(file_exists('view/'.$theme.'/'.$file)) {
+ $ret = 'view/'.$theme.'/'.$file;
+ }
+ elseif (file_exists('view/'.$defaultTheme.'/'.$file)) {
+ $ret = 'view/'.$defaultTheme.'/'.$file;
+ }
+
+ return $ret;
+ }
/**
* validate the given string with the given type. Optional check the string
switch ($mode) {
case 'mail':
- if(filter_var($input,FILTER_VALIDATE_EMAIL) === $input) {
- return true;
- }
- else {
- return false;
- }
+ if(filter_var($input,FILTER_VALIDATE_EMAIL) === $input) {
+ return true;
+ }
+ else {
+ return false;
+ }
break;
case 'rights':
static function is_utf8 ( $string ) {
// From http://w3.org/International/questions/qa-forms-utf-8.html
return preg_match('%^(?:
- [\x09\x0A\x0D\x20-\x7E] # ASCII
- | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
- | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
- | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
- | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
- | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
- | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
- | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
+ [\x09\x0A\x0D\x20-\x7E] # ASCII
+ | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
+ | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
+ | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
+ | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
+ | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
+ | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
+ | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $string);
}
return $ret;
}
- /**
- * Creates from given rights string the rights array
- * @param $rightsString
- * @return array
- */
+ /**
+ * Creates from given rights string the rights array
+ * @param $rightsString
+ * @return array
+ */
static function prepareRightsArray($rightsString) {
- $ret = array();
-
- if(self::isRightsString($rightsString) === true) {
- $ret['user']['read'] = '-';
- $ret['user']['write'] = '-';
- $ret['user']['delete'] = '-';
- if($rightsString[0] === 'r') $ret['user']['read'] = 'r';
- if($rightsString[1] === 'w') $ret['user']['write'] = 'w';
- if($rightsString[2] === 'x') $ret['user']['delete'] = 'x';
-
- $ret['group']['read'] = '-';
- $ret['group']['write'] = '-';
- $ret['group']['delete'] = '-';
- if($rightsString[3] === 'r') $ret['group']['read'] = 'r';
- if($rightsString[4] === 'w') $ret['group']['write'] = 'w';
- if($rightsString[5] === 'x') $ret['group']['delete'] = 'x';
-
- $ret['other']['read'] = '-';
- $ret['other']['write'] = '-';
- $ret['other']['delete'] = '-';
- if($rightsString[6] === 'r') $ret['other']['read'] = 'r';
- if($rightsString[7] === 'w') $ret['other']['write'] = 'w';
- if($rightsString[8] === 'x') $ret['other']['delete'] = 'x';
- }
-
- return $ret;
- }
+ $ret = array();
+
+ if(self::isRightsString($rightsString) === true) {
+ $ret['user']['read'] = '-';
+ $ret['user']['write'] = '-';
+ $ret['user']['delete'] = '-';
+ if($rightsString[0] === 'r') $ret['user']['read'] = 'r';
+ if($rightsString[1] === 'w') $ret['user']['write'] = 'w';
+ if($rightsString[2] === 'x') $ret['user']['delete'] = 'x';
+
+ $ret['group']['read'] = '-';
+ $ret['group']['write'] = '-';
+ $ret['group']['delete'] = '-';
+ if($rightsString[3] === 'r') $ret['group']['read'] = 'r';
+ if($rightsString[4] === 'w') $ret['group']['write'] = 'w';
+ if($rightsString[5] === 'x') $ret['group']['delete'] = 'x';
+
+ $ret['other']['read'] = '-';
+ $ret['other']['write'] = '-';
+ $ret['other']['delete'] = '-';
+ if($rightsString[6] === 'r') $ret['other']['read'] = 'r';
+ if($rightsString[7] === 'w') $ret['other']['write'] = 'w';
+ if($rightsString[8] === 'x') $ret['other']['delete'] = 'x';
+ }
+
+ return $ret;
+ }
/**
* get the mime type for given file
$mime = mime_content_type($file);
}
elseif(function_exists('finfo_open') === true) {
- # provide empty magic file, system default file will be used
- $finfo = finfo_open(FILEINFO_MIME_TYPE,null);
- if($finfo) {
- $mime = finfo_file($finfo, $file);
- finfo_close($finfo);
- }
+ # provide empty magic file, system default file will be used
+ $finfo = finfo_open(FILEINFO_MIME_TYPE,null);
+ if($finfo) {
+ $mime = finfo_file($finfo, $file);
+ finfo_close($finfo);
+ }
# the mime info returns sometimes "application/x-gzip; charset=binary"
# but wee need the part before the ;
if($file[0] ==".") continue;
if(!empty($ignore)) {
foreach ($ignore as $ig) {
- if(strstr($file,$ig)) continue 2;
- }
- }
-
- if(is_file($directory."/".$file)) {
- array_push($files, $directory."/".$file);
- }
- elseif($recursive === true) {
- array_push($files, $directory."/".$file);
- $files = array_merge($files, self::readDir($directory."/".$file,$ignore, $recursive));
- }
+ if(strstr($file,$ig)) continue 2;
+ }
+ }
+
+ if(is_file($directory."/".$file)) {
+ array_push($files, $directory."/".$file);
+ }
+ elseif($recursive === true) {
+ array_push($files, $directory."/".$file);
+ $files = array_merge($files, self::readDir($directory."/".$file,$ignore, $recursive));
+ }
elseif(is_dir($directory."/".$file)) {
array_push($files, $directory."/".$file);
}
}
}
- /**
- * execute a curl call to the fiven $url
- * @param string $url The request url
- * @param int $port
- * @return bool|string
- */
+ /**
+ * execute a curl call to the fiven $url
+ * @param string $url The request url
+ * @param int $port
+ * @return bool|string
+ */
static function curlCall($url,$port=80) {
$ret = false;
* @return bool|mixed
*/
static function ifset($array,$key) {
- return isset($array[$key]) ? $array[$key] : false;
+ return isset($array[$key]) ? $array[$key] : false;
}
/**
* based on self::ifset check also the value
- *
+ *
* @param $array
* @param $key
* @param $value
return false;
}
- /**
- * Replace in $heystack the $needle with $replace only once
- *
- * @param $haystack string
- * @param $needle string
- * @param $replace string
- * @return string
- */
+ /**
+ * Replace in $heystack the $needle with $replace only once
+ *
+ * @param $haystack string
+ * @param $needle string
+ * @param $replace string
+ * @return string
+ */
static function replaceOnce($haystack, $needle, $replace) {
- $newstring = $haystack;
- $pos = strpos($haystack, $needle);
- if ($pos !== false) {
- $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
- }
- return $newstring;
- }
-
- /**
- * http_build_query with modify array
- * modify will add: key AND value not empty
- * modify will remove: only key with no value
- *
- * @param $array
- * @param array $modify
- * @return string
- */
- static function createFromParameterLinkQuery($array,$modify=array()) {
- $ret = '';
-
- if(!empty($modify)) {
- foreach($modify as $k=>$v) {
- if(empty($v)) {
- unset($array[$k]);
- }
- else {
- $array[$k] = $v;
- }
- }
- }
-
- if(!empty($array)) {
- $ret = http_build_query($array);
- }
-
- return $ret;
- }
+ $newstring = $haystack;
+ $pos = strpos($haystack, $needle);
+ if ($pos !== false) {
+ $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
+ }
+ return $newstring;
+ }
+
+ /**
+ * http_build_query with modify array
+ * modify will add: key AND value not empty
+ * modify will remove: only key with no value
+ *
+ * @param $array
+ * @param array $modify
+ * @return string
+ */
+ static function createFromParameterLinkQuery($array,$modify=array()) {
+ $ret = '';
+
+ if(!empty($modify)) {
+ foreach($modify as $k=>$v) {
+ if(empty($v)) {
+ unset($array[$k]);
+ }
+ else {
+ $array[$k] = $v;
+ }
+ }
+ }
+
+ if(!empty($array)) {
+ $ret = http_build_query($array);
+ }
+
+ return $ret;
+ }
}
* Tools management
*/
class Tentacle {
- /**
- * the global DB object
- *
- * @var object
- */
- private $_DB;
+ /**
+ * the global DB object
+ *
+ * @var object
+ */
+ private $_DB;
- /**
- * The user object to query with
- *
- * @var object
- */
- private $_User;
+ /**
+ * The user object to query with
+ *
+ * @var object
+ */
+ private $_User;
- /**
- * Tentacle constructor.
- *
- * @param $databaseConnectionObject
- * @param $userObj
- */
- public function __construct($databaseConnectionObject, $userObj) {
- $this->_DB = $databaseConnectionObject;
- $this->_User = $userObj;
- }
+ /**
+ * Tentacle constructor.
+ *
+ * @param $databaseConnectionObject
+ * @param $userObj
+ */
+ public function __construct($databaseConnectionObject, $userObj) {
+ $this->_DB = $databaseConnectionObject;
+ $this->_User = $userObj;
+ }
- /**
- * Validate if given action is a valid tool and if the user has access
- *
- * @param $identifier
- * @return bool
- */
- public function validate($identifier) {
- $ret = false;
+ /**
+ * Validate if given action is a valid tool and if the user has access
+ *
+ * @param $identifier
+ * @return bool
+ */
+ public function validate($identifier) {
+ $ret = false;
- $queryStr = "SELECT `name`,`description`,`action`
- FROM `".DB_PREFIX."_tool`
- WHERE ".$this->_User->getSQLRightsString("read")."
- AND `action` = '".$this->_DB->real_escape_string($identifier)."'";
- try {
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows > 0) {
- $ret = $query->fetch_assoc();
- }
+ $queryStr = "SELECT `name`,`description`,`action`
+ FROM `".DB_PREFIX."_tool`
+ WHERE ".$this->_User->getSQLRightsString("read")."
+ AND `action` = '".$this->_DB->real_escape_string($identifier)."'";
+ try {
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows > 0) {
+ $ret = $query->fetch_assoc();
+ }
- } catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- }
+ } catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql catch: ".$e->getMessage());
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * Default creation info based on current user
- *
- * @return array
- */
- public function getDefaultCreationInfo() {
- return array(
- 'id' => $this->_User->param('id'),
- 'group' => $this->_User->param('baseGroupId'),
- 'rights' => 'rwxrwxr--'
- );
- }
+ /**
+ * Default creation info based on current user
+ *
+ * @return array
+ */
+ public function getDefaultCreationInfo() {
+ return array(
+ 'id' => $this->_User->param('id'),
+ 'group' => $this->_User->param('baseGroupId'),
+ 'rights' => 'rwxrwxr--'
+ );
+ }
}
*
*/
class Trite {
- /**
- * The database object
- *
- * @var object
- */
- private $_DB;
-
- /**
- * The user object to query with
- *
- * @var object
- */
- private $_User;
-
- /**
- * Currently loaded collection to work with
- *
- * @var number
- */
- private $_id;
-
- /**
- * Current loaded collection data as an array
- *
- * @var array
- */
- private $_collectionData;
-
- /**
- * Options for db queries
- * 'limit' => int,
- * 'offset' => int,
- * 'orderby' => string,
- * 'sortDirection' => ASC|DESC
- *
- * @var array
- */
- private $_queryOptions;
-
- /**
- * Trite constructor.
- *
- * @param $databaseConnectionObject
- * @param $userObj
- */
- public function __construct($databaseConnectionObject, $userObj) {
- $this->_DB = $databaseConnectionObject;
- $this->_User = $userObj;
-
- $this->_setDefaults();
- }
-
- /**
- * Set the following options which can be used in DB queries
- * array(
- * 'limit' => RESULTS_PER_PAGE,
- * 'offset' => (RESULTS_PER_PAGE * ($_curPage-1)),
- * 'orderby' => $_sort,
- * 'sortDirection' => $_sortDirection
- * );
- * @param array $options
- */
- public function setQueryOptions($options) {
-
- if(!isset($options['limit'])) $options['limit'] = 5;
- if(!isset($options['offset'])) $options['offset'] = false;
- if(!isset($options['sort'])) $options['sort'] = false;
- if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
-
- $this->_queryOptions = $options;
- }
-
- /**
- * Get information to display for current collection
- * based on current user and given rights
- *
- * @param int $id The collection ID to load
- * @param string $right The rights mode. read, write or delete
- * @return array
- */
- public function load($id,$right="read") {
- $this->_collectionData = array();
-
- if(!empty($id) && Summoner::validate($id, 'digit')) {
-
- $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
- `c`.`owner`, `c`.`group`, `c`.`rights`, `c`.`defaultSearchField`,
- `u`.`name` AS username, `g`.`name` AS groupname
- FROM `".DB_PREFIX."_collection` AS c
- LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
- LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
- WHERE ".$this->_User->getSQLRightsString($right, "c")."
- AND `c`.`id` = '".$this->_DB->real_escape_string($id)."'";
- try {
- $query = $this->_DB->query($queryStr);
- if ($query !== false && $query->num_rows > 0) {
- $this->_collectionData = $query->fetch_assoc();
- $this->_id = $this->_collectionData['id'];
- }
- } catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
- error_log("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
- }
- }
-
- return $this->_collectionData;
- }
-
- /**
- * get the value of the specified param from the collection data array
- *
- * @param string $param
- * @return bool|mixed
- */
- public function param($param) {
- $ret = false;
-
- $param = trim($param);
-
- if(!empty($param) && isset($this->_collectionData[$param])) {
- $ret = $this->_collectionData[$param];
- }
-
- return $ret;
- }
-
- /**
- * Get all available collections for display based on current user
- * and read mode
- *
- * @return array
- */
- public function getCollections() {
- $ret = array();
-
- $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`
- FROM `".DB_PREFIX."_collection` AS c
- LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
- LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
- WHERE ".$this->_User->getSQLRightsString("read", "c")."
- ORDER BY `c`.`name`";
- $query = $this->_DB->query($queryStr);
-
- if($query !== false && $query->num_rows > 0) {
- while(($result = $query->fetch_assoc()) != false) {
- $ret[$result['id']] = $result;
- }
- }
-
- return $ret;
- }
-
- /**
- * set some defaults by init of the class
- */
- private function _setDefaults() {
- // default query options
- $options['limit'] = 5;
- $options['offset'] = false;
- $options['sort'] = false;
- $options['sortDirection'] = false;
- $this->setQueryOptions($options);
- }
+ /**
+ * The database object
+ *
+ * @var object
+ */
+ private $_DB;
+
+ /**
+ * The user object to query with
+ *
+ * @var object
+ */
+ private $_User;
+
+ /**
+ * Currently loaded collection to work with
+ *
+ * @var number
+ */
+ private $_id;
+
+ /**
+ * Current loaded collection data as an array
+ *
+ * @var array
+ */
+ private $_collectionData;
+
+ /**
+ * Options for db queries
+ * 'limit' => int,
+ * 'offset' => int,
+ * 'orderby' => string,
+ * 'sortDirection' => ASC|DESC
+ *
+ * @var array
+ */
+ private $_queryOptions;
+
+ /**
+ * Trite constructor.
+ *
+ * @param $databaseConnectionObject
+ * @param $userObj
+ */
+ public function __construct($databaseConnectionObject, $userObj) {
+ $this->_DB = $databaseConnectionObject;
+ $this->_User = $userObj;
+
+ $this->_setDefaults();
+ }
+
+ /**
+ * Set the following options which can be used in DB queries
+ * array(
+ * 'limit' => RESULTS_PER_PAGE,
+ * 'offset' => (RESULTS_PER_PAGE * ($_curPage-1)),
+ * 'orderby' => $_sort,
+ * 'sortDirection' => $_sortDirection
+ * );
+ * @param array $options
+ */
+ public function setQueryOptions($options) {
+
+ if(!isset($options['limit'])) $options['limit'] = 5;
+ if(!isset($options['offset'])) $options['offset'] = false;
+ if(!isset($options['sort'])) $options['sort'] = false;
+ if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
+
+ $this->_queryOptions = $options;
+ }
+
+ /**
+ * Get information to display for current collection
+ * based on current user and given rights
+ *
+ * @param int $id The collection ID to load
+ * @param string $right The rights mode. read, write or delete
+ * @return array
+ */
+ public function load($id,$right="read") {
+ $this->_collectionData = array();
+
+ if(!empty($id) && Summoner::validate($id, 'digit')) {
+
+ $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
+ `c`.`owner`, `c`.`group`, `c`.`rights`, `c`.`defaultSearchField`,
+ `u`.`name` AS username, `g`.`name` AS groupname
+ FROM `".DB_PREFIX."_collection` AS c
+ LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
+ LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
+ WHERE ".$this->_User->getSQLRightsString($right, "c")."
+ AND `c`.`id` = '".$this->_DB->real_escape_string($id)."'";
+ try {
+ $query = $this->_DB->query($queryStr);
+ if ($query !== false && $query->num_rows > 0) {
+ $this->_collectionData = $query->fetch_assoc();
+ $this->_id = $this->_collectionData['id'];
+ }
+ } catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] ".__METHOD__." mysql query: ".$queryStr);
+ error_log("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
+ }
+ }
+
+ return $this->_collectionData;
+ }
+
+ /**
+ * get the value of the specified param from the collection data array
+ *
+ * @param string $param
+ * @return bool|mixed
+ */
+ public function param($param) {
+ $ret = false;
+
+ $param = trim($param);
+
+ if(!empty($param) && isset($this->_collectionData[$param])) {
+ $ret = $this->_collectionData[$param];
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Get all available collections for display based on current user
+ * and read mode
+ *
+ * @return array
+ */
+ public function getCollections() {
+ $ret = array();
+
+ $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`
+ FROM `".DB_PREFIX."_collection` AS c
+ LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
+ LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
+ WHERE ".$this->_User->getSQLRightsString("read", "c")."
+ ORDER BY `c`.`name`";
+ $query = $this->_DB->query($queryStr);
+
+ if($query !== false && $query->num_rows > 0) {
+ while(($result = $query->fetch_assoc()) != false) {
+ $ret[$result['id']] = $result;
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * set some defaults by init of the class
+ */
+ private function _setDefaults() {
+ // default query options
+ $options['limit'] = 5;
+ $options['offset'] = false;
+ $options['sort'] = false;
+ $options['sortDirection'] = false;
+ $this->setQueryOptions($options);
+ }
}
<?php if($Doomguy->isSignedIn() === true) { ?>
<h3 class="uk-h3">Logout</h3>
<a class="uk-button uk-button-primary" href="index.php?p=auth&m=logout">
- Logout
- <span uk-icon="icon: sign-out"></span>
+ Logout
+ <span uk-icon="icon: sign-out"></span>
</a>
<?php } else { ?>
<h3 class="uk-h3">Login</h3>
<div class="uk-flex uk-flex-wrap uk-flex-wrap-around">
- <form class="uk-form-horizontal uk-margin-small" method="post">
- <div class="uk-margin">
- <label class="uk-form-label" for="username">Username</label>
- <div class="uk-form-controls">
- <input class="uk-input" id="username" type="text" autocomplete="off" name="fdata[login]">
- </div>
- </div>
- <div class="uk-margin">
- <label class="uk-form-label" for="password">Password</label>
- <div class="uk-form-controls">
- <input class="uk-input" id="password" type="password" autocomplete="off" name="fdata[password]">
- </div>
- </div>
- <div class="uk-margin">
- <button class="uk-button uk-button-primary" type="submit" name="submitForm">
- Login
- <span class="uk-icon" uk-icon="icon: sign-in"></span>
- </button>
- </div>
- </form>
+ <form class="uk-form-horizontal uk-margin-small" method="post">
+ <div class="uk-margin">
+ <label class="uk-form-label" for="username">Username</label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="username" type="text" autocomplete="off" name="fdata[login]">
+ </div>
+ </div>
+ <div class="uk-margin">
+ <label class="uk-form-label" for="password">Password</label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="password" type="password" autocomplete="off" name="fdata[password]">
+ </div>
+ </div>
+ <div class="uk-margin">
+ <button class="uk-button uk-button-primary" type="submit" name="submitForm">
+ Login
+ <span class="uk-icon" uk-icon="icon: sign-in"></span>
+ </button>
+ </div>
+ </form>
</div>
<?php } ?>
// passwords used here: password_hash("somePassword", PASSWORD_DEFAULT);
if(isset($_GET['m']) && !empty($_GET['m'])) {
- if($_GET['m'] == "logout") {
- $Doomguy->logOut();
- $TemplateData['refresh'] = 'index.php';
- }
+ if($_GET['m'] == "logout") {
+ $Doomguy->logOut();
+ $TemplateData['refresh'] = 'index.php';
+ }
}
elseif(isset($_POST['submitForm'])) {
- $fdata = $_POST['fdata'];
- if(!empty($fdata)) {
- $_username = trim($fdata['login']);
- $_password = trim($fdata['password']);
+ $fdata = $_POST['fdata'];
+ if(!empty($fdata)) {
+ $_username = trim($fdata['login']);
+ $_password = trim($fdata['password']);
- if(!empty($_username) && !empty($_password)) {
- if(Summoner::validate($_username,'text') === true && Summoner::validate($_password,'text') === true) {
- $do = $Doomguy->authenticate($_username, $_password);
- if($do === true) {
- $TemplateData['refresh'] = 'index.php';
- }
- else {
- $TemplateData['message']['content'] = "Invalid username or password.";
- $TemplateData['message']['status'] = "error";
- }
- }
- else {
- $TemplateData['message']['content'] = "Please provide valid e-Mail and password.";
- $TemplateData['message']['status'] = "error";
- }
- }
- }
+ if(!empty($_username) && !empty($_password)) {
+ if(Summoner::validate($_username,'text') === true && Summoner::validate($_password,'text') === true) {
+ $do = $Doomguy->authenticate($_username, $_password);
+ if($do === true) {
+ $TemplateData['refresh'] = 'index.php';
+ }
+ else {
+ $TemplateData['message']['content'] = "Invalid username or password.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "Please provide valid e-Mail and password.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ }
}
<?php if(!empty($TemplateData['search'])) { ?>
<div uk-alert id="searchNotice">
- <button class="uk-alert-close" type="button" uk-close></button>
- <p>Display result for: <b><?php echo $TemplateData['search']; ?></b></p>
+ <button class="uk-alert-close" type="button" uk-close></button>
+ <p>Display result for: <b><?php echo $TemplateData['search']; ?></b></p>
</div>
<script type="text/javascript">
- UIkit.util.on('#searchNotice', 'hide', function () {
- window.location.href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>";
- });
+ UIkit.util.on('#searchNotice', 'hide', function () {
+ window.location.href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>";
+ });
</script>
<?php } ?>
<?php if(!empty($TemplateData['entries'])) { ?>
<div class="uk-grid-small uk-grid-match" uk-grid>
- <?php foreach($TemplateData['entries']['results'] as $entryK=>$entry) { ?>
- <div class="uk-width-1-4@s uk-width-1-6@l">
- <div class="uk-card uk-card-default uk-card-small">
- <div class="uk-card-media-top">
- <?php if(Summoner::ifset($entry['fields'], 'coverimage')) { ?>
- <img src="<?php echo $TemplateData['storagePath'].'/'.$entryK.'/'.$entry['fields']['coverimage']['value']; ?>"
- alt="<?php echo $entry['fields']['coverimage']['displayname']; ?>">
+ <?php foreach($TemplateData['entries']['results'] as $entryK=>$entry) { ?>
+ <div class="uk-width-1-4@s uk-width-1-6@l">
+ <div class="uk-card uk-card-default uk-card-small">
+ <div class="uk-card-media-top">
+ <?php if(Summoner::ifset($entry['fields'], 'coverimage')) { ?>
+ <img src="<?php echo $TemplateData['storagePath'].'/'.$entryK.'/'.$entry['fields']['coverimage']['value']; ?>"
+ alt="<?php echo $entry['fields']['coverimage']['displayname']; ?>">
- <?php } ?>
- </div>
- <div class="uk-card-body uk-visible@l">
- <?php if(Summoner::ifset($entry['fields'], 'title')) { ?>
- <h3 class="uk-card-title"><?php echo $entry['fields']['title']['value']; ?></h3>
- <?php } ?>
+ <?php } ?>
+ </div>
+ <div class="uk-card-body uk-visible@l">
+ <?php if(Summoner::ifset($entry['fields'], 'title')) { ?>
+ <h3 class="uk-card-title"><?php echo $entry['fields']['title']['value']; ?></h3>
+ <?php } ?>
- <?php if(Summoner::ifset($entry['fields'], 'description')) { ?>
- <p><?php echo $entry['fields']['description']['value']; ?></p>
- <?php } ?>
- </div>
- <div class="uk-card-footer">
- <a href="<?php echo $TemplateData['entryLinkPrefix']; ?>&id=<?php echo $entryK; ?>" class="uk-button uk-button-text">View</a>
- </div>
- </div>
- </div>
- <?php } ?>
+ <?php if(Summoner::ifset($entry['fields'], 'description')) { ?>
+ <p><?php echo $entry['fields']['description']['value']; ?></p>
+ <?php } ?>
+ </div>
+ <div class="uk-card-footer">
+ <a href="<?php echo $TemplateData['entryLinkPrefix']; ?>&id=<?php echo $entryK; ?>" class="uk-button uk-button-text">View</a>
+ </div>
+ </div>
+ </div>
+ <?php } ?>
</div>
<?php } elseif(!empty($TemplateData['collections'])) { ?>
<h3 class="uk-h3">Collection overview</h3>
<div class="uk-grid-small uk-grid-row-small uk-grid-row-small" uk-grid>
- <div class="uk-width-2-3@m uk-width-1-2@xl">
- <dl class="uk-description-list uk-description-list-divider">
- <?php foreach($TemplateData['collections'] as $k=>$v) { ?>
- <dt><a href="index.php?p=collections&collection=<?php echo $k; ?>"><?php echo $v['name']; ?></a></dt>
- <dd><?php echo $v['description']; ?></dd>
- <?php } ?>
- </dl>
- </div>
+ <div class="uk-width-2-3@m uk-width-1-2@xl">
+ <dl class="uk-description-list uk-description-list-divider">
+ <?php foreach($TemplateData['collections'] as $k=>$v) { ?>
+ <dt><a href="index.php?p=collections&collection=<?php echo $k; ?>"><?php echo $v['name']; ?></a></dt>
+ <dd><?php echo $v['description']; ?></dd>
+ <?php } ?>
+ </dl>
+ </div>
</div>
<?php } ?>
$_collection = false;
if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
}
// field id to search within
$_fid = false;
if(isset($_GET['fid']) && !empty($_GET['fid'])) {
- $_fid = trim($_GET['fid']);
- $_fid = Summoner::validate($_fid,'digit') ? $_fid : false;
+ $_fid = trim($_GET['fid']);
+ $_fid = Summoner::validate($_fid,'digit') ? $_fid : false;
}
// field value to look up
$_fv = false;
if(isset($_GET['fv']) && !empty($_GET['fv'])) {
- $_fv = trim($_GET['fv']);
- $_fv = Summoner::validate($_fv,'text') ? $_fv : false;
+ $_fv = trim($_GET['fv']);
+ $_fv = Summoner::validate($_fv,'text') ? $_fv : false;
}
$_search = false;
if(isset($_POST['navSearch'])) {
- $_search = trim($_POST['navSearch']);
- $_search = Summoner::validate($_search,'text') ? $_search : false;
+ $_search = trim($_POST['navSearch']);
+ $_search = Summoner::validate($_search,'text') ? $_search : false;
}
require_once(Summoner::themefile('system/pagination_before.php',UI_THEME));
$TemplateData['pagination']['currentGetParameters']['collection'] = $_collection;
if(!empty($_collection)) {
- $TemplateData['loadedCollection'] = $Trite->load($_collection);
- if(!empty($TemplateData['loadedCollection'])) {
- $Mancubus->setCollection($Trite->param('id'));
- $Mancubus->setQueryOptions($_queryOptions); // this comes from pagination_before!
- $TemplateData['storagePath'] = PATH_WEB_STORAGE . '/' . $_collection;
- $TemplateData['entryLinkPrefix'] = "index.php?p=entry&collection=".$_collection;
- $TemplateData['searchAction'] = 'index.php?p=collections&collection='.$_collection;
+ $TemplateData['loadedCollection'] = $Trite->load($_collection);
+ if(!empty($TemplateData['loadedCollection'])) {
+ $Mancubus->setCollection($Trite->param('id'));
+ $Mancubus->setQueryOptions($_queryOptions); // this comes from pagination_before!
+ $TemplateData['storagePath'] = PATH_WEB_STORAGE . '/' . $_collection;
+ $TemplateData['entryLinkPrefix'] = "index.php?p=entry&collection=".$_collection;
+ $TemplateData['searchAction'] = 'index.php?p=collections&collection='.$_collection;
- if (!empty($_fv) && !empty($_fid)) {
- $TemplateData['entries'] = $Mancubus->getEntriesByFieldValue($_fid, $_fv);
- $TemplateData['search'] = $_fv;
+ if (!empty($_fv) && !empty($_fid)) {
+ $TemplateData['entries'] = $Mancubus->getEntriesByFieldValue($_fid, $_fv);
+ $TemplateData['search'] = $_fv;
- $TemplateData['pagination']['currentGetParameters']['fid'] = $_fid;
- $TemplateData['pagination']['currentGetParameters']['fv'] = $_fv;
- } else {
- $TemplateData['entries'] = $Mancubus->getEntries($Trite->param('defaultSearchField'),$_search,true);
- if (!empty($_search)) {
- $TemplateData['search'] = $_search;
- }
- }
- }
- else {
- $TemplateData['message']['content'] = "Can not load given collection.";
- $TemplateData['message']['status'] = "error";
- }
+ $TemplateData['pagination']['currentGetParameters']['fid'] = $_fid;
+ $TemplateData['pagination']['currentGetParameters']['fv'] = $_fv;
+ } else {
+ $TemplateData['entries'] = $Mancubus->getEntries($Trite->param('defaultSearchField'),$_search,true);
+ if (!empty($_search)) {
+ $TemplateData['search'] = $_search;
+ }
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "Can not load given collection.";
+ $TemplateData['message']['status'] = "error";
+ }
}
else {
- $TemplateData['collections'] = $Trite->getCollections();
+ $TemplateData['collections'] = $Trite->getCollections();
}
require_once(Summoner::themefile('system/pagination_after.php',UI_THEME));
<?php if(!empty($TemplateData['search'])) { ?>
<div uk-alert id="searchNotice">
- <button class="uk-alert-close" type="button" uk-close></button>
- <p>Display result for: <b><?php echo $TemplateData['search']; ?></b></p>
+ <button class="uk-alert-close" type="button" uk-close></button>
+ <p>Display result for: <b><?php echo $TemplateData['search']; ?></b></p>
</div>
<script type="text/javascript">
- UIkit.util.on('#searchNotice', 'hide', function () {
- window.location.href="index.php";
- });
+ UIkit.util.on('#searchNotice', 'hide', function () {
+ window.location.href="index.php";
+ });
</script>
<?php } ?>
<div class="uk-grid-divider uk-child-width-expand@s" uk-grid>
<?php foreach($TemplateData['latest'] as $k=>$v) { ?>
- <div>
- <a href="index.php?p=collections&collection=<?php echo $k; ?>"><?php echo $v['name']; ?></a><br />
- <?php echo $v['description']; ?>
+ <div>
+ <a href="index.php?p=collections&collection=<?php echo $k; ?>"><?php echo $v['name']; ?></a><br />
+ <?php echo $v['description']; ?>
- <?php
- if(isset($v['entries']['results'])) {
- foreach($v['entries']['results'] as $entryK=>$entry) { ?>
+ <?php
+ if(isset($v['entries']['results'])) {
+ foreach($v['entries']['results'] as $entryK=>$entry) { ?>
- <div class="uk-card uk-card-default uk-grid-collapse uk-child-width-1-2@s uk-margin" uk-grid>
- <div class="uk-card-media-left uk-cover-container">
- <?php if(Summoner::ifset($entry['fields'], 'coverimage')) { ?>
- <img src="<?php echo PATH_WEB_STORAGE.'/'.$k.'/'.$entryK.'/'.$entry['fields']['coverimage']['value']; ?>"
- alt="<?php echo $entry['fields']['coverimage']['displayname']; ?>" uk-cover>
- <canvas width="600" height="400"></canvas>
- <?php } ?>
- </div>
- <div>
- <div class="uk-card-body">
- <?php if(Summoner::ifset($entry['fields'], 'title')) { ?>
- <h3 class="uk-card-title"><?php echo $entry['fields']['title']['value']; ?></h3>
- <?php } ?>
+ <div class="uk-card uk-card-default uk-grid-collapse uk-child-width-1-2@s uk-margin" uk-grid>
+ <div class="uk-card-media-left uk-cover-container">
+ <?php if(Summoner::ifset($entry['fields'], 'coverimage')) { ?>
+ <img src="<?php echo PATH_WEB_STORAGE.'/'.$k.'/'.$entryK.'/'.$entry['fields']['coverimage']['value']; ?>"
+ alt="<?php echo $entry['fields']['coverimage']['displayname']; ?>" uk-cover>
+ <canvas width="600" height="400"></canvas>
+ <?php } ?>
+ </div>
+ <div>
+ <div class="uk-card-body">
+ <?php if(Summoner::ifset($entry['fields'], 'title')) { ?>
+ <h3 class="uk-card-title"><?php echo $entry['fields']['title']['value']; ?></h3>
+ <?php } ?>
- <?php if(Summoner::ifset($entry['fields'], 'description')) { ?>
- <p><?php echo $entry['fields']['description']['value']; ?></p>
- <?php } ?>
- </div>
- <div class="uk-card-footer">
- <a href="index.php?p=entry&collection=<?php echo $k ?>&id=<?php echo $entryK; ?>" class="uk-button uk-button-text">View</a>
- </div>
- </div>
- </div>
+ <?php if(Summoner::ifset($entry['fields'], 'description')) { ?>
+ <p><?php echo $entry['fields']['description']['value']; ?></p>
+ <?php } ?>
+ </div>
+ <div class="uk-card-footer">
+ <a href="index.php?p=entry&collection=<?php echo $k ?>&id=<?php echo $entryK; ?>" class="uk-button uk-button-text">View</a>
+ </div>
+ </div>
+ </div>
- <?php
- }
- }
- ?>
+ <?php
+ }
+ }
+ ?>
- </div>
+ </div>
<?php } ?>
</div>
$_search = false;
if(isset($_POST['navSearch'])) {
- $_search = trim($_POST['navSearch']);
- $_search = Summoner::validate($_search,'text') ? $_search : false;
+ $_search = trim($_POST['navSearch']);
+ $_search = Summoner::validate($_search,'text') ? $_search : false;
}
$TemplateData['latest'] = $Mancubus->getLatest(5,5,$_search);
if (!empty($_search)) {
- $TemplateData['search'] = $_search;
+ $TemplateData['search'] = $_search;
}
<h3 class="uk-h3"><a href="index.php?p=collections&collection=<?php echo Summoner::ifset($TemplateData['loadedCollection'], 'id'); ?>"><?php echo Summoner::ifset($TemplateData['loadedCollection'], 'name'); ?></a></h3>
<div class="uk-grid-small uk-grid-row-small uk-grid-row-small" uk-grid>
- <div class="uk-width-1-2@l">
- <article class="uk-article">
- <?php if($TemplateData['showEdit'] === true) { ?>
- <p class="uk-article-meta"><a href="index.php?p=manageentry&collection=<?php echo Summoner::ifset($TemplateData['loadedCollection'], 'id'); ?>&id=<?php echo $TemplateData['entry']['id']; ?>">EDIT</a></p>
- <?php
- }
+ <div class="uk-width-1-2@l">
+ <article class="uk-article">
+ <?php if($TemplateData['showEdit'] === true) { ?>
+ <p class="uk-article-meta"><a href="index.php?p=manageentry&collection=<?php echo Summoner::ifset($TemplateData['loadedCollection'], 'id'); ?>&id=<?php echo $TemplateData['entry']['id']; ?>">EDIT</a></p>
+ <?php
+ }
- if(isset($TemplateData['entry']['fields'])) {
- foreach($TemplateData['entry']['fields'] as $field) {
+ if(isset($TemplateData['entry']['fields'])) {
+ foreach($TemplateData['entry']['fields'] as $field) {
- if($field['identifier'] == "coverimage") continue;
- if($field['identifier'] == "attachment") continue;
+ if($field['identifier'] == "coverimage") continue;
+ if($field['identifier'] == "attachment") continue;
- $_fieldViewSpecial = Summoner::themefile('entry/field-'.$field['type'].'-'.$field['identifier'].'.html', UI_THEME);
- $_fieldView = Summoner::themefile('entry/field-'.$field['type'].'.html', UI_THEME);
- if(file_exists($_fieldViewSpecial)) {
- require $_fieldViewSpecial;
- }
- elseif(file_exists($_fieldView)) {
- require $_fieldView;
- }
- else {
- require $TemplateData['fieldViewDefault'];
- }
- }
- }
- ?>
+ $_fieldViewSpecial = Summoner::themefile('entry/field-'.$field['type'].'-'.$field['identifier'].'.html', UI_THEME);
+ $_fieldView = Summoner::themefile('entry/field-'.$field['type'].'.html', UI_THEME);
+ if(file_exists($_fieldViewSpecial)) {
+ require $_fieldViewSpecial;
+ }
+ elseif(file_exists($_fieldView)) {
+ require $_fieldView;
+ }
+ else {
+ require $TemplateData['fieldViewDefault'];
+ }
+ }
+ }
+ ?>
- </article>
- </div>
- <div class="uk-width-1-2@l">
- <?php
- if(isset($TemplateData['entry']['fields'])) {
- foreach($TemplateData['entry']['fields'] as $field) {
- if($field['identifier'] == "coverimage" || $field['identifier'] == "attachment") {
+ </article>
+ </div>
+ <div class="uk-width-1-2@l">
+ <?php
+ if(isset($TemplateData['entry']['fields'])) {
+ foreach($TemplateData['entry']['fields'] as $field) {
+ if($field['identifier'] == "coverimage" || $field['identifier'] == "attachment") {
- $_fieldViewSpecial = Summoner::themefile('entry/field-'.$field['type'].'-'.$field['identifier'].'.html', UI_THEME);
- $_fieldView = Summoner::themefile('entry/field-'.$field['type'].'.html', UI_THEME);
- if(file_exists($_fieldViewSpecial)) {
- require $_fieldViewSpecial;
- }
- elseif(file_exists($_fieldView)) {
- require $_fieldView;
- }
- else {
- require $TemplateData['fieldViewDefault'];
- }
- }
- }
- }
- ?>
- </div>
+ $_fieldViewSpecial = Summoner::themefile('entry/field-'.$field['type'].'-'.$field['identifier'].'.html', UI_THEME);
+ $_fieldView = Summoner::themefile('entry/field-'.$field['type'].'.html', UI_THEME);
+ if(file_exists($_fieldViewSpecial)) {
+ require $_fieldViewSpecial;
+ }
+ elseif(file_exists($_fieldView)) {
+ require $_fieldView;
+ }
+ else {
+ require $TemplateData['fieldViewDefault'];
+ }
+ }
+ }
+ }
+ ?>
+ </div>
</div>
$_collection = false;
if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
}
$_id = false;
if(isset($_GET['id']) && !empty($_GET['id'])) {
- $_id = trim($_GET['id']);
- $_id = Summoner::validate($_id,'digit') ? $_id : false;
+ $_id = trim($_GET['id']);
+ $_id = Summoner::validate($_id,'digit') ? $_id : false;
}
$TemplateData['fieldViewDefault'] = Summoner::themefile('entry/field-unknown.html', UI_THEME);
$TemplateData['showEdit'] = false;
if(!empty($_collection) && !empty($_id)) {
- $TemplateData['loadedCollection'] = $Trite->load($_collection);
- if(!empty($TemplateData['loadedCollection'])) {
- $Mancubus->setCollection($Trite->param('id'));
- $TemplateData['entry'] = $Mancubus->getEntry($_id);
- $TemplateData['storagePath'] = PATH_WEB_STORAGE . '/' . $Trite->param('id') . '/' . $_id;
- $TemplateData['searchAction'] = 'index.php?p=collections&collection=' . $Trite->param('id');
+ $TemplateData['loadedCollection'] = $Trite->load($_collection);
+ if(!empty($TemplateData['loadedCollection'])) {
+ $Mancubus->setCollection($Trite->param('id'));
+ $TemplateData['entry'] = $Mancubus->getEntry($_id);
+ $TemplateData['storagePath'] = PATH_WEB_STORAGE . '/' . $Trite->param('id') . '/' . $_id;
+ $TemplateData['searchAction'] = 'index.php?p=collections&collection=' . $Trite->param('id');
- $ManageEntry->setCollection($Trite->param('id'));
- $TemplateData['showEdit'] = $ManageEntry->canEditEntry($_id);
- }
- else {
- $TemplateData['message']['content'] = 'Can not load given collection.';
- $TemplateData['message']['status'] = 'error';
- }
+ $ManageEntry->setCollection($Trite->param('id'));
+ $TemplateData['showEdit'] = $ManageEntry->canEditEntry($_id);
+ }
+ else {
+ $TemplateData['message']['content'] = 'Can not load given collection.';
+ $TemplateData['message']['status'] = 'error';
+ }
}
else {
- $TemplateData['message']['status'] = 'error';
- $TemplateData['message']['content'] = 'Missing required query parameters.';
+ $TemplateData['message']['status'] = 'error';
+ $TemplateData['message']['content'] = 'Missing required query parameters.';
}
<p data-field-name="date" data-field-id="<?php echo $field['identifier']; ?>">
- <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
- <a href="index.php?p=collections&collection='.$TemplateData['loadedCollection']['id'].'&fid='.$field['id'].'&fv='.urlencode(Summoner::ifset($field, 'value')).'"><?php echo Summoner::ifset($field, 'value'); ?></a>
+ <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
+ <a href="index.php?p=collections&collection='.$TemplateData['loadedCollection']['id'].'&fid='.$field['id'].'&fv='.urlencode(Summoner::ifset($field, 'value')).'"><?php echo Summoner::ifset($field, 'value'); ?></a>
</p>
<p data-field-name="lookupmultiple" data-field-id="<?php echo $field['identifier']; ?>">
- <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
- <?php
- foreach($field['value'] as $_fv) {
- echo '<a href="index.php?p=collections&collection='.$TemplateData['loadedCollection']['id'].'&fid='.$field['id'].'&fv='.urlencode($_fv).'">'.$_fv.'</a>, ';
- }
- ?>
+ <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
+ <?php
+ foreach($field['value'] as $_fv) {
+ echo '<a href="index.php?p=collections&collection='.$TemplateData['loadedCollection']['id'].'&fid='.$field['id'].'&fv='.urlencode($_fv).'">'.$_fv.'</a>, ';
+ }
+ ?>
</p>
<p data-field-name="selection" data-field-id="<?php echo $field['identifier']; ?>">
- <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
- <a href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>&fid=<?php echo $field['id']; ?>&fv=<?php echo urlencode(Summoner::ifset($field, 'value')); ?>"><?php echo Summoner::ifset($field, 'value'); ?></a>
+ <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
+ <a href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>&fid=<?php echo $field['id']; ?>&fv=<?php echo urlencode(Summoner::ifset($field, 'value')); ?>"><?php echo Summoner::ifset($field, 'value'); ?></a>
</p>
<div class="uk-margin" data-field-name="upload-coverimage">
- <img src="<?php echo $TemplateData['storagePath'].'/'.Summoner::ifset($field, 'value'); ?>"
- title="<?php echo Summoner::ifset($field, 'value'); ?>"
- width=""
- />
+ <img src="<?php echo $TemplateData['storagePath'].'/'.Summoner::ifset($field, 'value'); ?>"
+ title="<?php echo Summoner::ifset($field, 'value'); ?>"
+ width=""
+ />
</div>
<p data-field-name="upload" data-field-id="<?php echo $field['identifier']; ?>"><span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
- <a href="<?php echo $TemplateData['storagePath'].'/'.Summoner::ifset($field, 'value'); ?>" target="_blank"><?php echo Summoner::ifset($field, 'value'); ?></a>
+ <a href="<?php echo $TemplateData['storagePath'].'/'.Summoner::ifset($field, 'value'); ?>" target="_blank"><?php echo Summoner::ifset($field, 'value'); ?></a>
</p>
<div data-field-name="upload_multiple-attachment" class="uk-child-width-1-3@m" uk-grid uk-lightbox="animation: fade">
- <?php foreach ($field['value'] as $_uEntry) { ?>
- <div>
- <a class="uk-inline" href="<?php echo $TemplateData['storagePath'].'/'.$_uEntry; ?>" data-caption="<?php echo $_uEntry; ?>">
- <img src="<?php echo $TemplateData['storagePath'].'/'.$_uEntry; ?>" alt="<?php echo $_uEntry; ?>">
- </a>
- </div>
- <?php } ?>
+ <?php foreach ($field['value'] as $_uEntry) { ?>
+ <div>
+ <a class="uk-inline" href="<?php echo $TemplateData['storagePath'].'/'.$_uEntry; ?>" data-caption="<?php echo $_uEntry; ?>">
+ <img src="<?php echo $TemplateData['storagePath'].'/'.$_uEntry; ?>" alt="<?php echo $_uEntry; ?>">
+ </a>
+ </div>
+ <?php } ?>
</div>
<p data-field-name="upload_multiple" data-field-id="<?php echo $field['identifier']; ?>"><span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
<ul class="uk-list uk-list-collapse uk-list-disc">
- <?php foreach ($field['value'] as $_uEntry) { ?>
- <li><a href="<?php echo $TemplateData['storagePath'].'/'.$_uEntry; ?>" target="_blank"><?php echo $_uEntry; ?></a></li>
- <?php } ?>
+ <?php foreach ($field['value'] as $_uEntry) { ?>
+ <li><a href="<?php echo $TemplateData['storagePath'].'/'.$_uEntry; ?>" target="_blank"><?php echo $_uEntry; ?></a></li>
+ <?php } ?>
</ul>
</p>
-
<p data-field-name="year" data-field-id="<?php echo $field['identifier']; ?>">
- <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
- <a href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>&fid=<?php echo $field['id']; ?>&fv=<?php echo urlencode(Summoner::ifset($field, 'value')); ?>"><?php echo Summoner::ifset($field, 'value'); ?></a>
+ <span class="uk-text-muted"><?php echo $field['displayname']; ?>:</span>
+ <a href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>&fid=<?php echo $field['id']; ?>&fv=<?php echo urlencode(Summoner::ifset($field, 'value')); ?>"><?php echo Summoner::ifset($field, 'value'); ?></a>
</p>
<html>
<head>
<meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="view/default/ui/css/uikit.min.css" media="screen,projection"/>
<link type="text/css" rel="stylesheet" href="view/default/ui/css/style.css" media="screen,projection"/>
- <script type="text/javascript" src="view/default/ui/js/uikit.min.js"></script>
- <script type="text/javascript" src="view/default/ui/js/uikit-icons.min.js"></script>
+ <script type="text/javascript" src="view/default/ui/js/uikit.min.js"></script>
+ <script type="text/javascript" src="view/default/ui/js/uikit-icons.min.js"></script>
<meta name="author" content="https://www.bananas-playground.net/projekt/bibliotheca" />
<title>Bibliotheca</title>
</head>
<body>
- <header>
- <?php require_once $ViewMenu; ?>
- </header>
+ <header>
+ <?php require_once $ViewMenu; ?>
+ </header>
- <main>
- <div class="uk-container uk-container-expand uk-margin-top">
- <?php require_once $ViewMessage; ?>
- <?php require_once $ViewPagination; ?>
- <?php require_once $View; ?>
- </div>
+ <main>
+ <div class="uk-container uk-container-expand uk-margin-top">
+ <?php require_once $ViewMessage; ?>
+ <?php require_once $ViewPagination; ?>
+ <?php require_once $View; ?>
+ </div>
</main>
- <footer>
- <div class="uk-container uk-container-expand">
- <p> </p>
- </div>
- </footer>
+ <footer>
+ <div class="uk-container uk-container-expand">
+ <p> </p>
+ </div>
+ </footer>
</body>
</html>
<h3 class="uk-h3">Manage your fields for: <?php echo $TemplateData['editData']['name']; ?></h3>
<div class="uk-grid-small uk-grid-row-small uk-grid-row-small" uk-grid>
- <div class="uk-width-1-2">
- <h4 class="uk-h4">Add or remove a field</h4>
- <p>
- Just use drag and drop below to add, remove or order your fields.<br />
- <span class="" uk-icon="icon: warning"></span> Removing a field will remove
- the stored data from the collection.<br />
- <span class="" uk-icon="icon: warning"></span> Make sure at least the <b>title</b>
- field is available.
- </p>
- <div id="collectionFields" uk-sortable="group: sortable-group">
- <?php foreach($TemplateData['existingFields'] as $k=>$v) { ?>
- <div data-field-id="<?php echo $k; ?>">
- <span class="uk-sortable-handle uk-margin-small-right" uk-icon="icon: table"></span>
- <?php echo $v['displayname']; ?> (<?php echo $v['type']; ?>)
- </div>
- <?php } ?>
- </div>
+ <div class="uk-width-1-2">
+ <h4 class="uk-h4">Add or remove a field</h4>
+ <p>
+ Just use drag and drop below to add, remove or order your fields.<br />
+ <span class="" uk-icon="icon: warning"></span> Removing a field will remove
+ the stored data from the collection.<br />
+ <span class="" uk-icon="icon: warning"></span> Make sure at least the <b>title</b>
+ field is available.
+ </p>
+ <div id="collectionFields" uk-sortable="group: sortable-group">
+ <?php foreach($TemplateData['existingFields'] as $k=>$v) { ?>
+ <div data-field-id="<?php echo $k; ?>">
+ <span class="uk-sortable-handle uk-margin-small-right" uk-icon="icon: table"></span>
+ <?php echo $v['displayname']; ?> (<?php echo $v['type']; ?>)
+ </div>
+ <?php } ?>
+ </div>
- <form class="uk-form-horizontal uk-margin-small" method="post" onsubmit="return saveOrderAndSubmit()">
- <input type="hidden" name="fdata[fieldSortString]" id="fieldSort"
- value="<?php echo Summoner::ifset($TemplateData['editData'], 'fieldSortString'); ?>">
- <div class="uk-margin">
- <button class="uk-button uk-button-primary" type="submit" name="submitForm">
- Save
- </button>
- </div>
- </form>
- </div>
- <div class="uk-width-1-2">
- <h4 class="uk-h4">Available fields</h4>
- <div uk-sortable="group: sortable-group">
- <?php foreach($TemplateData['availableFields'] as $k=>$v) { ?>
- <div data-field-id="<?php echo $k; ?>">
- <span class="uk-sortable-handle uk-margin-small-right" uk-icon="icon: table"></span>
- <?php echo $v['displayname']; ?> (<?php echo $v['type']; ?>)
- </div>
- <?php } ?>
- </div>
- </div>
+ <form class="uk-form-horizontal uk-margin-small" method="post" onsubmit="return saveOrderAndSubmit()">
+ <input type="hidden" name="fdata[fieldSortString]" id="fieldSort"
+ value="<?php echo Summoner::ifset($TemplateData['editData'], 'fieldSortString'); ?>">
+ <div class="uk-margin">
+ <button class="uk-button uk-button-primary" type="submit" name="submitForm">
+ Save
+ </button>
+ </div>
+ </form>
+ </div>
+ <div class="uk-width-1-2">
+ <h4 class="uk-h4">Available fields</h4>
+ <div uk-sortable="group: sortable-group">
+ <?php foreach($TemplateData['availableFields'] as $k=>$v) { ?>
+ <div data-field-id="<?php echo $k; ?>">
+ <span class="uk-sortable-handle uk-margin-small-right" uk-icon="icon: table"></span>
+ <?php echo $v['displayname']; ?> (<?php echo $v['type']; ?>)
+ </div>
+ <?php } ?>
+ </div>
+ </div>
</div>
<script type="text/javascript">
- function saveOrderAndSubmit() {
- let list = document.getElementById("collectionFields");
- let fieldSort = document.getElementById("fieldSort");
- let sortString = '';
- if(list && list.children.length > 0 && fieldSort) {
- let fields = Array.from(list.children);
- fields.forEach(function(item, index) {
- sortString += item.getAttribute("data-field-id")+",";
- });
- fieldSort.value = sortString;
- return true;
- }
- return false;
- }
+ function saveOrderAndSubmit() {
+ let list = document.getElementById("collectionFields");
+ let fieldSort = document.getElementById("fieldSort");
+ let sortString = '';
+ if(list && list.children.length > 0 && fieldSort) {
+ let fields = Array.from(list.children);
+ fields.forEach(function(item, index) {
+ sortString += item.getAttribute("data-field-id")+",";
+ });
+ fieldSort.value = sortString;
+ return true;
+ }
+ return false;
+ }
</script>
$_id = false;
if(isset($_GET['id']) && !empty($_GET['id'])) {
- $_id = trim($_GET['id']);
- $_id = Summoner::validate($_id,'digit') ? $_id : false;
+ $_id = trim($_GET['id']);
+ $_id = Summoner::validate($_id,'digit') ? $_id : false;
}
if(!empty($_id)) {
- $TemplateData['editData'] = $ManangeCollections->getEditData($_id);
- $ManangeCollectionFields->setCollection($_id);
- $TemplateData['existingFields'] = $ManangeCollectionFields->getExistingFields();
- // reduce the selection for only the new ones
- if(!empty($TemplateData['existingFields'])) {
- foreach ($TemplateData['existingFields'] as $k=>$v) {
- unset($TemplateData['availableFields'][$k]);
- }
- }
+ $TemplateData['editData'] = $ManangeCollections->getEditData($_id);
+ $ManangeCollectionFields->setCollection($_id);
+ $TemplateData['existingFields'] = $ManangeCollectionFields->getExistingFields();
+ // reduce the selection for only the new ones
+ if(!empty($TemplateData['existingFields'])) {
+ foreach ($TemplateData['existingFields'] as $k=>$v) {
+ unset($TemplateData['availableFields'][$k]);
+ }
+ }
- // if loading failed redirect to overview
- if(!isset($TemplateData['editData']['name'])) {
- $TemplateData['refresh'] = 'index.php?p=managecolletions';
- }
+ // if loading failed redirect to overview
+ if(!isset($TemplateData['editData']['name'])) {
+ $TemplateData['refresh'] = 'index.php?p=managecolletions';
+ }
}
if(isset($_POST['submitForm'])) {
- $fdata = $_POST['fdata'];
- if (!empty($fdata)) {
- $_fieldSortString = trim($fdata['fieldSortString']);
- if($ManangeCollectionFields->validateFieldSortString($_fieldSortString)) {
- $do = $ManangeCollectionFields->updateFields($_fieldSortString);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=managecollectionfields&id='.$_id;
- } else {
- $TemplateData['message']['content'] = "Fields could not be updated.";
- $TemplateData['message']['status'] = "error";
- }
- }
- else {
- $TemplateData['message']['content'] = "Please provide valid fields.";
- $TemplateData['message']['status'] = "error";
- }
- }
+ $fdata = $_POST['fdata'];
+ if (!empty($fdata)) {
+ $_fieldSortString = trim($fdata['fieldSortString']);
+ if($ManangeCollectionFields->validateFieldSortString($_fieldSortString)) {
+ $do = $ManangeCollectionFields->updateFields($_fieldSortString);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=managecollectionfields&id='.$_id;
+ } else {
+ $TemplateData['message']['content'] = "Fields could not be updated.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "Please provide valid fields.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
}
// @todo providing the id is enough
$_editMode = false;
if(isset($_GET['m']) && !empty($_GET['m'])) {
- if($_GET['m'] == "edit") {
- $_editMode = true;
- }
+ if($_GET['m'] == "edit") {
+ $_editMode = true;
+ }
}
$_id = false;
if(isset($_GET['id']) && !empty($_GET['id'])) {
- $_id = trim($_GET['id']);
- $_id = Summoner::validate($_id,'digit') ? $_id : false;
+ $_id = trim($_GET['id']);
+ $_id = Summoner::validate($_id,'digit') ? $_id : false;
}
if($_editMode === true && !empty($_id)) {
- $TemplateData['editData'] = $ManangeCollections->getEditData($_id);
- $ManangeCollectionFields->setCollection($_id);
- $TemplateData['existingFields'] = $ManangeCollectionFields->getExistingFields();
- if(!isset($TemplateData['editData']['name'])) {
- $TemplateData['refresh'] = 'index.php?p=managecolletions';
- }
+ $TemplateData['editData'] = $ManangeCollections->getEditData($_id);
+ $ManangeCollectionFields->setCollection($_id);
+ $TemplateData['existingFields'] = $ManangeCollectionFields->getExistingFields();
+ if(!isset($TemplateData['editData']['name'])) {
+ $TemplateData['refresh'] = 'index.php?p=managecolletions';
+ }
}
$_saveData = array();
if(isset($_POST['submitForm'])) {
- $fdata = $_POST['fdata'];
- if (!empty($fdata)) {
- $_saveData['name'] = trim($fdata['name']);
- $_saveData['description'] = trim($fdata['description']);
- $_saveData['owner'] = trim($fdata['owner']);
- $_saveData['group'] = trim($fdata['group']);
- $_saveData['rights'] = Summoner::prepareRightsString($fdata['rights']);
- $_saveData['defaultSearchField'] = trim($fdata['defaultSearchField']);
- $_saveData['id'] = $_id;
+ $fdata = $_POST['fdata'];
+ if (!empty($fdata)) {
+ $_saveData['name'] = trim($fdata['name']);
+ $_saveData['description'] = trim($fdata['description']);
+ $_saveData['owner'] = trim($fdata['owner']);
+ $_saveData['group'] = trim($fdata['group']);
+ $_saveData['rights'] = Summoner::prepareRightsString($fdata['rights']);
+ $_saveData['defaultSearchField'] = trim($fdata['defaultSearchField']);
+ $_saveData['id'] = $_id;
- $_saveData['tool'] = array();
- if(isset($fdata['tool'])) {
- $_saveData['tool'] = $fdata['tool'];
- }
+ $_saveData['tool'] = array();
+ if(isset($fdata['tool'])) {
+ $_saveData['tool'] = $fdata['tool'];
+ }
- if(!empty($TemplateData['editData']['name'])) { // EDIT
- if(isset($fdata['doDelete'])) {
- $do = $ManangeCollections->deleteCollection($_id);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=managecolletions';
- } else {
- $TemplateData['message']['content'] = "Collection could not be deleted.";
- $TemplateData['message']['status'] = "error";
- }
- }
- else {
- if (Summoner::validate($_saveData['name'], 'nospace') === true
- && isset($TemplateData['groupSelection'][$_saveData['group']])
- && isset($TemplateData['ownerSelection'][$_saveData['owner']])
- ) {
- $do = $ManangeCollections->updateCollection($_saveData);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=managecolletions';
- } else {
- $TemplateData['message']['content'] = "Collection could not be updated.";
- $TemplateData['message']['status'] = "error";
- }
- } else {
- $TemplateData['message']['content'] = "Provide name, owner, group and valid rights.";
- $TemplateData['message']['status'] = "error";
- }
- }
- }
- else { // ADD
- if (!empty($_saveData['name']) && !empty($_saveData['owner']) && !empty($_saveData['group']) && !empty($_saveData['rights'])) {
- if (Summoner::validate($_saveData['name'], 'nospace') === true
- && isset($TemplateData['groupSelection'][$_saveData['group']])
- && isset($TemplateData['ownerSelection'][$_saveData['owner']])
- ) {
- $do = $ManangeCollections->createCollection($_saveData);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=managecolletions';
- } else {
- $TemplateData['message']['content'] = "Collection could not be created.";
- $TemplateData['message']['status'] = "error";
- }
- } else {
- $TemplateData['message']['content'] = "Provide name, owner, group and valid rights.";
- $TemplateData['message']['status'] = "error";
- }
- }
- }
+ if(!empty($TemplateData['editData']['name'])) { // EDIT
+ if(isset($fdata['doDelete'])) {
+ $do = $ManangeCollections->deleteCollection($_id);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=managecolletions';
+ } else {
+ $TemplateData['message']['content'] = "Collection could not be deleted.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ else {
+ if (Summoner::validate($_saveData['name'], 'nospace') === true
+ && isset($TemplateData['groupSelection'][$_saveData['group']])
+ && isset($TemplateData['ownerSelection'][$_saveData['owner']])
+ ) {
+ $do = $ManangeCollections->updateCollection($_saveData);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=managecolletions';
+ } else {
+ $TemplateData['message']['content'] = "Collection could not be updated.";
+ $TemplateData['message']['status'] = "error";
+ }
+ } else {
+ $TemplateData['message']['content'] = "Provide name, owner, group and valid rights.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ }
+ else { // ADD
+ if (!empty($_saveData['name']) && !empty($_saveData['owner']) && !empty($_saveData['group']) && !empty($_saveData['rights'])) {
+ if (Summoner::validate($_saveData['name'], 'nospace') === true
+ && isset($TemplateData['groupSelection'][$_saveData['group']])
+ && isset($TemplateData['ownerSelection'][$_saveData['owner']])
+ ) {
+ $do = $ManangeCollections->createCollection($_saveData);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=managecolletions';
+ } else {
+ $TemplateData['message']['content'] = "Collection could not be created.";
+ $TemplateData['message']['status'] = "error";
+ }
+ } else {
+ $TemplateData['message']['content'] = "Provide name, owner, group and valid rights.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ }
- }
+ }
}
<?php
$existingFieldValue = array();
if(Summoner::ifset($TemplateData['editData'], $field['identifier'])) {
- $existingFieldValue = $TemplateData['editData'][$field['identifier']];
+ $existingFieldValue = $TemplateData['editData'][$field['identifier']];
}
?>
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>-input"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <div class="input-multiple-listbox" id="<?php echo $field['identifier']; ?>-listbox">
- <?php
- if(!empty($existingFieldValue)) {
- foreach($existingFieldValue as $ev) { ?>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>-input"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <div class="input-multiple-listbox" id="<?php echo $field['identifier']; ?>-listbox">
+ <?php
+ if(!empty($existingFieldValue)) {
+ foreach($existingFieldValue as $ev) { ?>
- <div class="input-multiple-template" id="<?php echo $field['identifier']; ?>-<?php echo $ev; ?>">
- <a onclick="removeTag('<?php echo $ev; ?>','<?php echo $field['identifier']; ?>')" title="click to remove"><span class="uk-label"><?php echo $ev; ?></span></a>
- </div>
+ <div class="input-multiple-template" id="<?php echo $field['identifier']; ?>-<?php echo $ev; ?>">
+ <a onclick="removeTag('<?php echo $ev; ?>','<?php echo $field['identifier']; ?>')" title="click to remove"><span class="uk-label"><?php echo $ev; ?></span></a>
+ </div>
- <?php
- }
- }
- ?>
- </div>
- <input class="uk-input" id="<?php echo $field['identifier']; ?>-input" type="text" autocomplete="off"
- name="<?php echo $field['identifier']; ?>-input"
- list="<?php echo $field['identifier']; ?>-datalist"
- onkeypress="addTag(event,'<?php echo $field['identifier']; ?>')"
- placeholder="Write and press enter."
- >
- </div>
+ <?php
+ }
+ }
+ ?>
+ </div>
+ <input class="uk-input" id="<?php echo $field['identifier']; ?>-input" type="text" autocomplete="off"
+ name="<?php echo $field['identifier']; ?>-input"
+ list="<?php echo $field['identifier']; ?>-datalist"
+ onkeypress="addTag(event,'<?php echo $field['identifier']; ?>')"
+ placeholder="Write and press enter."
+ >
+ </div>
</div>
<datalist id="<?php echo $field['identifier']; ?>-datalist">
- <?php
- if(isset($field['suggestion'])) {
- foreach($field['suggestion'] as $t) {
- ?>
- <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
- <?php
- }
- }
- ?>
+ <?php
+ if(isset($field['suggestion'])) {
+ foreach($field['suggestion'] as $t) {
+ ?>
+ <option value="<?php echo $t; ?>"><?php echo $t; ?></option>
+ <?php
+ }
+ }
+ ?>
</datalist>
<input type="hidden" name="fdata[<?php echo $field['identifier']; ?>]" id="<?php echo $field['identifier']; ?>-save" value="<?php echo implode(',',$existingFieldValue); ?>" />
<div class="input-multiple-template" id="<?php echo $field['identifier']; ?>-template" style="display: none;">
- <a onclick="removeTag('','<?php echo $field['identifier']; ?>')" title="click to remove"><span class="uk-label"></span></a>
+ <a onclick="removeTag('','<?php echo $field['identifier']; ?>')" title="click to remove"><span class="uk-label"></span></a>
</div>
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <select class="uk-select" id="<?php echo $field['identifier']; ?>" name="fdata[<?php echo $field['identifier']; ?>]">
- <option value="">Please select</option>
- <?php foreach($field['options'] as $k=>$v) { ?>
- <option value="<?php echo $v; ?>"
- <?php if(Summoner::ifsetValue($TemplateData['editData'], $field['identifier'],$v)) echo 'selected'; ?>
- ><?php echo $v; ?></option>
- <?php } ?>
- </select>
- </div>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <select class="uk-select" id="<?php echo $field['identifier']; ?>" name="fdata[<?php echo $field['identifier']; ?>]">
+ <option value="">Please select</option>
+ <?php foreach($field['options'] as $k=>$v) { ?>
+ <option value="<?php echo $v; ?>"
+ <?php if(Summoner::ifsetValue($TemplateData['editData'], $field['identifier'],$v)) echo 'selected'; ?>
+ ><?php echo $v; ?></option>
+ <?php } ?>
+ </select>
+ </div>
</div>
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <input class="uk-input" id="<?php echo $field['identifier']; ?>" type="text" autocomplete="off"
- name="fdata[<?php echo $field['identifier']; ?>]"
- value="<?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?>"
- >
- </div>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="<?php echo $field['identifier']; ?>" type="text" autocomplete="off"
+ name="fdata[<?php echo $field['identifier']; ?>]"
+ value="<?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?>"
+ >
+ </div>
</div>
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <textarea class="uk-textarea" autocomplete="off"
- id="<?php echo $field['identifier']; ?>" rows="3"
- name="fdata[<?php echo $field['identifier']; ?>]"><?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?></textarea>
- </div>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <textarea class="uk-textarea" autocomplete="off"
+ id="<?php echo $field['identifier']; ?>" rows="3"
+ name="fdata[<?php echo $field['identifier']; ?>]"><?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?></textarea>
+ </div>
</div>
-
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <textarea class="uk-textarea" autocomplete="off"
- id="<?php echo $field['identifier']; ?>" rows="6"
- name="fdata[<?php echo $field['identifier']; ?>]"><?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?></textarea>
- </div>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <textarea class="uk-textarea" autocomplete="off"
+ id="<?php echo $field['identifier']; ?>" rows="6"
+ name="fdata[<?php echo $field['identifier']; ?>]"><?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?></textarea>
+ </div>
</div>
-
<div class="uk-margin">
- Missing template for: <?php echo $field['identifier']; ?>
+ Missing template for: <?php echo $field['identifier']; ?>
</div>
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <input type="file" id="<?php echo $field['identifier']; ?>" multiple="false"
- name="fdata[<?php echo $field['identifier']; ?>]"
- >
- <?php if(Summoner::ifset($TemplateData['editData'], $field['identifier'])) { ?>
- <div uk-lightbox>
- <?php echo '<a href="'.$TemplateData['storagePath'].'/'.Summoner::ifset($TemplateData['editData'], $field['identifier']).'">'.Summoner::ifset($TemplateData['editData'], $field['identifier']).'</a>'; ?>
- <input type="checkbox" value="<?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?>"
- name="fdata[<?php echo $field['identifier']; ?>_delete]"
- title="Delete"
- />
- </div>
- <?php } ?>
- </div>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <input type="file" id="<?php echo $field['identifier']; ?>" multiple="false"
+ name="fdata[<?php echo $field['identifier']; ?>]"
+ >
+ <?php if(Summoner::ifset($TemplateData['editData'], $field['identifier'])) { ?>
+ <div uk-lightbox>
+ <?php echo '<a href="'.$TemplateData['storagePath'].'/'.Summoner::ifset($TemplateData['editData'], $field['identifier']).'">'.Summoner::ifset($TemplateData['editData'], $field['identifier']).'</a>'; ?>
+ <input type="checkbox" value="<?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?>"
+ name="fdata[<?php echo $field['identifier']; ?>_delete]"
+ title="Delete"
+ />
+ </div>
+ <?php } ?>
+ </div>
</div>
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <input type="file" id="<?php echo $field['identifier']; ?>" multiple="true"
- name="fdata[<?php echo $field['identifier']; ?>][]"
- >
- <div uk-lightbox>
- <?php
- if(isset($TemplateData['editData']) && !empty($TemplateData['editData'][$field['identifier']])) {
- foreach($TemplateData['editData'][$field['identifier']] as $e) {
- ?>
- <a target="_blank" href="<?php echo $TemplateData['storagePath'].'/'.$e; ?>"><?php echo $e; ?></a>
- <input type="checkbox" value="<?php echo $e; ?>"
- name="fdata[<?php echo $field['identifier']; ?>_delete][]"
- title="Delete"
- />
- <br>
- <?php
- }
- }
- ?>
- </div>
- </div>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <input type="file" id="<?php echo $field['identifier']; ?>" multiple="true"
+ name="fdata[<?php echo $field['identifier']; ?>][]"
+ >
+ <div uk-lightbox>
+ <?php
+ if(isset($TemplateData['editData']) && !empty($TemplateData['editData'][$field['identifier']])) {
+ foreach($TemplateData['editData'][$field['identifier']] as $e) {
+ ?>
+ <a target="_blank" href="<?php echo $TemplateData['storagePath'].'/'.$e; ?>"><?php echo $e; ?></a>
+ <input type="checkbox" value="<?php echo $e; ?>"
+ name="fdata[<?php echo $field['identifier']; ?>_delete][]"
+ title="Delete"
+ />
+ <br>
+ <?php
+ }
+ }
+ ?>
+ </div>
+ </div>
</div>
<div class="uk-margin">
- <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
- <div class="uk-form-controls">
- <input class="uk-input" id="<?php echo $field['identifier']; ?>" type="number" autocomplete="off"
- placeholder="YYYY" min="0000" max="9999"
- name="fdata[<?php echo $field['identifier']; ?>]"
- value="<?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?>"
- >
- </div>
+ <label class="uk-form-label" for="<?php echo $field['identifier']; ?>"><?php echo $field['displayname']; ?></label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="<?php echo $field['identifier']; ?>" type="number" autocomplete="off"
+ placeholder="YYYY" min="0000" max="9999"
+ name="fdata[<?php echo $field['identifier']; ?>]"
+ value="<?php echo Summoner::ifset($TemplateData['editData'], $field['identifier']); ?>"
+ >
+ </div>
</div>
$_collection = false;
if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
}
$_id = false;
if(isset($_GET['id']) && !empty($_GET['id'])) {
- $_id = trim($_GET['id']);
- $_id = Summoner::validate($_id,'digit') ? $_id : false;
+ $_id = trim($_GET['id']);
+ $_id = Summoner::validate($_id,'digit') ? $_id : false;
}
if(!empty($_collection)) {
- $setCollection = $ManangeCollections->getCollection($_collection, "write");
+ $setCollection = $ManangeCollections->getCollection($_collection, "write");
- if(!empty($setCollection)) {
- $ManangeEntry->setCollection($_collection);
- $TemplateData['loadedCollection'] = $setCollection;
+ if(!empty($setCollection)) {
+ $ManangeEntry->setCollection($_collection);
+ $TemplateData['loadedCollection'] = $setCollection;
- $TemplateData['editFields'] = $ManangeEntry->getEditFields();
- $TemplateData['availableTools'] = $ManangeCollections->getAvailableTools($_collection);
+ $TemplateData['editFields'] = $ManangeEntry->getEditFields();
+ $TemplateData['availableTools'] = $ManangeCollections->getAvailableTools($_collection);
- if(!empty($_id)) {
- $TemplateData['storagePath'] = PATH_WEB_STORAGE . '/' . $_collection . '/' . $_id;
+ if(!empty($_id)) {
+ $TemplateData['storagePath'] = PATH_WEB_STORAGE . '/' . $_collection . '/' . $_id;
- // prefill template data. Used also later to check if on edit mode
- $TemplateData['editData'] = $ManangeEntry->getEditData($_id);
- // special case. Title field should be always available.
- if(!isset($TemplateData['editData']['title'])) {
- $TemplateData['message']['content'] = "Entry has no value in title field.";
- $TemplateData['message']['status'] = "error";
- }
- }
+ // prefill template data. Used also later to check if on edit mode
+ $TemplateData['editData'] = $ManangeEntry->getEditData($_id);
+ // special case. Title field should be always available.
+ if(!isset($TemplateData['editData']['title'])) {
+ $TemplateData['message']['content'] = "Entry has no value in title field.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
- if(isset($_POST['submitForm'])) {
- $fdata = $_POST['fdata'];
- $fupload = array('name' => ''); // match $_FILES
- if(!empty($_FILES) && isset($_FILES['fdata'])) {
- $fupload = $_FILES['fdata'];
- }
- $_fieldsToSave = array();
- if (!empty($fdata)) {
- // @todo there is no setting for individual rights available yet
- $_owner = $Doomguy->param('id');
- $_group = $Doomguy->param('baseGroupId');
- $_rights = 'rwxrwxr--';
+ if(isset($_POST['submitForm'])) {
+ $fdata = $_POST['fdata'];
+ $fupload = array('name' => ''); // match $_FILES
+ if(!empty($_FILES) && isset($_FILES['fdata'])) {
+ $fupload = $_FILES['fdata'];
+ }
+ $_fieldsToSave = array();
+ if (!empty($fdata)) {
+ // @todo there is no setting for individual rights available yet
+ $_owner = $Doomguy->param('id');
+ $_group = $Doomguy->param('baseGroupId');
+ $_rights = 'rwxrwxr--';
- foreach ($TemplateData['editFields'] as $fieldId=>$fieldData) {
- if(isset($fdata[$fieldData['identifier']])) {
- $_value = trim($fdata[$fieldData['identifier']]);
- $fieldData['valueToSave'] = trim($fdata[$fieldData['identifier']]);
- $_fieldsToSave[$fieldData['identifier']] = $fieldData;
- } elseif(isset($fupload['name'][$fieldData['identifier']])) {
- if(isset($fdata[$fieldData['identifier']."_delete"])) {
- $fieldData['deleteData'] = $fdata[$fieldData['identifier']."_delete"];
- }
- // special case upload
- // $_FILES data is combinend
- $fieldData['uploadData'] = $fupload;
+ foreach ($TemplateData['editFields'] as $fieldId=>$fieldData) {
+ if(isset($fdata[$fieldData['identifier']])) {
+ $_value = trim($fdata[$fieldData['identifier']]);
+ $fieldData['valueToSave'] = trim($fdata[$fieldData['identifier']]);
+ $_fieldsToSave[$fieldData['identifier']] = $fieldData;
+ } elseif(isset($fupload['name'][$fieldData['identifier']])) {
+ if(isset($fdata[$fieldData['identifier']."_delete"])) {
+ $fieldData['deleteData'] = $fdata[$fieldData['identifier']."_delete"];
+ }
+ // special case upload
+ // $_FILES data is combinend
+ $fieldData['uploadData'] = $fupload;
- $_fieldsToSave[$fieldData['identifier']] = $fieldData;
- }
- }
+ $_fieldsToSave[$fieldData['identifier']] = $fieldData;
+ }
+ }
- // special case. Title field should be always available.
- if(!empty($TemplateData['editData']['title'])) { // EDIT
- if(isset($fdata['doDelete'])) {
- $do = $ManangeEntry->delete($_id);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=collections&collection='.$_collection;
- } else {
- $TemplateData['message']['content'] = "Entry could not be removed.";
- $TemplateData['message']['status'] = "error";
- }
- } elseif (!empty($_fieldsToSave) && isset($_fieldsToSave['title'])) {
- $do = $ManangeEntry->create($_fieldsToSave, $_owner, $_group, $_rights, $_id);
- if ($do !== 0) {
- $TemplateData['refresh'] = 'index.php?p=manageentry&collection='.$_collection.'&id='.$_id;
- } else {
- $TemplateData['message']['content'] = "Entry could not be updated.";
- $TemplateData['message']['status'] = "error";
- }
- }
- }
- else { // ADD
- // special case. Title field should be always available.
- if (!empty($_fieldsToSave) && isset($_fieldsToSave['title'])) {
- $do = $ManangeEntry->create($_fieldsToSave, $_owner, $_group, $_rights);
- if (!empty($do)) {
- $TemplateData['message']['content'] = "New entry: <a href='index.php?p=manageentry&collection=".$_collection."&id=".$do."'>".$do."</a>";
- $TemplateData['message']['status'] = "success";
- } else {
- // use editData to display given data
- $TemplateData['editData'] = $fdata;
- $TemplateData['message']['content'] = "Entry could not be added.";
- $TemplateData['message']['status'] = "error";
- }
- } else {
- // use editData to display given data
- $TemplateData['editData'] = $fdata;
- $TemplateData['message']['content'] = "Provide at least 'Title'.";
- $TemplateData['message']['status'] = "error";
- }
- }
- }
- }
- }
- else {
- $TemplateData['message']['content'] = "Collection could not be loaded.";
- $TemplateData['message']['status'] = "error";
- }
+ // special case. Title field should be always available.
+ if(!empty($TemplateData['editData']['title'])) { // EDIT
+ if(isset($fdata['doDelete'])) {
+ $do = $ManangeEntry->delete($_id);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=collections&collection='.$_collection;
+ } else {
+ $TemplateData['message']['content'] = "Entry could not be removed.";
+ $TemplateData['message']['status'] = "error";
+ }
+ } elseif (!empty($_fieldsToSave) && isset($_fieldsToSave['title'])) {
+ $do = $ManangeEntry->create($_fieldsToSave, $_owner, $_group, $_rights, $_id);
+ if ($do !== 0) {
+ $TemplateData['refresh'] = 'index.php?p=manageentry&collection='.$_collection.'&id='.$_id;
+ } else {
+ $TemplateData['message']['content'] = "Entry could not be updated.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ }
+ else { // ADD
+ // special case. Title field should be always available.
+ if (!empty($_fieldsToSave) && isset($_fieldsToSave['title'])) {
+ $do = $ManangeEntry->create($_fieldsToSave, $_owner, $_group, $_rights);
+ if (!empty($do)) {
+ $TemplateData['message']['content'] = "New entry: <a href='index.php?p=manageentry&collection=".$_collection."&id=".$do."'>".$do."</a>";
+ $TemplateData['message']['status'] = "success";
+ } else {
+ // use editData to display given data
+ $TemplateData['editData'] = $fdata;
+ $TemplateData['message']['content'] = "Entry could not be added.";
+ $TemplateData['message']['status'] = "error";
+ }
+ } else {
+ // use editData to display given data
+ $TemplateData['editData'] = $fdata;
+ $TemplateData['message']['content'] = "Provide at least 'Title'.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ }
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "Collection could not be loaded.";
+ $TemplateData['message']['status'] = "error";
+ }
}
<h3 class="uk-h3">User management</h3>
<div class="uk-grid-small uk-grid-row-small uk-grid-row-small" uk-grid>
- <div class="uk-width-1-2">
- <h4 class="uk-h4">Add or modify a user</h4>
- <form class="uk-form-horizontal uk-margin-small" method="post">
- <div class="uk-margin">
- <label class="uk-form-label" for="username">Username</label>
- <div class="uk-form-controls">
- <input class="uk-input" id="username" type="text" autocomplete="off" name="fdata[username]"
- value="<?php echo Summoner::ifset($TemplateData['editData'], 'name'); ?>">
- </div>
- </div>
- <div class="uk-margin">
- <label class="uk-form-label" for="login">Login</label>
- <div class="uk-form-controls">
- <input class="uk-input" id="login" type="text" autocomplete="off" name="fdata[login]"
- value="<?php echo Summoner::ifset($TemplateData['editData'], 'login'); ?>">
- </div>
- </div>
- <div class="uk-margin">
- <label class="uk-form-label" for="password">Password</label>
- <div class="uk-form-controls">
- <input class="uk-input" id="password" type="password" autocomplete="off" name="fdata[password]">
- </div>
- </div>
- <div class="uk-margin">
- <label class="uk-form-label" for="group">Main group</label>
- <div class="uk-form-controls">
- <select class="uk-select" id="group" name="fdata[group]">
- <option value="">Please select</option>
- <?php foreach($TemplateData['existingGroups'] as $k=>$v) { ?>
- <option value="<?php echo $k; ?>"
- <?php if(Summoner::ifsetValue($TemplateData['editData'], 'baseGroupId',$k)) echo 'selected'; ?>
- ><?php echo $v['name']; ?> (<?php echo $v['description']; ?>)</option>
- <?php } ?>
- </select>
- </div>
- </div>
- <div class="uk-margin">
- <label class="uk-form-label" for="group">Additional groups</label>
- <div class="uk-form-controls">
- <select class="uk-select" id="additionalgroups" name="fdata[additionalgroups]">
- <option value="">To be done</option>
- </select>
- </div>
- </div>
- <div class="uk-margin">
- <div class="uk-form-label">Can login</div>
- <div class="uk-form-controls uk-form-controls-text">
- <label>
- <input class="uk-checkbox" type="checkbox" name="fdata[active]" value="1"
- <?php if(Summoner::ifset($TemplateData['editData'], 'active')) echo "checked"; ?>>
- </label>
- </div>
- </div>
- <?php if(Summoner::ifset($TemplateData['editData'], 'name')) { ?>
- <div class="uk-margin">
- <div class="uk-form-label">Delete <span uk-icon="warning"></span></div>
- <div class="uk-form-controls uk-form-controls-text">
- <label>
- <input class="uk-checkbox" type="checkbox" name="fdata[doDelete]" value="1">
- </label>
- </div>
- </div>
- <div class="uk-margin">
- <div class="uk-form-label">Create API Token</div>
- <div class="uk-form-controls uk-form-controls-text">
- <label>
- <input class="uk-checkbox" type="checkbox" name="fdata[refreshApiToken]" value="1"><br />
- Valid until: <?php echo Summoner::ifset($TemplateData['editData'], 'apiTokenValidDate'); ?><br />
- <?php echo Summoner::ifset($TemplateData['editData'], 'apiToken'); ?>
- </label>
- </div>
- </div>
- <?php } ?>
- <div class="uk-margin">
- <button class="uk-button uk-button-primary" type="submit" name="submitForm">
- Save
- </button>
- </div>
- </form>
- </div>
- <div class="uk-width-1-2">
- <h4 class="uk-h4">Available users</h4>
- <table class="uk-table">
- <thead>
- <tr>
- <th>Login</th>
- <th>Username</th>
- <th>Group(s)</th>
- <th>Status</th>
- <th></th>
- </tr>
- </thead>
- <tbody>
- <?php foreach($TemplateData['existingUsers'] as $k=>$v) { ?>
- <tr>
- <td>
- <?php echo $v['login']; ?><br/>
- <small><?php echo $v['created']; ?></small>
- </td>
- <td><?php echo $v['name']; ?></td>
- <td>
- <ul class="uk-list uk-list-disc uk-list-collapse">
- <?php foreach($v['groups'] as $gk=>$gv) { ?>
- <li class="<?php if($gk == $v['baseGroupId']) echo 'uk-text-emphasis'; ?>">
- <?php echo $gv['groupName']; ?>
- </li>
- <?php } ?>
- </ul>
- </td>
- <td><?php echo $v['active']; ?></td>
- <td>
- <?php if($v['protected'] == "0") { ?>
- <a href="index.php?p=manageusers&m=edit&id=<?php echo $k; ?>" uk-icon="pencil"></a>
- <?php } ?>
- </td>
- </tr>
- <?php } ?>
- </tbody>
- </table>
+ <div class="uk-width-1-2">
+ <h4 class="uk-h4">Add or modify a user</h4>
+ <form class="uk-form-horizontal uk-margin-small" method="post">
+ <div class="uk-margin">
+ <label class="uk-form-label" for="username">Username</label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="username" type="text" autocomplete="off" name="fdata[username]"
+ value="<?php echo Summoner::ifset($TemplateData['editData'], 'name'); ?>">
+ </div>
+ </div>
+ <div class="uk-margin">
+ <label class="uk-form-label" for="login">Login</label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="login" type="text" autocomplete="off" name="fdata[login]"
+ value="<?php echo Summoner::ifset($TemplateData['editData'], 'login'); ?>">
+ </div>
+ </div>
+ <div class="uk-margin">
+ <label class="uk-form-label" for="password">Password</label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="password" type="password" autocomplete="off" name="fdata[password]">
+ </div>
+ </div>
+ <div class="uk-margin">
+ <label class="uk-form-label" for="group">Main group</label>
+ <div class="uk-form-controls">
+ <select class="uk-select" id="group" name="fdata[group]">
+ <option value="">Please select</option>
+ <?php foreach($TemplateData['existingGroups'] as $k=>$v) { ?>
+ <option value="<?php echo $k; ?>"
+ <?php if(Summoner::ifsetValue($TemplateData['editData'], 'baseGroupId',$k)) echo 'selected'; ?>
+ ><?php echo $v['name']; ?> (<?php echo $v['description']; ?>)</option>
+ <?php } ?>
+ </select>
+ </div>
+ </div>
+ <div class="uk-margin">
+ <label class="uk-form-label" for="group">Additional groups</label>
+ <div class="uk-form-controls">
+ <select class="uk-select" id="additionalgroups" name="fdata[additionalgroups]">
+ <option value="">To be done</option>
+ </select>
+ </div>
+ </div>
+ <div class="uk-margin">
+ <div class="uk-form-label">Can login</div>
+ <div class="uk-form-controls uk-form-controls-text">
+ <label>
+ <input class="uk-checkbox" type="checkbox" name="fdata[active]" value="1"
+ <?php if(Summoner::ifset($TemplateData['editData'], 'active')) echo "checked"; ?>>
+ </label>
+ </div>
+ </div>
+ <?php if(Summoner::ifset($TemplateData['editData'], 'name')) { ?>
+ <div class="uk-margin">
+ <div class="uk-form-label">Delete <span uk-icon="warning"></span></div>
+ <div class="uk-form-controls uk-form-controls-text">
+ <label>
+ <input class="uk-checkbox" type="checkbox" name="fdata[doDelete]" value="1">
+ </label>
+ </div>
+ </div>
+ <div class="uk-margin">
+ <div class="uk-form-label">Create API Token</div>
+ <div class="uk-form-controls uk-form-controls-text">
+ <label>
+ <input class="uk-checkbox" type="checkbox" name="fdata[refreshApiToken]" value="1"><br />
+ Valid until: <?php echo Summoner::ifset($TemplateData['editData'], 'apiTokenValidDate'); ?><br />
+ <?php echo Summoner::ifset($TemplateData['editData'], 'apiToken'); ?>
+ </label>
+ </div>
+ </div>
+ <?php } ?>
+ <div class="uk-margin">
+ <button class="uk-button uk-button-primary" type="submit" name="submitForm">
+ Save
+ </button>
+ </div>
+ </form>
+ </div>
+ <div class="uk-width-1-2">
+ <h4 class="uk-h4">Available users</h4>
+ <table class="uk-table">
+ <thead>
+ <tr>
+ <th>Login</th>
+ <th>Username</th>
+ <th>Group(s)</th>
+ <th>Status</th>
+ <th></th>
+ </tr>
+ </thead>
+ <tbody>
+ <?php foreach($TemplateData['existingUsers'] as $k=>$v) { ?>
+ <tr>
+ <td>
+ <?php echo $v['login']; ?><br/>
+ <small><?php echo $v['created']; ?></small>
+ </td>
+ <td><?php echo $v['name']; ?></td>
+ <td>
+ <ul class="uk-list uk-list-disc uk-list-collapse">
+ <?php foreach($v['groups'] as $gk=>$gv) { ?>
+ <li class="<?php if($gk == $v['baseGroupId']) echo 'uk-text-emphasis'; ?>">
+ <?php echo $gv['groupName']; ?>
+ </li>
+ <?php } ?>
+ </ul>
+ </td>
+ <td><?php echo $v['active']; ?></td>
+ <td>
+ <?php if($v['protected'] == "0") { ?>
+ <a href="index.php?p=manageusers&m=edit&id=<?php echo $k; ?>" uk-icon="pencil"></a>
+ <?php } ?>
+ </td>
+ </tr>
+ <?php } ?>
+ </tbody>
+ </table>
- </div>
+ </div>
</div>
$_editMode = false;
if(isset($_GET['m']) && !empty($_GET['m'])) {
- if($_GET['m'] == "edit") {
- $_editMode = true;
- }
+ if($_GET['m'] == "edit") {
+ $_editMode = true;
+ }
}
$_id = false;
if(isset($_GET['id']) && !empty($_GET['id'])) {
- $_id = trim($_GET['id']);
- $_id = Summoner::validate($_id,'digit') ? $_id : false;
+ $_id = trim($_GET['id']);
+ $_id = Summoner::validate($_id,'digit') ? $_id : false;
}
if($_editMode === true && !empty($_id)) {
- $TemplateData['editData'] = $Possessed->getEditData($_id);
- if(!isset($TemplateData['editData']['name'])) {
- $TemplateData['refresh'] = 'index.php?p=manageusers';
- }
+ $TemplateData['editData'] = $Possessed->getEditData($_id);
+ if(!isset($TemplateData['editData']['name'])) {
+ $TemplateData['refresh'] = 'index.php?p=manageusers';
+ }
}
if(isset($_POST['submitForm'])) {
- $fdata = $_POST['fdata'];
- if(!empty($fdata)) {
+ $fdata = $_POST['fdata'];
+ if(!empty($fdata)) {
- $_login = trim($fdata['login']);
- $_group = trim($fdata['group']);
- $_username = trim($fdata['username']);
- $_password = trim($fdata['password']);
- $_active = false;
- if (isset($fdata['active'])) {
- $_active = true;
- }
+ $_login = trim($fdata['login']);
+ $_group = trim($fdata['group']);
+ $_username = trim($fdata['username']);
+ $_password = trim($fdata['password']);
+ $_active = false;
+ if (isset($fdata['active'])) {
+ $_active = true;
+ }
- if(!empty($TemplateData['editData'])) {
- if(isset($fdata['doDelete'])) {
- $do = $Possessed->deleteUser($_id);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=manageusers';
- } else {
- $TemplateData['message']['content'] = "User could not be deleted.";
- $TemplateData['message']['status'] = "error";
- }
- }
- elseif (!empty($_username) && !empty($_group) && !empty($_login)) {
- if (Summoner::validate($_username, 'text') === true
- && Summoner::validate($_login, 'nospace') === true
- && isset($TemplateData['existingGroups'][$_group])
- ) {
- $refreshApi = false;
- if(isset($fdata['refreshApiToken'])) {
- $refreshApi = true;
- }
- $do = $Possessed->updateUser($_id, $_username, $_login, $_password, $_group, $_active, $refreshApi);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=manageusers';
- } else {
- $TemplateData['message']['content'] = "User could not be updated.";
- $TemplateData['message']['status'] = "error";
- }
- } else {
- $TemplateData['message']['content'] = "Provide username, login and a valid user group.";
- $TemplateData['message']['status'] = "error";
- }
- }
- }
- else { // adding mode
- if (!empty($_username) && !empty($_password) && !empty($_group) && !empty($_login)) {
- if (Summoner::validate($_username, 'text') === true
- && Summoner::validate($_password, 'text') === true
- && Summoner::validate($_login, 'nospace') === true
- && isset($TemplateData['existingGroups'][$_group])
- ) {
- $do = $Possessed->createUser($_username, $_login, $_password, $_group, $_active);
- if ($do === true) {
- $TemplateData['refresh'] = 'index.php?p=manageusers';
- } else {
- $TemplateData['message']['content'] = "User could not be created.";
- $TemplateData['message']['status'] = "error";
- }
- } else {
- $TemplateData['message']['content'] = "Provide username, login, password and a valid user group.";
- $TemplateData['message']['status'] = "error";
- }
- }
- }
- }
+ if(!empty($TemplateData['editData'])) {
+ if(isset($fdata['doDelete'])) {
+ $do = $Possessed->deleteUser($_id);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=manageusers';
+ } else {
+ $TemplateData['message']['content'] = "User could not be deleted.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ elseif (!empty($_username) && !empty($_group) && !empty($_login)) {
+ if (Summoner::validate($_username, 'text') === true
+ && Summoner::validate($_login, 'nospace') === true
+ && isset($TemplateData['existingGroups'][$_group])
+ ) {
+ $refreshApi = false;
+ if(isset($fdata['refreshApiToken'])) {
+ $refreshApi = true;
+ }
+ $do = $Possessed->updateUser($_id, $_username, $_login, $_password, $_group, $_active, $refreshApi);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=manageusers';
+ } else {
+ $TemplateData['message']['content'] = "User could not be updated.";
+ $TemplateData['message']['status'] = "error";
+ }
+ } else {
+ $TemplateData['message']['content'] = "Provide username, login and a valid user group.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ }
+ else { // adding mode
+ if (!empty($_username) && !empty($_password) && !empty($_group) && !empty($_login)) {
+ if (Summoner::validate($_username, 'text') === true
+ && Summoner::validate($_password, 'text') === true
+ && Summoner::validate($_login, 'nospace') === true
+ && isset($TemplateData['existingGroups'][$_group])
+ ) {
+ $do = $Possessed->createUser($_username, $_login, $_password, $_group, $_active);
+ if ($do === true) {
+ $TemplateData['refresh'] = 'index.php?p=manageusers';
+ } else {
+ $TemplateData['message']['content'] = "User could not be created.";
+ $TemplateData['message']['status'] = "error";
+ }
+ } else {
+ $TemplateData['message']['content'] = "Provide username, login, password and a valid user group.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ }
+ }
}
$_menuManage = $Gorenest->get('manage');
?>
<nav class="uk-navbar-container" uk-navbar>
- <div class="uk-navbar-left">
- <ul class="uk-navbar-nav">
- <li class="uk-parent">
- <a href="">Show</a>
- <div class="uk-navbar-dropdown">
- <ul class="uk-nav uk-navbar-dropdown-nav">
- <?php foreach($_menuShow as $entry) { ?>
- <li>
- <a href="index.php?p=<?php echo $entry['action']; ?>">
- <span class="uk-icon uk-margin-small-right" uk-icon="icon: <?php echo $entry['icon']; ?>"></span>
- <?php echo $entry['text']; ?>
- </a>
- </li>
- <?php } ?>
- </ul>
- </div>
- </li>
- <?php if(!empty($_menuManage)) { ?>
- <li class="uk-parent">
- <a href="">Manage</a>
- <div class="uk-navbar-dropdown">
- <ul class="uk-nav uk-navbar-dropdown-nav">
- <?php foreach($_menuManage as $entry) { ?>
- <li>
- <a href="index.php?p=<?php echo $entry['action']; ?>">
- <span class="uk-icon uk-margin-small-right" uk-icon="icon: <?php echo $entry['icon']; ?>"></span>
- <?php echo $entry['text']; ?>
- </a>
- </li>
- <?php } ?>
- </ul>
- </div>
- </li>
- <?php } ?>
- <li>
- <a href="index.php?p=auth">
- <?php if($Doomguy->isSignedIn() === true) { echo "Logout"; } else { echo "Login"; } ?>
- </a>
- </li>
- </ul>
- </div>
- <div class="uk-navbar-right">
- <div>
- <a class="uk-navbar-toggle" uk-search-icon href="#"></a>
- <div class="uk-drop" uk-drop="mode: click; pos: left-center; offset: 0">
- <form class="uk-search uk-search-navbar uk-width-1-1" method="post" action="<?php echo $TemplateData['searchAction']; ?>">
- <input class="uk-search-input" type="search" placeholder="Search..." name="navSearch" autofocus>
- </form>
- </div>
- </div>
- </div>
+ <div class="uk-navbar-left">
+ <ul class="uk-navbar-nav">
+ <li class="uk-parent">
+ <a href="">Show</a>
+ <div class="uk-navbar-dropdown">
+ <ul class="uk-nav uk-navbar-dropdown-nav">
+ <?php foreach($_menuShow as $entry) { ?>
+ <li>
+ <a href="index.php?p=<?php echo $entry['action']; ?>">
+ <span class="uk-icon uk-margin-small-right" uk-icon="icon: <?php echo $entry['icon']; ?>"></span>
+ <?php echo $entry['text']; ?>
+ </a>
+ </li>
+ <?php } ?>
+ </ul>
+ </div>
+ </li>
+ <?php if(!empty($_menuManage)) { ?>
+ <li class="uk-parent">
+ <a href="">Manage</a>
+ <div class="uk-navbar-dropdown">
+ <ul class="uk-nav uk-navbar-dropdown-nav">
+ <?php foreach($_menuManage as $entry) { ?>
+ <li>
+ <a href="index.php?p=<?php echo $entry['action']; ?>">
+ <span class="uk-icon uk-margin-small-right" uk-icon="icon: <?php echo $entry['icon']; ?>"></span>
+ <?php echo $entry['text']; ?>
+ </a>
+ </li>
+ <?php } ?>
+ </ul>
+ </div>
+ </li>
+ <?php } ?>
+ <li>
+ <a href="index.php?p=auth">
+ <?php if($Doomguy->isSignedIn() === true) { echo "Logout"; } else { echo "Login"; } ?>
+ </a>
+ </li>
+ </ul>
+ </div>
+ <div class="uk-navbar-right">
+ <div>
+ <a class="uk-navbar-toggle" uk-search-icon href="#"></a>
+ <div class="uk-drop" uk-drop="mode: click; pos: left-center; offset: 0">
+ <form class="uk-search uk-search-navbar uk-width-1-1" method="post" action="<?php echo $TemplateData['searchAction']; ?>">
+ <input class="uk-search-input" type="search" placeholder="Search..." name="navSearch" autofocus>
+ </form>
+ </div>
+ </div>
+ </div>
</nav>
*/
if(isset($TemplateData['message']['content'])) {
- $cssClass = 'primary';
- if(isset($TemplateData['message']['status'])) {
- switch($TemplateData['message']['status']) {
- case 'error':
- $cssClass = 'danger';
- break;
- case 'warning':
- $cssClass = 'warning';
- break;
- case 'success':
- $cssClass = 'success';
- break;
+ $cssClass = 'primary';
+ if(isset($TemplateData['message']['status'])) {
+ switch($TemplateData['message']['status']) {
+ case 'error':
+ $cssClass = 'danger';
+ break;
+ case 'warning':
+ $cssClass = 'warning';
+ break;
+ case 'success':
+ $cssClass = 'success';
+ break;
- case 'info':
- default:
+ case 'info':
+ default:
- }
- }
+ }
+ }
?>
<div class="uk-alert-<?php echo $cssClass; ?>" uk-alert>
- <p><?php echo $TemplateData['message']['content']; ?></p>
+ <p><?php echo $TemplateData['message']['content']; ?></p>
</div>
<?php } ?>
<?php if(!empty($TemplateData['pagination']) && $TemplateData['pagination']['pages'] > 1) { ?>
<ul class="uk-pagination" uk-margin>
- <?php
- if($TemplateData['pagination']['curPage'] > 1) {
- echo '<li><a href="index.php?'.Summoner::createFromParameterLinkQuery($TemplateData['pagination']['currentGetParameters'],array('page'=>($TemplateData['pagination']['curPage']-1))).'">
- <span uk-pagination-previous></span></a></li>';
- }
+ <?php
+ if($TemplateData['pagination']['curPage'] > 1) {
+ echo '<li><a href="index.php?'.Summoner::createFromParameterLinkQuery($TemplateData['pagination']['currentGetParameters'],array('page'=>($TemplateData['pagination']['curPage']-1))).'">
+ <span uk-pagination-previous></span></a></li>';
+ }
- $ellipsisShown = 0;
- for($i=1;$i<=$TemplateData['pagination']['pages'];$i++) {
- $active = '';
- if($i == $TemplateData['pagination']['curPage']) $active = 'uk-active';
+ $ellipsisShown = 0;
+ for($i=1;$i<=$TemplateData['pagination']['pages'];$i++) {
+ $active = '';
+ if($i == $TemplateData['pagination']['curPage']) $active = 'uk-active';
- if(in_array($i,$TemplateData['pagination']['visibleRange'])) {
- echo '<li class="'.$active.'"><a href="index.php?'.Summoner::createFromParameterLinkQuery($TemplateData['pagination']['currentGetParameters'],array('page'=>$i)).'"
- title="Goto page '.$i.'">'.$i.'</a></li>';
- }
- else {
- if($i < $TemplateData['pagination']['currentRangeStart'] && $ellipsisShown == 0) {
- echo '<li class="uk-disabled"><span>…</span></li>';
- $ellipsisShown = 1;
- }
- if($i > $TemplateData['pagination']['currentRangeEnd'] && ($ellipsisShown == 0 || $ellipsisShown == 1)) {
- echo '<li class="uk-disabled"><span>…</span></li>';
- $ellipsisShown = 2;
- }
- }
- }
+ if(in_array($i,$TemplateData['pagination']['visibleRange'])) {
+ echo '<li class="'.$active.'"><a href="index.php?'.Summoner::createFromParameterLinkQuery($TemplateData['pagination']['currentGetParameters'],array('page'=>$i)).'"
+ title="Goto page '.$i.'">'.$i.'</a></li>';
+ }
+ else {
+ if($i < $TemplateData['pagination']['currentRangeStart'] && $ellipsisShown == 0) {
+ echo '<li class="uk-disabled"><span>…</span></li>';
+ $ellipsisShown = 1;
+ }
+ if($i > $TemplateData['pagination']['currentRangeEnd'] && ($ellipsisShown == 0 || $ellipsisShown == 1)) {
+ echo '<li class="uk-disabled"><span>…</span></li>';
+ $ellipsisShown = 2;
+ }
+ }
+ }
- if($TemplateData['pagination']['curPage'] < $TemplateData['pagination']['pages']) {
- echo '<li><a href="index.php?'.Summoner::createFromParameterLinkQuery($TemplateData['pagination']['currentGetParameters'],array('page'=>($TemplateData['pagination']['curPage']+1))).'">
- <span uk-pagination-next></span></a></li>';
- }
- ?>
+ if($TemplateData['pagination']['curPage'] < $TemplateData['pagination']['pages']) {
+ echo '<li><a href="index.php?'.Summoner::createFromParameterLinkQuery($TemplateData['pagination']['currentGetParameters'],array('page'=>($TemplateData['pagination']['curPage']+1))).'">
+ <span uk-pagination-next></span></a></li>';
+ }
+ ?>
</ul>
<?php } ?>
// $TemplateData['pagination']
if(!empty($TemplateData['entries']['amount'])) {
- $TemplateData['pagination']['pages'] = ceil($TemplateData['entries']['amount'] / RESULTS_PER_PAGE);
- $TemplateData['pagination']['curPage'] = $_curPage;
+ $TemplateData['pagination']['pages'] = ceil($TemplateData['entries']['amount'] / RESULTS_PER_PAGE);
+ $TemplateData['pagination']['curPage'] = $_curPage;
- $TemplateData['pagination']['currentGetParameters']['page'] = $_curPage;
+ $TemplateData['pagination']['currentGetParameters']['page'] = $_curPage;
}
if($TemplateData['pagination']['pages'] > 11) {
- # first pages
- $TemplateData['pagination']['visibleRange'] = range(1,3);
- # last pages
- foreach(range($TemplateData['pagination']['pages']-2, $TemplateData['pagination']['pages']) as $e) {
- array_push($TemplateData['pagination']['visibleRange'], $e);
- }
- # pages before and after current page
- $cRange = range($TemplateData['pagination']['curPage']-1, $TemplateData['pagination']['curPage']+1);
- foreach($cRange as $e) {
- array_push($TemplateData['pagination']['visibleRange'], $e);
- }
- $TemplateData['pagination']['currentRangeStart'] = array_shift($cRange);
- $TemplateData['pagination']['currentRangeEnd'] = array_pop($cRange);
+ # first pages
+ $TemplateData['pagination']['visibleRange'] = range(1,3);
+ # last pages
+ foreach(range($TemplateData['pagination']['pages']-2, $TemplateData['pagination']['pages']) as $e) {
+ array_push($TemplateData['pagination']['visibleRange'], $e);
+ }
+ # pages before and after current page
+ $cRange = range($TemplateData['pagination']['curPage']-1, $TemplateData['pagination']['curPage']+1);
+ foreach($cRange as $e) {
+ array_push($TemplateData['pagination']['visibleRange'], $e);
+ }
+ $TemplateData['pagination']['currentRangeStart'] = array_shift($cRange);
+ $TemplateData['pagination']['currentRangeEnd'] = array_pop($cRange);
}
else {
- $TemplateData['pagination']['visibleRange'] = range(1,$TemplateData['pagination']['pages']);
+ $TemplateData['pagination']['visibleRange'] = range(1,$TemplateData['pagination']['pages']);
}
$_curPage = 1;
if(isset($_GET['page']) && !empty($_GET['page'])) {
- $_curPage = trim($_GET['page']);
- $_curPage = Summoner::validate($_curPage,'digit') ? $_curPage : 1;
+ $_curPage = trim($_GET['page']);
+ $_curPage = Summoner::validate($_curPage,'digit') ? $_curPage : 1;
}
$_sort = false;
if(isset($_GET['s']) && !empty($_GET['s'])) {
- $_sort = trim($_GET['s']);
- $_sort = Summoner::validate($_sort,'nospace') ? $_sort : false;
+ $_sort = trim($_GET['s']);
+ $_sort = Summoner::validate($_sort,'nospace') ? $_sort : false;
}
$_sortDirection = false;
if(isset($_GET['sd']) && !empty($_GET['sd'])) {
- $_sortDirection = trim($_GET['sd']);
- $_sortDirection = Summoner::validate($_sortDirection,'nospace') ? $_sortDirection : false;
+ $_sortDirection = trim($_GET['sd']);
+ $_sortDirection = Summoner::validate($_sortDirection,'nospace') ? $_sortDirection : false;
}
$_queryOptions = array(
- 'limit' => RESULTS_PER_PAGE,
- 'offset' => (RESULTS_PER_PAGE * ($_curPage-1)),
- 'orderby' => $_sort,
- 'sortDirection' => $_sortDirection
+ 'limit' => RESULTS_PER_PAGE,
+ 'offset' => (RESULTS_PER_PAGE * ($_curPage-1)),
+ 'orderby' => $_sort,
+ 'sortDirection' => $_sortDirection
);
<div class="uk-grid-small uk-grid-row-small uk-grid-row-small" uk-grid>
- <div class="uk-width-1-2@l">
- <?php if(!empty($TemplateData['tags'])) { ?>
- <h3 class="uk-h3">Selectable tags for: <?php echo Summoner::ifset($TemplateData['loadedCollection'], 'name'); ?></h3>
+ <div class="uk-width-1-2@l">
+ <?php if(!empty($TemplateData['tags'])) { ?>
+ <h3 class="uk-h3">Selectable tags for: <?php echo Summoner::ifset($TemplateData['loadedCollection'], 'name'); ?></h3>
- <?php if(!empty($TemplateData['search'])) { ?>
- <div uk-alert id="searchNotice">
- <button class="uk-alert-close" type="button" uk-close></button>
- <p>Display result for: <b><?php echo $TemplateData['search']; ?></b></p>
- </div>
- <script type="text/javascript">
- UIkit.util.on('#searchNotice', 'hide', function () {
- window.location.href="index.php?p=tags&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>";
- });
- </script>
- <?php } ?>
+ <?php if(!empty($TemplateData['search'])) { ?>
+ <div uk-alert id="searchNotice">
+ <button class="uk-alert-close" type="button" uk-close></button>
+ <p>Display result for: <b><?php echo $TemplateData['search']; ?></b></p>
+ </div>
+ <script type="text/javascript">
+ UIkit.util.on('#searchNotice', 'hide', function () {
+ window.location.href="index.php?p=tags&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>";
+ });
+ </script>
+ <?php } ?>
- <?php foreach($TemplateData['tags'] as $k=>$v) { ?>
- <h4 class="uk-heading-line"><span><a uk-toggle="target: #toggle-<?php echo $k; ?>"><?php echo $v['displayname']; ?></a></span></h4>
- <div id="toggle-<?php echo $k; ?>">
- <?php foreach($v['entries'] as $ek=>$ev) { ?>
- <a href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>&fid=<?php echo $k; ?>&fv=<?php echo urlencode($ev); ?>"><?php echo $ev; ?></a>,
- <?php } ?>
- </div>
- <?php } ?>
+ <?php foreach($TemplateData['tags'] as $k=>$v) { ?>
+ <h4 class="uk-heading-line"><span><a uk-toggle="target: #toggle-<?php echo $k; ?>"><?php echo $v['displayname']; ?></a></span></h4>
+ <div id="toggle-<?php echo $k; ?>">
+ <?php foreach($v['entries'] as $ek=>$ev) { ?>
+ <a href="index.php?p=collections&collection=<?php echo $TemplateData['loadedCollection']['id']; ?>&fid=<?php echo $k; ?>&fv=<?php echo urlencode($ev); ?>"><?php echo $ev; ?></a>,
+ <?php } ?>
+ </div>
+ <?php } ?>
- <?php } elseif(!empty($TemplateData['collections'])) { ?>
- <h3 class="uk-h3">Please select a collection first</h3>
- <dl class="uk-description-list uk-description-list-divider">
- <?php foreach($TemplateData['collections'] as $k=>$v) { ?>
- <dt><a href="index.php?p=tags&collection=<?php echo $k; ?>"><?php echo $v['name']; ?></a></dt>
- <dd><?php echo $v['description']; ?></dd>
- <?php } ?>
- </dl>
- <?php } ?>
- </div>
+ <?php } elseif(!empty($TemplateData['collections'])) { ?>
+ <h3 class="uk-h3">Please select a collection first</h3>
+ <dl class="uk-description-list uk-description-list-divider">
+ <?php foreach($TemplateData['collections'] as $k=>$v) { ?>
+ <dt><a href="index.php?p=tags&collection=<?php echo $k; ?>"><?php echo $v['name']; ?></a></dt>
+ <dd><?php echo $v['description']; ?></dd>
+ <?php } ?>
+ </dl>
+ <?php } ?>
+ </div>
</div>
$_collection = false;
if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
}
$_id = false;
if(isset($_GET['id']) && !empty($_GET['id'])) {
- $_id = trim($_GET['id']);
- $_id = Summoner::validate($_id,'digit') ? $_id : false;
+ $_id = trim($_GET['id']);
+ $_id = Summoner::validate($_id,'digit') ? $_id : false;
}
$TemplateData['loadedCollection'] = array();
$_search = false;
if(isset($_POST['navSearch'])) {
- $_search = trim($_POST['navSearch']);
- $_search = Summoner::validate($_search,'text') ? $_search : false;
+ $_search = trim($_POST['navSearch']);
+ $_search = Summoner::validate($_search,'text') ? $_search : false;
}
if(!empty($_collection)) {
- $TemplateData['loadedCollection'] = $Trite->load($_collection);
- if(!empty($TemplateData['loadedCollection'])) {
- $TemplateData['searchAction'] = 'index.php?p=tags&collection='.$Trite->param('id');
- $Mancubus->setCollection($Trite->param('id'));
- $TemplateData['tags'] = $Mancubus->getTags($_search);
- if(!empty($_search)) {
- $TemplateData['search'] = $_search;
- }
- }
- else {
- $TemplateData['message']['content'] = "Can not load given collection.";
- $TemplateData['message']['status'] = "error";
- }
+ $TemplateData['loadedCollection'] = $Trite->load($_collection);
+ if(!empty($TemplateData['loadedCollection'])) {
+ $TemplateData['searchAction'] = 'index.php?p=tags&collection='.$Trite->param('id');
+ $Mancubus->setCollection($Trite->param('id'));
+ $TemplateData['tags'] = $Mancubus->getTags($_search);
+ if(!empty($_search)) {
+ $TemplateData['search'] = $_search;
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "Can not load given collection.";
+ $TemplateData['message']['status'] = "error";
+ }
}
else {
- $TemplateData['collections'] = $Trite->getCollections();
+ $TemplateData['collections'] = $Trite->getCollections();
}
<p>Data will be overwritten</p>
<form class="uk-form-horizontal uk-margin-small" method="post" enctype="multipart/form-data">
- <div class="uk-margin">
- <label class="uk-form-label" for="search">Search</label>
- <div class="uk-form-controls">
- <input class="uk-input" id="search" type="text" autocomplete="off"
- name="fdata[search]"
- value="<?php echo Summoner::ifset($TemplateData['editEntry'], 'title'); ?>"
- >
- </div>
- <div class="uk-margin">
- <button class="uk-button uk-button-primary" type="submit" name="submitFormSearch">
- Search
- </button>
- </div>
- </div>
+ <div class="uk-margin">
+ <label class="uk-form-label" for="search">Search</label>
+ <div class="uk-form-controls">
+ <input class="uk-input" id="search" type="text" autocomplete="off"
+ name="fdata[search]"
+ value="<?php echo Summoner::ifset($TemplateData['editEntry'], 'title'); ?>"
+ >
+ </div>
+ <div class="uk-margin">
+ <button class="uk-button uk-button-primary" type="submit" name="submitFormSearch">
+ Search
+ </button>
+ </div>
+ </div>
</form>
<?php if($TemplateData['showMatchingForm']) { ?>
<form class="uk-form-horizontal uk-margin-small uk-grid-small" method="post" enctype="multipart/form-data" uk-grid>
- <input type="hidden" name="fdata[imdbId]" value="<?php echo $TemplateData['movieImdbId']; ?>">
- <?php
- if(!empty($TemplateData['movieData'])) {
- foreach($TemplateData['movieData'] as $k=>$v) {
- ?>
+ <input type="hidden" name="fdata[imdbId]" value="<?php echo $TemplateData['movieImdbId']; ?>">
+ <?php
+ if(!empty($TemplateData['movieData'])) {
+ foreach($TemplateData['movieData'] as $k=>$v) {
+ ?>
- <div class="uk-width-1-2@s uk-overflow-hidden">
- <p>
- <b><?php echo $v['name']; ?></b><br />
- <?php echo $v['value']; ?>
- </p>
- </div>
- <div class="uk-width-1-2@s">
- <select class="uk-select" name="fdata[into][<?php echo $k; ?>]">
- <option value="">None</option>
- <?php echo $TemplateData['saveToSelection']; ?>
- </select>
- </div>
+ <div class="uk-width-1-2@s uk-overflow-hidden">
+ <p>
+ <b><?php echo $v['name']; ?></b><br />
+ <?php echo $v['value']; ?>
+ </p>
+ </div>
+ <div class="uk-width-1-2@s">
+ <select class="uk-select" name="fdata[into][<?php echo $k; ?>]">
+ <option value="">None</option>
+ <?php echo $TemplateData['saveToSelection']; ?>
+ </select>
+ </div>
- <?php
- }
- }
- ?>
+ <?php
+ }
+ }
+ ?>
- <div class="uk-margin">
- <button class="uk-button uk-button-primary" type="submit" name="submitFormSave">
- Save
- </button>
- </div>
+ <div class="uk-margin">
+ <button class="uk-button uk-button-primary" type="submit" name="submitFormSave">
+ Save
+ </button>
+ </div>
</form>
<?php } ?>
require_once 'lib/imdbwebparser.class.php';
$IMDB = new IMDB(array(
- 'sSearchFor' => 'movie',
- 'storage' => PATH_SYSTEMOUT,
- 'debug' => false
+ 'sSearchFor' => 'movie',
+ 'storage' => PATH_SYSTEMOUT,
+ 'debug' => false
));
// create one time and then reuse it
$collectionFields = $ManangeCollectionsFields->getExistingFields();
if(!empty($collectionFields)) {
- foreach ($collectionFields as $k=>$v) {
- $TemplateData['saveToSelection'] .= "<option value='".$k."'>".$v['displayname']."</option>\n";
- }
+ foreach ($collectionFields as $k=>$v) {
+ $TemplateData['saveToSelection'] .= "<option value='".$k."'>".$v['displayname']."</option>\n";
+ }
}
if(isset($_POST['submitFormSearch'])) {
- $fdata = $_POST['fdata'];
- if (!empty($fdata)) {
- $search = trim($fdata['search']);
- $search = Summoner::validate($search) ? $search : false;
-
- if(!empty($search)) {
- try {
- $IMDB->search($search);
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] imdb search catch: ".$e->getMessage());
- }
-
- if ($IMDB->isReady) {
- $TemplateData['movieData'] = $IMDB->getAll();
- $TemplateData['movieImdbId'] = "tt".$IMDB->iId; // this is the IMDB id you can search for
- $TemplateData['showMatchingForm'] = true;
- } else {
- $TemplateData['message']['content'] = "Nothing found.";
- $TemplateData['message']['status'] = "error";
- }
- }
- else {
- $TemplateData['message']['content'] = "Invalid search term";
- $TemplateData['message']['status'] = "error";
- }
- }
+ $fdata = $_POST['fdata'];
+ if (!empty($fdata)) {
+ $search = trim($fdata['search']);
+ $search = Summoner::validate($search) ? $search : false;
+
+ if(!empty($search)) {
+ try {
+ $IMDB->search($search);
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] imdb search catch: ".$e->getMessage());
+ }
+
+ if ($IMDB->isReady) {
+ $TemplateData['movieData'] = $IMDB->getAll();
+ $TemplateData['movieImdbId'] = "tt".$IMDB->iId; // this is the IMDB id you can search for
+ $TemplateData['showMatchingForm'] = true;
+ } else {
+ $TemplateData['message']['content'] = "Nothing found.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "Invalid search term";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
}
if(isset($_POST['submitFormSave'])) {
- $fdata = $_POST['fdata'];
- if (!empty($fdata)) {
- $_imdbId = $fdata['imdbId'];
- $_imdbId = Summoner::validate($_imdbId,'nospace') ? $_imdbId : false;
-
- if(!empty($_imdbId)) {
- try {
- $IMDB->search($_imdbId);
- }
- catch (Exception $e) {
- if(DEBUG) error_log("[DEBUG] imdb search catch: ".$e->getMessage());
- }
-
- if ($IMDB->isReady) {
- $TemplateData['movieImdbId'] = $_imdbId;
- $_movieData = $IMDB->getAll();
-
- // build data array based on submit
- // see creation log for structure
- $_data = array();
- foreach($fdata['into'] as $k=>$v) {
- if(!empty($v)) {
- $_t = $IMDB->$k();
-
- // multiple selections format for field type lookup_multiple
- if(strstr($_t, $IMDB->sSeparator)) {
- $_t = str_replace($IMDB->sSeparator,",", $_t);
- }
-
- if(isset($collectionFields[$v])) {
- $_data[$v] = $collectionFields[$v];
- $_data[$v]['valueToSave'] = $_t;
- }
- }
- }
-
- $_r = $Tools->getDefaultCreationInfo();
- if(!empty($TemplateData['editEntry'])) {
- // update existing one
- $do = $Manageentry->create($_data,
- $_r['id'],
- $_r['group'],
- $_r['rights'],
- $TemplateData['editEntry']['id']
- );
- $TemplateData['message']['content'] = "Date saved successfully";
- }
- else {
- // create into loaded collection
- $do = $Manageentry->create($_data,
- $_r['id'],
- $_r['group'],
- $_r['rights']
- );
- $TemplateData['message']['content'] = "Date saved successfully:
- <a href='index.php?p=manageentry&collection=".$collection['id']."&id=".$do."'>Here</a>";
- }
-
- if(!empty($do)) {
- $TemplateData['message']['status'] = "success";
- }
- else {
- $TemplateData['message']['content'] = "Data could not be saved. See logs for more.";
- $TemplateData['message']['status'] = "error";
- }
- } else {
- $TemplateData['message']['content'] = "Nothing found.";
- $TemplateData['message']['status'] = "error";
- }
- }
- else {
- $TemplateData['message']['content'] = "IMDB search result information lost.";
- $TemplateData['message']['status'] = "error";
- }
- }
+ $fdata = $_POST['fdata'];
+ if (!empty($fdata)) {
+ $_imdbId = $fdata['imdbId'];
+ $_imdbId = Summoner::validate($_imdbId,'nospace') ? $_imdbId : false;
+
+ if(!empty($_imdbId)) {
+ try {
+ $IMDB->search($_imdbId);
+ }
+ catch (Exception $e) {
+ if(DEBUG) error_log("[DEBUG] imdb search catch: ".$e->getMessage());
+ }
+
+ if ($IMDB->isReady) {
+ $TemplateData['movieImdbId'] = $_imdbId;
+ $_movieData = $IMDB->getAll();
+
+ // build data array based on submit
+ // see creation log for structure
+ $_data = array();
+ foreach($fdata['into'] as $k=>$v) {
+ if(!empty($v)) {
+ $_t = $IMDB->$k();
+
+ // multiple selections format for field type lookup_multiple
+ if(strstr($_t, $IMDB->sSeparator)) {
+ $_t = str_replace($IMDB->sSeparator,",", $_t);
+ }
+
+ if(isset($collectionFields[$v])) {
+ $_data[$v] = $collectionFields[$v];
+ $_data[$v]['valueToSave'] = $_t;
+ }
+ }
+ }
+
+ $_r = $Tools->getDefaultCreationInfo();
+ if(!empty($TemplateData['editEntry'])) {
+ // update existing one
+ $do = $Manageentry->create($_data,
+ $_r['id'],
+ $_r['group'],
+ $_r['rights'],
+ $TemplateData['editEntry']['id']
+ );
+ $TemplateData['message']['content'] = "Date saved successfully";
+ }
+ else {
+ // create into loaded collection
+ $do = $Manageentry->create($_data,
+ $_r['id'],
+ $_r['group'],
+ $_r['rights']
+ );
+ $TemplateData['message']['content'] = "Date saved successfully:
+ <a href='index.php?p=manageentry&collection=".$collection['id']."&id=".$do."'>Here</a>";
+ }
+
+ if(!empty($do)) {
+ $TemplateData['message']['status'] = "success";
+ }
+ else {
+ $TemplateData['message']['content'] = "Data could not be saved. See logs for more.";
+ $TemplateData['message']['status'] = "error";
+ }
+ } else {
+ $TemplateData['message']['content'] = "Nothing found.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "IMDB search result information lost.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
}
-
<h3 class="uk-h3">Using <?php echo $TemplateData['tool']['name']; ?> with collection: <?php echo $TemplateData['collection']['name']; ?></h3>
<?php if(!empty($TemplateData['editEntry'])) { ?>
<h4><span uk-icon="arrow-left"></span>
- <a href="index.php?p=manageentry&collection=<?php echo $TemplateData['collection']['id']; ?>&id=<?php echo $TemplateData['editEntry']['id']; ?>"><?php echo Summoner::ifset($TemplateData['editEntry'], 'title'); ?></a>
+ <a href="index.php?p=manageentry&collection=<?php echo $TemplateData['collection']['id']; ?>&id=<?php echo $TemplateData['editEntry']['id']; ?>"><?php echo Summoner::ifset($TemplateData['editEntry'], 'title'); ?></a>
</h4>
<?php } ?>
<div class="uk-grid-small uk-grid-row-small" uk-grid>
- <div class="uk-width-1-2">
- <?php if(!empty($TemplateData['tool']['viewFile'])) { require_once $TemplateData['tool']['viewFile']; } ?>
- </div>
+ <div class="uk-width-1-2">
+ <?php if(!empty($TemplateData['tool']['viewFile'])) { require_once $TemplateData['tool']['viewFile']; } ?>
+ </div>
</div>
$_collection = false;
if(isset($_GET['collection']) && !empty($_GET['collection'])) {
- $_collection = trim($_GET['collection']);
- $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
+ $_collection = trim($_GET['collection']);
+ $_collection = Summoner::validate($_collection,'digit') ? $_collection : false;
}
$_id = false;
if(isset($_GET['id']) && !empty($_GET['id'])) {
- $_id = trim($_GET['id']);
- $_id = Summoner::validate($_id,'digit') ? $_id : false;
+ $_id = trim($_GET['id']);
+ $_id = Summoner::validate($_id,'digit') ? $_id : false;
}
$_t = false;
if(isset($_GET['t']) && !empty($_GET['t'])) {
- $_t = trim($_GET['t']);
- $_t = Summoner::validate($_t,'nospace') ? $_t : false;
+ $_t = trim($_GET['t']);
+ $_t = Summoner::validate($_t,'nospace') ? $_t : false;
}
if(!empty($_collection) && !empty($_t)) {
- $collection = $ManangeCollections->getCollection($_collection,"write");
- $toolInfo = $Tools->validate($_t);
+ $collection = $ManangeCollections->getCollection($_collection,"write");
+ $toolInfo = $Tools->validate($_t);
- if(!empty($collection) && !empty($toolInfo)) {
- $TemplateData['tool'] = $toolInfo;
- $TemplateData['collection'] = $collection;
+ if(!empty($collection) && !empty($toolInfo)) {
+ $TemplateData['tool'] = $toolInfo;
+ $TemplateData['collection'] = $collection;
- $ManangeCollectionsFields->setCollection($_collection);
- $Manageentry->setCollection($_collection);
+ $ManangeCollectionsFields->setCollection($_collection);
+ $Manageentry->setCollection($_collection);
- if(!empty($_id)) {
- $TemplateData['editEntry'] = $Manageentry->getEditData($_id);
- }
+ if(!empty($_id)) {
+ $TemplateData['editEntry'] = $Manageentry->getEditData($_id);
+ }
- $_toolFile = Summoner::themefile('tool/tool-'.$toolInfo['action'].'.php', UI_THEME);
- $_toolViewFile = Summoner::themefile('tool/tool-'.$toolInfo['action'].'.html', UI_THEME);
- if(file_exists($_toolFile) && file_exists($_toolViewFile)) {
- require_once $_toolFile;
- $TemplateData['tool']['viewFile'] = $_toolViewFile;
- }
- else {
- $TemplateData['tool']['viewFile'] = '';
- $TemplateData['message']['content'] = "Required tool files can not be found.";
- $TemplateData['message']['status'] = "error";
- }
- }
- else {
- $TemplateData['message']['content'] = "Collection nor tool could not be loaded.";
- $TemplateData['message']['status'] = "error";
- }
+ $_toolFile = Summoner::themefile('tool/tool-'.$toolInfo['action'].'.php', UI_THEME);
+ $_toolViewFile = Summoner::themefile('tool/tool-'.$toolInfo['action'].'.html', UI_THEME);
+ if(file_exists($_toolFile) && file_exists($_toolViewFile)) {
+ require_once $_toolFile;
+ $TemplateData['tool']['viewFile'] = $_toolViewFile;
+ }
+ else {
+ $TemplateData['tool']['viewFile'] = '';
+ $TemplateData['message']['content'] = "Required tool files can not be found.";
+ $TemplateData['message']['status'] = "error";
+ }
+ }
+ else {
+ $TemplateData['message']['content'] = "Collection nor tool could not be loaded.";
+ $TemplateData['message']['status'] = "error";
+ }
}
-
.uk-label {
- text-transform: none;
+ text-transform: none;
}
.input-multiple-listbox {
- display: flex;
- flex-direction: row;
- flex-wrap: wrap;
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
}
.input-multiple-template {
- margin: 1px;
+ margin: 1px;
}
* @param String targetStartString
*/
function removeTag(tagString,targetStartString) {
- let toRemove = document.getElementById(targetStartString + '-' + tagString);
- let saveInput = document.getElementById(targetStartString + '-save');
-
- if(toRemove && saveInput) {
- let newSaveValue = _removeFromCommaString(saveInput.value,tagString);
- saveInput.value = newSaveValue;
- toRemove.remove();
- }
- else {
- console.log("Delete element not found");
- }
+ let toRemove = document.getElementById(targetStartString + '-' + tagString);
+ let saveInput = document.getElementById(targetStartString + '-save');
+
+ if(toRemove && saveInput) {
+ let newSaveValue = _removeFromCommaString(saveInput.value,tagString);
+ saveInput.value = newSaveValue;
+ toRemove.remove();
+ }
+ else {
+ console.log("Delete element not found");
+ }
}
/**
* @param String targetStartString
*/
function addTag(e,targetStartString) {
- e = e || window.event;
+ e = e || window.event;
- if(e.keyCode === 13) {
- let elem = e.srcElement || e.target;
- let saveInput = document.getElementById(targetStartString + '-save');
- let listBox = document.getElementById(targetStartString + '-listbox');
- let newTagTemplate = document.getElementById(targetStartString + '-template');
+ if(e.keyCode === 13) {
+ let elem = e.srcElement || e.target;
+ let saveInput = document.getElementById(targetStartString + '-save');
+ let listBox = document.getElementById(targetStartString + '-listbox');
+ let newTagTemplate = document.getElementById(targetStartString + '-template');
- if(saveInput && listBox && elem && newTagTemplate) {
- let toAdd = elem.value;
- let newSaveValue = _appendToCommaString(saveInput.value,toAdd);
+ if(saveInput && listBox && elem && newTagTemplate) {
+ let toAdd = elem.value;
+ let newSaveValue = _appendToCommaString(saveInput.value,toAdd);
- let newT = newTagTemplate.cloneNode(true);
- newT = _fillTagTemplate(newT,toAdd,targetStartString);
- listBox.appendChild(newT);
+ let newT = newTagTemplate.cloneNode(true);
+ newT = _fillTagTemplate(newT,toAdd,targetStartString);
+ listBox.appendChild(newT);
- saveInput.value = newSaveValue;
- }
+ saveInput.value = newSaveValue;
+ }
- elem.value = '';
- e.preventDefault();
- }
+ elem.value = '';
+ e.preventDefault();
+ }
}
/**
* @private
*/
function _appendToCommaString(theString,toAdd) {
- if(theString.length > 0 && toAdd.length > 0) {
- let theArray = theString.split(',');
- if(!theArray.includes(toAdd)) {
- theString = theString + "," + toAdd
- }
- }
- else if (toAdd.length > 0) {
- theString = toAdd;
- }
-
- return theString;
+ if(theString.length > 0 && toAdd.length > 0) {
+ let theArray = theString.split(',');
+ if(!theArray.includes(toAdd)) {
+ theString = theString + "," + toAdd
+ }
+ }
+ else if (toAdd.length > 0) {
+ theString = toAdd;
+ }
+
+ return theString;
}
/**
* @private
*/
function _removeFromCommaString(theString,toRemove) {
- if(theString.length > 0 && toRemove.length > 0) {
- let theArray = theString.split(',');
+ if(theString.length > 0 && toRemove.length > 0) {
+ let theArray = theString.split(',');
- if(theArray.includes(toRemove)) {
- for( let i = theArray.length-1; i >= 0; i--){
- if ( theArray[i] === toRemove) theArray.splice(i, 1);
- }
+ if(theArray.includes(toRemove)) {
+ for( let i = theArray.length-1; i >= 0; i--){
+ if ( theArray[i] === toRemove) theArray.splice(i, 1);
+ }
- theString = theArray.join(",");
- }
- }
+ theString = theArray.join(",");
+ }
+ }
- return theString;
+ return theString;
}
/**
* @private
*/
function _removeFromDatalist(list, value) {
- if(list.options.length > 0 && value && value.length > 0) {
- for (i = 0; i < list.options.length; i++) {
- if(list.options[i].value == value) {
- list.options[i].remove();
- }
- }
- }
+ if(list.options.length > 0 && value && value.length > 0) {
+ for (i = 0; i < list.options.length; i++) {
+ if(list.options[i].value == value) {
+ list.options[i].remove();
+ }
+ }
+ }
}
/**
* @private
*/
function _fillTagTemplate(el,newTagString,targetStartString) {
- el.removeAttribute('style');
- el.setAttribute('id',targetStartString + '-' + newTagString);
+ el.removeAttribute('style');
+ el.setAttribute('id',targetStartString + '-' + newTagString);
- let spanEl = el.querySelector('span');
- spanEl.innerHTML = newTagString;
+ let spanEl = el.querySelector('span');
+ spanEl.innerHTML = newTagString;
- let aEl = el.querySelector('a');
- aEl.setAttribute('onclick', "removeTag('"+newTagString+"','"+targetStartString+"');");
+ let aEl = el.querySelector('a');
+ aEl.setAttribute('onclick', "removeTag('"+newTagString+"','"+targetStartString+"');");
- return el;
+ return el;
}