]> git.mxchange.org Git - friendica.git/blob - src/Model/Tag.php
8509c309387aa670db010de3b97a8ccc4e862a77
[friendica.git] / src / Model / Tag.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (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 Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Cache\Enum\Duration;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\System;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Protocol\ActivityPub;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Strings;
35
36 /**
37  * Class Tag
38  *
39  * This Model class handles tag table interactions.
40  * This tables stores relevant tags related to posts, like hashtags and mentions.
41  */
42 class Tag
43 {
44         const UNKNOWN  = 0;
45         const HASHTAG  = 1;
46         const MENTION  = 2;
47         /**
48          * An implicit mention is a mention in a comment body that is redundant with the threading information.
49          */
50         const IMPLICIT_MENTION  = 8;
51         /**
52          * An exclusive mention transmits the post only to the target account without transmitting it to the followers, usually a forum.
53          */
54         const EXCLUSIVE_MENTION = 9;
55
56         const TO  = 10;
57         const CC  = 11;
58         const BTO = 12;
59         const BCC = 13;
60
61         const ACCOUNT             = 1;
62         const GENERAL_COLLECTION  = 2;
63         const FOLLOWER_COLLECTION = 3;
64         const PUBLIC_COLLECTION   = 4;
65
66         const TAG_CHARACTER = [
67                 self::HASHTAG           => '#',
68                 self::MENTION           => '@',
69                 self::EXCLUSIVE_MENTION => '!',
70                 self::IMPLICIT_MENTION  => '%',
71         ];
72
73         /**
74          * Store tag/mention elements
75          *
76          * @param integer $uriId
77          * @param integer $type Tag type
78          * @param string  $name Tag name
79          * @param string  $url Contact URL (optional)
80          * @param integer $target Target (default: null)
81          * @return void
82          */
83         public static function store(int $uriId, int $type, string $name, string $url = '', int $target = null)
84         {
85                 if ($type == self::HASHTAG) {
86                         // Trim Unicode non-word characters
87                         $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
88
89                         $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
90                         if (count($tags) > 1) {
91                                 foreach ($tags as $tag) {
92                                         self::store($uriId, $type, $tag, $url);
93                                 }
94                                 return;
95                         }
96                 }
97
98                 if (empty($name)) {
99                         return;
100                 }
101
102                 $cid = 0;
103                 $tagid = 0;
104
105                 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION, self::TO, self::CC, self::BTO, self::BCC])) {
106                         if (empty($url)) {
107                                 // No mention without a contact url
108                                 return;
109                         }
110
111                         if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
112                                 Logger::notice('Wrong scheme in url', ['url' => $url, 'callstack' => System::callstack(20)]);
113                         }
114
115                         $cid = Contact::getIdForURL($url, 0, false);
116                         Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]);
117
118                         if (empty($cid)) {
119                                 $tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]);
120                                 if (!empty($tag)) {
121                                         if ($tag['name'] != substr($name, 0, 96)) {
122                                                 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url, 'type' => $tag['type']]);
123                                         }
124                                         if (!empty($target) && ($tag['type'] != $target)) {
125                                                 DBA::update('tag', ['type' => $target], ['url' => $url]);
126                                         }
127                                 }
128                         }
129                 }
130
131                 if (empty($cid)) {
132                         if (!in_array($type, [self::TO, self::CC, self::BTO, self::BCC])) {
133                                 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
134                                         $url = strtolower($url);
135                                 } else {
136                                         $url = '';
137                                 }
138                         }
139
140                         $tagid = self::getID($name, $url, $target);
141                         if (empty($tagid)) {
142                                 return;
143                         }
144                 }
145
146                 $fields = ['uri-id' => $uriId, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
147
148                 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
149                         $condition = $fields;
150                         $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
151                         if (DBA::exists('post-tag', $condition)) {
152                                 Logger::info('Tag already exists', $fields);
153                                 return;
154                         }
155                 }
156
157                 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
158
159                 Logger::debug('Stored tag/mention', ['uri-id' => $uriId, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
160         }
161
162         /**
163          * Fetch the target type for the given url
164          *
165          * @param string $url
166          * @param bool   $fetch Fetch information via network operations
167          * @return null|int
168          */
169         public static function getTargetType(string $url, bool $fetch = true)
170         {
171                 $target = null;
172
173                 if (empty($url)) {
174                         return $target;
175                 }
176
177                 $tag = DBA::selectFirst('tag', ['url', 'type'], ['url' => $url]);
178                 if (!empty($tag['type'])) {
179                         $target = $tag['type'];
180                         if ($target != self::GENERAL_COLLECTION) {
181                                 Logger::debug('Found existing type', ['type' => $tag['type'], 'url' => $url]);
182                                 return $target;
183                         }
184                 }
185
186                 if ($url == ActivityPub::PUBLIC_COLLECTION) {
187                         $target = self::PUBLIC_COLLECTION;
188                         Logger::debug('Public collection', ['url' => $url]);
189                 } else {
190                         if (DBA::exists('apcontact', ['followers' => $url])) {
191                                 $target = self::FOLLOWER_COLLECTION;
192                                 Logger::debug('Found collection via existing apcontact', ['url' => $url]);
193                         } elseif (Contact::getIdForURL($url, 0, $fetch ? null : false)) {
194                                 $target = self::ACCOUNT;
195                                 Logger::debug('URL is an account', ['url' => $url]);
196                         } elseif ($fetch && ($target != self::GENERAL_COLLECTION)) {
197                                 $content = ActivityPub::fetchContent($url);
198                                 if (!empty($content['type']) && ($content['type'] == 'OrderedCollection')) {
199                                         $target = self::GENERAL_COLLECTION;
200                                         Logger::debug('URL is an ordered collection', ['url' => $url]);
201                                 }
202                         }
203                 }
204
205                 if (!empty($target) && !empty($tag['url']) && ($tag['type'] != $target)) {
206                         DBA::update('tag', ['type' => $target], ['url' => $url]);
207                 }
208
209                 if (empty($target)) {
210                         Logger::debug('No type could be detected', ['url' => $url]);
211                 }
212
213                 return $target;
214         }
215
216         /**
217          * Get a tag id for a given tag name and URL
218          *
219          * @param string $name Name of tag
220          * @param string $url
221          * @param int    $type Type of tag
222          * @return int Tag id
223          */
224         public static function getID(string $name, string $url = '', int $type = null): int
225         {
226                 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
227
228                 $tag = DBA::selectFirst('tag', ['id', 'type'], $fields);
229                 if (DBA::isResult($tag)) {
230                         if (empty($tag['type']) && !empty($type)) {
231                                 DBA::update('tag', ['type' => $type], $fields);
232                         }
233                         return $tag['id'];
234                 }
235
236                 if (!empty($type)) {
237                         $fields['type'] = $type;
238                 }
239
240                 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
241                 $tid = DBA::lastInsertId();
242                 if (!empty($tid)) {
243                         return $tid;
244                 }
245
246                 // Also log type
247                 $fields['type'] = $type;
248
249                 Logger::error('No tag id created', $fields);
250                 return 0;
251         }
252
253         /**
254          * Store tag/mention elements
255          *
256          * @param integer $uriId
257          * @param string $hash
258          * @param string $name
259          * @param string $url
260          * @return void
261          */
262         public static function storeByHash(int $uriId, string $hash, string $name, string $url = '')
263         {
264                 $type = self::getTypeForHash($hash);
265                 if ($type == self::UNKNOWN) {
266                         return;
267                 }
268
269                 self::store($uriId, $type, $name, $url);
270         }
271
272         /**
273          * Get tags and mentions from the body
274          *
275          * @param string  $body    Body of the post
276          * @param string  $tags    Accepted tags
277          *
278          * @return array Tag list
279          */
280         public static function getFromBody(string $body, string $tags = null): array
281         {
282                 if (is_null($tags)) {
283                         $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
284                 }
285
286                 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
287                         return [];
288                 }
289
290                 return $result;
291         }
292
293         /**
294          * Store tags and mentions from the body
295          *
296          * @param integer $uriId   URI-Id
297          * @param string  $body    Body of the post
298          * @param string  $tags    Accepted tags
299          * @return void
300          */
301         public static function storeFromBody(int $uriId, string $body, string $tags = null)
302         {
303                 $item = ['uri-id' => $uriId, 'body' => $body, 'quote-uri-id' => null];
304                 self::storeFromArray($item, $tags);
305         }
306
307         /**
308          * Store tags and mentions from the item array
309          *
310          * @param array   $item    Item array
311          * @param string  $tags    Accepted tags
312          * @return void
313          */
314         public static function storeFromArray(array $item, string $tags = null)
315         {
316                 Logger::info('Check for tags', ['uri-id' => $item['uri-id'], 'hash' => $tags, 'callstack' => System::callstack()]);
317
318                 if (is_null($tags)) {
319                         $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
320                 }
321
322                 foreach (self::getFromBody($item['body'], $tags) as $tag) {
323                         self::storeByHash($item['uri-id'], $tag[1], $tag[3], $tag[2]);
324                 }
325
326                 $shared = DI::contentItem()->getSharedPost($item, ['uri-id']);
327
328                 // Search for hashtags in the shared body (but only if hashtags are wanted)
329                 if (!empty($shared) && (strpos($tags, self::TAG_CHARACTER[self::HASHTAG]) !== false)) {
330                         foreach (self::getByURIId($shared['post']['uri-id'], [self::HASHTAG]) as $tag) {
331                                 self::store($item['uri-id'], $tag['type'], $tag['name'], $tag['url']);
332                         }
333                 }
334         }
335
336         /**
337          * Store raw tags (not encapsulated in links) from the body
338          * This function is needed in the intermediate phase.
339          * Later we can call item::setHashtags in advance to have all tags converted.
340          *
341          * @param integer $uriId URI-Id
342          * @param string  $body   Body of the post
343          * @return void
344          */
345         public static function storeRawTagsFromBody(int $uriId, string $body)
346         {
347                 Logger::info('Check for tags', ['uri-id' => $uriId, 'callstack' => System::callstack()]);
348
349                 $result = BBCode::getTags($body);
350                 if (empty($result)) {
351                         return;
352                 }
353
354                 Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]);
355
356                 foreach ($result as $tag) {
357                         if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
358                                 continue;
359                         }
360                         self::storeByHash($uriId, substr($tag, 0, 1), substr($tag, 1));
361                 }
362         }
363
364         /**
365          * Checks for stored hashtags and mentions for the given post
366          *
367          * @param integer $uriId
368          * @return bool
369          */
370         public static function existsForPost(int $uriId): bool
371         {
372                 return DBA::exists('post-tag', ['uri-id' => $uriId, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
373         }
374
375         /**
376          * Remove tag/mention
377          *
378          * @param integer $uriId
379          * @param integer $type Type
380          * @param string $name Name
381          * @param string $url URL
382          * @return void
383          */
384         public static function remove(int $uriId, int $type, string $name, string $url = '')
385         {
386                 $condition = ['uri-id' => $uriId, 'type' => $type, 'url' => $url];
387                 if ($type == self::HASHTAG) {
388                         $condition['name'] = $name;
389                 }
390
391                 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
392                 if (!DBA::isResult($tag)) {
393                         return;
394                 }
395
396                 Logger::debug('Removing tag/mention', ['uri-id' => $uriId, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
397                 DBA::delete('post-tag', ['uri-id' => $uriId, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
398         }
399
400         /**
401          * Remove tag/mention
402          *
403          * @param integer $uriId
404          * @param string $hash
405          * @param string $name
406          * @param string $url
407          * @return void
408          */
409         public static function removeByHash(int $uriId, string $hash, string $name, string $url = '')
410         {
411                 $type = self::getTypeForHash($hash);
412                 if ($type == self::UNKNOWN) {
413                         return;
414                 }
415
416                 self::remove($uriId, $type, $name, $url);
417         }
418
419         /**
420          * Get the type for the given hash
421          *
422          * @param string $hash
423          * @return integer Tag type
424          */
425         private static function getTypeForHash(string $hash): int
426         {
427                 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
428                         return self::MENTION;
429                 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
430                         return self::EXCLUSIVE_MENTION;
431                 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
432                         return self::IMPLICIT_MENTION;
433                 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
434                         return self::HASHTAG;
435                 } else {
436                         return self::UNKNOWN;
437                 }
438         }
439
440         /**
441          * Create implicit mentions for a given post
442          *
443          * @param integer $uriId
444          * @param integer $parentUriId
445          * @return void
446          */
447         public static function createImplicitMentions(int $uriId, int $parentUriId)
448         {
449                 // Always mention the direct parent author
450                 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parentUriId]);
451                 self::store($uriId, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
452
453                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
454                         return;
455                 }
456
457                 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parentUriId, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
458                 while ($tag = DBA::fetch($tags)) {
459                         self::store($uriId, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
460                 }
461                 DBA::close($tags);
462         }
463
464         /**
465          * Retrieves the terms from the provided type(s) associated with the provided item ID.
466          *
467          * @param int   $uriId
468          * @param array $type Tag type(s)
469          * @return array|bool Array on success, false on error
470          * @throws \Exception
471          */
472         public static function getByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
473         {
474                 $condition = ['uri-id' => $uriId, 'type' => $type];
475                 return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
476         }
477
478         /**
479          * Checks if the given url is mentioned in the post
480          *
481          * @param integer $uriId
482          * @param string $url
483          * @param array $type
484          *
485          * @return boolean
486          */
487         public static function isMentioned(int $uriId, string $url, array $type = [self::MENTION, self::EXCLUSIVE_MENTION]): bool
488         {
489                 $tags = self::getByURIId($uriId, $type);
490                 foreach ($tags as $tag) {
491                         if (Strings::compareLink($url, $tag['url'])) {
492                                 return true;
493                         }
494                 }
495                 return false;
496         }
497
498         /**
499          * Return a string with all tags and mentions
500          *
501          * @param integer $uriId
502          * @param array   $type Tag type(s)
503          * @return string tags and mentions
504          * @throws \Exception
505          */
506         public static function getCSVByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]): string
507         {
508                 $tag_list = [];
509                 foreach (self::getByURIId($uriId, $type) as $tag) {
510                         $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
511                 }
512
513                 return implode(',', $tag_list);
514         }
515
516         /**
517          * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
518          * provided item's body with them.
519          *
520          * @param array $item
521          * @return array
522          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
523          * @throws \ImagickException
524          */
525         public static function populateFromItem(array &$item): array
526         {
527                 $return = [
528                         'tags' => [],
529                         'hashtags' => [],
530                         'mentions' => [],
531                         'implicit_mentions' => [],
532                 ];
533
534                 $searchpath = DI::baseUrl() . '/search?tag=';
535
536                 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
537                         ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
538                 while ($tag = DBA::fetch($taglist)) {
539                         if ($tag['url'] == '') {
540                                 $tag['url'] = $searchpath . rawurlencode($tag['name']);
541                         }
542
543                         $orig_tag = $tag['url'];
544
545                         $prefix = self::TAG_CHARACTER[$tag['type']];
546                         switch($tag['type']) {
547                                 case self::HASHTAG:
548                                         if ($orig_tag != $tag['url']) {
549                                                 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
550                                         }
551
552                                         $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
553                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
554                                         break;
555
556                                 case self::MENTION:
557                                 case self::EXCLUSIVE_MENTION:
558                                         if (!empty($tag['cid'])) {
559                                                 $tag['url'] = Contact::magicLinkById($tag['cid']);
560                                         } else {
561                                                 $tag['url'] = Contact::magicLink($tag['url']);
562                                         }
563                                         $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
564                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
565                                         break;
566
567                                 case self::IMPLICIT_MENTION:
568                                         $return['implicit_mentions'][] = $prefix . $tag['name'];
569                                         break;
570
571                                 default:
572                                         Logger::warning('Unknown tag type found', $tag);
573                         }
574                 }
575                 DBA::close($taglist);
576
577                 return $return;
578         }
579
580         /**
581          * Counts posts for given tag
582          *
583          * @param string $search
584          * @param integer $uid
585          * @return integer number of posts
586          */
587         public static function countByTag(string $search, int $uid = 0): int
588         {
589                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
590                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
591                         $search, 0, $uid,
592                         Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
593                 ];
594
595                 return DBA::count('tag-search-view', $condition);
596         }
597
598         /**
599          * Search posts for given tag
600          *
601          * @param string $search Tag to search for
602          * @param integer $uid User Id
603          * @param integer $start Starting record
604          * @param integer $limit Maximum count of records
605          * @param integer $last_uriid
606          * @return array with URI-ID
607          */
608         public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0): array
609         {
610                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
611                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
612                         $search, 0, $uid,
613                         Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
614                 ];
615
616                 if (!empty($last_uriid)) {
617                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
618                 }
619
620                 $params = [
621                         'order' => ['uri-id' => true],
622                         'limit' => [$start, $limit]
623                 ];
624
625                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
626
627                 $uriIds = [];
628                 while ($tag = DBA::fetch($tags)) {
629                         $uriIds[] = $tag['uri-id'];
630                 }
631                 DBA::close($tags);
632
633                 return $uriIds;
634         }
635
636         /**
637          * Returns a list of the most frequent global hashtags over the given period
638          *
639          * @param int $period Period in hours to consider posts
640          * @param int $limit  Number of returned tags
641          * @return array
642          * @throws \Exception
643          */
644         public static function getGlobalTrendingHashtags(int $period, $limit = 10): array
645         {
646                 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
647                 if (!empty($tags)) {
648                         return $tags;
649                 } else {
650                         return self::setGlobalTrendingHashtags($period, $limit);
651                 }
652         }
653
654         /**
655          * Fetch the blocked tags as SQL
656          *
657          * @return string SQL for blocked tag names or empty string
658          */
659         private static function getBlockedSQL(): string
660         {
661                 $blocked_txt = DI::config()->get('system', 'blocked_tags');
662                 if (empty($blocked_txt)) {
663                         return '';
664                 }
665
666                 $blocked = explode(',', $blocked_txt);
667                 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
668                 return ' AND NOT `name` IN (' . implode(',', $blocked) . ')';
669         }
670
671         /**
672          * Creates a list of the most frequent global hashtags over the given period
673          *
674          * @param int $period Period in hours to consider posts
675          * @param int $limit  Number of returned tags
676          * @return array
677          * @throws \Exception
678          */
679         public static function setGlobalTrendingHashtags(int $period, int $limit = 10): array
680         {
681                 /*
682                 * Get a uri-id that is at least X hours old.
683                 * We use the uri-id in the query for the hash tags since this is much faster
684                 */
685                 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
686                         ['order' => ['received' => true]]);
687
688                 if (empty($post['uri-id'])) {
689                         return [];
690                 }
691
692                 $block_sql = self::getBlockedSQL();
693
694                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
695                         FROM `tag-search-view`
696                         WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
697                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
698                         Item::PUBLIC, 0, $post['uri-id'],
699                         $limit
700                 );
701
702                 if (DBA::isResult($tagsStmt)) {
703                         $tags = DBA::toArray($tagsStmt);
704                         DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
705                         return $tags;
706                 }
707
708                 return [];
709         }
710
711         /**
712          * Returns a list of the most frequent local hashtags over the given period
713          *
714          * @param int $period Period in hours to consider posts
715          * @param int $limit  Number of returned tags
716          * @return array
717          * @throws \Exception
718          */
719         public static function getLocalTrendingHashtags(int $period, $limit = 10): array
720         {
721                 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
722                 if (!empty($tags)) {
723                         return $tags;
724                 } else {
725                         return self::setLocalTrendingHashtags($period, $limit);
726                 }
727         }
728
729         /**
730          * Returns a list of the most frequent local hashtags over the given period
731          *
732          * @param int $period Period in hours to consider posts
733          * @param int $limit  Number of returned tags
734          * @return array
735          * @throws \Exception
736          */
737         public static function setLocalTrendingHashtags(int $period, int $limit = 10): array
738         {
739                 // Get a uri-id that is at least X hours old.
740                 // We use the uri-id in the query for the hash tags since this is much faster
741                 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
742                         ['order' => ['received' => true]]);
743                 if (empty($post['uri-id'])) {
744                         return [];
745                 }
746
747                 $block_sql = self::getBlockedSQL();
748
749                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
750                         FROM `tag-search-view`
751                         WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
752                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
753                         Item::PUBLIC, $post['uri-id'],
754                         $limit
755                 );
756
757                 if (DBA::isResult($tagsStmt)) {
758                         $tags = DBA::toArray($tagsStmt);
759                         DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
760                         return $tags;
761                 }
762
763                 return [];
764         }
765
766         /**
767          * Check if the provided tag is of one of the provided term types.
768          *
769          * @param string $tag Tag name
770          * @param int    ...$types
771          * @return bool
772          */
773         public static function isType(string $tag, ...$types): bool
774         {
775                 $tag_chars = [];
776                 foreach ($types as $type) {
777                         if (array_key_exists($type, self::TAG_CHARACTER)) {
778                                 $tag_chars[] = self::TAG_CHARACTER[$type];
779                         }
780                 }
781
782                 return Strings::startsWithChars($tag, $tag_chars);
783         }
784
785         /**
786          * Fetch user who subscribed to the given tag
787          *
788          * @param string $tag
789          * @return array User list
790          */
791         private static function getUIDListByTag(string $tag): array
792         {
793                 $uids = [];
794                 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
795                 while ($search = DBA::fetch($searches)) {
796                         $uids[] = $search['uid'];
797                 }
798                 DBA::close($searches);
799
800                 return $uids;
801         }
802
803         /**
804          * Fetch user who subscribed to the tags of the given item
805          *
806          * @param integer $uriId
807          * @return array User list
808          */
809         public static function getUIDListByURIId(int $uriId): array
810         {
811                 $uids = [];
812                 $tags = self::getByURIId($uriId, [self::HASHTAG]);
813
814                 foreach ($tags as $tag) {
815                         $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
816                 }
817
818                 return array_unique($uids);
819         }
820 }