From: Banana Date: Wed, 30 Dec 2020 12:25:37 +0000 (+0100) Subject: tabs all the way. X-Git-Tag: 1.0~46 X-Git-Url: http://91.132.146.200/gitweb/?a=commitdiff_plain;h=8134578e5a024d2db7d96b034820e4ba1f8a7bc3;p=bibliotheca-php.git tabs all the way. --- diff --git a/documentation/api.txt b/documentation/api.txt index f968463..d7fdb60 100644 --- a/documentation/api.txt +++ b/documentation/api.txt @@ -5,26 +5,26 @@ api.php?QUERY_PARAMETERS # 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": {} } diff --git a/webclient/api.php b/webclient/api.php index 8610ab1..7edfd5c 100644 --- a/webclient/api.php +++ b/webclient/api.php @@ -50,177 +50,177 @@ $Spectre = new Spectre($DB, $Doomguy); $_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 diff --git a/webclient/index.php b/webclient/index.php index 01164a6..ff65231 100644 --- a/webclient/index.php +++ b/webclient/index.php @@ -62,25 +62,25 @@ $Gorenest = new GoreNest($DB,$Doomguy); $_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 diff --git a/webclient/lib/doomguy.class.php b/webclient/lib/doomguy.class.php index 1d20d91..74c0938 100644 --- a/webclient/lib/doomguy.class.php +++ b/webclient/lib/doomguy.class.php @@ -22,454 +22,454 @@ */ 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; + } } diff --git a/webclient/lib/gorenest.class.php b/webclient/lib/gorenest.class.php index cfd5cd8..5f41c2a 100644 --- a/webclient/lib/gorenest.class.php +++ b/webclient/lib/gorenest.class.php @@ -21,86 +21,86 @@ */ 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; + } } diff --git a/webclient/lib/imdbwebparser.class.php b/webclient/lib/imdbwebparser.class.php index 38ea398..9af2fa8 100644 --- a/webclient/lib/imdbwebparser.class.php +++ b/webclient/lib/imdbwebparser.class.php @@ -21,1788 +21,1788 @@ */ 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 = '~]*>\s*Also\s*Known\s*As\s*\s*(.+)~Uis'; - const IMDB_ASPECT_RATIO = '~]*>Aspect\s*Ratio\s*(.+)~Uis'; - const IMDB_AWARDS = '~\s*Awards:(.+)~Uis'; - const IMDB_BUDGET = '~]*>Budget<\/td>\s*\s*(.*)(?:\(estimated\))\s*<\/td>~Ui'; - const IMDB_CAST = '~]*itemprop="actor"[^>]*>\s*]*>\s*(.+)~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 = '~]*>\s*Runtime\s*\s*(.+)~Ui'; - const IMDB_SEARCH = '~ (?:.*)<\/a>~Ui'; - const IMDB_SEASONS = '~episodes\?season=(?:\d+)">(\d+)<~Ui'; - const IMDB_SOUND_MIX = '~]*>\s*Sound\s*Mix\s*\s*(.+)~Ui'; - const IMDB_TAGLINE = '~]*>\s*Taglines\s*\s*(.+)~Ui'; - const IMDB_TITLE = '~itemprop="name">(.*)(<\/h3>|'; - } - - // 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 '
Using redirect: ' . basename($sRedirectFile) . '
'; - } - $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 '
Using cache: ' . basename($sCacheFile) . '
'; - } - $this->sSource = file_get_contents($sCacheFile); - $this->isReady = true; - - return true; - } - } - - // Run cURL on the URL. - if ($this->IMDB_DEBUG) { - echo '
Running cURL: ' . $this->sUrl . '
'; - } - - $aCurlInfo = $this->runCurl($this->sUrl); - $sSource = $aCurlInfo['contents']; - - if (false === $sSource) { - if ($this->IMDB_DEBUG) { - echo '
cURL error: ' . var_dump($aCurlInfo) . '
'; - } - - 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 '
New redirect saved: ' . basename($sRedirectFile) . ' => ' . $sUrl . '
'; - } - 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 '
Movie not found: ' . $sSearch . '
'; - } - - return false; - } - - $this->sSource = str_replace( - [ - "\n", - "\r\n", - "\r", - ], - '', - $sSource - ); - $this->isReady = true; - - // Save cache. - if (false === $bSearch) { - if ($this->IMDB_DEBUG) { - echo '
Cache created: ' . basename($sCacheFile) . '
'; - } - 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 '
cURL error: ' . var_dump($aCurlInfo) . '
'; - } - - return false; - } - - $aReturned = $this->matchRegex($sSource, "~(.*?)<\/td>\s+(.*?)<\/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[] = '
' . $this->cleanString( - $sName - ) . ''; - } - - $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[] = '' . $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); - } - - /** - * @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 '' . $this->cleanString( - $aMatch[2][0] - ) . ''; - } - } - - 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[] = '' . $this->cleanString( - $sName - ) . ''; - } - - 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[] = '' . $this->cleanString( - $sName - ) . ''; - } - - 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[] = '' . $this->cleanString( - $sName - ) . ''; - } - - 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[] = '' . $this->cleanString( - $sName - ) . ''; - } - - 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[] = '' . $this->cleanString( - $sName - ) . ''; - } - - 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[] = '' . $this->cleanString( - $sName - ) . ''; - } - - 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 '
cURL error: ' . var_dump($aCurlInfo) . '
'; - } - - 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 '
cURL error: ' . var_dump($aCurlInfo) . '
'; - } - - return false; - } - - $aReturned = $this->matchRegex( - $sSource, - '~>(.*)<\/a><\/td>\s+(.*)<\/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[] = '' . $sName . ''; - } - - 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[] = '' . $this->cleanString( - $sName - ) . ''; - } - - 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('', ' | ', $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 '
cURL returned wrong HTTP code “' . $aCurlInfo['http_code'] . '”, aborting.
'; - } - - 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 = '~]*>\s*Also\s*Known\s*As\s*\s*(.+)~Uis'; + const IMDB_ASPECT_RATIO = '~]*>Aspect\s*Ratio\s*(.+)~Uis'; + const IMDB_AWARDS = '~\s*Awards:(.+)~Uis'; + const IMDB_BUDGET = '~]*>Budget<\/td>\s*\s*(.*)(?:\(estimated\))\s*<\/td>~Ui'; + const IMDB_CAST = '~]*itemprop="actor"[^>]*>\s*]*>\s*(.+)~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 = '~]*>\s*Runtime\s*\s*(.+)~Ui'; + const IMDB_SEARCH = '~ (?:.*)<\/a>~Ui'; + const IMDB_SEASONS = '~episodes\?season=(?:\d+)">(\d+)<~Ui'; + const IMDB_SOUND_MIX = '~]*>\s*Sound\s*Mix\s*\s*(.+)~Ui'; + const IMDB_TAGLINE = '~]*>\s*Taglines\s*\s*(.+)~Ui'; + const IMDB_TITLE = '~itemprop="name">(.*)(<\/h3>|'; + } + + // 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 '
Using redirect: ' . basename($sRedirectFile) . '
'; + } + $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 '
Using cache: ' . basename($sCacheFile) . '
'; + } + $this->sSource = file_get_contents($sCacheFile); + $this->isReady = true; + + return true; + } + } + + // Run cURL on the URL. + if ($this->IMDB_DEBUG) { + echo '
Running cURL: ' . $this->sUrl . '
'; + } + + $aCurlInfo = $this->runCurl($this->sUrl); + $sSource = $aCurlInfo['contents']; + + if (false === $sSource) { + if ($this->IMDB_DEBUG) { + echo '
cURL error: ' . var_dump($aCurlInfo) . '
'; + } + + 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 '
New redirect saved: ' . basename($sRedirectFile) . ' => ' . $sUrl . '
'; + } + 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 '
Movie not found: ' . $sSearch . '
'; + } + + return false; + } + + $this->sSource = str_replace( + [ + "\n", + "\r\n", + "\r", + ], + '', + $sSource + ); + $this->isReady = true; + + // Save cache. + if (false === $bSearch) { + if ($this->IMDB_DEBUG) { + echo '
Cache created: ' . basename($sCacheFile) . '
'; + } + 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 '
cURL error: ' . var_dump($aCurlInfo) . '
'; + } + + return false; + } + + $aReturned = $this->matchRegex($sSource, "~(.*?)<\/td>\s+(.*?)<\/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[] = '
' . $this->cleanString( + $sName + ) . ''; + } + + $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[] = '' . $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); + } + + /** + * @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 '' . $this->cleanString( + $aMatch[2][0] + ) . ''; + } + } + + 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[] = '' . $this->cleanString( + $sName + ) . ''; + } + + 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[] = '' . $this->cleanString( + $sName + ) . ''; + } + + 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[] = '' . $this->cleanString( + $sName + ) . ''; + } + + 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[] = '' . $this->cleanString( + $sName + ) . ''; + } + + 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[] = '' . $this->cleanString( + $sName + ) . ''; + } + + 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[] = '' . $this->cleanString( + $sName + ) . ''; + } + + 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 '
cURL error: ' . var_dump($aCurlInfo) . '
'; + } + + 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 '
cURL error: ' . var_dump($aCurlInfo) . '
'; + } + + return false; + } + + $aReturned = $this->matchRegex( + $sSource, + '~>(.*)<\/a><\/td>\s+(.*)<\/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[] = '' . $sName . ''; + } + + 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[] = '' . $this->cleanString( + $sName + ) . ''; + } + + 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('', ' | ', $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 '
cURL returned wrong HTTP code “' . $aCurlInfo['http_code'] . '”, aborting.
'; + } + + 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; + } } diff --git a/webclient/lib/managecollectionfields.class.php b/webclient/lib/managecollectionfields.class.php index af19d83..c4c6574 100644 --- a/webclient/lib/managecollectionfields.class.php +++ b/webclient/lib/managecollectionfields.class.php @@ -21,240 +21,240 @@ */ 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; + } } diff --git a/webclient/lib/managecollections.class.php b/webclient/lib/managecollections.class.php index fc6104d..e37266e 100644 --- a/webclient/lib/managecollections.class.php +++ b/webclient/lib/managecollections.class.php @@ -22,468 +22,468 @@ 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; + } } diff --git a/webclient/lib/manageentry.class.php b/webclient/lib/manageentry.class.php index ef14375..6bfaee1 100644 --- a/webclient/lib/manageentry.class.php +++ b/webclient/lib/manageentry.class.php @@ -17,673 +17,673 @@ */ 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']); + } + } + } + } } diff --git a/webclient/lib/mancubus.class.php b/webclient/lib/mancubus.class.php index 1d1682e..1d67360 100644 --- a/webclient/lib/mancubus.class.php +++ b/webclient/lib/mancubus.class.php @@ -20,607 +20,607 @@ * 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); + } } diff --git a/webclient/lib/possessed.class.php b/webclient/lib/possessed.class.php index 0be12c8..873328b 100644 --- a/webclient/lib/possessed.class.php +++ b/webclient/lib/possessed.class.php @@ -26,352 +26,352 @@ * */ 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; + } } diff --git a/webclient/lib/spectre.class.php b/webclient/lib/spectre.class.php index ced903f..fcb1d74 100644 --- a/webclient/lib/spectre.class.php +++ b/webclient/lib/spectre.class.php @@ -21,88 +21,88 @@ * 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; + } } diff --git a/webclient/lib/summoner.class.php b/webclient/lib/summoner.class.php index 15ccefd..1d38ffc 100644 --- a/webclient/lib/summoner.class.php +++ b/webclient/lib/summoner.class.php @@ -21,26 +21,26 @@ */ 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 @@ -69,12 +69,12 @@ class Summoner { 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': @@ -152,14 +152,14 @@ class Summoner { 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); } @@ -255,39 +255,39 @@ class Summoner { 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 @@ -302,12 +302,12 @@ class Summoner { $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 ; @@ -356,17 +356,17 @@ class Summoner { 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); } @@ -456,12 +456,12 @@ class Summoner { } } - /** - * 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; @@ -618,12 +618,12 @@ class Summoner { * @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 @@ -636,50 +636,50 @@ class Summoner { 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; + } } diff --git a/webclient/lib/tentacle.class.php b/webclient/lib/tentacle.class.php index 398d220..344793f 100644 --- a/webclient/lib/tentacle.class.php +++ b/webclient/lib/tentacle.class.php @@ -21,68 +21,68 @@ * 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--' + ); + } } diff --git a/webclient/lib/trite.class.php b/webclient/lib/trite.class.php index 22a0e83..02d5d48 100644 --- a/webclient/lib/trite.class.php +++ b/webclient/lib/trite.class.php @@ -24,167 +24,167 @@ * */ 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); + } } diff --git a/webclient/view/default/auth/auth.html b/webclient/view/default/auth/auth.html index 625e0f6..e463ce4 100644 --- a/webclient/view/default/auth/auth.html +++ b/webclient/view/default/auth/auth.html @@ -1,31 +1,31 @@ isSignedIn() === true) { ?>

Logout

- Logout - + Logout +

Login

-
-
- -
- -
-
-
- -
- -
-
-
- -
-
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+
diff --git a/webclient/view/default/auth/auth.php b/webclient/view/default/auth/auth.php index 4747933..6bf1881 100644 --- a/webclient/view/default/auth/auth.php +++ b/webclient/view/default/auth/auth.php @@ -19,32 +19,32 @@ // 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"; + } + } + } } diff --git a/webclient/view/default/collections/collections.html b/webclient/view/default/collections/collections.html index 73ec71c..2eb04bb 100644 --- a/webclient/view/default/collections/collections.html +++ b/webclient/view/default/collections/collections.html @@ -2,54 +2,54 @@
- -

Display result for:

+ +

Display result for:

- $entry) { ?> -
-
-
- - <?php echo $entry['fields']['coverimage']['displayname']; ?> + $entry) { ?> +
+
+
+ + <?php echo $entry['fields']['coverimage']['displayname']; ?> - -
-
- -

- + +
+
+ +

+ - -

- -
- -
-
- + +

+ +
+ +
+
+

Collection overview

-
-
- $v) { ?> -
-
- -
-
+
+
+ $v) { ?> +
+
+ +
+
diff --git a/webclient/view/default/collections/collections.php b/webclient/view/default/collections/collections.php index b29698a..6d36390 100644 --- a/webclient/view/default/collections/collections.php +++ b/webclient/view/default/collections/collections.php @@ -23,28 +23,28 @@ $Trite = new Trite($DB,$Doomguy); $_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)); @@ -59,34 +59,34 @@ $TemplateData['pagination']['currentGetParameters']['p'] = 'collections'; $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)); diff --git a/webclient/view/default/dashboard/dashboard.html b/webclient/view/default/dashboard/dashboard.html index 6ad47e0..0c2b314 100644 --- a/webclient/view/default/dashboard/dashboard.html +++ b/webclient/view/default/dashboard/dashboard.html @@ -1,54 +1,54 @@
- -

Display result for:

+ +

Display result for:

$v) { ?> -
-
- +
+
+ - $entry) { ?> + $entry) { ?> -
-
- - <?php echo $entry['fields']['coverimage']['displayname']; ?> - - -
-
-
- -

- +
+
+ + <?php echo $entry['fields']['coverimage']['displayname']; ?> + + +
+
+
+ +

+ - -

- -
- -
-
+ +

+ +
+ +
+
- + -
+
diff --git a/webclient/view/default/dashboard/dashboard.php b/webclient/view/default/dashboard/dashboard.php index a4a843f..1a27178 100644 --- a/webclient/view/default/dashboard/dashboard.php +++ b/webclient/view/default/dashboard/dashboard.php @@ -24,11 +24,11 @@ $TemplateData['searchAction'] = 'index.php'; $_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; } diff --git a/webclient/view/default/entry/entry.html b/webclient/view/default/entry/entry.html index 4c83cc1..eeda4fc 100644 --- a/webclient/view/default/entry/entry.html +++ b/webclient/view/default/entry/entry.html @@ -1,55 +1,55 @@

-
-
- - - +
+ + + + $_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']; + } + } + } + } + ?> +
diff --git a/webclient/view/default/entry/entry.php b/webclient/view/default/entry/entry.php index a554905..6e75ecc 100644 --- a/webclient/view/default/entry/entry.php +++ b/webclient/view/default/entry/entry.php @@ -25,14 +25,14 @@ $Trite = new Trite($DB,$Doomguy); $_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); @@ -42,22 +42,22 @@ $TemplateData['storagePath'] = ''; $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.'; } diff --git a/webclient/view/default/entry/field-date.html b/webclient/view/default/entry/field-date.html index 61f0e48..8909717 100644 --- a/webclient/view/default/entry/field-date.html +++ b/webclient/view/default/entry/field-date.html @@ -1,4 +1,4 @@

- : - + : +

diff --git a/webclient/view/default/entry/field-lookupmultiple.html b/webclient/view/default/entry/field-lookupmultiple.html index 47d42e0..e15139c 100644 --- a/webclient/view/default/entry/field-lookupmultiple.html +++ b/webclient/view/default/entry/field-lookupmultiple.html @@ -1,8 +1,8 @@

- : - '.$_fv.', '; - } - ?> + : + '.$_fv.', '; + } + ?>

diff --git a/webclient/view/default/entry/field-selection.html b/webclient/view/default/entry/field-selection.html index 2872380..3667f9a 100644 --- a/webclient/view/default/entry/field-selection.html +++ b/webclient/view/default/entry/field-selection.html @@ -1,4 +1,4 @@

- : - + : +

diff --git a/webclient/view/default/entry/field-upload-coverimage.html b/webclient/view/default/entry/field-upload-coverimage.html index 8e78315..e4f2cec 100644 --- a/webclient/view/default/entry/field-upload-coverimage.html +++ b/webclient/view/default/entry/field-upload-coverimage.html @@ -1,6 +1,6 @@
- +
diff --git a/webclient/view/default/entry/field-upload.html b/webclient/view/default/entry/field-upload.html index 5acb876..ddbea47 100644 --- a/webclient/view/default/entry/field-upload.html +++ b/webclient/view/default/entry/field-upload.html @@ -1,3 +1,3 @@

: - +

diff --git a/webclient/view/default/entry/field-upload_multiple-attachment.html b/webclient/view/default/entry/field-upload_multiple-attachment.html index 6145c89..8e62709 100644 --- a/webclient/view/default/entry/field-upload_multiple-attachment.html +++ b/webclient/view/default/entry/field-upload_multiple-attachment.html @@ -1,9 +1,9 @@
- -
- - <?php echo $_uEntry; ?> - -
- + +
+ + <?php echo $_uEntry; ?> + +
+
diff --git a/webclient/view/default/entry/field-upload_multiple.html b/webclient/view/default/entry/field-upload_multiple.html index 955ccfd..622adba 100644 --- a/webclient/view/default/entry/field-upload_multiple.html +++ b/webclient/view/default/entry/field-upload_multiple.html @@ -1,8 +1,7 @@

:

    - -
  • - + +
  • +

- diff --git a/webclient/view/default/entry/field-year.html b/webclient/view/default/entry/field-year.html index 7f04a91..0376451 100644 --- a/webclient/view/default/entry/field-year.html +++ b/webclient/view/default/entry/field-year.html @@ -1,4 +1,4 @@

- : - + : +

diff --git a/webclient/view/default/main.php b/webclient/view/default/main.php index ff5fec7..48511cc 100644 --- a/webclient/view/default/main.php +++ b/webclient/view/default/main.php @@ -2,33 +2,33 @@ - + - - + + Bibliotheca -
- -
+
+ +
-
-
- - - -
+
+
+ + + +
-
-
-

 

-
-
+
+
+

 

+
+
diff --git a/webclient/view/default/managecollectionfields/managecollectionfields.html b/webclient/view/default/managecollectionfields/managecollectionfields.html index ddc23b0..dacb6c0 100644 --- a/webclient/view/default/managecollectionfields/managecollectionfields.html +++ b/webclient/view/default/managecollectionfields/managecollectionfields.html @@ -1,60 +1,60 @@

Manage your fields for:

-
-

Add or remove a field

-

- Just use drag and drop below to add, remove or order your fields.
- Removing a field will remove - the stored data from the collection.
- Make sure at least the title - field is available. -

-
- $v) { ?> -
- - () -
- -
+
+

Add or remove a field

+

+ Just use drag and drop below to add, remove or order your fields.
+ Removing a field will remove + the stored data from the collection.
+ Make sure at least the title + field is available. +

+
+ $v) { ?> +
+ + () +
+ +
-
- -
- -
-
-
-
-

Available fields

-
- $v) { ?> -
- - () -
- -
-
+
+ +
+ +
+
+
+
+

Available fields

+
+ $v) { ?> +
+ + () +
+ +
+
diff --git a/webclient/view/default/managecollectionfields/managecollectionfields.php b/webclient/view/default/managecollectionfields/managecollectionfields.php index 536f372..cc37fe7 100644 --- a/webclient/view/default/managecollectionfields/managecollectionfields.php +++ b/webclient/view/default/managecollectionfields/managecollectionfields.php @@ -29,43 +29,43 @@ $TemplateData['existingFields'] = array(); $_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"; + } + } } diff --git a/webclient/view/default/managecolletions/managecolletions.php b/webclient/view/default/managecolletions/managecolletions.php index 14d126d..8cc214e 100644 --- a/webclient/view/default/managecolletions/managecolletions.php +++ b/webclient/view/default/managecolletions/managecolletions.php @@ -34,90 +34,90 @@ $TemplateData['existingFields'] = array(); // @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"; + } + } + } - } + } } diff --git a/webclient/view/default/manageentry/field-lookupmultiple.html b/webclient/view/default/manageentry/field-lookupmultiple.html index cb885e2..b6134a0 100644 --- a/webclient/view/default/manageentry/field-lookupmultiple.html +++ b/webclient/view/default/manageentry/field-lookupmultiple.html @@ -1,49 +1,49 @@
- -
-
- + +
+
+ -
- -
+
+ +
- -
- -
+ +
+ +
- - - + + + diff --git a/webclient/view/default/manageentry/field-selection.html b/webclient/view/default/manageentry/field-selection.html index 6dafc78..65cf8a1 100644 --- a/webclient/view/default/manageentry/field-selection.html +++ b/webclient/view/default/manageentry/field-selection.html @@ -1,13 +1,13 @@
- -
- -
+ +
+ +
diff --git a/webclient/view/default/manageentry/field-text.html b/webclient/view/default/manageentry/field-text.html index a6c5c41..82761c6 100644 --- a/webclient/view/default/manageentry/field-text.html +++ b/webclient/view/default/manageentry/field-text.html @@ -1,9 +1,9 @@
- -
- -
+ +
+ +
diff --git a/webclient/view/default/manageentry/field-text3.html b/webclient/view/default/manageentry/field-text3.html index 974b0da..7256353 100644 --- a/webclient/view/default/manageentry/field-text3.html +++ b/webclient/view/default/manageentry/field-text3.html @@ -1,9 +1,8 @@
- -
- -
+ +
+ +
- diff --git a/webclient/view/default/manageentry/field-textarea.html b/webclient/view/default/manageentry/field-textarea.html index 0e20fdb..ca66b43 100644 --- a/webclient/view/default/manageentry/field-textarea.html +++ b/webclient/view/default/manageentry/field-textarea.html @@ -1,9 +1,8 @@
- -
- -
+ +
+ +
- diff --git a/webclient/view/default/manageentry/field-unknown.html b/webclient/view/default/manageentry/field-unknown.html index a1cdcbf..568d0f1 100644 --- a/webclient/view/default/manageentry/field-unknown.html +++ b/webclient/view/default/manageentry/field-unknown.html @@ -1,3 +1,3 @@
- Missing template for: + Missing template for:
diff --git a/webclient/view/default/manageentry/field-upload.html b/webclient/view/default/manageentry/field-upload.html index 152a325..91bcff4 100644 --- a/webclient/view/default/manageentry/field-upload.html +++ b/webclient/view/default/manageentry/field-upload.html @@ -1,17 +1,17 @@
- -
- - -
- '.Summoner::ifset($TemplateData['editData'], $field['identifier']).''; ?> - -
- -
+ +
+ + +
+ '.Summoner::ifset($TemplateData['editData'], $field['identifier']).''; ?> + +
+ +
diff --git a/webclient/view/default/manageentry/field-upload_multiple.html b/webclient/view/default/manageentry/field-upload_multiple.html index 52e64d2..e098aef 100644 --- a/webclient/view/default/manageentry/field-upload_multiple.html +++ b/webclient/view/default/manageentry/field-upload_multiple.html @@ -1,24 +1,24 @@
- -
- -
- - - -
- -
-
+ +
+ +
+ + + +
+ +
+
diff --git a/webclient/view/default/manageentry/field-year.html b/webclient/view/default/manageentry/field-year.html index 75b687e..4b0158e 100644 --- a/webclient/view/default/manageentry/field-year.html +++ b/webclient/view/default/manageentry/field-year.html @@ -1,10 +1,10 @@
- -
- -
+ +
+ +
diff --git a/webclient/view/default/manageentry/manageentry.php b/webclient/view/default/manageentry/manageentry.php index 5cbb984..06eb6e1 100644 --- a/webclient/view/default/manageentry/manageentry.php +++ b/webclient/view/default/manageentry/manageentry.php @@ -31,113 +31,113 @@ $TemplateData['_editFieldViewDefault'] = Summoner::themefile('manageentry/field- $_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: ".$do.""; - $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: ".$do.""; + $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"; + } } diff --git a/webclient/view/default/manageusers/manageusers.html b/webclient/view/default/manageusers/manageusers.html index 4dc33d2..fd7e98b 100644 --- a/webclient/view/default/manageusers/manageusers.html +++ b/webclient/view/default/manageusers/manageusers.html @@ -1,125 +1,125 @@

User management

-
-

Add or modify a user

-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
-
Can login
-
- -
-
- -
-
Delete
-
- -
-
-
-
Create API Token
-
- -
-
- -
- -
-
-
-
-

Available users

- - - - - - - - - - - - $v) { ?> - - - - - - - - - -
LoginUsernameGroup(s)Status
-
- -
-
    - $gv) { ?> -
  • - -
  • - -
-
- - - -
+
+

Add or modify a user

+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+
+
+
Can login
+
+ +
+
+ +
+
Delete
+
+ +
+
+
+
Create API Token
+
+ +
+
+ +
+ +
+
+
+
+

Available users

+ + + + + + + + + + + + $v) { ?> + + + + + + + + + +
LoginUsernameGroup(s)Status
+
+ +
+
    + $gv) { ?> +
  • + +
  • + +
+
+ + + +
-
+
diff --git a/webclient/view/default/manageusers/manageusers.php b/webclient/view/default/manageusers/manageusers.php index a7e1b89..cf043ca 100644 --- a/webclient/view/default/manageusers/manageusers.php +++ b/webclient/view/default/manageusers/manageusers.php @@ -23,89 +23,89 @@ $TemplateData['editData'] = false; $_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"; + } + } + } + } } diff --git a/webclient/view/default/system/menu.php b/webclient/view/default/system/menu.php index 53bab8c..b9f42cd 100644 --- a/webclient/view/default/system/menu.php +++ b/webclient/view/default/system/menu.php @@ -20,55 +20,55 @@ $_menuShow = $Gorenest->get('show'); $_menuManage = $Gorenest->get('manage'); ?> diff --git a/webclient/view/default/system/message.php b/webclient/view/default/system/message.php index fc8e008..786eaa2 100644 --- a/webclient/view/default/system/message.php +++ b/webclient/view/default/system/message.php @@ -17,26 +17,26 @@ */ 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: - } - } + } + } ?>
-

+

diff --git a/webclient/view/default/system/pagination.html b/webclient/view/default/system/pagination.html index 5fdafa4..08f49ba 100644 --- a/webclient/view/default/system/pagination.html +++ b/webclient/view/default/system/pagination.html @@ -1,36 +1,36 @@ 1) { ?>
    - 1) { - echo '
  • -
  • '; - } + 1) { + echo '
  • +
  • '; + } - $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 '
  • '.$i.'
  • '; - } - else { - if($i < $TemplateData['pagination']['currentRangeStart'] && $ellipsisShown == 0) { - echo '
  • '; - $ellipsisShown = 1; - } - if($i > $TemplateData['pagination']['currentRangeEnd'] && ($ellipsisShown == 0 || $ellipsisShown == 1)) { - echo '
  • '; - $ellipsisShown = 2; - } - } - } + if(in_array($i,$TemplateData['pagination']['visibleRange'])) { + echo '
  • '.$i.'
  • '; + } + else { + if($i < $TemplateData['pagination']['currentRangeStart'] && $ellipsisShown == 0) { + echo '
  • '; + $ellipsisShown = 1; + } + if($i > $TemplateData['pagination']['currentRangeEnd'] && ($ellipsisShown == 0 || $ellipsisShown == 1)) { + echo '
  • '; + $ellipsisShown = 2; + } + } + } - if($TemplateData['pagination']['curPage'] < $TemplateData['pagination']['pages']) { - echo '
  • -
  • '; - } - ?> + if($TemplateData['pagination']['curPage'] < $TemplateData['pagination']['pages']) { + echo '
  • +
  • '; + } + ?>
diff --git a/webclient/view/default/system/pagination_after.php b/webclient/view/default/system/pagination_after.php index 48a106b..0579f02 100644 --- a/webclient/view/default/system/pagination_after.php +++ b/webclient/view/default/system/pagination_after.php @@ -28,27 +28,27 @@ // $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']); } diff --git a/webclient/view/default/system/pagination_before.php b/webclient/view/default/system/pagination_before.php index ac24626..e964ba8 100644 --- a/webclient/view/default/system/pagination_before.php +++ b/webclient/view/default/system/pagination_before.php @@ -28,24 +28,24 @@ $TemplateData['pagination'] = array('pages' => 0); $_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 ); diff --git a/webclient/view/default/tags/tags.html b/webclient/view/default/tags/tags.html index 16f10c1..4034f18 100644 --- a/webclient/view/default/tags/tags.html +++ b/webclient/view/default/tags/tags.html @@ -1,37 +1,37 @@
-
- -

Selectable tags for:

+
+ +

Selectable tags for:

- -
- -

Display result for:

-
- - + +
+ +

Display result for:

+
+ + - $v) { ?> -

-
- $ev) { ?> - , - -
- + $v) { ?> +

+
+ $ev) { ?> + , + +
+ - -

Please select a collection first

-
- $v) { ?> -
-
- -
- -
+ +

Please select a collection first

+
+ $v) { ?> +
+
+ +
+ +
diff --git a/webclient/view/default/tags/tags.php b/webclient/view/default/tags/tags.php index ecda30d..7db18b1 100644 --- a/webclient/view/default/tags/tags.php +++ b/webclient/view/default/tags/tags.php @@ -23,14 +23,14 @@ $Trite = new Trite($DB,$Doomguy); $_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(); @@ -39,26 +39,26 @@ $TemplateData['search'] = 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; } 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(); } diff --git a/webclient/view/default/tool/tool-imdbweb.html b/webclient/view/default/tool/tool-imdbweb.html index cdc541b..2009d43 100644 --- a/webclient/view/default/tool/tool-imdbweb.html +++ b/webclient/view/default/tool/tool-imdbweb.html @@ -4,53 +4,53 @@

Data will be overwritten

-
- -
- -
-
- -
-
+
+ +
+ +
+
+ +
+
- - $v) { - ?> + + $v) { + ?> -
-

-
- -

-
-
- -
+
+

+
+ +

+
+
+ +
- + -
- -
+
+ +
diff --git a/webclient/view/default/tool/tool-imdbweb.php b/webclient/view/default/tool/tool-imdbweb.php index d04cd58..fc1c447 100644 --- a/webclient/view/default/tool/tool-imdbweb.php +++ b/webclient/view/default/tool/tool-imdbweb.php @@ -24,9 +24,9 @@ require_once 'lib/imdbwebparser.class.php'; $IMDB = new IMDB(array( - 'sSearchFor' => 'movie', - 'storage' => PATH_SYSTEMOUT, - 'debug' => false + 'sSearchFor' => 'movie', + 'storage' => PATH_SYSTEMOUT, + 'debug' => false )); @@ -38,116 +38,115 @@ $TemplateData['showMatchingForm'] = false; // create one time and then reuse it $collectionFields = $ManangeCollectionsFields->getExistingFields(); if(!empty($collectionFields)) { - foreach ($collectionFields as $k=>$v) { - $TemplateData['saveToSelection'] .= "\n"; - } + foreach ($collectionFields as $k=>$v) { + $TemplateData['saveToSelection'] .= "\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: - Here"; - } - - 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: + Here"; + } + + 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"; + } + } } - diff --git a/webclient/view/default/tool/tool.html b/webclient/view/default/tool/tool.html index 8cf10d4..da49a9f 100644 --- a/webclient/view/default/tool/tool.html +++ b/webclient/view/default/tool/tool.html @@ -1,12 +1,12 @@

Using with collection:

- +

-
- -
+
+ +
diff --git a/webclient/view/default/tool/tool.php b/webclient/view/default/tool/tool.php index 9f5e6f5..9ba6890 100644 --- a/webclient/view/default/tool/tool.php +++ b/webclient/view/default/tool/tool.php @@ -32,52 +32,51 @@ $TemplateData['editEntry'] = array(); $_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"; + } } - diff --git a/webclient/view/default/ui/css/style.css b/webclient/view/default/ui/css/style.css index e71cb60..4ac5c05 100644 --- a/webclient/view/default/ui/css/style.css +++ b/webclient/view/default/ui/css/style.css @@ -1,13 +1,13 @@ .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; } diff --git a/webclient/view/default/ui/js/suggest-tag.js b/webclient/view/default/ui/js/suggest-tag.js index 2cfdcef..6f5cc7c 100644 --- a/webclient/view/default/ui/js/suggest-tag.js +++ b/webclient/view/default/ui/js/suggest-tag.js @@ -5,17 +5,17 @@ * @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"); + } } /** @@ -26,28 +26,28 @@ function removeTag(tagString,targetStartString) { * @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(); + } } /** @@ -59,17 +59,17 @@ function addTag(e,targetStartString) { * @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; } /** @@ -81,19 +81,19 @@ function _appendToCommaString(theString,toAdd) { * @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; } /** @@ -104,13 +104,13 @@ function _removeFromCommaString(theString,toRemove) { * @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(); + } + } + } } /** @@ -124,14 +124,14 @@ function _removeFromDatalist(list, value) { * @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; }