]> git.mxchange.org Git - friendica.git/blob - src/Model/Tag.php
Continued:
[friendica.git] / src / Model / Tag.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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 URI id
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]);
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::info('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 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 and tag id
247                 $fields['type'] = $type;
248                 $fields['tid'] = $tid;
249
250                 Logger::error('No tag id created', $fields);
251                 return 0;
252         }
253
254         /**
255          * Store tag/mention elements
256          *
257          * @param integer $uriId URI id
258          * @param string $hash Hash
259          * @param string $name Name
260          * @param string $url URL
261          * @param boolean $probing Whether probing is active
262          * @return void
263          */
264         public static function storeByHash(int $uriId, string $hash, string $name, string $url = '', bool $probing = true)
265         {
266                 $type = self::getTypeForHash($hash);
267                 if ($type == self::UNKNOWN) {
268                         return;
269                 }
270
271                 self::store($uriId, $type, $name, $url, $probing);
272         }
273
274         /**
275          * Get tags and mentions from the body
276          *
277          * @param string  $body    Body of the post
278          * @param string  $tags    Accepted tags
279          *
280          * @return array Tag list
281          */
282         public static function getFromBody(string $body, string $tags = null): array
283         {
284                 if (is_null($tags)) {
285                         $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
286                 }
287
288                 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
289                         return [];
290                 }
291
292                 return $result;
293         }
294
295         /**
296          * Store tags and mentions from the body
297          *
298          * @param integer $uriId   URI-Id
299          * @param string  $body    Body of the post
300          * @param string  $tags    Accepted tags
301          * @param boolean $probing Perform a probing for contacts, adding them if needed
302          * @return void
303          */
304         public static function storeFromBody(int $uriId, string $body, string $tags = null, bool $probing = true)
305         {
306                 Logger::info('Check for tags', ['uri-id' => $uriId, 'hash' => $tags, 'callstack' => System::callstack()]);
307
308                 if (is_null($tags)) {
309                         $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
310                 }
311
312                 // Only remove the shared data from "real" reshares
313                 $shared = BBCode::fetchShareAttributes($body);
314                 if (!empty($shared['guid'])) {
315                         if (preg_match("/\s*\[share .*?\](.*?)\[\/share\]\s*/ism",  $body, $matches)) {
316                                 $share_body = $matches[1];
317                         }
318                         $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
319                 }
320
321                 foreach (self::getFromBody($body, $tags) as $tag) {
322                         self::storeByHash($uriId, $tag[1], $tag[3], $tag[2], $probing);
323                 }
324
325                 // Search for hashtags in the shared body (but only if hashtags are wanted)
326                 if (!empty($share_body) && (strpos($tags, self::TAG_CHARACTER[self::HASHTAG]) !== false)) {
327                         foreach (self::getFromBody($share_body, self::TAG_CHARACTER[self::HASHTAG]) as $tag) {
328                                 self::storeByHash($uriId, $tag[1], $tag[3], $tag[2], $probing);
329                         }
330                 }
331         }
332
333         /**
334          * Store raw tags (not encapsulated in links) from the body
335          * This function is needed in the intermediate phase.
336          * Later we can call item::setHashtags in advance to have all tags converted.
337          *
338          * @param integer $uriId URI-Id
339          * @param string  $body   Body of the post
340          * @return void
341          */
342         public static function storeRawTagsFromBody(int $uriId, string $body)
343         {
344                 Logger::info('Check for tags', ['uri-id' => $uriId, 'callstack' => System::callstack()]);
345
346                 $result = BBCode::getTags($body);
347                 if (empty($result)) {
348                         return;
349                 }
350
351                 Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]);
352
353                 foreach ($result as $tag) {
354                         if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
355                                 continue;
356                         }
357                         self::storeByHash($uriId, substr($tag, 0, 1), substr($tag, 1));
358                 }
359         }
360
361         /**
362          * Checks for stored hashtags and mentions for the given post
363          *
364          * @param integer $uriId
365          * @return bool
366          */
367         public static function existsForPost(int $uriId): bool
368         {
369                 return DBA::exists('post-tag', ['uri-id' => $uriId, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
370         }
371
372         /**
373          * Remove tag/mention
374          *
375          * @param integer $uriId URI id
376          * @param integer $type Type
377          * @param string $name Name
378          * @param string $url URL
379          * @return void
380          */
381         public static function remove(int $uriId, int $type, string $name, string $url = '')
382         {
383                 $condition = ['uri-id' => $uriId, 'type' => $type, 'url' => $url];
384                 if ($type == self::HASHTAG) {
385                         $condition['name'] = $name;
386                 }
387
388                 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
389                 if (!DBA::isResult($tag)) {
390                         return;
391                 }
392
393                 Logger::info('Removing tag/mention', ['uri-id' => $uriId, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
394                 DBA::delete('post-tag', ['uri-id' => $uriId, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
395         }
396
397         /**
398          * Remove tag/mention
399          *
400          * @param integer $uriId URI id
401          * @param string $hash Hash
402          * @param string $name Name
403          * @param string $url URL
404          * @return void
405          */
406         public static function removeByHash(int $uriId, string $hash, string $name, string $url = '')
407         {
408                 $type = self::getTypeForHash($hash);
409                 if ($type == self::UNKNOWN) {
410                         return;
411                 }
412
413                 self::remove($uriId, $type, $name, $url);
414         }
415
416         /**
417          * Get the type for the given hash
418          *
419          * @param string $hash Hash
420          * @return integer Tag type
421          */
422         private static function getTypeForHash(string $hash): int
423         {
424                 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
425                         return self::MENTION;
426                 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
427                         return self::EXCLUSIVE_MENTION;
428                 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
429                         return self::IMPLICIT_MENTION;
430                 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
431                         return self::HASHTAG;
432                 } else {
433                         return self::UNKNOWN;
434                 }
435         }
436
437         /**
438          * Create implicit mentions for a given post
439          *
440          * @param integer $uriId URI Id
441          * @param integer $parentUriId Parent URI id
442          * @return void
443          */
444         public static function createImplicitMentions(int $uriId, int $parentUriId)
445         {
446                 // Always mention the direct parent author
447                 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parentUriId]);
448                 self::store($uriId, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
449
450                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
451                         return;
452                 }
453
454                 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parentUriId, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
455                 while ($tag = DBA::fetch($tags)) {
456                         self::store($uriId, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
457                 }
458                 DBA::close($tags);
459         }
460
461         /**
462          * Retrieves the terms from the provided type(s) associated with the provided item ID.
463          *
464          * @param int       $uriId URI id
465          * @param array $type Tag type(s)
466          * @return array|bool Array on success, false on error
467          * @throws \Exception
468          */
469         public static function getByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
470         {
471                 $condition = ['uri-id' => $uriId, 'type' => $type];
472                 return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
473         }
474
475         /**
476          * Return a string with all tags and mentions
477          *
478          * @param integer $uriId URI id
479          * @param array   $type Tag type(s)
480          * @return string tags and mentions
481          * @throws \Exception
482          */
483         public static function getCSVByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]): string
484         {
485                 $tag_list = [];
486                 foreach (self::getByURIId($uriId, $type) as $tag) {
487                         $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
488                 }
489
490                 return implode(',', $tag_list);
491         }
492
493         /**
494          * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
495          * provided item's body with them.
496          *
497          * @param array $item
498          * @return array
499          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
500          * @throws \ImagickException
501          */
502         public static function populateFromItem(array &$item): array
503         {
504                 $return = [
505                         'tags' => [],
506                         'hashtags' => [],
507                         'mentions' => [],
508                         'implicit_mentions' => [],
509                 ];
510
511                 $searchpath = DI::baseUrl() . '/search?tag=';
512
513                 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
514                         ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
515                 while ($tag = DBA::fetch($taglist)) {
516                         if ($tag['url'] == '') {
517                                 $tag['url'] = $searchpath . rawurlencode($tag['name']);
518                         }
519
520                         $orig_tag = $tag['url'];
521
522                         $prefix = self::TAG_CHARACTER[$tag['type']];
523                         switch($tag['type']) {
524                                 case self::HASHTAG:
525                                         if ($orig_tag != $tag['url']) {
526                                                 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
527                                         }
528
529                                         $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
530                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
531                                         break;
532
533                                 case self::MENTION:
534                                 case self::EXCLUSIVE_MENTION:
535                                         if (!empty($tag['cid'])) {
536                                                 $tag['url'] = Contact::magicLinkById($tag['cid']);
537                                         } else {
538                                                 $tag['url'] = Contact::magicLink($tag['url']);
539                                         }
540                                         $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
541                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
542                                         break;
543
544                                 case self::IMPLICIT_MENTION:
545                                         $return['implicit_mentions'][] = $prefix . $tag['name'];
546                                         break;
547
548                                 default:
549                                         Logger:warning('Unknown tag type found', $tag);
550                         }
551                 }
552                 DBA::close($taglist);
553
554                 return $return;
555         }
556
557         /**
558          * Counts posts for given tag
559          *
560          * @param string $search
561          * @param integer $uid
562          * @return integer number of posts
563          */
564         public static function countByTag(string $search, int $uid = 0): int
565         {
566                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
567                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
568                         $search,
569                         0,
570                         $uid,
571                         Protocol::ACTIVITYPUB,
572                         Protocol::DFRN,
573                         Protocol::DIASPORA,
574                         Protocol::OSTATUS,
575                         $uid,
576                         0,
577                 ];
578
579                 return DBA::count('tag-search-view', $condition);
580         }
581
582         /**
583          * Search posts for given tag
584          *
585          * @param string $search Tag to search for
586          * @param integer $uid User Id
587          * @param integer $start Starting record
588          * @param integer $limit Maximum count of records
589          * @param integer $last_uriid
590          * @return array with URI-ID
591          */
592         public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0): array
593         {
594                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
595                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
596                         $search,
597                         0,
598                         $uid,
599                         Protocol::ACTIVITYPUB,
600                         Protocol::DFRN,
601                         Protocol::DIASPORA,
602                         Protocol::OSTATUS,
603                         $uid,
604                         0,
605                 ];
606
607                 if (!empty($last_uriid)) {
608                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
609                 }
610
611                 $params = [
612                         'order' => ['uri-id' => true],
613                         'limit' => [$start, $limit]
614                 ];
615
616                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
617
618                 $uriIds = [];
619                 while ($tag = DBA::fetch($tags)) {
620                         $uriIds[] = $tag['uri-id'];
621                 }
622                 DBA::close($tags);
623
624                 return $uriIds;
625         }
626
627         /**
628          * Returns a list of the most frequent global hashtags over the given period
629          *
630          * @param int $period Period in hours to consider posts
631          * @param int $limit  Number of returned tags
632          * @return array
633          * @throws \Exception
634          */
635         public static function getGlobalTrendingHashtags(int $period, $limit = 10): array
636         {
637                 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
638                 if (!empty($tags)) {
639                         return $tags;
640                 } else {
641                         return self::setGlobalTrendingHashtags($period, $limit);
642                 }
643         }
644
645         /**
646          * Fetch the blocked tags as SQL
647          *
648          * @return string SQL for blocked tag names or empty string
649          */
650         private static function getBlockedSQL(): string
651         {
652                 $blocked_txt = DI::config()->get('system', 'blocked_tags');
653                 if (empty($blocked_txt)) {
654                         return '';
655                 }
656
657                 $blocked = explode(',', $blocked_txt);
658                 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
659                 return ' AND NOT `name` IN (' . implode(',', $blocked) . ')';
660         }
661
662         /**
663          * Creates a list of the most frequent global hashtags over the given period
664          *
665          * @param int $period Period in hours to consider posts
666          * @param int $limit  Number of returned tags
667          * @return array
668          * @throws \Exception
669          */
670         public static function setGlobalTrendingHashtags(int $period, int $limit = 10): array
671         {
672                 /*
673                 * Get a uri-id that is at least X hours old.
674                 * We use the uri-id in the query for the hash tags since this is much faster
675                 */
676                 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
677                         ['order' => ['received' => true]]);
678
679                 if (empty($post['uri-id'])) {
680                         return [];
681                 }
682
683                 $block_sql = self::getBlockedSQL();
684
685                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
686                         FROM `tag-search-view`
687                         WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
688                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
689                         Item::PUBLIC,
690                         0,
691                         $post['uri-id'],
692                         $limit
693                 );
694
695                 if (DBA::isResult($tagsStmt)) {
696                         $tags = DBA::toArray($tagsStmt);
697                         DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
698                         return $tags;
699                 }
700
701                 return [];
702         }
703
704         /**
705          * Returns a list of the most frequent local hashtags over the given period
706          *
707          * @param int $period Period in hours to consider posts
708          * @param int $limit  Number of returned tags
709          * @return array
710          * @throws \Exception
711          */
712         public static function getLocalTrendingHashtags(int $period, $limit = 10): array
713         {
714                 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
715                 if (!empty($tags)) {
716                         return $tags;
717                 } else {
718                         return self::setLocalTrendingHashtags($period, $limit);
719                 }
720         }
721
722         /**
723          * Returns a list of the most frequent local hashtags over the given period
724          *
725          * @param int $period Period in hours to consider posts
726          * @param int $limit  Number of returned tags
727          * @return array
728          * @throws \Exception
729          */
730         public static function setLocalTrendingHashtags(int $period, int $limit = 10): array
731         {
732                 // Get a uri-id that is at least X hours old.
733                 // We use the uri-id in the query for the hash tags since this is much faster
734                 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
735                         ['order' => ['received' => true]]);
736                 if (empty($post['uri-id'])) {
737                         return [];
738                 }
739
740                 $block_sql = self::getBlockedSQL();
741
742                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
743                         FROM `tag-search-view`
744                         WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
745                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
746                         Item::PUBLIC,
747                         $post['uri-id'],
748                         $limit
749                 );
750
751                 if (DBA::isResult($tagsStmt)) {
752                         $tags = DBA::toArray($tagsStmt);
753                         DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
754                         return $tags;
755                 }
756
757                 return [];
758         }
759
760         /**
761          * Check if the provided tag is of one of the provided term types.
762          *
763          * @param string $tag Tag name
764          * @param int    ...$types
765          * @return bool
766          */
767         public static function isType(string $tag, ...$types): bool
768         {
769                 $tag_chars = [];
770                 foreach ($types as $type) {
771                         if (array_key_exists($type, self::TAG_CHARACTER)) {
772                                 $tag_chars[] = self::TAG_CHARACTER[$type];
773                         }
774                 }
775
776                 return Strings::startsWithChars($tag, $tag_chars);
777         }
778
779         /**
780          * Fetch user who subscribed to the given tag
781          *
782          * @param string $tag
783          * @return array User list
784          */
785         private static function getUIDListByTag(string $tag): array
786         {
787                 $uids = [];
788                 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
789                 while ($search = DBA::fetch($searches)) {
790                         $uids[] = $search['uid'];
791                 }
792                 DBA::close($searches);
793
794                 return $uids;
795         }
796
797         /**
798          * Fetch user who subscribed to the tags of the given item
799          *
800          * @param integer $uriId URI Id
801          * @return array User list
802          */
803         public static function getUIDListByURIId(int $uriId): array
804         {
805                 $uids = [];
806                 $tags = self::getByURIId($uriId, [self::HASHTAG]);
807
808                 foreach ($tags as $tag) {
809                         $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
810                 }
811
812                 return array_unique($uids);
813         }
814 }