management.class.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. <?php
  2. /**
  3. * Insipid
  4. * Personal web-bookmark-system
  5. *
  6. * Copyright 2016-2023 Johannes Keßler
  7. *
  8. * Development starting from 2011: Johannes Keßler
  9. * https://www.bananas-playground.net/projekt/insipid/
  10. *
  11. * creator:
  12. * Luke Reeves <luke@neuro-tech.net>
  13. *
  14. * This program is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation, either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.
  26. *
  27. */
  28. /**
  29. * Class Management
  30. */
  31. class Management {
  32. /**
  33. * Default value
  34. */
  35. const LINK_QUERY_STATUS = 2;
  36. /**
  37. * the database object
  38. *
  39. * @var mysqli
  40. */
  41. private mysqli $DB;
  42. /**
  43. * Type of links based on status to show
  44. *
  45. * @var int
  46. */
  47. private int $_queryStatus = self::LINK_QUERY_STATUS;
  48. /**
  49. * @var array Store already loaded categories to avoid unneeded queries
  50. */
  51. private array $_categories;
  52. /**
  53. * Management constructor.
  54. *
  55. * @param mysqli $databaseConnectionObject
  56. * @return void
  57. */
  58. public function __construct(mysqli $databaseConnectionObject) {
  59. $this->DB = $databaseConnectionObject;
  60. }
  61. /**
  62. * Show private links or not
  63. *
  64. * @param boolean $bool
  65. * @return void
  66. */
  67. public function setShowPrivate(bool $bool): void {
  68. $this->_queryStatus = self::LINK_QUERY_STATUS;
  69. if($bool === true) {
  70. $this->_queryStatus = 1;
  71. }
  72. }
  73. /**
  74. * Show awaiting moderation links or not
  75. *
  76. * @param boolean $bool
  77. * @return void
  78. */
  79. public function setShowAwm(bool $bool): void {
  80. $this->_queryStatus = self::LINK_QUERY_STATUS;
  81. if($bool === true) {
  82. $this->_queryStatus = 3;
  83. }
  84. }
  85. /**
  86. * get all the available categories from the DB.
  87. * optional limit
  88. * optional stats
  89. *
  90. * @param string $limit
  91. * @param bool $stats
  92. * @return array
  93. */
  94. public function categories(string $limit="0", bool $stats=false): array {
  95. $ret = array();
  96. $statsInfo = array();
  97. if(!empty($this->_categories)) return $this->_categories;
  98. if($stats === true) {
  99. $queryStr = "SELECT
  100. COUNT(*) AS amount,
  101. cr.categoryid AS categoryId
  102. FROM `".DB_PREFIX."_categoryrelation` AS cr,
  103. `".DB_PREFIX."_link` AS t
  104. WHERE cr.linkid = t.id";
  105. $queryStr .= " AND ".$this->_decideLinkTypeForQuery();
  106. $queryStr .= " GROUP BY categoryid";
  107. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  108. try {
  109. $query = $this->DB->query($queryStr);
  110. if(!empty($query) && $query->num_rows > 0) {
  111. while($result = $query->fetch_assoc()) {
  112. $statsInfo[$result['categoryId']] = $result['amount'];
  113. }
  114. }
  115. } catch (Exception $e) {
  116. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  117. }
  118. }
  119. $queryStr = "SELECT `id`, `name`
  120. FROM `".DB_PREFIX."_category`
  121. ORDER BY `name` ASC";
  122. if(!empty($limit)) {
  123. $queryStr .= " LIMIT $limit";
  124. }
  125. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  126. try {
  127. $query = $this->DB->query($queryStr);
  128. if(!empty($query) && $query->num_rows > 0) {
  129. while($result = $query->fetch_assoc()) {
  130. if($stats === true && isset($statsInfo[$result['id']])) {
  131. $ret[$result['id']] = array('name' => $result['name'], 'amount' => $statsInfo[$result['id']]);
  132. }
  133. else {
  134. $ret[$result['id']] = array('name' => $result['name'], 'amount' => 0);
  135. }
  136. }
  137. }
  138. } catch (Exception $e) {
  139. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  140. }
  141. $this->_categories = $ret;
  142. return $ret;
  143. }
  144. /**
  145. * get all the available tags from the DB.
  146. * optional limit
  147. * optional stats
  148. *
  149. * @param string $limit
  150. * @param bool $stats
  151. * @return array
  152. */
  153. public function tags(string $limit="0", bool $stats=false): array {
  154. $ret = array();
  155. $statsInfo = array();
  156. if($stats === true) {
  157. $queryStr = "SELECT COUNT(*) AS amount,
  158. tr.tagid AS tagId
  159. FROM `".DB_PREFIX."_tagrelation` AS tr, `".DB_PREFIX."_link` AS t
  160. WHERE tr.linkid = t.id";
  161. $queryStr .= " AND ".$this->_decideLinkTypeForQuery();
  162. $queryStr .= " GROUP BY tagId";
  163. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  164. try {
  165. $query = $this->DB->query($queryStr);
  166. if(!empty($query) && $query->num_rows > 0) {
  167. while($result = $query->fetch_assoc()) {
  168. $statsInfo[$result['tagId']] = $result['amount'];
  169. }
  170. }
  171. } catch (Exception $e) {
  172. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  173. }
  174. }
  175. $queryStr = "SELECT `id`, `name`
  176. FROM `".DB_PREFIX."_tag`
  177. ORDER BY `name` ASC";
  178. if(!empty($limit)) {
  179. $queryStr .= " LIMIT $limit";
  180. }
  181. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  182. try {
  183. $query = $this->DB->query($queryStr);
  184. if(!empty($query) && $query->num_rows > 0) {
  185. while($result = $query->fetch_assoc()) {
  186. if($stats === true && isset($statsInfo[$result['id']])) {
  187. $ret[$result['id']] = array('name' => $result['name'], 'amount' => $statsInfo[$result['id']]);
  188. }
  189. else {
  190. $ret[$result['id']] = array('name' => $result['name'], 'amount' => 0);
  191. }
  192. }
  193. }
  194. } catch (Exception $e) {
  195. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  196. }
  197. return $ret;
  198. }
  199. /**
  200. * return the latest added links
  201. *
  202. * @param string $limit
  203. * @return array
  204. */
  205. public function latestLinks(string $limit="5"): array {
  206. $ret = array();
  207. $queryStr = "SELECT `title`, `link` FROM `".DB_PREFIX."_link` AS t";
  208. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  209. $queryStr .= " ORDER BY `created` DESC";
  210. if(!empty($limit)) {
  211. $queryStr .= " LIMIT $limit";
  212. }
  213. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  214. try {
  215. $query = $this->DB->query($queryStr);
  216. if(!empty($query) && $query->num_rows > 0) {
  217. $ret = $query->fetch_all(MYSQLI_ASSOC);
  218. }
  219. } catch (Exception $e) {
  220. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  221. }
  222. return $ret;
  223. }
  224. /**
  225. * Return a random entry from link table.
  226. * Slow but does the trick for now. If there is way more entries
  227. * re-think this solution
  228. *
  229. * @param String $limit
  230. * @return array
  231. */
  232. public function randomLink(string $limit="1"): array {
  233. $ret = array();
  234. $amount = $this->linkAmount();
  235. $offset = rand(0, $amount-1);
  236. $queryStr = "SELECT `title`, `link`, `hash` FROM `".DB_PREFIX."_link` AS t";
  237. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  238. $queryStr .= " LIMIT $offset, $limit";
  239. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  240. try {
  241. $query = $this->DB->query($queryStr);
  242. if(!empty($query) && $query->num_rows > 0) {
  243. $ret = $query->fetch_all(MYSQLI_ASSOC);
  244. }
  245. } catch (Exception $e) {
  246. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  247. }
  248. return $ret;
  249. }
  250. /**
  251. * Get a random category
  252. *
  253. * @param string $limit
  254. * @return array
  255. */
  256. public function randomCategory(string $limit="1"): array {
  257. $ret = array();
  258. $amount = $this->categoryAmount();
  259. $offset = rand(0, $amount-1);
  260. $queryStr = "SELECT `id`, `name` FROM `".DB_PREFIX."_category`";
  261. $queryStr .= " LIMIT $offset, $limit";
  262. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  263. try {
  264. $query = $this->DB->query($queryStr);
  265. if(!empty($query) && $query->num_rows > 0) {
  266. $ret = $query->fetch_all(MYSQLI_ASSOC);
  267. }
  268. } catch (Exception $e) {
  269. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  270. }
  271. return $ret;
  272. }
  273. /**
  274. * Get a random tag
  275. *
  276. * @param string $limit
  277. * @return array
  278. */
  279. public function randomTag(string $limit="1"): array {
  280. $ret = array();
  281. $amount = $this->tagAmount();
  282. $offset = rand(0, $amount-1);
  283. $queryStr = "SELECT `id`, `name` FROM `".DB_PREFIX."_tag`";
  284. $queryStr .= " LIMIT $offset, $limit";
  285. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  286. try {
  287. $query = $this->DB->query($queryStr);
  288. if(!empty($query) && $query->num_rows > 0) {
  289. $ret = $query->fetch_all(MYSQLI_ASSOC);
  290. }
  291. } catch (Exception $e) {
  292. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  293. }
  294. return $ret;
  295. }
  296. /**
  297. * get all the categories ordered by link added date
  298. *
  299. * @return array
  300. */
  301. public function categoriesByDateAdded(): array {
  302. $ret = array();
  303. $categories = $this->categories();
  304. foreach($categories as $k=>$v) {
  305. $latestLink = $this->latestLinkForCategory($k);
  306. if(!empty($latestLink)) {
  307. $ret[] = array('created' => $latestLink[0]['created'], 'id' => $k, 'name' => $v['name']);
  308. }
  309. }
  310. $_created = array_column($ret, 'created');
  311. array_multisort($_created, SORT_DESC, $ret);
  312. return $ret;
  313. }
  314. /**
  315. * find all links by given category string or id.
  316. * Return array sorted by creation date DESC
  317. *
  318. * @param string $id Category ID
  319. * @param array $options Array with limit|offset|sort|sortDirection
  320. * @return array
  321. */
  322. public function linksByCategory(string $id, array $options=array()): array {
  323. $ret = array();
  324. if(!isset($options['limit'])) $options['limit'] = 5;
  325. if(!isset($options['offset'])) $options['offset'] = false;
  326. if(!isset($options['sort'])) $options['sort'] = false;
  327. if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
  328. $querySelect = "SELECT `id`, `link`, `created`, `status`, `title`, `hash`, `description`, `image`";
  329. $queryFrom = " FROM `".DB_PREFIX."_link` AS t
  330. LEFT JOIN insipid_categoryrelation AS cr ON cr.linkid = t.id";
  331. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  332. if(!empty($id) && is_numeric($id)) {
  333. $queryWhere .= " AND cr.categoryId = '" . $this->DB->real_escape_string($id) . "'";
  334. }
  335. else {
  336. return $ret;
  337. }
  338. $queryOrder = " ORDER BY";
  339. if(!empty($options['sort'])) {
  340. $queryOrder .= ' t.'.$options['sort'];
  341. }
  342. else {
  343. $queryOrder .= " t.created";
  344. }
  345. if(!empty($options['sortDirection'])) {
  346. $queryOrder .= ' '.$options['sortDirection'];
  347. }
  348. else {
  349. $queryOrder .= " DESC";
  350. }
  351. $queryLimit = '';
  352. # this allows the set the limit to false
  353. if(!empty($options['limit'])) {
  354. $queryLimit .= " LIMIT ".$options['limit'];
  355. # offset can be 0
  356. if($options['offset'] !== false) {
  357. $queryLimit .= " OFFSET ".$options['offset'];
  358. }
  359. }
  360. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit));
  361. try {
  362. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
  363. if(!empty($query) && $query->num_rows > 0) {
  364. while($result = $query->fetch_assoc()) {
  365. $linkObj = new Link($this->DB);
  366. $ret['results'][] = $linkObj->loadFromDataShortInfo($result);
  367. unset($linkObj);
  368. }
  369. $query = $this->DB->query("SELECT COUNT(DISTINCT(t.hash)) AS amount ".$queryFrom.$queryWhere);
  370. $result = $query->fetch_assoc();
  371. $ret['amount'] = $result['amount'];
  372. }
  373. } catch (Exception $e) {
  374. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  375. }
  376. return $ret;
  377. }
  378. /**
  379. * find all links by given tag string or id.
  380. * Return array sorted by creation date DESC
  381. *
  382. * @param string $id Tag id
  383. * @param array $options Array with limit|offset|sort|sortDirection
  384. * @return array
  385. */
  386. public function linksByTag(string $id, array $options=array()): array {
  387. $ret = array();
  388. if(!isset($options['limit'])) $options['limit'] = 5;
  389. if(!isset($options['offset'])) $options['offset'] = false;
  390. if(!isset($options['sort'])) $options['sort'] = false;
  391. if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
  392. $querySelect = "SELECT `id`, `link`, `created`, `status`, `title`, `hash`, `description`, `image`";
  393. $queryFrom = " FROM `".DB_PREFIX."_link` AS t
  394. LEFT JOIN insipid_tagrelation AS tr ON tr.linkid = t.id";
  395. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  396. if(!empty($id) && is_numeric($id)) {
  397. $queryWhere .= " AND tr.tagId = '".$this->DB->real_escape_string($id)."'";
  398. }
  399. else {
  400. return $ret;
  401. }
  402. $queryOrder = " ORDER BY";
  403. if(!empty($options['sort'])) {
  404. $queryOrder .= ' t.'.$options['sort'];
  405. }
  406. else {
  407. $queryOrder .= " t.created";
  408. }
  409. if(!empty($options['sortDirection'])) {
  410. $queryOrder .= ' '.$options['sortDirection'];
  411. }
  412. else {
  413. $queryOrder .= " DESC";
  414. }
  415. $queryLimit = '';
  416. # this allows the set the limit to false
  417. if(!empty($options['limit'])) {
  418. $queryLimit .= " LIMIT ".$options['limit'];
  419. # offset can be 0
  420. if($options['offset'] !== false) {
  421. $queryLimit .= " OFFSET ".$options['offset'];
  422. }
  423. }
  424. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit));
  425. try {
  426. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
  427. if(!empty($query) && $query->num_rows > 0) {
  428. while($result = $query->fetch_assoc()) {
  429. $linkObj = new Link($this->DB);
  430. $ret['results'][] = $linkObj->loadFromDataShortInfo($result);
  431. unset($linkObj);
  432. }
  433. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryFrom.$queryWhere));
  434. $query = $this->DB->query("SELECT COUNT(DISTINCT(t.hash)) AS amount ".$queryFrom.$queryWhere);
  435. $result = $query->fetch_assoc();
  436. $ret['amount'] = $result['amount'];
  437. }
  438. } catch (Exception $e) {
  439. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  440. }
  441. return $ret;
  442. }
  443. /**
  444. * return all links and Info we have from the combined view
  445. *
  446. * @param array $options
  447. * @return array
  448. */
  449. public function links(array $options=array()): array {
  450. $ret = array();
  451. if(!isset($options['limit'])) $options['limit'] = 5;
  452. if(!isset($options['offset'])) $options['offset'] = false;
  453. if(!isset($options['sort'])) $options['sort'] = false;
  454. if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
  455. $querySelect = "SELECT `hash`";
  456. $queryFrom = " FROM `".DB_PREFIX."_link` AS t";
  457. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  458. $queryOrder = " ORDER BY";
  459. if(!empty($options['sort'])) {
  460. $queryOrder .= ' t.'.$options['sort'];
  461. }
  462. else {
  463. $queryOrder .= " t.created";
  464. }
  465. if(!empty($options['sortDirection'])) {
  466. $queryOrder .= ' '.$options['sortDirection'];
  467. }
  468. else {
  469. $queryOrder .= " DESC";
  470. }
  471. $queryLimit = '';
  472. # this allows the set the limit to false
  473. if(!empty($options['limit'])) {
  474. $queryLimit .= " LIMIT ".$options['limit'];
  475. # offset can be 0
  476. if($options['offset'] !== false) {
  477. $queryLimit .= " OFFSET ".$options['offset'];
  478. }
  479. }
  480. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit));
  481. try {
  482. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
  483. if(!empty($query) && $query->num_rows > 0) {
  484. while($result = $query->fetch_assoc()) {
  485. $linkObj = new Link($this->DB);
  486. $ret['results'][] = $linkObj->loadShortInfo($result['hash']);
  487. unset($linkObj);
  488. }
  489. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryFrom.$queryWhere));
  490. $query = $this->DB->query("SELECT COUNT(t.hash) AS amount ".$queryFrom.$queryWhere);
  491. $result = $query->fetch_assoc();
  492. $ret['amount'] = $result['amount'];
  493. }
  494. } catch (Exception $e) {
  495. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  496. }
  497. return $ret;
  498. }
  499. /**
  500. * return the latest added link for given category id
  501. *
  502. * @param string $categoryid
  503. * @return array
  504. */
  505. public function latestLinkForCategory(string $categoryid): array {
  506. $ret = array();
  507. if(!empty($categoryid) && is_numeric($categoryid)) {
  508. $queryStr = "SELECT `id`, `link`, `created`, `status`, `description`, `title`, `image`, `hash`,
  509. `tag`, `category`, `categoryId`, `tagId`
  510. FROM `".DB_PREFIX."_combined` AS t";
  511. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  512. $queryStr .= " AND t.categoryId = '" . $this->DB->real_escape_string($categoryid) . "'
  513. ORDER BY t.created DESC
  514. LIMIT 1";
  515. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  516. try {
  517. $query = $this->DB->query($queryStr);
  518. if(!empty($query) && $query->num_rows > 0) {
  519. $ret = $query->fetch_all(MYSQLI_ASSOC);
  520. }
  521. } catch (Exception $e) {
  522. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  523. }
  524. }
  525. return $ret;
  526. }
  527. /**
  528. * Search for the given url in the links table
  529. *
  530. * @param string $url
  531. * @return array
  532. */
  533. public function searchForLinkByURL(string $url): array {
  534. $ret = array();
  535. if(!empty($url)) {
  536. $queryStr = "SELECT `id`, `link`, `title`, `hash`
  537. FROM `".DB_PREFIX."_link` AS t";
  538. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  539. $queryStr .= " AND t.link = '".$this->DB->real_escape_string($url)."'";
  540. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  541. try {
  542. $query = $this->DB->query($queryStr);
  543. if(!empty($query) && $query->num_rows > 0) {
  544. $ret = $query->fetch_all(MYSQLI_ASSOC);
  545. }
  546. } catch (Exception $e) {
  547. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  548. }
  549. }
  550. return $ret;
  551. }
  552. /**
  553. * search for given searchstring in the search data of the links
  554. *
  555. * @param string $searchStr
  556. * @return array
  557. */
  558. public function searchForLinkBySearchData(string $searchStr): array {
  559. $ret = array();
  560. if(!empty($searchStr)) {
  561. $queryStr = "SELECT `id`, `link`, `title`, `hash`,
  562. MATCH (`search`) AGAINST ('".$this->DB->real_escape_string($searchStr)."' IN BOOLEAN MODE) AS score
  563. FROM `".DB_PREFIX."_link` AS t
  564. WHERE MATCH (`search`) AGAINST ('".$this->DB->real_escape_string($searchStr)."' IN BOOLEAN MODE)";
  565. $queryStr .= " AND ".$this->_decideLinkTypeForQuery();
  566. $queryStr .= " ORDER BY score DESC";
  567. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  568. try {
  569. $query = $this->DB->query($queryStr);
  570. if(!empty($query) && $query->num_rows > 0) {
  571. $ret = $query->fetch_all(MYSQLI_ASSOC);
  572. }
  573. } catch (Exception $e) {
  574. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  575. }
  576. }
  577. return $ret;
  578. }
  579. /**
  580. * amount of links in the DB. Status 1 and 2 only
  581. *
  582. * @return string
  583. */
  584. public function linkAmount(): string {
  585. $ret = 0;
  586. $queryStr = "SELECT COUNT(*) AS amount
  587. FROM `".DB_PREFIX."_link` AS t";
  588. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  589. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  590. try {
  591. $query = $this->DB->query($queryStr);
  592. if(!empty($query) && $query->num_rows > 0) {
  593. $result = $query->fetch_assoc();
  594. $ret = $result['amount'];
  595. }
  596. } catch (Exception $e) {
  597. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  598. }
  599. return $ret;
  600. }
  601. /**
  602. * amount of tags
  603. *
  604. * @return string
  605. */
  606. public function tagAmount(): string {
  607. $ret = 0;
  608. $queryStr = "SELECT COUNT(*) AS amount FROM `".DB_PREFIX."_tag`";
  609. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  610. try {
  611. $query = $this->DB->query($queryStr);
  612. if(!empty($query) && $query->num_rows > 0) {
  613. $result = $query->fetch_assoc();
  614. $ret = $result['amount'];
  615. }
  616. } catch (Exception $e) {
  617. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  618. }
  619. return $ret;
  620. }
  621. /**
  622. * amount of categories
  623. *
  624. * @return string
  625. */
  626. public function categoryAmount(): string {
  627. $ret = 0;
  628. $queryStr = "SELECT COUNT(*) AS amount FROM `".DB_PREFIX."_category`";
  629. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  630. try {
  631. $query = $this->DB->query($queryStr);
  632. if(!empty($query) && $query->num_rows > 0) {
  633. $result = $query->fetch_assoc();
  634. $ret = $result['amount'];
  635. }
  636. } catch (Exception $e) {
  637. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  638. }
  639. return $ret;
  640. }
  641. /**
  642. * Amount of links need moderation
  643. *
  644. * @return string
  645. */
  646. public function moderationAmount(): string {
  647. $ret = 0;
  648. $queryStr = "SELECT COUNT(*) AS amount FROM `".DB_PREFIX."_link`";
  649. $queryStr .= " WHERE `status` = 3";
  650. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  651. try {
  652. $query = $this->DB->query($queryStr);
  653. if(!empty($query) && $query->num_rows > 0) {
  654. $result = $query->fetch_assoc();
  655. $ret = $result['amount'];
  656. }
  657. } catch (Exception $e) {
  658. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  659. }
  660. return $ret;
  661. }
  662. /**
  663. * get the used disk space for local image storage
  664. *
  665. * @return int
  666. */
  667. public function storageAmount(): int {
  668. $ret = 0;
  669. $_storageFolder = ABSOLUTE_PATH.'/'.LOCAL_STORAGE;
  670. if(file_exists($_storageFolder) && is_readable($_storageFolder)) {
  671. $ret = Summoner::folderSize($_storageFolder);
  672. }
  673. return $ret;
  674. }
  675. /**
  676. * empties the local storage directory
  677. *
  678. * @return bool
  679. */
  680. public function clearLocalStorage(): bool {
  681. $ret = false;
  682. $_storageFolder = ABSOLUTE_PATH.'/'.LOCAL_STORAGE;
  683. if(file_exists($_storageFolder) && is_writable($_storageFolder)) {
  684. $ret = Summoner::recursive_remove_directory($_storageFolder,true);
  685. }
  686. return $ret;
  687. }
  688. /**
  689. * Load link by given hash. Do not use Link class directly.
  690. * Otherwise the authentication will be ignored.
  691. *
  692. * @param String $hash Link hash
  693. * @param bool $fullInfo Load all the info we have
  694. * @param bool $withObject An array with data and the link obj itself
  695. * @return array
  696. */
  697. public function loadLink(string $hash, bool $fullInfo=true, bool $withObject=false): array {
  698. $ret = array();
  699. if (!empty($hash)) {
  700. $querySelect = "SELECT `hash`";
  701. $queryFrom = " FROM `".DB_PREFIX."_link` AS t";
  702. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  703. $queryWhere .= " AND t.hash = '".$this->DB->real_escape_string($hash)."'";
  704. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere));
  705. try {
  706. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere);
  707. if (!empty($query) && $query->num_rows == 1) {
  708. $linkObj = new Link($this->DB);
  709. if($fullInfo === true) {
  710. $ret = $linkObj->load($hash);
  711. }
  712. else {
  713. $ret = $linkObj->loadShortInfo($hash);
  714. }
  715. if($withObject === true) {
  716. $ret = array(
  717. 'data' => $ret,
  718. 'obj' => $linkObj
  719. );
  720. }
  721. }
  722. } catch (Exception $e) {
  723. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  724. }
  725. }
  726. return $ret;
  727. }
  728. /**
  729. * Delete link by given hash
  730. *
  731. * @param string $hash
  732. * @return bool
  733. */
  734. public function deleteLink(string $hash): bool {
  735. $ret = false;
  736. if (!empty($hash)) {
  737. $linkData = $this->loadLink($hash,false,true);
  738. if(!empty($linkData)) {
  739. $linkData['obj']->deleteRelations();
  740. $queryStr = "DELETE FROM `" . DB_PREFIX . "_link`
  741. WHERE `hash` = '" . $this->DB->real_escape_string($hash) . "'";
  742. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  743. try {
  744. $query = $this->DB->query($queryStr);
  745. if (!empty($query)) {
  746. $ret = true;
  747. }
  748. } catch (Exception $e) {
  749. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  750. }
  751. }
  752. }
  753. return $ret;
  754. }
  755. /**
  756. * Export given link for download as a xml file
  757. *
  758. * @param string $hash
  759. * @param Link|null $linkObj Use already existing link obj
  760. * @return string
  761. */
  762. public function exportLinkData(string $hash, Link $linkObj=null): string {
  763. $ret = '';
  764. if(DEBUG) {
  765. Summoner::sysLog("DEBUG Start to export link with hash $hash");
  766. }
  767. if (!empty($hash)) {
  768. $linkData = $this->loadLink($hash, true, true);
  769. if (!empty($linkData)) {
  770. $data = $linkData;
  771. } elseif(DEBUG) {
  772. Summoner::sysLog("ERROR Could not load link with $hash");
  773. }
  774. }
  775. elseif(!empty($linkObj) && is_a($linkObj,'Link')) {
  776. $data = $linkObj->getData();
  777. }
  778. if(!empty($data) && isset($data['link'])) {
  779. if(DEBUG) {
  780. Summoner::sysLog("DEBUG Using data: ".var_export($data, true));
  781. }
  782. require_once 'lib/import-export.class.php';
  783. $ImEx = new ImportExport();
  784. $ret = $ImEx->createSingleLinkExportXML($data);
  785. } elseif(DEBUG) {
  786. Summoner::sysLog("ERROR Missing link data for hash $hash");
  787. }
  788. return $ret;
  789. }
  790. /**
  791. * for simpler management we have the search data in a separate column
  792. * it is not fancy or even technical nice but it damn works
  793. *
  794. * @return boolean
  795. */
  796. public function updateSearchIndex(): bool {
  797. $ret = false;
  798. $allLinks = array();
  799. $queryStr = "SELECT hash FROM `".DB_PREFIX."_link`";
  800. $query = $this->DB->query($queryStr);
  801. if(!empty($query) && $query->num_rows > 0) {
  802. $allLinks = $query->fetch_all(MYSQLI_ASSOC);
  803. }
  804. if(!empty($allLinks)) {
  805. foreach($allLinks as $link) {
  806. $LinkObj = new Link($this->DB);
  807. $l = $LinkObj->load($link['hash']);
  808. $_t = parse_url($l['link']);
  809. $searchStr = $l['title'];
  810. $searchStr .= ' '.$l['description'];
  811. $searchStr .= ' '.implode(' ',$l['tags']);
  812. $searchStr .= ' '.implode(' ',$l['categories']);
  813. $searchStr .= ' '.$_t['host'];
  814. if(isset($_t['path'])) {
  815. $searchStr .= ' '.implode(' ',explode('/',$_t['path']));
  816. }
  817. $searchStr = trim($searchStr);
  818. $searchStr = strtolower($searchStr);
  819. # now update the search string
  820. $queryStr = "UPDATE `".DB_PREFIX."_link`
  821. SET `search` = '".$this->DB->real_escape_string($searchStr)."'
  822. WHERE `hash` = '".$this->DB->real_escape_string($link['hash'])."'";
  823. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  824. try {
  825. $this->DB->query($queryStr);
  826. } catch (Exception $e) {
  827. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  828. }
  829. unset($LinkObj,$l,$searchStr,$_t,$queryStr);
  830. }
  831. $ret = true;
  832. }
  833. return $ret;
  834. }
  835. /**
  836. * process the given xml file. Based on the export file
  837. * options are overwrite => true|false
  838. *
  839. * @param array $file
  840. * @param array $options
  841. * @return array
  842. */
  843. public function processImportFile(array $file, array $options): array {
  844. $ret = array(
  845. 'status' => 'error',
  846. 'message' => 'Processing error'
  847. );
  848. $links = array();
  849. require_once 'lib/import-export.class.php';
  850. $ImEx = new ImportExport();
  851. try {
  852. $ImEx->loadImportFile($file);
  853. $links = $ImEx->parseImportFile();
  854. }
  855. catch (Exception $e) {
  856. $ret['message'] = $e->getMessage();
  857. }
  858. $_existing = 0;
  859. $_new = 0;
  860. if(!empty($links)) {
  861. $_amount = count($links);
  862. foreach($links as $linkToImport) {
  863. $do = false;
  864. if($this->_linkExistsById($linkToImport['id'])) {
  865. if(isset($options['overwrite']) && $options['overwrite'] === true) {
  866. $linkObj = new Link($this->DB);
  867. $linkObj->load($linkToImport['hash']);
  868. $do = $linkObj->update($linkToImport);
  869. }
  870. $_existing++;
  871. }
  872. else {
  873. $linkObj = new Link($this->DB);
  874. $this->DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
  875. try {
  876. $do = $linkObj->create(array(
  877. 'hash' => $linkToImport['hash'],
  878. 'link' => $linkToImport['link'],
  879. 'status' => $linkToImport['private'],
  880. 'description' => $linkToImport['description'],
  881. 'title' => $linkToImport['title'],
  882. 'image' => $linkToImport['image']
  883. ), true);
  884. } catch (Exception $e) {
  885. continue;
  886. }
  887. if(!empty($do)) {
  888. $linkToImport['catArr'] = Summoner::prepareTagOrCategoryStr($linkToImport['category']);
  889. $linkToImport['tagArr'] = Summoner::prepareTagOrCategoryStr($linkToImport['tag']);
  890. if(!empty($linkToImport['catArr'])) {
  891. foreach($linkToImport['catArr'] as $c) {
  892. $catObj = new Category($this->DB);
  893. $catObj->initbystring($c);
  894. $catObj->setRelation($do);
  895. unset($catObj);
  896. }
  897. }
  898. if(!empty($linkToImport['tagArr'])) {
  899. foreach($linkToImport['tagArr'] as $t) {
  900. $tagObj = new Tag($this->DB);
  901. $tagObj->initbystring($t);
  902. $tagObj->setRelation($do);
  903. unset($tagObj);
  904. }
  905. }
  906. $this->DB->commit();
  907. $this->updateSearchIndex();
  908. }
  909. else {
  910. $this->DB->rollback();
  911. }
  912. $_new++;
  913. }
  914. }
  915. if(isset($options['overwrite']) && $options['overwrite'] === true) {
  916. $_msg = "Found $_amount link(s) to import. Overwritten $_existing existing and imported $_new new one(s).";
  917. }
  918. else {
  919. $_msg = "Found $_amount link(s) to import. Skipped $_existing existing and imported $_new new one(s).";
  920. }
  921. $ret = array(
  922. 'status' => 'success',
  923. 'message' => $_msg
  924. );
  925. }
  926. return $ret;
  927. }
  928. /**
  929. * Top 5 combinations of either tag or category
  930. *
  931. * array(
  932. * array(
  933. * amount => number
  934. * rel => array(rel, name)
  935. * )
  936. * )
  937. *
  938. * @param string $type
  939. * @return array
  940. */
  941. public function linkRelationStats(string $type='tag'): array {
  942. $ret = array();
  943. // build the digit string which describes the tag/cat combination
  944. $_relCombination = array();
  945. if($type == 'category') {
  946. $queryStr = "SELECT `linkid`, `categoryid` AS rel
  947. FROM `".DB_PREFIX."_categoryrelation`
  948. ORDER BY `linkid`, rel ASC";
  949. } else {
  950. $queryStr = "SELECT `linkid`, `tagid` AS rel
  951. FROM `".DB_PREFIX."_tagrelation`
  952. ORDER BY `linkid`, rel ASC";
  953. }
  954. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  955. try {
  956. $query = $this->DB->query($queryStr);
  957. if(!empty($query) && $query->num_rows > 0) {
  958. while($result = $query->fetch_assoc()) {
  959. if(isset($_relCombination[$result['linkid']])) {
  960. $_relCombination[$result['linkid']] .= ",".$result['rel'];
  961. } else {
  962. // https://www.php.net/manual/en/language.types.array.php "Strings containing valid decimal ints ... will be cast to the int type
  963. // if not not done the arsort results are messed up
  964. $_relCombination[$result['linkid']] = "0".$result['rel'];
  965. }
  966. }
  967. }
  968. } catch (Exception $e) {
  969. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  970. }
  971. // now count the unique digit strings
  972. $_relCombination_amount = array();
  973. if(!empty($_relCombination)) {
  974. foreach($_relCombination as $k=>$v) {
  975. if(isset($_relCombination_amount[$v])) {
  976. $_relCombination_amount[$v]++;
  977. } else {
  978. $_relCombination_amount[$v] = 1;
  979. }
  980. }
  981. }
  982. // now sort and return top 5 combinations
  983. // also resolve tag/cat name
  984. if(!empty($_relCombination_amount)) {
  985. arsort($_relCombination_amount);
  986. $_top5 = array_splice($_relCombination_amount,0,5);
  987. foreach($_top5 as $k=>$v) {
  988. $_t = array();
  989. if($k[0] === "0") {
  990. $k = substr($k,1);
  991. }
  992. $_t['amount'] = $v;
  993. $_rel = explode(",",$k);
  994. $_existingRelInfo = array(); // avoid duplicate queries
  995. foreach($_rel as $t) {
  996. if(!isset($_existingRelInfo[$t])) {
  997. if($type == 'category') {
  998. $queryStr = "SELECT `name` FROM `".DB_PREFIX."_category`
  999. WHERE `id` = '".$this->DB->real_escape_string($t)."'";
  1000. } else {
  1001. $queryStr = "SELECT `name` FROM `".DB_PREFIX."_tag`
  1002. WHERE `id` = '".$this->DB->real_escape_string($t)."'";
  1003. }
  1004. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  1005. try {
  1006. $query = $this->DB->query($queryStr);
  1007. if(!empty($query) && $query->num_rows > 0) {
  1008. $relinfo = $query->fetch_assoc();
  1009. $_existingRelInfo[$t] = $relinfo['name'];
  1010. $_t['rel'][$t] = $relinfo['name'];
  1011. }
  1012. } catch (Exception $e) {
  1013. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  1014. }
  1015. } else {
  1016. $_t['rel'][$t] = $_existingRelInfo[$t];
  1017. }
  1018. }
  1019. $ret[] = $_t;
  1020. }
  1021. }
  1022. return $ret;
  1023. }
  1024. /**
  1025. * Return the query string for the correct status type
  1026. *
  1027. * @return string
  1028. */
  1029. private function _decideLinkTypeForQuery(): string {
  1030. return match ($this->_queryStatus) {
  1031. 1 => "t.status IN (2,1)",
  1032. 3 => "t.status = 3",
  1033. default => "t.status = 2",
  1034. };
  1035. }
  1036. /**
  1037. * Check if given id (not hash) exists in link database
  1038. *
  1039. * @param string $id
  1040. * @return bool
  1041. */
  1042. private function _linkExistsById(string $id): bool {
  1043. $ret = false;
  1044. if(!empty($id)) {
  1045. $queryStr = "SELECT `id`
  1046. FROM `" . DB_PREFIX . "_link`
  1047. WHERE `id` = '" . $this->DB->real_escape_string($id) . "'";
  1048. if(QUERY_DEBUG) Summoner::sysLog("[QUERY] ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  1049. try {
  1050. $query = $this->DB->query($queryStr);
  1051. if(!empty($query) && $query->num_rows > 0) {
  1052. $ret = true;
  1053. }
  1054. } catch (Exception $e) {
  1055. Summoner::sysLog("[ERROR] ".__METHOD__." mysql catch: ".$e->getMessage());
  1056. }
  1057. }
  1058. return $ret;
  1059. }
  1060. }