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