management.class.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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 `hash` 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. while($result = $query->fetch_assoc()) {
  218. $linkObj = new Link($this->DB);
  219. $ret[] = $linkObj->loadShortInfo($result['hash']);
  220. }
  221. }
  222. } catch (Exception $e) {
  223. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  224. }
  225. return $ret;
  226. }
  227. /**
  228. * Return a random entry from link table.
  229. * Slow but does the trick for now. If there is way more entries
  230. * re-think this solution
  231. *
  232. * @param String $limit
  233. * @return array
  234. */
  235. public function randomLink(string $limit="1"): array {
  236. $ret = array();
  237. $amount = $this->linkAmount();
  238. $offset = rand(0, $amount-1);
  239. $queryStr = "SELECT `title`, `link`, `hash` FROM `".DB_PREFIX."_link` AS t";
  240. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  241. $queryStr .= " LIMIT $offset, $limit";
  242. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  243. try {
  244. $query = $this->DB->query($queryStr);
  245. if(!empty($query) && $query->num_rows > 0) {
  246. $ret = $query->fetch_all(MYSQLI_ASSOC);
  247. }
  248. } catch (Exception $e) {
  249. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  250. }
  251. return $ret;
  252. }
  253. /**
  254. * Get a random category
  255. *
  256. * @param string $limit
  257. * @return array
  258. */
  259. public function randomCategory(string $limit="1"): array {
  260. $ret = array();
  261. $amount = $this->categoryAmount();
  262. $offset = rand(0, $amount-1);
  263. $queryStr = "SELECT `id`, `name` FROM `".DB_PREFIX."_category`";
  264. $queryStr .= " LIMIT $offset, $limit";
  265. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  266. try {
  267. $query = $this->DB->query($queryStr);
  268. if(!empty($query) && $query->num_rows > 0) {
  269. $ret = $query->fetch_all(MYSQLI_ASSOC);
  270. }
  271. } catch (Exception $e) {
  272. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  273. }
  274. return $ret;
  275. }
  276. /**
  277. * Get a random tag
  278. *
  279. * @param string $limit
  280. * @return array
  281. */
  282. public function randomTag(string $limit="1"): array {
  283. $ret = array();
  284. $amount = $this->tagAmount();
  285. $offset = rand(0, $amount-1);
  286. $queryStr = "SELECT `id`, `name` FROM `".DB_PREFIX."_tag`";
  287. $queryStr .= " LIMIT $offset, $limit";
  288. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  289. try {
  290. $query = $this->DB->query($queryStr);
  291. if(!empty($query) && $query->num_rows > 0) {
  292. $ret = $query->fetch_all(MYSQLI_ASSOC);
  293. }
  294. } catch (Exception $e) {
  295. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  296. }
  297. return $ret;
  298. }
  299. /**
  300. * get all the categories ordered by link added date
  301. *
  302. * @return array
  303. */
  304. public function categoriesByDateAdded(): array {
  305. $ret = array();
  306. $categories = $this->categories();
  307. foreach($categories as $k=>$v) {
  308. $latestLink = $this->latestLinkForCategory($k);
  309. if(!empty($latestLink)) {
  310. $ret[] = array('created' => $latestLink[0]['created'], 'id' => $k, 'name' => $v['name']);
  311. }
  312. }
  313. $_created = array_column($ret, 'created');
  314. array_multisort($_created, SORT_DESC, $ret);
  315. return $ret;
  316. }
  317. /**
  318. * find all links by given category string or id.
  319. * Return array sorted by creation date DESC
  320. *
  321. * @param string $id Category ID
  322. * @param array $options Array with limit|offset|sort|sortDirection
  323. * @return array
  324. */
  325. public function linksByCategory(string $id, array $options=array()): array {
  326. $ret = array();
  327. if(!isset($options['limit'])) $options['limit'] = 5;
  328. if(!isset($options['offset'])) $options['offset'] = false;
  329. if(!isset($options['sort'])) $options['sort'] = false;
  330. if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
  331. $querySelect = "SELECT `id`, `link`, `created`, `status`, `title`, `hash`, `description`, `image`";
  332. $queryFrom = " FROM `".DB_PREFIX."_link` AS t
  333. LEFT JOIN insipid_categoryrelation AS cr ON cr.linkid = t.id";
  334. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  335. if(!empty($id) && is_numeric($id)) {
  336. $queryWhere .= " AND cr.categoryId = '" . $this->DB->real_escape_string($id) . "'";
  337. }
  338. else {
  339. return $ret;
  340. }
  341. $queryOrder = " ORDER BY";
  342. if(!empty($options['sort'])) {
  343. $queryOrder .= ' t.'.$options['sort'];
  344. }
  345. else {
  346. $queryOrder .= " t.created";
  347. }
  348. if(!empty($options['sortDirection'])) {
  349. $queryOrder .= ' '.$options['sortDirection'];
  350. }
  351. else {
  352. $queryOrder .= " DESC";
  353. }
  354. $queryLimit = '';
  355. # this allows the set the limit to false
  356. if(!empty($options['limit'])) {
  357. $queryLimit .= " LIMIT ".$options['limit'];
  358. # offset can be 0
  359. if($options['offset'] !== false) {
  360. $queryLimit .= " OFFSET ".$options['offset'];
  361. }
  362. }
  363. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit));
  364. try {
  365. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
  366. if(!empty($query) && $query->num_rows > 0) {
  367. while($result = $query->fetch_assoc()) {
  368. $linkObj = new Link($this->DB);
  369. $ret['results'][] = $linkObj->loadFromDataShortInfo($result);
  370. unset($linkObj);
  371. }
  372. $query = $this->DB->query("SELECT COUNT(DISTINCT(t.hash)) AS amount ".$queryFrom.$queryWhere);
  373. $result = $query->fetch_assoc();
  374. $ret['amount'] = $result['amount'];
  375. }
  376. } catch (Exception $e) {
  377. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  378. }
  379. return $ret;
  380. }
  381. /**
  382. * find all links by given tag string or id.
  383. * Return array sorted by creation date DESC
  384. *
  385. * @param string $id Tag id
  386. * @param array $options Array with limit|offset|sort|sortDirection
  387. * @return array
  388. */
  389. public function linksByTag(string $id, array $options=array()): array {
  390. $ret = array();
  391. if(!isset($options['limit'])) $options['limit'] = 5;
  392. if(!isset($options['offset'])) $options['offset'] = false;
  393. if(!isset($options['sort'])) $options['sort'] = false;
  394. if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
  395. $querySelect = "SELECT `id`, `link`, `created`, `status`, `title`, `hash`, `description`, `image`";
  396. $queryFrom = " FROM `".DB_PREFIX."_link` AS t
  397. LEFT JOIN insipid_tagrelation AS tr ON tr.linkid = t.id";
  398. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  399. if(!empty($id) && is_numeric($id)) {
  400. $queryWhere .= " AND tr.tagId = '".$this->DB->real_escape_string($id)."'";
  401. }
  402. else {
  403. return $ret;
  404. }
  405. $queryOrder = " ORDER BY";
  406. if(!empty($options['sort'])) {
  407. $queryOrder .= ' t.'.$options['sort'];
  408. }
  409. else {
  410. $queryOrder .= " t.created";
  411. }
  412. if(!empty($options['sortDirection'])) {
  413. $queryOrder .= ' '.$options['sortDirection'];
  414. }
  415. else {
  416. $queryOrder .= " DESC";
  417. }
  418. $queryLimit = '';
  419. # this allows the set the limit to false
  420. if(!empty($options['limit'])) {
  421. $queryLimit .= " LIMIT ".$options['limit'];
  422. # offset can be 0
  423. if($options['offset'] !== false) {
  424. $queryLimit .= " OFFSET ".$options['offset'];
  425. }
  426. }
  427. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit));
  428. try {
  429. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
  430. if(!empty($query) && $query->num_rows > 0) {
  431. while($result = $query->fetch_assoc()) {
  432. $linkObj = new Link($this->DB);
  433. $ret['results'][] = $linkObj->loadFromDataShortInfo($result);
  434. unset($linkObj);
  435. }
  436. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryFrom.$queryWhere));
  437. $query = $this->DB->query("SELECT COUNT(DISTINCT(t.hash)) AS amount ".$queryFrom.$queryWhere);
  438. $result = $query->fetch_assoc();
  439. $ret['amount'] = $result['amount'];
  440. }
  441. } catch (Exception $e) {
  442. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  443. }
  444. return $ret;
  445. }
  446. /**
  447. * return all links and Info we have from the combined view
  448. *
  449. * @param array $options
  450. * @return array
  451. */
  452. public function links(array $options=array()): array {
  453. $ret = array();
  454. if(!isset($options['limit'])) $options['limit'] = 5;
  455. if(!isset($options['offset'])) $options['offset'] = false;
  456. if(!isset($options['sort'])) $options['sort'] = false;
  457. if(!isset($options['sortDirection'])) $options['sortDirection'] = false;
  458. $querySelect = "SELECT `hash`";
  459. $queryFrom = " FROM `".DB_PREFIX."_link` AS t";
  460. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  461. $queryOrder = " ORDER BY";
  462. if(!empty($options['sort'])) {
  463. $queryOrder .= ' t.'.$options['sort'];
  464. }
  465. else {
  466. $queryOrder .= " t.created";
  467. }
  468. if(!empty($options['sortDirection'])) {
  469. $queryOrder .= ' '.$options['sortDirection'];
  470. }
  471. else {
  472. $queryOrder .= " DESC";
  473. }
  474. $queryLimit = '';
  475. # this allows the set the limit to false
  476. if(!empty($options['limit'])) {
  477. $queryLimit .= " LIMIT ".$options['limit'];
  478. # offset can be 0
  479. if($options['offset'] !== false) {
  480. $queryLimit .= " OFFSET ".$options['offset'];
  481. }
  482. }
  483. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit));
  484. try {
  485. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere.$queryOrder.$queryLimit);
  486. if(!empty($query) && $query->num_rows > 0) {
  487. while($result = $query->fetch_assoc()) {
  488. $linkObj = new Link($this->DB);
  489. $ret['results'][] = $linkObj->loadShortInfo($result['hash']);
  490. unset($linkObj);
  491. }
  492. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryFrom.$queryWhere));
  493. $query = $this->DB->query("SELECT COUNT(t.hash) AS amount ".$queryFrom.$queryWhere);
  494. $result = $query->fetch_assoc();
  495. $ret['amount'] = $result['amount'];
  496. }
  497. } catch (Exception $e) {
  498. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  499. }
  500. return $ret;
  501. }
  502. /**
  503. * return the latest added link for given category id
  504. *
  505. * @param string $categoryid
  506. * @return array
  507. */
  508. public function latestLinkForCategory(string $categoryid): array {
  509. $ret = array();
  510. if(!empty($categoryid) && is_numeric($categoryid)) {
  511. $queryStr = "SELECT `id`, `link`, `created`, `status`, `description`, `title`, `image`, `hash`,
  512. `tag`, `category`, `categoryId`, `tagId`
  513. FROM `".DB_PREFIX."_combined` AS t";
  514. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  515. $queryStr .= " AND t.categoryId = '" . $this->DB->real_escape_string($categoryid) . "'
  516. ORDER BY t.created DESC
  517. LIMIT 1";
  518. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  519. try {
  520. $query = $this->DB->query($queryStr);
  521. if(!empty($query) && $query->num_rows > 0) {
  522. $ret = $query->fetch_all(MYSQLI_ASSOC);
  523. }
  524. } catch (Exception $e) {
  525. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  526. }
  527. }
  528. return $ret;
  529. }
  530. /**
  531. * Search for the given url in the links table
  532. *
  533. * @param string $url
  534. * @return array
  535. */
  536. public function searchForLinkByURL(string $url): array {
  537. $ret = array();
  538. if(!empty($url)) {
  539. $queryStr = "SELECT `id`, `link`, `title`, `hash`
  540. FROM `".DB_PREFIX."_link` AS t";
  541. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  542. $queryStr .= " AND t.link = '".$this->DB->real_escape_string($url)."'";
  543. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  544. try {
  545. $query = $this->DB->query($queryStr);
  546. if(!empty($query) && $query->num_rows > 0) {
  547. $ret = $query->fetch_all(MYSQLI_ASSOC);
  548. }
  549. } catch (Exception $e) {
  550. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  551. }
  552. }
  553. return $ret;
  554. }
  555. /**
  556. * search for given searchstring in the search data of the links
  557. *
  558. * @param string $searchStr
  559. * @return array
  560. */
  561. public function searchForLinkBySearchData(string $searchStr): array {
  562. $ret = array();
  563. if(!empty($searchStr)) {
  564. $queryStr = "SELECT `id`, `link`, `title`, `hash`,
  565. MATCH (`search`) AGAINST ('".$this->DB->real_escape_string($searchStr)."' IN BOOLEAN MODE) AS score
  566. FROM `".DB_PREFIX."_link` AS t
  567. WHERE MATCH (`search`) AGAINST ('".$this->DB->real_escape_string($searchStr)."' IN BOOLEAN MODE)";
  568. $queryStr .= " AND ".$this->_decideLinkTypeForQuery();
  569. $queryStr .= " ORDER BY score DESC";
  570. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  571. try {
  572. $query = $this->DB->query($queryStr);
  573. if(!empty($query) && $query->num_rows > 0) {
  574. $ret = $query->fetch_all(MYSQLI_ASSOC);
  575. }
  576. } catch (Exception $e) {
  577. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  578. }
  579. }
  580. return $ret;
  581. }
  582. /**
  583. * amount of links in the DB. Status 1 and 2 only
  584. *
  585. * @return string
  586. */
  587. public function linkAmount(): string {
  588. $ret = 0;
  589. $queryStr = "SELECT COUNT(*) AS amount
  590. FROM `".DB_PREFIX."_link` AS t";
  591. $queryStr .= " WHERE ".$this->_decideLinkTypeForQuery();
  592. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  593. try {
  594. $query = $this->DB->query($queryStr);
  595. if(!empty($query) && $query->num_rows > 0) {
  596. $result = $query->fetch_assoc();
  597. $ret = $result['amount'];
  598. }
  599. } catch (Exception $e) {
  600. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  601. }
  602. return $ret;
  603. }
  604. /**
  605. * amount of tags
  606. *
  607. * @return string
  608. */
  609. public function tagAmount(): string {
  610. $ret = 0;
  611. $queryStr = "SELECT COUNT(*) AS amount FROM `".DB_PREFIX."_tag`";
  612. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  613. try {
  614. $query = $this->DB->query($queryStr);
  615. if(!empty($query) && $query->num_rows > 0) {
  616. $result = $query->fetch_assoc();
  617. $ret = $result['amount'];
  618. }
  619. } catch (Exception $e) {
  620. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  621. }
  622. return $ret;
  623. }
  624. /**
  625. * amount of categories
  626. *
  627. * @return string
  628. */
  629. public function categoryAmount(): string {
  630. $ret = 0;
  631. $queryStr = "SELECT COUNT(*) AS amount FROM `".DB_PREFIX."_category`";
  632. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  633. try {
  634. $query = $this->DB->query($queryStr);
  635. if(!empty($query) && $query->num_rows > 0) {
  636. $result = $query->fetch_assoc();
  637. $ret = $result['amount'];
  638. }
  639. } catch (Exception $e) {
  640. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  641. }
  642. return $ret;
  643. }
  644. /**
  645. * Amount of links need moderation
  646. *
  647. * @return string
  648. */
  649. public function moderationAmount(): string {
  650. $ret = 0;
  651. $queryStr = "SELECT COUNT(*) AS amount FROM `".DB_PREFIX."_link`";
  652. $queryStr .= " WHERE `status` = 3";
  653. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  654. try {
  655. $query = $this->DB->query($queryStr);
  656. if(!empty($query) && $query->num_rows > 0) {
  657. $result = $query->fetch_assoc();
  658. $ret = $result['amount'];
  659. }
  660. } catch (Exception $e) {
  661. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  662. }
  663. return $ret;
  664. }
  665. /**
  666. * get the used disk space for local image storage
  667. *
  668. * @return int
  669. */
  670. public function storageAmount(): int {
  671. $ret = 0;
  672. $_storageFolder = ABSOLUTE_PATH.'/'.LOCAL_STORAGE;
  673. if(file_exists($_storageFolder) && is_readable($_storageFolder)) {
  674. $ret = Summoner::folderSize($_storageFolder);
  675. }
  676. return $ret;
  677. }
  678. /**
  679. * empties the local storage directory
  680. *
  681. * @return bool
  682. */
  683. public function clearLocalStorage(): bool {
  684. $ret = false;
  685. $_storageFolder = ABSOLUTE_PATH.'/'.LOCAL_STORAGE;
  686. if(file_exists($_storageFolder) && is_writable($_storageFolder)) {
  687. $ret = Summoner::recursive_remove_directory($_storageFolder,true);
  688. }
  689. return $ret;
  690. }
  691. /**
  692. * Load link by given hash. Do not use Link class directly.
  693. * Otherwise the authentication will be ignored.
  694. *
  695. * @param String $hash Link hash
  696. * @param bool $fullInfo Load all the info we have
  697. * @param bool $withObject An array with data and the link obj itself
  698. * @return array
  699. */
  700. public function loadLink(string $hash, bool $fullInfo=true, bool $withObject=false): array {
  701. $ret = array();
  702. if (!empty($hash)) {
  703. $querySelect = "SELECT `hash`";
  704. $queryFrom = " FROM `".DB_PREFIX."_link` AS t";
  705. $queryWhere = " WHERE ".$this->_decideLinkTypeForQuery();
  706. $queryWhere .= " AND t.hash = '".$this->DB->real_escape_string($hash)."'";
  707. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($querySelect.$queryFrom.$queryWhere));
  708. try {
  709. $query = $this->DB->query($querySelect.$queryFrom.$queryWhere);
  710. if (!empty($query) && $query->num_rows == 1) {
  711. $linkObj = new Link($this->DB);
  712. if($fullInfo === true) {
  713. $ret = $linkObj->load($hash);
  714. }
  715. else {
  716. $ret = $linkObj->loadShortInfo($hash);
  717. }
  718. if($withObject === true) {
  719. $ret = array(
  720. 'data' => $ret,
  721. 'obj' => $linkObj
  722. );
  723. }
  724. }
  725. } catch (Exception $e) {
  726. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  727. }
  728. }
  729. return $ret;
  730. }
  731. /**
  732. * Delete link by given hash
  733. *
  734. * @param string $hash
  735. * @return bool
  736. */
  737. public function deleteLink(string $hash): bool {
  738. $ret = false;
  739. if (!empty($hash)) {
  740. $linkData = $this->loadLink($hash,false,true);
  741. if(!empty($linkData)) {
  742. $linkData['obj']->deleteRelations();
  743. $queryStr = "DELETE FROM `" . DB_PREFIX . "_link`
  744. WHERE `hash` = '" . $this->DB->real_escape_string($hash) . "'";
  745. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  746. try {
  747. $query = $this->DB->query($queryStr);
  748. if (!empty($query)) {
  749. $ret = true;
  750. }
  751. } catch (Exception $e) {
  752. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  753. }
  754. }
  755. }
  756. return $ret;
  757. }
  758. /**
  759. * Export given link for download as a xml file
  760. *
  761. * @param string $hash
  762. * @param Link|null $linkObj Use already existing link obj
  763. * @return string
  764. */
  765. public function exportLinkData(string $hash, Link $linkObj=null): string {
  766. $ret = '';
  767. if(DEBUG) {
  768. Summoner::sysLog("DEBUG Start to export link with hash $hash");
  769. }
  770. if (!empty($hash)) {
  771. $linkData = $this->loadLink($hash, true, true);
  772. if (!empty($linkData)) {
  773. $data = $linkData;
  774. } elseif(DEBUG) {
  775. Summoner::sysLog("ERROR Could not load link with $hash");
  776. }
  777. }
  778. elseif(!empty($linkObj) && is_a($linkObj,'Link')) {
  779. $data = $linkObj->getData();
  780. }
  781. if(!empty($data) && isset($data['link'])) {
  782. if(DEBUG) {
  783. Summoner::sysLog("DEBUG Using data: ".Summoner::cleanForLog($data));
  784. }
  785. require_once 'lib/import-export.class.php';
  786. $ImEx = new ImportExport();
  787. $ret = $ImEx->createSingleLinkExportXML($data);
  788. } elseif(DEBUG) {
  789. Summoner::sysLog("ERROR Missing link data for hash $hash");
  790. }
  791. return $ret;
  792. }
  793. /**
  794. * for simpler management we have the search data in a separate column
  795. * it is not fancy or even technical nice but it damn works
  796. *
  797. * @return boolean
  798. */
  799. public function updateSearchIndex(): bool {
  800. $ret = false;
  801. $allLinks = array();
  802. $queryStr = "SELECT hash FROM `".DB_PREFIX."_link`";
  803. $query = $this->DB->query($queryStr);
  804. if(!empty($query) && $query->num_rows > 0) {
  805. $allLinks = $query->fetch_all(MYSQLI_ASSOC);
  806. }
  807. if(!empty($allLinks)) {
  808. foreach($allLinks as $link) {
  809. $LinkObj = new Link($this->DB);
  810. $l = $LinkObj->load($link['hash']);
  811. $_t = parse_url($l['link']);
  812. $searchStr = $l['title'];
  813. $searchStr .= ' '.$l['description'];
  814. $searchStr .= ' '.implode(' ',$l['tags']);
  815. $searchStr .= ' '.implode(' ',$l['categories']);
  816. $searchStr .= ' '.$_t['host'];
  817. if(isset($_t['path'])) {
  818. $searchStr .= ' '.implode(' ',explode('/',$_t['path']));
  819. }
  820. $searchStr = trim($searchStr);
  821. $searchStr = strtolower($searchStr);
  822. # now update the search string
  823. $queryStr = "UPDATE `".DB_PREFIX."_link`
  824. SET `search` = '".$this->DB->real_escape_string($searchStr)."'
  825. WHERE `hash` = '".$this->DB->real_escape_string($link['hash'])."'";
  826. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  827. try {
  828. $this->DB->query($queryStr);
  829. } catch (Exception $e) {
  830. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  831. }
  832. unset($LinkObj,$l,$searchStr,$_t,$queryStr);
  833. }
  834. $ret = true;
  835. }
  836. return $ret;
  837. }
  838. /**
  839. * process the given xml file. Based on the export file
  840. * options are overwrite => true|false
  841. *
  842. * @param array $file
  843. * @param array $options
  844. * @return array
  845. */
  846. public function processImportFile(array $file, array $options): array {
  847. $ret = array(
  848. 'status' => 'error',
  849. 'message' => 'Processing error'
  850. );
  851. $links = array();
  852. require_once 'lib/import-export.class.php';
  853. $ImEx = new ImportExport();
  854. try {
  855. $ImEx->loadImportFile($file);
  856. $links = $ImEx->parseImportFile();
  857. }
  858. catch (Exception $e) {
  859. $ret['message'] = $e->getMessage();
  860. }
  861. $_existing = 0;
  862. $_new = 0;
  863. if(!empty($links)) {
  864. $_amount = count($links);
  865. foreach($links as $linkToImport) {
  866. $do = false;
  867. if($this->_linkExistsById($linkToImport['id'])) {
  868. if(isset($options['overwrite']) && $options['overwrite'] === true) {
  869. $linkObj = new Link($this->DB);
  870. $linkObj->load($linkToImport['hash']);
  871. $do = $linkObj->update($linkToImport);
  872. }
  873. $_existing++;
  874. }
  875. else {
  876. $linkObj = new Link($this->DB);
  877. $this->DB->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
  878. try {
  879. $do = $linkObj->create(array(
  880. 'hash' => $linkToImport['hash'],
  881. 'link' => $linkToImport['link'],
  882. 'status' => $linkToImport['private'],
  883. 'description' => $linkToImport['description'],
  884. 'title' => $linkToImport['title'],
  885. 'image' => $linkToImport['image']
  886. ), true);
  887. } catch (Exception $e) {
  888. continue;
  889. }
  890. if(!empty($do)) {
  891. $linkToImport['catArr'] = Summoner::prepareTagOrCategoryStr($linkToImport['category']);
  892. $linkToImport['tagArr'] = Summoner::prepareTagOrCategoryStr($linkToImport['tag']);
  893. if(!empty($linkToImport['catArr'])) {
  894. foreach($linkToImport['catArr'] as $c) {
  895. $catObj = new Category($this->DB);
  896. $catObj->initbystring($c);
  897. $catObj->setRelation($do);
  898. unset($catObj);
  899. }
  900. }
  901. if(!empty($linkToImport['tagArr'])) {
  902. foreach($linkToImport['tagArr'] as $t) {
  903. $tagObj = new Tag($this->DB);
  904. $tagObj->initbystring($t);
  905. $tagObj->setRelation($do);
  906. unset($tagObj);
  907. }
  908. }
  909. $this->DB->commit();
  910. $this->updateSearchIndex();
  911. }
  912. else {
  913. $this->DB->rollback();
  914. }
  915. $_new++;
  916. }
  917. }
  918. if(isset($options['overwrite']) && $options['overwrite'] === true) {
  919. $_msg = "Found $_amount link(s) to import. Overwritten $_existing existing and imported $_new new one(s).";
  920. }
  921. else {
  922. $_msg = "Found $_amount link(s) to import. Skipped $_existing existing and imported $_new new one(s).";
  923. }
  924. $ret = array(
  925. 'status' => 'success',
  926. 'message' => $_msg
  927. );
  928. }
  929. return $ret;
  930. }
  931. /**
  932. * Top 5 combinations of either tag or category
  933. *
  934. * array(
  935. * array(
  936. * amount => number
  937. * rel => array(rel, name)
  938. * )
  939. * )
  940. *
  941. * @param string $type
  942. * @return array
  943. */
  944. public function linkRelationStats(string $type='tag'): array {
  945. $ret = array();
  946. // build the digit string which describes the tag/cat combination
  947. $_relCombination = array();
  948. if($type == 'category') {
  949. $queryStr = "SELECT `linkid`, `categoryid` AS rel
  950. FROM `".DB_PREFIX."_categoryrelation`
  951. ORDER BY `linkid`, rel ASC";
  952. } else {
  953. $queryStr = "SELECT `linkid`, `tagid` AS rel
  954. FROM `".DB_PREFIX."_tagrelation`
  955. ORDER BY `linkid`, rel ASC";
  956. }
  957. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  958. try {
  959. $query = $this->DB->query($queryStr);
  960. if(!empty($query) && $query->num_rows > 0) {
  961. while($result = $query->fetch_assoc()) {
  962. if(isset($_relCombination[$result['linkid']])) {
  963. $_relCombination[$result['linkid']] .= ",".$result['rel'];
  964. } else {
  965. // https://www.php.net/manual/en/language.types.array.php "Strings containing valid decimal ints ... will be cast to the int type
  966. // if not not done the arsort results are messed up
  967. $_relCombination[$result['linkid']] = "0".$result['rel'];
  968. }
  969. }
  970. }
  971. } catch (Exception $e) {
  972. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  973. }
  974. // now count the unique digit strings
  975. $_relCombination_amount = array();
  976. if(!empty($_relCombination)) {
  977. foreach($_relCombination as $k=>$v) {
  978. if(isset($_relCombination_amount[$v])) {
  979. $_relCombination_amount[$v]++;
  980. } else {
  981. $_relCombination_amount[$v] = 1;
  982. }
  983. }
  984. }
  985. // now sort and return top 5 combinations
  986. // also resolve tag/cat name
  987. if(!empty($_relCombination_amount)) {
  988. arsort($_relCombination_amount);
  989. $_top5 = array_splice($_relCombination_amount,0,5);
  990. foreach($_top5 as $k=>$v) {
  991. $_t = array();
  992. if($k[0] === "0") {
  993. $k = substr($k,1);
  994. }
  995. $_t['amount'] = $v;
  996. $_rel = explode(",",$k);
  997. $_existingRelInfo = array(); // avoid duplicate queries
  998. foreach($_rel as $t) {
  999. if(!isset($_existingRelInfo[$t])) {
  1000. if($type == 'category') {
  1001. $queryStr = "SELECT `name` FROM `".DB_PREFIX."_category`
  1002. WHERE `id` = '".$this->DB->real_escape_string($t)."'";
  1003. } else {
  1004. $queryStr = "SELECT `name` FROM `".DB_PREFIX."_tag`
  1005. WHERE `id` = '".$this->DB->real_escape_string($t)."'";
  1006. }
  1007. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  1008. try {
  1009. $query = $this->DB->query($queryStr);
  1010. if(!empty($query) && $query->num_rows > 0) {
  1011. $relinfo = $query->fetch_assoc();
  1012. $_existingRelInfo[$t] = $relinfo['name'];
  1013. $_t['rel'][$t] = $relinfo['name'];
  1014. }
  1015. } catch (Exception $e) {
  1016. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  1017. }
  1018. } else {
  1019. $_t['rel'][$t] = $_existingRelInfo[$t];
  1020. }
  1021. }
  1022. $ret[] = $_t;
  1023. }
  1024. }
  1025. return $ret;
  1026. }
  1027. /**
  1028. * Return the query string for the correct status type
  1029. *
  1030. * @return string
  1031. */
  1032. private function _decideLinkTypeForQuery(): string {
  1033. return match ($this->_queryStatus) {
  1034. 1 => "t.status IN (2,1)",
  1035. 3 => "t.status = 3",
  1036. default => "t.status = 2",
  1037. };
  1038. }
  1039. /**
  1040. * Check if given id (not hash) exists in link database
  1041. *
  1042. * @param string $id
  1043. * @return bool
  1044. */
  1045. private function _linkExistsById(string $id): bool {
  1046. $ret = false;
  1047. if(!empty($id)) {
  1048. $queryStr = "SELECT `id`
  1049. FROM `" . DB_PREFIX . "_link`
  1050. WHERE `id` = '" . $this->DB->real_escape_string($id) . "'";
  1051. if(QUERY_DEBUG) Summoner::sysLog("QUERY ".__METHOD__." query: ".Summoner::cleanForLog($queryStr));
  1052. try {
  1053. $query = $this->DB->query($queryStr);
  1054. if(!empty($query) && $query->num_rows > 0) {
  1055. $ret = true;
  1056. }
  1057. } catch (Exception $e) {
  1058. Summoner::sysLog("ERROR ".__METHOD__." mysql catch: ".$e->getMessage());
  1059. }
  1060. }
  1061. return $ret;
  1062. }
  1063. }