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