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