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
80 * @param integer $target
82 public static function store(int $uriid, int $type, string $name, string $url = '', int $target = null)
84 if ($type == self::HASHTAG) {
85 // Trim Unicode non-word characters
86 $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
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);
104 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION, self::TO, self::CC, self::BTO, self::BCC])) {
106 // No mention without a contact url
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)]);
114 $cid = Contact::getIdForURL($url, 0, false);
115 Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]);
118 $tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]);
120 if ($tag['name'] != substr($name, 0, 96)) {
121 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
123 if (!empty($target) && ($tag['type'] != $target)) {
124 DBA::update('tag', ['type' => $target], ['url' => $url]);
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);
139 $tagid = self::getID($name, $url, $target);
145 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
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);
156 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
158 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
162 * Fetch the target type for the given url
165 * @param bool $fetch Fetch information via network operations
168 public static function getTargetType(string $url, bool $fetch = true)
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]);
185 if ($url == ActivityPub::PUBLIC_COLLECTION) {
186 $target = self::PUBLIC_COLLECTION;
187 Logger::debug('Public collection', ['url' => $url]);
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]);
204 if (!empty($target) && !empty($tag['url']) && ($tag['type'] != $target)) {
205 DBA::update('tag', ['type' => $target], ['url' => $url]);
208 if (empty($target)) {
209 Logger::debug('No type could be detected', ['url' => $url]);
216 * Get a tag id for a given tag name and url
218 * @param string $name
223 public static function getID(string $name, string $url = '', int $type = null)
225 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
227 $tag = DBA::selectFirst('tag', ['id', 'type'], $fields);
228 if (DBA::isResult($tag)) {
229 if (empty($tag['type']) && !empty($type)) {
230 DBA::update('tag', ['type' => $type], $fields);
236 $fields['type'] = $type;
239 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
240 $tid = DBA::lastInsertId();
245 Logger::error('No tag id created', $fields);
250 * Store tag/mention elements
252 * @param integer $uriid
253 * @param string $hash
254 * @param string $name
256 * @param boolean $probing
258 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
260 $type = self::getTypeForHash($hash);
261 if ($type == self::UNKNOWN) {
265 self::store($uriid, $type, $name, $url, $probing);
269 * Get tags and mentions from the body
271 * @param string $body Body of the post
272 * @param string $tags Accepted tags
274 * @return array Tag list
276 public static function getFromBody(string $body, string $tags = null)
278 if (is_null($tags)) {
279 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
282 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
290 * Store tags and mentions from the body
292 * @param integer $uriid URI-Id
293 * @param string $body Body of the post
294 * @param string $tags Accepted tags
295 * @param boolean $probing Perform a probing for contacts, adding them if needed
297 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
299 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
301 $result = self::getFromBody($body, $tags);
302 if (empty($result)) {
306 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
308 foreach ($result as $tag) {
309 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
314 * Store raw tags (not encapsulated in links) from the body
315 * This function is needed in the intermediate phase.
316 * Later we can call item::setHashtags in advance to have all tags converted.
318 * @param integer $uriid URI-Id
319 * @param string $body Body of the post
321 public static function storeRawTagsFromBody(int $uriid, string $body)
323 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
325 $result = BBCode::getTags($body);
326 if (empty($result)) {
330 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
332 foreach ($result as $tag) {
333 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
336 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
341 * Checks for stored hashtags and mentions for the given post
343 * @param integer $uriid
346 public static function existsForPost(int $uriid)
348 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
354 * @param integer $uriid
355 * @param integer $type
356 * @param string $name
359 public static function remove(int $uriid, int $type, string $name, string $url = '')
361 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
362 if ($type == self::HASHTAG) {
363 $condition['name'] = $name;
366 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
367 if (!DBA::isResult($tag)) {
371 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
372 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
378 * @param integer $uriid
379 * @param string $hash
380 * @param string $name
383 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
385 $type = self::getTypeForHash($hash);
386 if ($type == self::UNKNOWN) {
390 self::remove($uriid, $type, $name, $url);
394 * Get the type for the given hash
396 * @param string $hash
397 * @return integer type
399 private static function getTypeForHash(string $hash)
401 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
402 return self::MENTION;
403 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
404 return self::EXCLUSIVE_MENTION;
405 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
406 return self::IMPLICIT_MENTION;
407 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
408 return self::HASHTAG;
410 return self::UNKNOWN;
415 * Create implicit mentions for a given post
417 * @param integer $uri_id
418 * @param integer $parent_uri_id
420 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
422 // Always mention the direct parent author
423 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
424 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
426 if (DI::config()->get('system', 'disable_implicit_mentions')) {
430 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
431 while ($tag = DBA::fetch($tags)) {
432 self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
438 * Retrieves the terms from the provided type(s) associated with the provided item ID.
440 * @param int $item_id
441 * @param int|array $type
445 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
447 $condition = ['uri-id' => $uri_id, 'type' => $type];
448 return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
452 * Return a string with all tags and mentions
454 * @param integer $uri_id
456 * @return string tags and mentions
459 public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
462 $tags = self::getByURIId($uri_id, $type);
463 foreach ($tags as $tag) {
464 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
467 return implode(',', $tag_list);
471 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
472 * provided item's body with them.
476 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
477 * @throws \ImagickException
479 public static function populateFromItem(&$item)
485 'implicit_mentions' => [],
488 $searchpath = DI::baseUrl() . "/search?tag=";
490 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
491 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
492 while ($tag = DBA::fetch($taglist)) {
493 if ($tag['url'] == '') {
494 $tag['url'] = $searchpath . rawurlencode($tag['name']);
497 $orig_tag = $tag['url'];
499 $prefix = self::TAG_CHARACTER[$tag['type']];
500 switch($tag['type']) {
502 if ($orig_tag != $tag['url']) {
503 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
506 $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
507 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
510 case self::EXCLUSIVE_MENTION:
511 if (!empty($tag['cid'])) {
512 $tag['url'] = Contact::magicLinkById($tag['cid']);
514 $tag['url'] = Contact::magicLink($tag['url']);
516 $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
517 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
519 case self::IMPLICIT_MENTION:
520 $return['implicit_mentions'][] = $prefix . $tag['name'];
524 DBA::close($taglist);
530 * Counts posts for given tag
532 * @param string $search
533 * @param integer $uid
534 * @return integer number of posts
536 public static function countByTag(string $search, int $uid = 0)
538 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
539 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
540 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
542 return DBA::count('tag-search-view', $condition);
546 * Search posts for given tag
548 * @param string $search
549 * @param integer $uid
550 * @param integer $start
551 * @param integer $limit
552 * @param integer $last_uriid
553 * @return array with URI-ID
555 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
557 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
558 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
559 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
561 if (!empty($last_uriid)) {
562 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
566 'order' => ['uri-id' => true],
567 'limit' => [$start, $limit]
570 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
573 while ($tag = DBA::fetch($tags)) {
574 $uriids[] = $tag['uri-id'];
582 * Returns a list of the most frequent global hashtags over the given period
584 * @param int $period Period in hours to consider posts
585 * @param int $limit Number of returned tags
589 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
591 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
595 return self::setGlobalTrendingHashtags($period, $limit);
600 * Fetch the blocked tags as SQL
604 private static function getBlockedSQL()
606 $blocked_txt = DI::config()->get('system', 'blocked_tags');
607 if (empty($blocked_txt)) {
611 $blocked = explode(',', $blocked_txt);
612 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
613 return " AND NOT `name` IN (" . implode(',', $blocked) . ")";
617 * Creates a list of the most frequent global hashtags over the given period
619 * @param int $period Period in hours to consider posts
620 * @param int $limit Number of returned tags
624 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
626 // Get a uri-id that is at least X hours old.
627 // We use the uri-id in the query for the hash tags since this is much faster
628 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
629 ['order' => ['received' => true]]);
630 if (empty($post['uri-id'])) {
634 $block_sql = self::getBlockedSQL();
636 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
637 FROM `tag-search-view`
638 WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
639 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
640 Item::PUBLIC, 0, $post['uri-id'], $limit);
642 if (DBA::isResult($tagsStmt)) {
643 $tags = DBA::toArray($tagsStmt);
644 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
652 * Returns a list of the most frequent local hashtags over the given period
654 * @param int $period Period in hours to consider posts
655 * @param int $limit Number of returned tags
659 public static function getLocalTrendingHashtags(int $period, $limit = 10)
661 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
665 return self::setLocalTrendingHashtags($period, $limit);
670 * Returns a list of the most frequent local hashtags over the given period
672 * @param int $period Period in hours to consider posts
673 * @param int $limit Number of returned tags
677 public static function setLocalTrendingHashtags(int $period, int $limit = 10)
679 // Get a uri-id that is at least X hours old.
680 // We use the uri-id in the query for the hash tags since this is much faster
681 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
682 ['order' => ['received' => true]]);
683 if (empty($post['uri-id'])) {
687 $block_sql = self::getBlockedSQL();
689 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
690 FROM `tag-search-view`
691 WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
692 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
693 Item::PUBLIC, $post['uri-id'], $limit);
695 if (DBA::isResult($tagsStmt)) {
696 $tags = DBA::toArray($tagsStmt);
697 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
705 * Check if the provided tag is of one of the provided term types.
708 * @param int ...$types
711 public static function isType($tag, ...$types)
714 foreach ($types as $type) {
715 if (array_key_exists($type, self::TAG_CHARACTER)) {
716 $tag_chars[] = self::TAG_CHARACTER[$type];
720 return Strings::startsWithChars($tag, $tag_chars);
724 * Fetch user who subscribed to the given tag
727 * @return array User list
729 private static function getUIDListByTag(string $tag)
732 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
733 while ($search = DBA::fetch($searches)) {
734 $uids[] = $search['uid'];
736 DBA::close($searches);
742 * Fetch user who subscribed to the tags of the given item
744 * @param integer $uri_id
745 * @return array User list
747 public static function getUIDListByURIId(int $uri_id)
750 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
752 foreach ($tags as $tag) {
753 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
756 return array_unique($uids);