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