3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Model;
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\Database\Database;
29 use Friendica\Database\DBA;
31 use Friendica\Protocol\ActivityPub;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\HTTPSignature;
34 use Friendica\Util\Strings;
39 * This Model class handles tag table interactions.
40 * This tables stores relevant tags related to posts, like hashtags and mentions.
48 * An implicit mention is a mention in a comment body that is redundant with the threading information.
50 const IMPLICIT_MENTION = 8;
52 * An exclusive mention transmits the post only to the target account without transmitting it to the followers, usually a group.
54 const EXCLUSIVE_MENTION = 9;
61 const ATTRIBUTED = 15;
64 const GENERAL_COLLECTION = 2;
65 const FOLLOWER_COLLECTION = 3;
66 const PUBLIC_COLLECTION = 4;
68 const TAG_CHARACTER = [
71 self::EXCLUSIVE_MENTION => '!',
72 self::IMPLICIT_MENTION => '%',
76 * Store tag/mention elements
78 * @param integer $uriId
79 * @param integer $type Tag type
80 * @param string $name Tag name
81 * @param string $url Contact URL (optional)
82 * @param integer $target Target (default: null)
85 public static function store(int $uriId, int $type, string $name, string $url = '', int $target = null)
87 if ($type == self::HASHTAG) {
88 // Trim Unicode non-word characters
89 $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
91 $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
92 if (count($tags) > 1) {
93 foreach ($tags as $tag) {
94 self::store($uriId, $type, $tag, $url);
107 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION, self::TO, self::CC, self::BTO, self::BCC, self::AUDIENCE, self::ATTRIBUTED])) {
109 // No mention without a contact url
113 if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
114 Logger::notice('Wrong scheme in url', ['url' => $url]);
117 $cid = Contact::getIdForURL($url, 0, false);
118 Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]);
121 $tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]);
123 if ($tag['name'] != substr($name, 0, 96)) {
124 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url, 'type' => $tag['type']]);
126 if (!empty($target) && ($tag['type'] != $target)) {
127 DBA::update('tag', ['type' => $target], ['url' => $url]);
134 if (!in_array($type, [self::TO, self::CC, self::BTO, self::BCC, self::AUDIENCE, self::ATTRIBUTED])) {
135 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
136 $url = strtolower($url);
142 $tagid = self::getID($name, $url, $target);
148 $fields = ['uri-id' => $uriId, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
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);
159 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
161 Logger::debug('Stored tag/mention', ['uri-id' => $uriId, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type]);
165 * Fetch the target type for the given url
168 * @param bool $fetch Fetch information via network operations
171 public static function getTargetType(string $url, bool $fetch = true)
179 $tag = DBA::selectFirst('tag', ['url', 'type'], ['url' => $url]);
180 if (!empty($tag['type'])) {
181 $target = $tag['type'];
182 if ($target != self::GENERAL_COLLECTION) {
183 Logger::debug('Found existing type', ['type' => $tag['type'], 'url' => $url]);
188 if ($url == ActivityPub::PUBLIC_COLLECTION) {
189 $target = self::PUBLIC_COLLECTION;
190 Logger::debug('Public collection', ['url' => $url]);
192 if (DBA::exists('apcontact', ['followers' => $url])) {
193 $target = self::FOLLOWER_COLLECTION;
194 Logger::debug('Found collection via existing apcontact', ['url' => $url]);
195 } elseif (Contact::getIdForURL($url, 0, $fetch ? null : false)) {
196 $target = self::ACCOUNT;
197 Logger::debug('URL is an account', ['url' => $url]);
198 } elseif ($fetch && ($target != self::GENERAL_COLLECTION)) {
199 $content = HTTPSignature::fetch($url);
200 if (!empty($content['type']) && ($content['type'] == 'OrderedCollection')) {
201 $target = self::GENERAL_COLLECTION;
202 Logger::debug('URL is an ordered collection', ['url' => $url]);
207 if (!empty($target) && !empty($tag['url']) && ($tag['type'] != $target)) {
208 DBA::update('tag', ['type' => $target], ['url' => $url]);
211 if (empty($target)) {
212 Logger::debug('No type could be detected', ['url' => $url]);
219 * Get a tag id for a given tag name and URL
221 * @param string $name Name of tag
223 * @param int $type Type of tag
226 public static function getID(string $name, string $url = '', int $type = null): int
228 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
230 $tag = DBA::selectFirst('tag', ['id', 'type'], $fields);
231 if (DBA::isResult($tag)) {
232 if (empty($tag['type']) && !empty($type)) {
233 DBA::update('tag', ['type' => $type], $fields);
239 $fields['type'] = $type;
242 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
243 $tid = DBA::lastInsertId();
249 $fields['type'] = $type;
251 Logger::error('No tag id created', $fields);
256 * Store tag/mention elements
258 * @param integer $uriId
259 * @param string $hash
260 * @param string $name
264 public static function storeByHash(int $uriId, string $hash, string $name, string $url = '')
266 $type = self::getTypeForHash($hash);
267 if ($type == self::UNKNOWN) {
271 self::store($uriId, $type, $name, $url);
275 * Get tags and mentions from the body
277 * @param string $body Body of the post
278 * @param string $tags Accepted tags
280 * @return array Tag list
282 public static function getFromBody(string $body, string $tags = null): array
284 if (is_null($tags)) {
285 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
288 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
296 * Store tags and mentions from the body
298 * @param integer $uriId URI-Id
299 * @param string $body Body of the post
300 * @param string $tags Accepted tags
303 public static function storeFromBody(int $uriId, string $body, string $tags = null)
305 $item = ['uri-id' => $uriId, 'body' => $body, 'quote-uri-id' => null];
306 self::storeFromArray($item, $tags);
310 * Store tags and mentions from the item array
312 * @param array $item Item array
313 * @param string $tags Accepted tags
316 public static function storeFromArray(array $item, string $tags = null)
318 Logger::info('Check for tags', ['uri-id' => $item['uri-id'], 'hash' => $tags]);
320 if (is_null($tags)) {
321 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
324 foreach (self::getFromBody($item['body'], $tags) as $tag) {
325 self::storeByHash($item['uri-id'], $tag[1], $tag[3], $tag[2]);
328 $shared = DI::contentItem()->getSharedPost($item, ['uri-id']);
330 // Search for hashtags in the shared body (but only if hashtags are wanted)
331 if (!empty($shared) && (strpos($tags, self::TAG_CHARACTER[self::HASHTAG]) !== false)) {
332 foreach (self::getByURIId($shared['post']['uri-id'], [self::HASHTAG]) as $tag) {
333 self::store($item['uri-id'], $tag['type'], $tag['name'], $tag['url']);
339 * Store raw tags (not encapsulated in links) from the body
340 * This function is needed in the intermediate phase.
341 * Later we can call item::setHashtags in advance to have all tags converted.
343 * @param integer $uriId URI-Id
344 * @param string $body Body of the post
347 public static function storeRawTagsFromBody(int $uriId, string $body)
349 Logger::info('Check for tags', ['uri-id' => $uriId]);
351 $result = BBCode::getTags($body);
352 if (empty($result)) {
356 Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]);
358 foreach ($result as $tag) {
359 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
362 self::storeByHash($uriId, substr($tag, 0, 1), substr($tag, 1));
367 * Checks for stored hashtags and mentions for the given post
369 * @param integer $uriId
372 public static function existsForPost(int $uriId): bool
374 return DBA::exists('post-tag', ['uri-id' => $uriId, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
380 * @param integer $uriId
381 * @param integer $type Type
382 * @param string $name Name
383 * @param string $url URL
386 public static function remove(int $uriId, int $type, string $name, string $url = '')
388 $condition = ['uri-id' => $uriId, 'type' => $type, 'url' => $url];
389 if ($type == self::HASHTAG) {
390 $condition['name'] = $name;
393 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
394 if (!DBA::isResult($tag)) {
398 Logger::debug('Removing tag/mention', ['uri-id' => $uriId, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url]);
399 DBA::delete('post-tag', ['uri-id' => $uriId, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
405 * @param integer $uriId
406 * @param string $hash
407 * @param string $name
411 public static function removeByHash(int $uriId, string $hash, string $name, string $url = '')
413 $type = self::getTypeForHash($hash);
414 if ($type == self::UNKNOWN) {
418 self::remove($uriId, $type, $name, $url);
422 * Get the type for the given hash
424 * @param string $hash
425 * @return integer Tag type
427 private static function getTypeForHash(string $hash): int
429 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
430 return self::MENTION;
431 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
432 return self::EXCLUSIVE_MENTION;
433 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
434 return self::IMPLICIT_MENTION;
435 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
436 return self::HASHTAG;
438 return self::UNKNOWN;
443 * Create implicit mentions for a given post
445 * @param integer $uriId
446 * @param integer $parentUriId
449 public static function createImplicitMentions(int $uriId, int $parentUriId)
451 // Always mention the direct parent author
452 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parentUriId]);
453 self::store($uriId, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
455 if (DI::config()->get('system', 'disable_implicit_mentions')) {
459 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parentUriId, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
460 while ($tag = DBA::fetch($tags)) {
461 self::store($uriId, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
467 * Retrieves the terms from the provided type(s) associated with the provided item ID.
470 * @param array $type Tag type(s)
471 * @return array|bool Array on success, false on error
474 public static function getByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
476 $condition = ['uri-id' => $uriId, 'type' => $type];
477 return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
481 * Checks if the given url is mentioned in the post
483 * @param integer $uriId
489 public static function isMentioned(int $uriId, string $url, array $type = [self::MENTION, self::EXCLUSIVE_MENTION, self::AUDIENCE]): bool
491 $tags = self::getByURIId($uriId, $type);
492 foreach ($tags as $tag) {
493 if (Strings::compareLink($url, $tag['url'])) {
501 * Return a string with all tags and mentions
503 * @param integer $uriId
504 * @param array $type Tag type(s)
505 * @return string tags and mentions
508 public static function getCSVByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]): string
511 foreach (self::getByURIId($uriId, $type) as $tag) {
512 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
515 return implode(',', $tag_list);
519 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
520 * provided item's body with them.
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
525 * @throws \ImagickException
527 public static function populateFromItem(array &$item): array
533 'implicit_mentions' => [],
536 $searchpath = DI::baseUrl() . '/search?tag=';
538 $taglist = DBA::select(
540 ['type', 'name', 'url', 'cid'],
541 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]
543 while ($tag = DBA::fetch($taglist)) {
544 if ($tag['url'] == '') {
545 $tag['url'] = $searchpath . rawurlencode($tag['name']);
548 $orig_tag = $tag['url'];
550 $prefix = self::TAG_CHARACTER[$tag['type']];
551 switch ($tag['type']) {
553 if ($orig_tag != $tag['url']) {
554 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
557 $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
558 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
562 case self::EXCLUSIVE_MENTION:
563 if (!empty($tag['cid'])) {
564 $tag['url'] = Contact::magicLinkById($tag['cid']);
566 $tag['url'] = Contact::magicLink($tag['url']);
568 $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
569 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
572 case self::IMPLICIT_MENTION:
573 $return['implicit_mentions'][] = $prefix . $tag['name'];
577 Logger::warning('Unknown tag type found', $tag);
580 DBA::close($taglist);
586 * Counts posts for given tag
588 * @param string $search
589 * @param integer $uid
590 * @return integer number of posts
592 public static function countByTag(string $search, int $uid = 0): int
594 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
595 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
597 Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
600 return DBA::count('tag-search-view', $condition);
604 * Search posts for given tag
606 * @param string $search Tag to search for
607 * @param integer $uid User Id
608 * @param integer $start Starting record
609 * @param integer $limit Maximum count of records
610 * @param integer $last_uriid
611 * @return array with URI-ID
613 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0): array
615 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
616 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
618 Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
621 if (!empty($last_uriid)) {
622 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
626 'order' => ['uri-id' => true],
627 'limit' => [$start, $limit]
630 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
633 while ($tag = DBA::fetch($tags)) {
634 $uriIds[] = $tag['uri-id'];
642 * Returns a list of the most frequent global hashtags over the given period
644 * @param int $period Period in hours to consider posts
645 * @param int $limit Number of returned tags
646 * @param int $offset Page offset in results
650 public static function getGlobalTrendingHashtags(int $period, int $limit = 10, int $offset = 0): array
652 $tags = DI::cache()->get("global_trending_tags-$period");
654 $tags = self::setGlobalTrendingHashtags($period, 1000);
656 return array_slice($tags, $offset, $limit);
660 * Fetch the blocked tags as SQL
662 * @return string SQL for blocked tag names or empty string
664 private static function getBlockedSQL(): string
666 $blocked_txt = DI::config()->get('system', 'blocked_tags');
667 if (empty($blocked_txt)) {
671 $blocked = explode(',', $blocked_txt);
672 array_walk($blocked, function (&$value) {
673 $value = "'" . DBA::escape(trim($value)) . "'";
675 return ' AND NOT `name` IN (' . implode(',', $blocked) . ')';
679 * Creates a list of the most frequent global hashtags over the given period
681 * @param int $period Period in hours to consider posts
682 * @param int $limit Number of returned tags
686 public static function setGlobalTrendingHashtags(int $period, int $limit = 10): array
689 * Get a uri-id that is at least X hours old.
690 * We use the uri-id in the query for the hash tags since this is much faster
692 $post = Post::selectFirstThread(
694 ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
695 ['order' => ['received' => true]]
698 if (empty($post['uri-id'])) {
702 $block_sql = self::getBlockedSQL();
705 "SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
706 FROM `tag-search-view`
707 WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
708 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
715 if (DBA::isResult($tagsStmt)) {
716 $tags = DBA::toArray($tagsStmt);
717 DI::cache()->set("global_trending_tags-$period", $tags, Duration::HOUR);
725 * Returns a list of the most frequent local hashtags over the given period
727 * @param int $period Period in hours to consider posts
728 * @param int $limit Number of returned tags
729 * @param int $offset Page offset in results
733 public static function getLocalTrendingHashtags(int $period, $limit = 10, int $offset = 0): array
735 $tags = DI::cache()->get("local_trending_tags-$period");
737 $tags = self::setLocalTrendingHashtags($period, 1000);
739 return array_slice($tags, $offset, $limit);
743 * Returns a list of the most frequent local hashtags over the given period
745 * @param int $period Period in hours to consider posts
746 * @param int $limit Number of returned tags
750 public static function setLocalTrendingHashtags(int $period, int $limit = 10): array
752 // Get a uri-id that is at least X hours old.
753 // We use the uri-id in the query for the hash tags since this is much faster
754 $post = Post::selectFirstThread(
756 ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
757 ['order' => ['received' => true]]
759 if (empty($post['uri-id'])) {
763 $block_sql = self::getBlockedSQL();
766 "SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
767 FROM `tag-search-view`
768 WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
769 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
775 if (DBA::isResult($tagsStmt)) {
776 $tags = DBA::toArray($tagsStmt);
777 DI::cache()->set("local_trending_tags-$period", $tags, Duration::HOUR);
785 * Check if the provided tag is of one of the provided term types.
787 * @param string $tag Tag name
788 * @param int ...$types
791 public static function isType(string $tag, ...$types): bool
794 foreach ($types as $type) {
795 if (array_key_exists($type, self::TAG_CHARACTER)) {
796 $tag_chars[] = self::TAG_CHARACTER[$type];
800 return Strings::startsWithChars($tag, $tag_chars);
804 * Fetch user who subscribed to the given tag
807 * @return array User list
809 private static function getUIDListByTag(string $tag): array
812 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
813 while ($search = DBA::fetch($searches)) {
814 $uids[] = $search['uid'];
816 DBA::close($searches);
822 * Fetch user who subscribed to the tags of the given item
824 * @param integer $uriId
825 * @return array User list
827 public static function getUIDListByURIId(int $uriId): array
831 foreach (self::getByURIId($uriId, [self::HASHTAG]) as $tag) {
832 foreach (self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']) as $uid) {
833 $uids[$uid][] = $tag['name'];