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\Util\DateTimeFormat;
33 use Friendica\Util\Strings;
38 * This Model class handles tag table interactions.
39 * This tables stores relevant tags related to posts, like hashtags and mentions.
47 * An implicit mention is a mention in a comment body that is redundant with the threading information.
49 const IMPLICIT_MENTION = 8;
51 * An exclusive mention transmits the post only to the target account without transmitting it to the followers, usually a forum.
53 const EXCLUSIVE_MENTION = 9;
60 const TAG_CHARACTER = [
63 self::IMPLICIT_MENTION => '%',
64 self::EXCLUSIVE_MENTION => '!',
68 * Store tag/mention elements
70 * @param integer $uriid
71 * @param integer $type
75 public static function store(int $uriid, int $type, string $name, string $url = '')
77 if ($type == self::HASHTAG) {
78 // Trim Unicode non-word characters
79 $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
81 $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
82 if (count($tags) > 1) {
83 foreach ($tags as $tag) {
84 self::store($uriid, $type, $tag, $url);
97 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION, self::TO, self::CC, self::BTO, self::BCC])) {
99 // No mention without a contact url
103 if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
104 Logger::notice('Wrong scheme in url', ['url' => $url, 'callstack' => System::callstack(20)]);
107 $cid = Contact::getIdForURL($url, 0, false);
108 Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]);
111 // The contact wasn't found in the system (most likely some dead account)
112 // We ensure that we only store a single entry by overwriting the previous name
113 Logger::info('URL is not a known contact, updating tag', ['url' => $url, 'name' => $name]);
114 if (!DBA::exists('tag', ['name' => substr($name, 0, 96), 'url' => $url])) {
115 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
121 if (!in_array($type, [self::TO, self::CC, self::BTO, self::BCC])) {
122 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
123 $url = strtolower($url);
129 $tagid = self::getID($name, $url);
135 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
137 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
138 $condition = $fields;
139 $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
140 if (DBA::exists('post-tag', $condition)) {
141 Logger::info('Tag already exists', $fields);
146 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
148 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
152 * Get a tag id for a given tag name and url
154 * @param string $name
158 public static function getID(string $name, string $url = '')
160 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
162 $tag = DBA::selectFirst('tag', ['id'], $fields);
163 if (DBA::isResult($tag)) {
167 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
168 $tid = DBA::lastInsertId();
173 Logger::error('No tag id created', $fields);
178 * Store tag/mention elements
180 * @param integer $uriid
181 * @param string $hash
182 * @param string $name
184 * @param boolean $probing
186 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
188 $type = self::getTypeForHash($hash);
189 if ($type == self::UNKNOWN) {
193 self::store($uriid, $type, $name, $url, $probing);
197 * Get tags and mentions from the body
199 * @param string $body Body of the post
200 * @param string $tags Accepted tags
202 * @return array Tag list
204 public static function getFromBody(string $body, string $tags = null)
206 if (is_null($tags)) {
207 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
210 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
218 * Store tags and mentions from the body
220 * @param integer $uriid URI-Id
221 * @param string $body Body of the post
222 * @param string $tags Accepted tags
223 * @param boolean $probing Perform a probing for contacts, adding them if needed
225 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
227 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
229 $result = self::getFromBody($body, $tags);
230 if (empty($result)) {
234 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
236 foreach ($result as $tag) {
237 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
242 * Store raw tags (not encapsulated in links) from the body
243 * This function is needed in the intermediate phase.
244 * Later we can call item::setHashtags in advance to have all tags converted.
246 * @param integer $uriid URI-Id
247 * @param string $body Body of the post
249 public static function storeRawTagsFromBody(int $uriid, string $body)
251 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
253 $result = BBCode::getTags($body);
254 if (empty($result)) {
258 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
260 foreach ($result as $tag) {
261 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
264 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
269 * Checks for stored hashtags and mentions for the given post
271 * @param integer $uriid
274 public static function existsForPost(int $uriid)
276 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
282 * @param integer $uriid
283 * @param integer $type
284 * @param string $name
287 public static function remove(int $uriid, int $type, string $name, string $url = '')
289 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
290 if ($type == self::HASHTAG) {
291 $condition['name'] = $name;
294 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
295 if (!DBA::isResult($tag)) {
299 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
300 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
306 * @param integer $uriid
307 * @param string $hash
308 * @param string $name
311 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
313 $type = self::getTypeForHash($hash);
314 if ($type == self::UNKNOWN) {
318 self::remove($uriid, $type, $name, $url);
322 * Get the type for the given hash
324 * @param string $hash
325 * @return integer type
327 private static function getTypeForHash(string $hash)
329 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
330 return self::MENTION;
331 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
332 return self::EXCLUSIVE_MENTION;
333 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
334 return self::IMPLICIT_MENTION;
335 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
336 return self::HASHTAG;
338 return self::UNKNOWN;
343 * Create implicit mentions for a given post
345 * @param integer $uri_id
346 * @param integer $parent_uri_id
348 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
350 // Always mention the direct parent author
351 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
352 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
354 if (DI::config()->get('system', 'disable_implicit_mentions')) {
358 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id]);
359 while ($tag = DBA::fetch($tags)) {
360 self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
366 * Retrieves the terms from the provided type(s) associated with the provided item ID.
368 * @param int $item_id
369 * @param int|array $type
373 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
375 $condition = ['uri-id' => $uri_id, 'type' => $type];
376 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
380 * Return a string with all tags and mentions
382 * @param integer $uri_id
384 * @return string tags and mentions
387 public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
390 $tags = self::getByURIId($uri_id, $type);
391 foreach ($tags as $tag) {
392 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
395 return implode(',', $tag_list);
399 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
400 * provided item's body with them.
404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
405 * @throws \ImagickException
407 public static function populateFromItem(&$item)
413 'implicit_mentions' => [],
416 $searchpath = DI::baseUrl() . "/search?tag=";
418 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
419 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
420 while ($tag = DBA::fetch($taglist)) {
421 if ($tag['url'] == '') {
422 $tag['url'] = $searchpath . rawurlencode($tag['name']);
425 $orig_tag = $tag['url'];
427 $prefix = self::TAG_CHARACTER[$tag['type']];
428 switch($tag['type']) {
430 if ($orig_tag != $tag['url']) {
431 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
434 $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
435 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
438 case self::EXCLUSIVE_MENTION:
439 if (!empty($tag['cid'])) {
440 $tag['url'] = Contact::magicLinkById($tag['cid']);
442 $tag['url'] = Contact::magicLink($tag['url']);
444 $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
445 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
447 case self::IMPLICIT_MENTION:
448 $return['implicit_mentions'][] = $prefix . $tag['name'];
452 DBA::close($taglist);
458 * Counts posts for given tag
460 * @param string $search
461 * @param integer $uid
462 * @return integer number of posts
464 public static function countByTag(string $search, int $uid = 0)
466 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
467 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
468 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
470 return DBA::count('tag-search-view', $condition);
474 * Search posts for given tag
476 * @param string $search
477 * @param integer $uid
478 * @param integer $start
479 * @param integer $limit
480 * @param integer $last_uriid
481 * @return array with URI-ID
483 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
485 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
486 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
487 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
489 if (!empty($last_uriid)) {
490 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
494 'order' => ['uri-id' => true],
495 'limit' => [$start, $limit]
498 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
501 while ($tag = DBA::fetch($tags)) {
502 $uriids[] = $tag['uri-id'];
510 * Returns a list of the most frequent global hashtags over the given period
512 * @param int $period Period in hours to consider posts
513 * @param int $limit Number of returned tags
517 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
519 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
523 return self::setGlobalTrendingHashtags($period, $limit);
528 * Fetch the blocked tags as SQL
532 private static function getBlockedSQL()
534 $blocked_txt = DI::config()->get('system', 'blocked_tags');
535 if (empty($blocked_txt)) {
539 $blocked = explode(',', $blocked_txt);
540 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
541 return " AND NOT `name` IN (" . implode(',', $blocked) . ")";
545 * Creates a list of the most frequent global hashtags over the given period
547 * @param int $period Period in hours to consider posts
548 * @param int $limit Number of returned tags
552 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
554 // Get a uri-id that is at least X hours old.
555 // We use the uri-id in the query for the hash tags since this is much faster
556 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
557 ['order' => ['received' => true]]);
558 if (empty($post['uri-id'])) {
562 $block_sql = self::getBlockedSQL();
564 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
565 FROM `tag-search-view`
566 WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
567 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
568 Item::PUBLIC, 0, $post['uri-id'], $limit);
570 if (DBA::isResult($tagsStmt)) {
571 $tags = DBA::toArray($tagsStmt);
572 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
580 * Returns a list of the most frequent local hashtags over the given period
582 * @param int $period Period in hours to consider posts
583 * @param int $limit Number of returned tags
587 public static function getLocalTrendingHashtags(int $period, $limit = 10)
589 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
593 return self::setLocalTrendingHashtags($period, $limit);
598 * Returns a list of the most frequent local hashtags over the given period
600 * @param int $period Period in hours to consider posts
601 * @param int $limit Number of returned tags
605 public static function setLocalTrendingHashtags(int $period, int $limit = 10)
607 // Get a uri-id that is at least X hours old.
608 // We use the uri-id in the query for the hash tags since this is much faster
609 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
610 ['order' => ['received' => true]]);
611 if (empty($post['uri-id'])) {
615 $block_sql = self::getBlockedSQL();
617 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
618 FROM `tag-search-view`
619 WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
620 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
621 Item::PUBLIC, $post['uri-id'], $limit);
623 if (DBA::isResult($tagsStmt)) {
624 $tags = DBA::toArray($tagsStmt);
625 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
633 * Check if the provided tag is of one of the provided term types.
636 * @param int ...$types
639 public static function isType($tag, ...$types)
642 foreach ($types as $type) {
643 if (array_key_exists($type, self::TAG_CHARACTER)) {
644 $tag_chars[] = self::TAG_CHARACTER[$type];
648 return Strings::startsWithChars($tag, $tag_chars);
652 * Fetch user who subscribed to the given tag
655 * @return array User list
657 private static function getUIDListByTag(string $tag)
660 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
661 while ($search = DBA::fetch($searches)) {
662 $uids[] = $search['uid'];
664 DBA::close($searches);
670 * Fetch user who subscribed to the tags of the given item
672 * @param integer $uri_id
673 * @return array User list
675 public static function getUIDListByURIId(int $uri_id)
678 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
680 foreach ($tags as $tag) {
681 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
684 return array_unique($uids);