mancubus.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. <?php
  2. /**
  3. * Bibliotheca
  4. *
  5. * Copyright 2018-2023 Johannes Keßler
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.
  19. */
  20. /**
  21. * Class Mancubus everything to show an entry
  22. */
  23. class Mancubus {
  24. /**
  25. * The database object
  26. *
  27. * @var mysqli
  28. */
  29. private mysqli $_DB;
  30. /**
  31. * The user object to query with
  32. *
  33. * @var Doomguy
  34. */
  35. private Doomguy $_User;
  36. /**
  37. * Currently loaded collection to work with
  38. *
  39. * @var string Number
  40. */
  41. private string $_collectionId;
  42. /**
  43. * Options for db queries
  44. * 'limit' => int,
  45. * 'offset' => int,
  46. * 'orderby' => string,
  47. * 'sortDirection' => ASC|DESC
  48. *
  49. * @var array
  50. */
  51. private array $_queryOptions;
  52. /**
  53. * Store the all the values for an entry from lookup table
  54. *
  55. * @var array
  56. */
  57. private array $_cacheLookupValuesForEntry = array();
  58. /**
  59. * Store entryFields for run time
  60. *
  61. * @var array
  62. */
  63. private array $_cacheEntryFields = array();
  64. /**
  65. * Mancubus constructor.
  66. *
  67. * @param mysqli $databaseConnectionObject
  68. * @param Doomguy $userObj
  69. */
  70. public function __construct(mysqli $databaseConnectionObject, Doomguy $userObj) {
  71. $this->_DB = $databaseConnectionObject;
  72. $this->_User = $userObj;
  73. $this->_setDefaults();
  74. }
  75. /**
  76. * Set the to work with collection id
  77. *
  78. * @param string $collectionId Number
  79. */
  80. public function setCollection(string $collectionId): void {
  81. if(!empty($collectionId)) {
  82. $this->_collectionId = $collectionId;
  83. }
  84. }
  85. /**
  86. * Set the following options which can be used in DB queries
  87. * array(
  88. * 'limit' => RESULTS_PER_PAGE,
  89. * 'offset' => (RESULTS_PER_PAGE * ($_curPage-1)),
  90. * 'orderby' => $_sort,
  91. * 'sortDirection' => $_sortDirection
  92. * );
  93. *
  94. * @param array $options
  95. */
  96. public function setQueryOptions(array $options): void {
  97. if(!isset($options['limit'])) $options['limit'] = 5;
  98. if(!isset($options['offset'])) $options['offset'] = false;
  99. if(!isset($options['sort'])) $options['sort'] = false;
  100. if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
  101. $this->_queryOptions = $options;
  102. }
  103. /**
  104. * Get all available collections for display based on current user
  105. *
  106. * @param string $selections Number of selections
  107. * @param string $entries Number of entries
  108. * @param string $search Search string to search for
  109. * @return array
  110. */
  111. public function getLatest(string $selections, string $entries, string $search = ''): array {
  112. $ret = array();
  113. $queryStr = "SELECT `c`.`id`, `c`.`name`, `c`.`description`, `c`.`created`,
  114. `c`.`owner`, `c`.`group`, `c`.`rights`,
  115. `u`.`name` AS username, `g`.`name` AS groupname
  116. FROM `".DB_PREFIX."_collection` AS c
  117. LEFT JOIN `".DB_PREFIX."_user` AS u ON `c`.`owner` = `u`.`id`
  118. LEFT JOIN `".DB_PREFIX."_group` AS g ON `c`.`group` = `g`.`id`
  119. WHERE ".$this->_User->getSQLRightsString("read", "c")."
  120. ORDER BY `c`.`name`
  121. LIMIT $selections";
  122. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  123. try {
  124. $query = $this->_DB->query($queryStr);
  125. if($query !== false && $query->num_rows > 0) {
  126. while(($result = $query->fetch_assoc()) != false) {
  127. $_mObj = new Mancubus($this->_DB,$this->_User);
  128. $_mObj->setCollection($result['id']);
  129. if(!empty($search)) {
  130. require_once 'lib/trite.class.php';
  131. $_colObj = new Trite($this->_DB,$this->_User);
  132. $_colObj->load($result['id']);
  133. $_fd = $_colObj->getCollectionFields();
  134. $_defSearchField = $_colObj->param('defaultSearchField');
  135. $_mObj->setQueryOptions(array(
  136. 'limit' => $entries,
  137. 'sortDirection' => $_colObj->param('defaultSortOrder'),
  138. 'sort' => $_colObj->param('defaultSortField')
  139. ));
  140. $_defSearchField = $_colObj->param('defaultSearchField');
  141. if(!empty($_defSearchField)) {
  142. $result['entries'] = $_mObj->getEntries(
  143. array(
  144. 0 => array(
  145. 'colName' => $_defSearchField,
  146. 'colValue' => $search,
  147. 'fieldData' => $_fd[$_defSearchField]
  148. )
  149. )
  150. );
  151. }
  152. else {
  153. Summoner::sysLog("[WARN] ".__METHOD__." missing default search field for collectionid: ".$result['id']);
  154. }
  155. }
  156. else {
  157. $result['entries'] = $_mObj->getEntries();
  158. }
  159. $ret[$result['id']] = $result;
  160. unset($_mObj);
  161. }
  162. }
  163. }
  164. catch (Exception $e) {
  165. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  166. }
  167. return $ret;
  168. }
  169. /**
  170. * Get entries for loaded collection limited by search
  171. * and already set query options
  172. *
  173. * array[0] => array(
  174. * 'colName' => 'column name to search in',
  175. * 'colValue' => 'Value to search for',
  176. * 'fieldData' => field data from Trite->getCollectionFields()
  177. * 'exactTagMatch' => true to make a binary compare. false for match against search
  178. * )
  179. *
  180. * return array(
  181. * 'results' => array(),
  182. * 'amount' => int,
  183. * 'ids' => array()
  184. * )
  185. *
  186. * @param array $searchData
  187. * @return array
  188. */
  189. public function getEntries(array $searchData = array()): array {
  190. $ret = array();
  191. if(!empty($this->_collectionId)) {
  192. // split since part of it is used later
  193. $querySelect = "SELECT *";
  194. $queryFrom = " FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."` AS t";
  195. $queryJoin = '';
  196. $queryWhere = " WHERE ".$this->_User->getSQLRightsString("read", "t")."";
  197. $_isFulltext = false;
  198. if(!empty($searchData)) {
  199. // this search supports fulltext search and number <> search.
  200. // also can search in the entry2lookup table.
  201. // not perfect but it works
  202. foreach($searchData as $k=>$sd) {
  203. if(!isset($sd['colName']) || !isset($sd['colValue']) || empty($sd['colValue'])) continue;
  204. if($sd['fieldData']['searchtype'] == "tag") {
  205. $_isFulltext = true;
  206. $queryJoin = " LEFT JOIN `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."` AS e2l ON e2l.fk_entry=t.id";
  207. $queryWhere .= " AND e2l.fk_field = '".$this->_DB->real_escape_string($sd['fieldData']['id'])."'";
  208. if(isset($sd['exactTagMatch']) && $sd['exactTagMatch'] === true) {
  209. $queryWhere .= " AND e2l.value = BINARY '".$this->_DB->real_escape_string($sd['colValue'])."'";
  210. $_isFulltext = false;
  211. }
  212. else {
  213. $queryWhere .= " AND MATCH (e2l.value) AGAINST ('".$this->_DB->real_escape_string($sd['colValue'])."' IN BOOLEAN MODE)";
  214. }
  215. }
  216. elseif ($sd['fieldData']['searchtype'] == "entrySingleNum" && strstr($sd['colValue'],'<')) {
  217. $_s = str_replace('<','',$sd['colValue']);
  218. $queryWhere .= " AND `t`.`".$this->_DB->real_escape_string($sd['colName'])."` < ".(int)$_s."";
  219. }
  220. elseif ($sd['fieldData']['searchtype'] == "entrySingleNum" && strstr($sd['colValue'],'>')) {
  221. $_s = str_replace('>','',$sd['colValue']);
  222. $queryWhere .= " AND `t`.`".$this->_DB->real_escape_string($sd['colName'])."` > ".(int)$_s."";
  223. }
  224. elseif($sd['fieldData']['searchtype'] == "entryText") {
  225. $_isFulltext = true;
  226. $queryWhere .= " AND MATCH (`t`.`".$this->_DB->real_escape_string($sd['colName'])."`)
  227. AGAINST ('".$this->_DB->real_escape_string($sd['colValue'])."' IN BOOLEAN MODE)";
  228. }
  229. else {
  230. $queryWhere .= " AND `t`.`".$this->_DB->real_escape_string($sd['colName'])."` = '".$this->_DB->real_escape_string($sd['colValue'])."'";
  231. }
  232. }
  233. }
  234. $queryOrder = '';
  235. if(!$_isFulltext) { // fulltext do not order. Which results in ordering be relevance of the match
  236. $queryOrder = " ORDER BY";
  237. if (!empty($this->_queryOptions['sort'])) {
  238. $queryOrder .= ' t.'.$this->_queryOptions['sort'];
  239. }
  240. else {
  241. $queryOrder .= " t.created";
  242. }
  243. if (!empty($this->_queryOptions['sortDirection'])) {
  244. $queryOrder .= ' '.$this->_queryOptions['sortDirection'];
  245. }
  246. else {
  247. $queryOrder .= " ASC";
  248. }
  249. }
  250. $queryLimit = '';
  251. if(!empty($this->_queryOptions['limit'])) {
  252. $queryLimit .= " LIMIT ".$this->_queryOptions['limit'];
  253. # offset can be 0
  254. if($this->_queryOptions['offset'] !== false) {
  255. $queryLimit .= " OFFSET ".$this->_queryOptions['offset'];
  256. }
  257. }
  258. $queryStr = $querySelect.$queryFrom.$queryJoin.$queryWhere.$queryOrder.$queryLimit;
  259. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  260. try {
  261. $query = $this->_DB->query($queryStr);
  262. if($query !== false && $query->num_rows > 0) {
  263. $_entryFields = $this->_getEntryFields();
  264. while(($result = $query->fetch_assoc()) != false) {
  265. $result = $this->_mergeEntryWithFields($result, $_entryFields);
  266. $ret['results'][$result['id']] = $result;
  267. $ret['ids'][] = $result['id'];
  268. }
  269. $queryStrCount = "SELECT COUNT(t.id) AS amount ".$queryFrom.$queryJoin.$queryWhere;
  270. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStrCount));
  271. $query = $this->_DB->query($queryStrCount);
  272. $result = $query->fetch_assoc();
  273. $ret['amount'] = $result['amount'];
  274. }
  275. }
  276. catch (Exception $e) {
  277. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  278. }
  279. }
  280. return $ret;
  281. }
  282. /**
  283. * Retrieve all the data needed to display the entry for given entryId
  284. *
  285. * @param string $entryId Number
  286. * @return array
  287. */
  288. public function getEntry(string $entryId): array {
  289. $ret = array();
  290. if(!empty($this->_collectionId) && !empty($entryId)) {
  291. $queryStr = "SELECT *
  292. FROM `".DB_PREFIX."_collection_entry_".$this->_DB->real_escape_string($this->_collectionId)."`
  293. WHERE ".$this->_User->getSQLRightsString()."
  294. AND `id` = '".$this->_DB->real_escape_string($entryId)."'";
  295. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  296. try {
  297. $query = $this->_DB->query($queryStr);
  298. if($query !== false && $query->num_rows > 0) {
  299. $_entryFields = $this->_getEntryFields();
  300. if(($result = $query->fetch_assoc()) != false) {
  301. $ret = $this->_mergeEntryWithFields($result, $_entryFields);
  302. }
  303. }
  304. }
  305. catch (Exception $e) {
  306. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  307. }
  308. }
  309. return $ret;
  310. }
  311. /**
  312. * Return the storage info for loaded collection
  313. * Used by API
  314. *
  315. * @return array
  316. */
  317. public function getEntryStructure(): array {
  318. $ret = array();
  319. $_entryFields = $this->_getEntryFields();
  320. $ret = $this->_mergeEntryWithFields($ret, $_entryFields);
  321. return $ret;
  322. }
  323. /**
  324. * Load the fields from the loaded collection
  325. *
  326. * @return array
  327. */
  328. private function _getEntryFields(): array {
  329. if(!empty($this->_cacheEntryFields)) {
  330. return $this->_cacheEntryFields;
  331. }
  332. if(!empty($this->_collectionId)) {
  333. $queryStr = "SELECT `cf`.`fk_field_id` AS id, `sf`.`type`, `sf`.`displayname`, `sf`.`identifier`,
  334. `sf`.`value` AS preValue, `sf`.`apiinfo` , `sf`.`searchtype`
  335. FROM `".DB_PREFIX."_collection_fields_".$this->_DB->real_escape_string($this->_collectionId)."` AS cf
  336. LEFT JOIN `".DB_PREFIX."_sys_fields` AS sf ON `cf`.`fk_field_id` = `sf`.`id`
  337. ORDER BY `cf`.`sort`";
  338. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  339. try {
  340. $query = $this->_DB->query($queryStr);
  341. if($query !== false && $query->num_rows > 0) {
  342. while(($result = $query->fetch_assoc()) != false) {
  343. $this->_cacheEntryFields[$result['id']] = $result;
  344. }
  345. }
  346. }
  347. catch (Exception $e) {
  348. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  349. }
  350. }
  351. return $this->_cacheEntryFields;
  352. }
  353. /**
  354. * Merge the loaded information from collection_entry with the given
  355. * configured fields
  356. *
  357. * @param array $entryData Loaded entry
  358. * @param array $entryFields Loaded fields
  359. * @return mixed
  360. */
  361. private function _mergeEntryWithFields(array $entryData, array $entryFields): array {
  362. if(!empty($entryFields)) {
  363. foreach($entryFields as $f) {
  364. $_mnValue = '_loadFieldValue_'.$f['type'];
  365. if(isset($entryData[$f['identifier']])) {
  366. $f['value'] = $entryData[$f['identifier']];
  367. unset($entryData[$f['identifier']]);
  368. } elseif(method_exists($this, $_mnValue) && isset($entryData['id'])) {
  369. $f['value'] = $this->$_mnValue($entryData['id'], $f);
  370. }
  371. $_mnSelectionValue = '_loadFieldSelection_'.$f['type'];
  372. if(method_exists($this, $_mnSelectionValue) && isset($f['preValue'])) {
  373. $f['preValue'] = $this->$_mnSelectionValue($f['preValue']);
  374. }
  375. $entryData['fields'][$f['identifier']] = $f;
  376. }
  377. }
  378. return $entryData;
  379. }
  380. /**
  381. * Load the values for given $entryId for $fieldData
  382. * lookup function for field type lookupmultiple
  383. *
  384. * @param string $entryId Number
  385. * @param array $fieldData
  386. * @return array
  387. */
  388. private function _loadFieldValue_lookupmultiple(string $entryId, array $fieldData): array {
  389. $ret = array();
  390. if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
  391. // avoid db query for each wanted value
  392. if(isset($this->_cacheLookupValuesForEntry[$this->_collectionId])) {
  393. if(isset($this->_cacheLookupValuesForEntry[$this->_collectionId][$entryId][$fieldData['id']])) {
  394. $ret = $this->_cacheLookupValuesForEntry[$this->_collectionId][$entryId][$fieldData['id']];
  395. }
  396. }
  397. else {
  398. $queryStr = "SELECT `fk_field`, `value`, `fk_entry`
  399. FROM `".DB_PREFIX."_collection_entry2lookup_".$this->_DB->real_escape_string($this->_collectionId)."`";
  400. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  401. try {
  402. $query = $this->_DB->query($queryStr);
  403. if($query !== false && $query->num_rows > 0) {
  404. while(($result = $query->fetch_assoc()) != false) {
  405. $this->_cacheLookupValuesForEntry[$this->_collectionId][$result['fk_entry']][$result['fk_field']][$result['value']] = $result['value'];
  406. }
  407. }
  408. }
  409. catch (Exception $e) {
  410. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  411. }
  412. if(isset($this->_cacheLookupValuesForEntry[$this->_collectionId][$entryId][$fieldData['id']])) {
  413. $ret = $this->_cacheLookupValuesForEntry[$this->_collectionId][$entryId][$fieldData['id']];
  414. }
  415. }
  416. }
  417. return $ret;
  418. }
  419. /**
  420. * Get the single upload file from storage location
  421. * lookup function for field type upload
  422. *
  423. * @param string $entryId Number
  424. * @param array $fieldData
  425. * @return string
  426. */
  427. private function _loadFieldValue_upload(string $entryId, array $fieldData): string {
  428. $ret = "";
  429. if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
  430. $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
  431. if(!empty($uploadedFile)) {
  432. foreach ($uploadedFile as $f) {
  433. $ret = basename($f);
  434. break;
  435. }
  436. }
  437. }
  438. return $ret;
  439. }
  440. /**
  441. * Get the multiple upload files from storage location
  442. * lookup function for field type upload_multiple
  443. *
  444. * @param string $entryId Number
  445. * @param array $fieldData
  446. * @return array
  447. */
  448. private function _loadFieldValue_upload_multiple(string $entryId, array $fieldData): array {
  449. $ret = array();
  450. if(!empty($entryId) && !empty($fieldData) && !empty($this->_collectionId)) {
  451. $uploadedFile = glob(PATH_STORAGE.'/'.$this->_collectionId.'/'.$entryId.'/'.$fieldData['identifier'].'-*');
  452. if(!empty($uploadedFile)) {
  453. foreach ($uploadedFile as $f) {
  454. $ret[] = basename($f);
  455. }
  456. }
  457. }
  458. return $ret;
  459. }
  460. /**
  461. * Load and prepare the value for a selection field
  462. *
  463. * @param string $data
  464. * @return array
  465. */
  466. private function _loadFieldSelection_selection(string $data): array {
  467. $ret = array();
  468. if(is_string($data)) {
  469. if(strstr($data, ',')) {
  470. $ret = explode(',',$data);
  471. }
  472. else {
  473. $ret[] = $data;
  474. }
  475. }
  476. return $ret;
  477. }
  478. /**
  479. * set some defaults by init of the class
  480. *
  481. * @return void
  482. */
  483. private function _setDefaults(): void {
  484. // default query options
  485. $options['limit'] = 5;
  486. $options['offset'] = false;
  487. $options['sort'] = false;
  488. $options['sortDirection'] = false;
  489. $this->setQueryOptions($options);
  490. }
  491. }