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;
64 const TAG_CHARACTER = [
67 self::EXCLUSIVE_MENTION => '!',
68 self::IMPLICIT_MENTION => '%',
72 * Store tag/mention elements
74 * @param integer $uriid
75 * @param integer $type
78 * @param integer $target
80 public static function store(int $uriid, int $type, string $name, string $url = '', int $target = null)
82 if ($type == self::HASHTAG) {
83 // Trim Unicode non-word characters
84 $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
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);
102 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION, self::TO, self::CC, self::BTO, self::BCC])) {
104 // No mention without a contact url
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)]);
112 $cid = Contact::getIdForURL($url, 0, false);
113 Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]);
116 $tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]);
118 if ($tag['name'] != substr($name, 0, 96)) {
119 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
121 if (!empty($target) && ($tag['type'] != $target)) {
122 DBA::update('tag', ['type' => $target], ['url' => $url]);
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);
137 $tagid = self::getID($name, $url, $target);
143 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
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);
154 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
156 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
159 public static function getTargetType(string $url)
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]);
173 if ($url == ActivityPub::PUBLIC_COLLECTION) {
174 $target = Tag::COLLECTION;
175 Logger::debug('Public collection', ['url' => $url]);
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]);
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]);
192 if (!empty($target) && !empty($tag['url']) && empty($tag['type'])) {
193 DBA::update('tag', ['type' => $target], ['url' => $url]);
196 if (empty($target)) {
197 Logger::debug('No type could be detected', ['url' => $url]);
204 * Get a tag id for a given tag name and url
206 * @param string $name
211 public static function getID(string $name, string $url = '', int $type = null)
213 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
216 $fields['type'] = $type;
219 $tag = DBA::selectFirst('tag', ['id'], $fields);
220 if (DBA::isResult($tag)) {
224 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
225 $tid = DBA::lastInsertId();
230 Logger::error('No tag id created', $fields);
235 * Store tag/mention elements
237 * @param integer $uriid
238 * @param string $hash
239 * @param string $name
241 * @param boolean $probing
243 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
245 $type = self::getTypeForHash($hash);
246 if ($type == self::UNKNOWN) {
250 self::store($uriid, $type, $name, $url, $probing);
254 * Get tags and mentions from the body
256 * @param string $body Body of the post
257 * @param string $tags Accepted tags
259 * @return array Tag list
261 public static function getFromBody(string $body, string $tags = null)
263 if (is_null($tags)) {
264 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
267 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
275 * Store tags and mentions from the body
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
282 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
284 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
286 $result = self::getFromBody($body, $tags);
287 if (empty($result)) {
291 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
293 foreach ($result as $tag) {
294 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
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.
303 * @param integer $uriid URI-Id
304 * @param string $body Body of the post
306 public static function storeRawTagsFromBody(int $uriid, string $body)
308 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
310 $result = BBCode::getTags($body);
311 if (empty($result)) {
315 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
317 foreach ($result as $tag) {
318 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
321 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
326 * Checks for stored hashtags and mentions for the given post
328 * @param integer $uriid
331 public static function existsForPost(int $uriid)
333 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
339 * @param integer $uriid
340 * @param integer $type
341 * @param string $name
344 public static function remove(int $uriid, int $type, string $name, string $url = '')
346 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
347 if ($type == self::HASHTAG) {
348 $condition['name'] = $name;
351 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
352 if (!DBA::isResult($tag)) {
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']]);
363 * @param integer $uriid
364 * @param string $hash
365 * @param string $name
368 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
370 $type = self::getTypeForHash($hash);
371 if ($type == self::UNKNOWN) {
375 self::remove($uriid, $type, $name, $url);
379 * Get the type for the given hash
381 * @param string $hash
382 * @return integer type
384 private static function getTypeForHash(string $hash)
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;
395 return self::UNKNOWN;
400 * Create implicit mentions for a given post
402 * @param integer $uri_id
403 * @param integer $parent_uri_id
405 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
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']);
411 if (DI::config()->get('system', 'disable_implicit_mentions')) {
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']);
423 * Retrieves the terms from the provided type(s) associated with the provided item ID.
425 * @param int $item_id
426 * @param int|array $type
430 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
432 $condition = ['uri-id' => $uri_id, 'type' => $type];
433 return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
437 * Return a string with all tags and mentions
439 * @param integer $uri_id
441 * @return string tags and mentions
444 public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
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]';
452 return implode(',', $tag_list);
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.
461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462 * @throws \ImagickException
464 public static function populateFromItem(&$item)
470 'implicit_mentions' => [],
473 $searchpath = DI::baseUrl() . "/search?tag=";
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']);
482 $orig_tag = $tag['url'];
484 $prefix = self::TAG_CHARACTER[$tag['type']];
485 switch($tag['type']) {
487 if ($orig_tag != $tag['url']) {
488 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
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>';
495 case self::EXCLUSIVE_MENTION:
496 if (!empty($tag['cid'])) {
497 $tag['url'] = Contact::magicLinkById($tag['cid']);
499 $tag['url'] = Contact::magicLink($tag['url']);
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>';
504 case self::IMPLICIT_MENTION:
505 $return['implicit_mentions'][] = $prefix . $tag['name'];
509 DBA::close($taglist);
515 * Counts posts for given tag
517 * @param string $search
518 * @param integer $uid
519 * @return integer number of posts
521 public static function countByTag(string $search, int $uid = 0)
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];
527 return DBA::count('tag-search-view', $condition);
531 * Search posts for given tag
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
540 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
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];
546 if (!empty($last_uriid)) {
547 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
551 'order' => ['uri-id' => true],
552 'limit' => [$start, $limit]
555 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
558 while ($tag = DBA::fetch($tags)) {
559 $uriids[] = $tag['uri-id'];
567 * Returns a list of the most frequent global hashtags over the given period
569 * @param int $period Period in hours to consider posts
570 * @param int $limit Number of returned tags
574 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
576 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
580 return self::setGlobalTrendingHashtags($period, $limit);
585 * Fetch the blocked tags as SQL
589 private static function getBlockedSQL()
591 $blocked_txt = DI::config()->get('system', 'blocked_tags');
592 if (empty($blocked_txt)) {
596 $blocked = explode(',', $blocked_txt);
597 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
598 return " AND NOT `name` IN (" . implode(',', $blocked) . ")";
602 * Creates a list of the most frequent global hashtags over the given period
604 * @param int $period Period in hours to consider posts
605 * @param int $limit Number of returned tags
609 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
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'])) {
619 $block_sql = self::getBlockedSQL();
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);
627 if (DBA::isResult($tagsStmt)) {
628 $tags = DBA::toArray($tagsStmt);
629 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
637 * Returns a list of the most frequent local hashtags over the given period
639 * @param int $period Period in hours to consider posts
640 * @param int $limit Number of returned tags
644 public static function getLocalTrendingHashtags(int $period, $limit = 10)
646 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
650 return self::setLocalTrendingHashtags($period, $limit);
655 * Returns a list of the most frequent local hashtags over the given period
657 * @param int $period Period in hours to consider posts
658 * @param int $limit Number of returned tags
662 public static function setLocalTrendingHashtags(int $period, int $limit = 10)
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'])) {
672 $block_sql = self::getBlockedSQL();
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);
680 if (DBA::isResult($tagsStmt)) {
681 $tags = DBA::toArray($tagsStmt);
682 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
690 * Check if the provided tag is of one of the provided term types.
693 * @param int ...$types
696 public static function isType($tag, ...$types)
699 foreach ($types as $type) {
700 if (array_key_exists($type, self::TAG_CHARACTER)) {
701 $tag_chars[] = self::TAG_CHARACTER[$type];
705 return Strings::startsWithChars($tag, $tag_chars);
709 * Fetch user who subscribed to the given tag
712 * @return array User list
714 private static function getUIDListByTag(string $tag)
717 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
718 while ($search = DBA::fetch($searches)) {
719 $uids[] = $search['uid'];
721 DBA::close($searches);
727 * Fetch user who subscribed to the tags of the given item
729 * @param integer $uri_id
730 * @return array User list
732 public static function getUIDListByURIId(int $uri_id)
735 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
737 foreach ($tags as $tag) {
738 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
741 return array_unique($uids);