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