]> git.mxchange.org Git - friendica.git/blob - src/Model/Tag.php
Merge pull request #11438 from MrPetovan/bug/11371-settings-forms
[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                 if (!empty($type)) {
228                         $fields['type'] = $type;
229                 }
230
231                 $tag = DBA::selectFirst('tag', ['id'], $fields);
232                 if (DBA::isResult($tag)) {
233                         return $tag['id'];
234                 }
235
236                 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
237                 $tid = DBA::lastInsertId();
238                 if (!empty($tid)) {
239                         return $tid;
240                 }
241
242                 Logger::error('No tag id created', $fields);
243                 return 0;
244         }
245
246         /**
247          * Store tag/mention elements
248          *
249          * @param integer $uriid
250          * @param string $hash
251          * @param string $name
252          * @param string $url
253          * @param boolean $probing
254          */
255         public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
256         {
257                 $type = self::getTypeForHash($hash);
258                 if ($type == self::UNKNOWN) {
259                         return;
260                 }
261
262                 self::store($uriid, $type, $name, $url, $probing);
263         }
264
265         /**
266          * Get tags and mentions from the body
267          *
268          * @param string  $body    Body of the post
269          * @param string  $tags    Accepted tags
270          *
271          * @return array Tag list
272          */
273         public static function getFromBody(string $body, string $tags = null)
274         {
275                 if (is_null($tags)) {
276                         $tags =  self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
277                 }
278
279                 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
280                         return [];
281                 }
282
283                 return $result;
284         }
285
286         /**
287          * Store tags and mentions from the body
288          *
289          * @param integer $uriid   URI-Id
290          * @param string  $body    Body of the post
291          * @param string  $tags    Accepted tags
292          * @param boolean $probing Perform a probing for contacts, adding them if needed
293          */
294         public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
295         {
296                 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
297
298                 $result = self::getFromBody($body, $tags);
299                 if (empty($result)) {
300                         return;
301                 }
302
303                 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
304
305                 foreach ($result as $tag) {
306                         self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
307                 }
308         }
309
310         /**
311          * Store raw tags (not encapsulated in links) from the body
312          * This function is needed in the intermediate phase.
313          * Later we can call item::setHashtags in advance to have all tags converted.
314          *
315          * @param integer $uriid URI-Id
316          * @param string  $body   Body of the post
317          */
318         public static function storeRawTagsFromBody(int $uriid, string $body)
319         {
320                 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
321
322                 $result = BBCode::getTags($body);
323                 if (empty($result)) {
324                         return;
325                 }
326
327                 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
328
329                 foreach ($result as $tag) {
330                         if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
331                                 continue;
332                         }
333                         self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
334                 }
335         }
336
337         /**
338          * Checks for stored hashtags and mentions for the given post
339          *
340          * @param integer $uriid
341          * @return bool
342          */
343         public static function existsForPost(int $uriid)
344         {
345                 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
346         }
347
348         /**
349          * Remove tag/mention
350          *
351          * @param integer $uriid
352          * @param integer $type
353          * @param string $name
354          * @param string $url
355          */
356         public static function remove(int $uriid, int $type, string $name, string $url = '')
357         {
358                 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
359                 if ($type == self::HASHTAG) {
360                         $condition['name'] = $name;
361                 }
362
363                 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
364                 if (!DBA::isResult($tag)) {
365                         return;
366                 }
367
368                 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
369                 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
370         }
371
372         /**
373          * Remove tag/mention
374          *
375          * @param integer $uriid
376          * @param string $hash
377          * @param string $name
378          * @param string $url
379          */
380         public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
381         {
382                 $type = self::getTypeForHash($hash);
383                 if ($type == self::UNKNOWN) {
384                         return;
385                 }
386
387                 self::remove($uriid, $type, $name, $url);
388         }
389
390         /**
391          * Get the type for the given hash
392          *
393          * @param string $hash
394          * @return integer type
395          */
396         private static function getTypeForHash(string $hash)
397         {
398                 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
399                         return self::MENTION;
400                 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
401                         return self::EXCLUSIVE_MENTION;
402                 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
403                         return self::IMPLICIT_MENTION;
404                 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
405                         return self::HASHTAG;
406                 } else {
407                         return self::UNKNOWN;
408                 }
409         }
410
411         /**
412          * Create implicit mentions for a given post
413          *
414          * @param integer $uri_id
415          * @param integer $parent_uri_id
416          */
417         public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
418         {
419                 // Always mention the direct parent author
420                 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
421                 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
422
423                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
424                         return;
425                 }
426
427                 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
428                 while ($tag = DBA::fetch($tags)) {
429                         self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
430                 }
431                 DBA::close($tags);
432         }
433
434         /**
435          * Retrieves the terms from the provided type(s) associated with the provided item ID.
436          *
437          * @param int       $item_id
438          * @param int|array $type
439          * @return array
440          * @throws \Exception
441          */
442         public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
443         {
444                 $condition = ['uri-id' => $uri_id, 'type' => $type];
445                 return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
446         }
447
448         /**
449          * Return a string with all tags and mentions
450          *
451          * @param integer $uri_id
452          * @param array   $type
453          * @return string tags and mentions
454          * @throws \Exception
455          */
456         public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
457         {
458                 $tag_list = [];
459                 $tags = self::getByURIId($uri_id, $type);
460                 foreach ($tags as $tag) {
461                         $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
462                 }
463
464                 return implode(',', $tag_list);
465         }
466
467         /**
468          * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
469          * provided item's body with them.
470          *
471          * @param array $item
472          * @return array
473          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
474          * @throws \ImagickException
475          */
476         public static function populateFromItem(&$item)
477         {
478                 $return = [
479                         'tags' => [],
480                         'hashtags' => [],
481                         'mentions' => [],
482                         'implicit_mentions' => [],
483                 ];
484
485                 $searchpath = DI::baseUrl() . "/search?tag=";
486
487                 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
488                         ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
489                 while ($tag = DBA::fetch($taglist)) {
490                         if ($tag['url'] == '') {
491                                 $tag['url'] = $searchpath . rawurlencode($tag['name']);
492                         }
493
494                         $orig_tag = $tag['url'];
495
496                         $prefix = self::TAG_CHARACTER[$tag['type']];
497                         switch($tag['type']) {
498                                 case self::HASHTAG:
499                                         if ($orig_tag != $tag['url']) {
500                                                 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
501                                         }
502
503                                         $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
504                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
505                                         break;
506                                 case self::MENTION:
507                                 case self::EXCLUSIVE_MENTION:
508                                         if (!empty($tag['cid'])) {
509                                                 $tag['url'] = Contact::magicLinkById($tag['cid']);
510                                         } else {
511                                                 $tag['url'] = Contact::magicLink($tag['url']);
512                                         }
513                                         $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
514                                         $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
515                                         break;
516                                 case self::IMPLICIT_MENTION:
517                                         $return['implicit_mentions'][] = $prefix . $tag['name'];
518                                         break;
519                         }
520                 }
521                 DBA::close($taglist);
522
523                 return $return;
524         }
525
526         /**
527          * Counts posts for given tag
528          *
529          * @param string $search
530          * @param integer $uid
531          * @return integer number of posts
532          */
533         public static function countByTag(string $search, int $uid = 0)
534         {
535                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
536                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
537                         $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
538
539                 return DBA::count('tag-search-view', $condition);
540         }
541
542         /**
543          * Search posts for given tag
544          *
545          * @param string $search
546          * @param integer $uid
547          * @param integer $start
548          * @param integer $limit
549          * @param integer $last_uriid
550          * @return array with URI-ID
551          */
552         public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
553         {
554                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
555                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
556                         $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
557
558                 if (!empty($last_uriid)) {
559                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
560                 }
561
562                 $params = [
563                         'order' => ['uri-id' => true],
564                         'limit' => [$start, $limit]
565                 ];
566
567                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
568
569                 $uriids = [];
570                 while ($tag = DBA::fetch($tags)) {
571                         $uriids[] = $tag['uri-id'];
572                 }
573                 DBA::close($tags);
574
575                 return $uriids;
576         }
577
578         /**
579          * Returns a list of the most frequent global hashtags over the given period
580          *
581          * @param int $period Period in hours to consider posts
582          * @param int $limit  Number of returned tags
583          * @return array
584          * @throws \Exception
585          */
586         public static function getGlobalTrendingHashtags(int $period, $limit = 10)
587         {
588                 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
589                 if (!empty($tags)) {
590                         return $tags;
591                 } else {
592                         return self::setGlobalTrendingHashtags($period, $limit);
593                 }
594         }
595
596         /**
597          * Fetch the blocked tags as SQL
598          *
599          * @return string
600          */
601         private static function getBlockedSQL()
602         {
603                 $blocked_txt = DI::config()->get('system', 'blocked_tags');
604                 if (empty($blocked_txt)) {
605                         return '';
606                 }
607
608                 $blocked = explode(',', $blocked_txt);
609                 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
610                 return " AND NOT `name` IN (" . implode(',', $blocked) . ")";
611         }
612
613         /**
614          * Creates a list of the most frequent global hashtags over the given period
615          *
616          * @param int $period Period in hours to consider posts
617          * @param int $limit  Number of returned tags
618          * @return array
619          * @throws \Exception
620          */
621         public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
622         {
623                 // Get a uri-id that is at least X hours old.
624                 // We use the uri-id in the query for the hash tags since this is much faster
625                 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
626                         ['order' => ['received' => true]]);
627                 if (empty($post['uri-id'])) {
628                         return [];
629                 }
630
631                 $block_sql = self::getBlockedSQL();
632
633                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
634                         FROM `tag-search-view`
635                         WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
636                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
637                         Item::PUBLIC, 0, $post['uri-id'], $limit);
638
639                 if (DBA::isResult($tagsStmt)) {
640                         $tags = DBA::toArray($tagsStmt);
641                         DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
642                         return $tags;
643                 }
644
645                 return [];
646         }
647
648         /**
649          * Returns a list of the most frequent local hashtags over the given period
650          *
651          * @param int $period Period in hours to consider posts
652          * @param int $limit  Number of returned tags
653          * @return array
654          * @throws \Exception
655          */
656         public static function getLocalTrendingHashtags(int $period, $limit = 10)
657         {
658                 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
659                 if (!empty($tags)) {
660                         return $tags;
661                 } else {
662                         return self::setLocalTrendingHashtags($period, $limit);
663                 }
664         }
665
666         /**
667          * Returns a list of the most frequent local hashtags over the given period
668          *
669          * @param int $period Period in hours to consider posts
670          * @param int $limit  Number of returned tags
671          * @return array
672          * @throws \Exception
673          */
674         public static function setLocalTrendingHashtags(int $period, int $limit = 10)
675         {
676                 // Get a uri-id that is at least X hours old.
677                 // We use the uri-id in the query for the hash tags since this is much faster
678                 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
679                         ['order' => ['received' => true]]);
680                 if (empty($post['uri-id'])) {
681                         return [];
682                 }
683
684                 $block_sql = self::getBlockedSQL();
685
686                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
687                         FROM `tag-search-view`
688                         WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
689                         GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
690                         Item::PUBLIC, $post['uri-id'], $limit);
691
692                 if (DBA::isResult($tagsStmt)) {
693                         $tags = DBA::toArray($tagsStmt);
694                         DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
695                         return $tags;
696                 }
697
698                 return [];
699         }
700
701         /**
702          * Check if the provided tag is of one of the provided term types.
703          *
704          * @param string $tag
705          * @param int    ...$types
706          * @return bool
707          */
708         public static function isType($tag, ...$types)
709         {
710                 $tag_chars = [];
711                 foreach ($types as $type) {
712                         if (array_key_exists($type, self::TAG_CHARACTER)) {
713                                 $tag_chars[] = self::TAG_CHARACTER[$type];
714                         }
715                 }
716
717                 return Strings::startsWithChars($tag, $tag_chars);
718         }
719
720         /**
721          * Fetch user who subscribed to the given tag
722          *
723          * @param string $tag
724          * @return array User list
725          */
726         private static function getUIDListByTag(string $tag)
727         {
728                 $uids = [];
729                 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
730                 while ($search = DBA::fetch($searches)) {
731                         $uids[] = $search['uid'];
732                 }
733                 DBA::close($searches);
734
735                 return $uids;
736         }
737
738         /**
739          * Fetch user who subscribed to the tags of the given item
740          *
741          * @param integer $uri_id
742          * @return array User list
743          */
744         public static function getUIDListByURIId(int $uri_id)
745         {
746                 $uids = [];
747                 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
748
749                 foreach ($tags as $tag) {
750                         $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
751                 }
752
753                 return array_unique($uids);
754         }
755 }