]> git.mxchange.org Git - friendica.git/blob - src/Model/Tag.php
Merge branch 'develop' into notifications-summary
[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)) {
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(
538                         'tag-view',
539                         ['type', 'name', 'url', 'cid'],
540                         ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]
541                 );
542                 while ($tag = DBA::fetch($taglist)) {
543                         if ($tag['url'] == '') {
544                                 $tag['url'] = $searchpath . rawurlencode($tag['name']);
545                         }
546
547                         $orig_tag = $tag['url'];
548
549                         $prefix = self::TAG_CHARACTER[$tag['type']];
550                         switch ($tag['type']) {
551                                 case self::HASHTAG:
552                                         if ($orig_tag != $tag['url']) {
553                                                 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
554                                         }
555
556                                         $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
557                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
558                                         break;
559
560                                 case self::MENTION:
561                                 case self::EXCLUSIVE_MENTION:
562                                         if (!empty($tag['cid'])) {
563                                                 $tag['url'] = Contact::magicLinkById($tag['cid']);
564                                         } else {
565                                                 $tag['url'] = Contact::magicLink($tag['url']);
566                                         }
567                                         $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
568                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
569                                         break;
570
571                                 case self::IMPLICIT_MENTION:
572                                         $return['implicit_mentions'][] = $prefix . $tag['name'];
573                                         break;
574
575                                 default:
576                                         Logger::warning('Unknown tag type found', $tag);
577                         }
578                 }
579                 DBA::close($taglist);
580
581                 return $return;
582         }
583
584         /**
585          * Counts posts for given tag
586          *
587          * @param string $search
588          * @param integer $uid
589          * @return integer number of posts
590          */
591         public static function countByTag(string $search, int $uid = 0): int
592         {
593                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
594                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
595                         $search, 0, $uid,
596                         Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
597                 ];
598
599                 return DBA::count('tag-search-view', $condition);
600         }
601
602         /**
603          * Search posts for given tag
604          *
605          * @param string $search Tag to search for
606          * @param integer $uid User Id
607          * @param integer $start Starting record
608          * @param integer $limit Maximum count of records
609          * @param integer $last_uriid
610          * @return array with URI-ID
611          */
612         public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0): array
613         {
614                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
615                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
616                         $search, 0, $uid,
617                         Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
618                 ];
619
620                 if (!empty($last_uriid)) {
621                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
622                 }
623
624                 $params = [
625                         'order' => ['uri-id' => true],
626                         'limit' => [$start, $limit]
627                 ];
628
629                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
630
631                 $uriIds = [];
632                 while ($tag = DBA::fetch($tags)) {
633                         $uriIds[] = $tag['uri-id'];
634                 }
635                 DBA::close($tags);
636
637                 return $uriIds;
638         }
639
640         /**
641          * Returns a list of the most frequent global hashtags over the given period
642          *
643          * @param int $period Period in hours to consider posts
644          * @param int $limit  Number of returned tags
645          * @param int $offset  Page offset in results
646          * @return array
647          * @throws \Exception
648          */
649         public static function getGlobalTrendingHashtags(int $period, int $limit = 10, int $offset = 0): array
650         {
651                 $tags = DI::cache()->get("global_trending_tags-$period");
652                 if (empty($tags)) {
653                         $tags = self::setGlobalTrendingHashtags($period, 1000);
654                 }
655                 return array_slice($tags, $offset, $limit);
656         }
657
658         /**
659          * Fetch the blocked tags as SQL
660          *
661          * @return string SQL for blocked tag names or empty string
662          */
663         private static function getBlockedSQL(): string
664         {
665                 $blocked_txt = DI::config()->get('system', 'blocked_tags');
666                 if (empty($blocked_txt)) {
667                         return '';
668                 }
669
670                 $blocked = explode(',', $blocked_txt);
671                 array_walk($blocked, function (&$value) {
672                         $value = "'" . DBA::escape(trim($value)) . "'";
673                 });
674                 return ' AND NOT `name` IN (' . implode(',', $blocked) . ')';
675         }
676
677         /**
678          * Creates a list of the most frequent global hashtags over the given period
679          *
680          * @param int $period Period in hours to consider posts
681          * @param int $limit  Number of returned tags
682          * @return array
683          * @throws \Exception
684          */
685         public static function setGlobalTrendingHashtags(int $period, int $limit = 10): array
686         {
687                 /*
688                 * Get a uri-id that is at least X hours old.
689                 * We use the uri-id in the query for the hash tags since this is much faster
690                 */
691                 $post = Post::selectFirstThread(
692                         ['uri-id'],
693                         ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
694                         ['order' => ['received' => true]]
695                 );
696
697                 if (empty($post['uri-id'])) {
698                         return [];
699                 }
700
701                 $block_sql = self::getBlockedSQL();
702
703                 $tagsStmt = DBA::p(
704                         "SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
705                         FROM `tag-search-view`
706                         WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
707                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
708                         Item::PUBLIC,
709                         0,
710                         $post['uri-id'],
711                         $limit
712                 );
713
714                 if (DBA::isResult($tagsStmt)) {
715                         $tags = DBA::toArray($tagsStmt);
716                         DI::cache()->set("global_trending_tags-$period", $tags, Duration::HOUR);
717                         return $tags;
718                 }
719
720                 return [];
721         }
722
723         /**
724          * Returns a list of the most frequent local hashtags over the given period
725          *
726          * @param int $period Period in hours to consider posts
727          * @param int $limit  Number of returned tags
728          * @param int $offset  Page offset in results
729          * @return array
730          * @throws \Exception
731          */
732         public static function getLocalTrendingHashtags(int $period, $limit = 10, int $offset = 0): array
733         {
734                 $tags = DI::cache()->get("local_trending_tags-$period");
735                 if (empty($tags)) {
736                         $tags = self::setLocalTrendingHashtags($period, 1000);
737                 }
738                 return array_slice($tags, $offset, $limit);
739         }
740
741         /**
742          * Returns a list of the most frequent local hashtags over the given period
743          *
744          * @param int $period Period in hours to consider posts
745          * @param int $limit  Number of returned tags
746          * @return array
747          * @throws \Exception
748          */
749         public static function setLocalTrendingHashtags(int $period, int $limit = 10): array
750         {
751                 // Get a uri-id that is at least X hours old.
752                 // We use the uri-id in the query for the hash tags since this is much faster
753                 $post = Post::selectFirstThread(
754                         ['uri-id'],
755                         ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
756                         ['order' => ['received' => true]]
757                 );
758                 if (empty($post['uri-id'])) {
759                         return [];
760                 }
761
762                 $block_sql = self::getBlockedSQL();
763
764                 $tagsStmt = DBA::p(
765                         "SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
766                         FROM `tag-search-view`
767                         WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
768                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
769                         Item::PUBLIC,
770                         $post['uri-id'],
771                         $limit
772                 );
773
774                 if (DBA::isResult($tagsStmt)) {
775                         $tags = DBA::toArray($tagsStmt);
776                         DI::cache()->set("local_trending_tags-$period", $tags, Duration::HOUR);
777                         return $tags;
778                 }
779
780                 return [];
781         }
782
783         /**
784          * Check if the provided tag is of one of the provided term types.
785          *
786          * @param string $tag Tag name
787          * @param int    ...$types
788          * @return bool
789          */
790         public static function isType(string $tag, ...$types): bool
791         {
792                 $tag_chars = [];
793                 foreach ($types as $type) {
794                         if (array_key_exists($type, self::TAG_CHARACTER)) {
795                                 $tag_chars[] = self::TAG_CHARACTER[$type];
796                         }
797                 }
798
799                 return Strings::startsWithChars($tag, $tag_chars);
800         }
801
802         /**
803          * Fetch user who subscribed to the given tag
804          *
805          * @param string $tag
806          * @return array User list
807          */
808         private static function getUIDListByTag(string $tag): array
809         {
810                 $uids = [];
811                 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
812                 while ($search = DBA::fetch($searches)) {
813                         $uids[] = $search['uid'];
814                 }
815                 DBA::close($searches);
816
817                 return $uids;
818         }
819
820         /**
821          * Fetch user who subscribed to the tags of the given item
822          *
823          * @param integer $uriId
824          * @return array User list
825          */
826         public static function getUIDListByURIId(int $uriId): array
827         {
828                 $uids = [];
829                 $tags = self::getByURIId($uriId, [self::HASHTAG]);
830
831                 foreach ($tags as $tag) {
832                         $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
833                 }
834
835                 return array_unique($uids);
836         }
837 }