3 * @copyright Copyright (C) 2010-2022, 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\Core\System;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
32 use Friendica\Protocol\ActivityPub;
33 use Friendica\Util\DateTimeFormat;
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 forum.
54 const EXCLUSIVE_MENTION = 9;
62 const GENERAL_COLLECTION = 2;
63 const FOLLOWER_COLLECTION = 3;
64 const PUBLIC_COLLECTION = 4;
66 const TAG_CHARACTER = [
69 self::EXCLUSIVE_MENTION => '!',
70 self::IMPLICIT_MENTION => '%',
74 * Store tag/mention elements
76 * @param integer $uriId
77 * @param integer $type Tag type
78 * @param string $name Tag name
79 * @param string $url Contact URL (optional)
80 * @param integer $target Target (default: null)
83 public static function store(int $uriId, int $type, string $name, string $url = '', int $target = null)
85 if ($type == self::HASHTAG) {
86 // Trim Unicode non-word characters
87 $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
89 $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
90 if (count($tags) > 1) {
91 foreach ($tags as $tag) {
92 self::store($uriId, $type, $tag, $url);
105 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION, self::TO, self::CC, self::BTO, self::BCC])) {
107 // No mention without a contact url
111 if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
112 Logger::notice('Wrong scheme in url', ['url' => $url, 'callstack' => System::callstack(20)]);
115 $cid = Contact::getIdForURL($url, 0, false);
116 Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]);
119 $tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]);
121 if ($tag['name'] != substr($name, 0, 96)) {
122 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
124 if (!empty($target) && ($tag['type'] != $target)) {
125 DBA::update('tag', ['type' => $target], ['url' => $url]);
132 if (!in_array($type, [self::TO, self::CC, self::BTO, self::BCC])) {
133 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
134 $url = strtolower($url);
140 $tagid = self::getID($name, $url, $target);
146 $fields = ['uri-id' => $uriId, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
148 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
149 $condition = $fields;
150 $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
151 if (DBA::exists('post-tag', $condition)) {
152 Logger::info('Tag already exists', $fields);
157 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
159 Logger::debug('Stored tag/mention', ['uri-id' => $uriId, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
163 * Fetch the target type for the given url
166 * @param bool $fetch Fetch information via network operations
169 public static function getTargetType(string $url, bool $fetch = true)
177 $tag = DBA::selectFirst('tag', ['url', 'type'], ['url' => $url]);
178 if (!empty($tag['type'])) {
179 $target = $tag['type'];
180 if ($target != self::GENERAL_COLLECTION) {
181 Logger::debug('Found existing type', ['type' => $tag['type'], 'url' => $url]);
186 if ($url == ActivityPub::PUBLIC_COLLECTION) {
187 $target = self::PUBLIC_COLLECTION;
188 Logger::debug('Public collection', ['url' => $url]);
190 if (DBA::exists('apcontact', ['followers' => $url])) {
191 $target = self::FOLLOWER_COLLECTION;
192 Logger::debug('Found collection via existing apcontact', ['url' => $url]);
193 } elseif (Contact::getIdForURL($url, 0, $fetch ? null : false)) {
194 $target = self::ACCOUNT;
195 Logger::debug('URL is an account', ['url' => $url]);
196 } elseif ($fetch && ($target != self::GENERAL_COLLECTION)) {
197 $content = ActivityPub::fetchContent($url);
198 if (!empty($content['type']) && ($content['type'] == 'OrderedCollection')) {
199 $target = self::GENERAL_COLLECTION;
200 Logger::debug('URL is an ordered collection', ['url' => $url]);
205 if (!empty($target) && !empty($tag['url']) && ($tag['type'] != $target)) {
206 DBA::update('tag', ['type' => $target], ['url' => $url]);
209 if (empty($target)) {
210 Logger::debug('No type could be detected', ['url' => $url]);
217 * Get a tag id for a given tag name and URL
219 * @param string $name Name of tag
221 * @param int $type Type of tag
224 public static function getID(string $name, string $url = '', int $type = null): int
226 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
228 $tag = DBA::selectFirst('tag', ['id', 'type'], $fields);
229 if (DBA::isResult($tag)) {
230 if (empty($tag['type']) && !empty($type)) {
231 DBA::update('tag', ['type' => $type], $fields);
237 $fields['type'] = $type;
240 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
241 $tid = DBA::lastInsertId();
247 $fields['type'] = $type;
249 Logger::error('No tag id created', $fields);
254 * Store tag/mention elements
256 * @param integer $uriId
257 * @param string $hash
258 * @param string $name
262 public static function storeByHash(int $uriId, string $hash, string $name, string $url = '')
264 $type = self::getTypeForHash($hash);
265 if ($type == self::UNKNOWN) {
269 self::store($uriId, $type, $name, $url);
273 * Get tags and mentions from the body
275 * @param string $body Body of the post
276 * @param string $tags Accepted tags
278 * @return array Tag list
280 public static function getFromBody(string $body, string $tags = null): array
282 if (is_null($tags)) {
283 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
286 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
294 * Store tags and mentions from the body
296 * @param integer $uriId URI-Id
297 * @param string $body Body of the post
298 * @param string $tags Accepted tags
301 public static function storeFromBody(int $uriId, string $body, string $tags = null)
303 $item = ['uri-id' => $uriId, 'body' => $body, 'quote-uri-id' => null];
304 self::storeFromArray($item, $tags);
308 * Store tags and mentions from the item array
310 * @param array $item Item array
311 * @param string $tags Accepted tags
314 public static function storeFromArray(array $item, string $tags = null)
316 Logger::info('Check for tags', ['uri-id' => $item['uri-id'], 'hash' => $tags, 'callstack' => System::callstack()]);
318 if (is_null($tags)) {
319 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
322 // Only remove the shared data from "real" reshares
323 $shared = DI::contentItem()->getSharedPost($item, ['uri-id']);
324 if (!empty($shared)) {
325 $item['body'] = BBCode::removeSharedData($item['body']);
328 foreach (self::getFromBody($item['body'], $tags) as $tag) {
329 self::storeByHash($item['uri-id'], $tag[1], $tag[3], $tag[2]);
332 // Search for hashtags in the shared body (but only if hashtags are wanted)
333 if (!empty($shared) && (strpos($tags, self::TAG_CHARACTER[self::HASHTAG]) !== false)) {
334 foreach (self::getByURIId($shared['post']['uri-id'], [self::HASHTAG]) as $tag) {
335 self::store($item['uri-id'], $tag['type'], $tag['name'], $tag['url']);
341 * Store raw tags (not encapsulated in links) from the body
342 * This function is needed in the intermediate phase.
343 * Later we can call item::setHashtags in advance to have all tags converted.
345 * @param integer $uriId URI-Id
346 * @param string $body Body of the post
349 public static function storeRawTagsFromBody(int $uriId, string $body)
351 Logger::info('Check for tags', ['uri-id' => $uriId, 'callstack' => System::callstack()]);
353 $result = BBCode::getTags($body);
354 if (empty($result)) {
358 Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]);
360 foreach ($result as $tag) {
361 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
364 self::storeByHash($uriId, substr($tag, 0, 1), substr($tag, 1));
369 * Checks for stored hashtags and mentions for the given post
371 * @param integer $uriId
374 public static function existsForPost(int $uriId): bool
376 return DBA::exists('post-tag', ['uri-id' => $uriId, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
382 * @param integer $uriId
383 * @param integer $type Type
384 * @param string $name Name
385 * @param string $url URL
388 public static function remove(int $uriId, int $type, string $name, string $url = '')
390 $condition = ['uri-id' => $uriId, 'type' => $type, 'url' => $url];
391 if ($type == self::HASHTAG) {
392 $condition['name'] = $name;
395 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
396 if (!DBA::isResult($tag)) {
400 Logger::debug('Removing tag/mention', ['uri-id' => $uriId, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
401 DBA::delete('post-tag', ['uri-id' => $uriId, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
407 * @param integer $uriId
408 * @param string $hash
409 * @param string $name
413 public static function removeByHash(int $uriId, string $hash, string $name, string $url = '')
415 $type = self::getTypeForHash($hash);
416 if ($type == self::UNKNOWN) {
420 self::remove($uriId, $type, $name, $url);
424 * Get the type for the given hash
426 * @param string $hash
427 * @return integer Tag type
429 private static function getTypeForHash(string $hash): int
431 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
432 return self::MENTION;
433 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
434 return self::EXCLUSIVE_MENTION;
435 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
436 return self::IMPLICIT_MENTION;
437 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
438 return self::HASHTAG;
440 return self::UNKNOWN;
445 * Create implicit mentions for a given post
447 * @param integer $uriId
448 * @param integer $parentUriId
451 public static function createImplicitMentions(int $uriId, int $parentUriId)
453 // Always mention the direct parent author
454 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parentUriId]);
455 self::store($uriId, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
457 if (DI::config()->get('system', 'disable_implicit_mentions')) {
461 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parentUriId, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
462 while ($tag = DBA::fetch($tags)) {
463 self::store($uriId, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
469 * Retrieves the terms from the provided type(s) associated with the provided item ID.
472 * @param array $type Tag type(s)
473 * @return array|bool Array on success, false on error
476 public static function getByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
478 $condition = ['uri-id' => $uriId, 'type' => $type];
479 return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
483 * Checks if the given url is mentioned in the post
485 * @param integer $uriId
491 public static function isMentioned(int $uriId, string $url, array $type = [self::MENTION, self::EXCLUSIVE_MENTION]): bool
493 $tags = self::getByURIId($uriId, $type);
494 foreach ($tags as $tag) {
495 if (Strings::compareLink($url, $tag['url'])) {
503 * Return a string with all tags and mentions
505 * @param integer $uriId
506 * @param array $type Tag type(s)
507 * @return string tags and mentions
510 public static function getCSVByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]): string
513 foreach (self::getByURIId($uriId, $type) as $tag) {
514 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
517 return implode(',', $tag_list);
521 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
522 * provided item's body with them.
526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527 * @throws \ImagickException
529 public static function populateFromItem(array &$item): array
535 'implicit_mentions' => [],
538 $searchpath = DI::baseUrl() . '/search?tag=';
540 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
541 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
542 while ($tag = DBA::fetch($taglist)) {
543 if ($tag['url'] == '') {
544 $tag['url'] = $searchpath . rawurlencode($tag['name']);
547 $orig_tag = $tag['url'];
549 $prefix = self::TAG_CHARACTER[$tag['type']];
550 switch($tag['type']) {
552 if ($orig_tag != $tag['url']) {
553 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
556 $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
557 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
561 case self::EXCLUSIVE_MENTION:
562 if (!empty($tag['cid'])) {
563 $tag['url'] = Contact::magicLinkById($tag['cid']);
565 $tag['url'] = Contact::magicLink($tag['url']);
567 $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
568 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
571 case self::IMPLICIT_MENTION:
572 $return['implicit_mentions'][] = $prefix . $tag['name'];
576 Logger::warning('Unknown tag type found', $tag);
579 DBA::close($taglist);
585 * Counts posts for given tag
587 * @param string $search
588 * @param integer $uid
589 * @return integer number of posts
591 public static function countByTag(string $search, int $uid = 0): int
593 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
594 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
596 Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
599 return DBA::count('tag-search-view', $condition);
603 * Search posts for given tag
605 * @param string $search Tag to search for
606 * @param integer $uid User Id
607 * @param integer $start Starting record
608 * @param integer $limit Maximum count of records
609 * @param integer $last_uriid
610 * @return array with URI-ID
612 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0): array
614 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
615 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
617 Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
620 if (!empty($last_uriid)) {
621 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
625 'order' => ['uri-id' => true],
626 'limit' => [$start, $limit]
629 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
632 while ($tag = DBA::fetch($tags)) {
633 $uriIds[] = $tag['uri-id'];
641 * Returns a list of the most frequent global hashtags over the given period
643 * @param int $period Period in hours to consider posts
644 * @param int $limit Number of returned tags
648 public static function getGlobalTrendingHashtags(int $period, $limit = 10): array
650 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
654 return self::setGlobalTrendingHashtags($period, $limit);
659 * Fetch the blocked tags as SQL
661 * @return string SQL for blocked tag names or empty string
663 private static function getBlockedSQL(): string
665 $blocked_txt = DI::config()->get('system', 'blocked_tags');
666 if (empty($blocked_txt)) {
670 $blocked = explode(',', $blocked_txt);
671 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
672 return ' AND NOT `name` IN (' . implode(',', $blocked) . ')';
676 * Creates a list of the most frequent global hashtags over the given period
678 * @param int $period Period in hours to consider posts
679 * @param int $limit Number of returned tags
683 public static function setGlobalTrendingHashtags(int $period, int $limit = 10): array
686 * Get a uri-id that is at least X hours old.
687 * We use the uri-id in the query for the hash tags since this is much faster
689 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
690 ['order' => ['received' => true]]);
692 if (empty($post['uri-id'])) {
696 $block_sql = self::getBlockedSQL();
698 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
699 FROM `tag-search-view`
700 WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
701 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
702 Item::PUBLIC, 0, $post['uri-id'],
706 if (DBA::isResult($tagsStmt)) {
707 $tags = DBA::toArray($tagsStmt);
708 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
716 * Returns a list of the most frequent local hashtags over the given period
718 * @param int $period Period in hours to consider posts
719 * @param int $limit Number of returned tags
723 public static function getLocalTrendingHashtags(int $period, $limit = 10): array
725 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
729 return self::setLocalTrendingHashtags($period, $limit);
734 * Returns a list of the most frequent local hashtags over the given period
736 * @param int $period Period in hours to consider posts
737 * @param int $limit Number of returned tags
741 public static function setLocalTrendingHashtags(int $period, int $limit = 10): array
743 // Get a uri-id that is at least X hours old.
744 // We use the uri-id in the query for the hash tags since this is much faster
745 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
746 ['order' => ['received' => true]]);
747 if (empty($post['uri-id'])) {
751 $block_sql = self::getBlockedSQL();
753 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
754 FROM `tag-search-view`
755 WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
756 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
757 Item::PUBLIC, $post['uri-id'],
761 if (DBA::isResult($tagsStmt)) {
762 $tags = DBA::toArray($tagsStmt);
763 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
771 * Check if the provided tag is of one of the provided term types.
773 * @param string $tag Tag name
774 * @param int ...$types
777 public static function isType(string $tag, ...$types): bool
780 foreach ($types as $type) {
781 if (array_key_exists($type, self::TAG_CHARACTER)) {
782 $tag_chars[] = self::TAG_CHARACTER[$type];
786 return Strings::startsWithChars($tag, $tag_chars);
790 * Fetch user who subscribed to the given tag
793 * @return array User list
795 private static function getUIDListByTag(string $tag): array
798 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
799 while ($search = DBA::fetch($searches)) {
800 $uids[] = $search['uid'];
802 DBA::close($searches);
808 * Fetch user who subscribed to the tags of the given item
810 * @param integer $uriId
811 * @return array User list
813 public static function getUIDListByURIId(int $uriId): array
816 $tags = self::getByURIId($uriId, [self::HASHTAG]);
818 foreach ($tags as $tag) {
819 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
822 return array_unique($uids);