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