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 transfers the ownership of the post to the target account, usually a forum.
53 const EXCLUSIVE_MENTION = 9;
55 const TAG_CHARACTER = [
58 self::IMPLICIT_MENTION => '%',
59 self::EXCLUSIVE_MENTION => '!',
63 * Store tag/mention elements
65 * @param integer $uriid
66 * @param integer $type
69 * @param boolean $probing
71 public static function store(int $uriid, int $type, string $name, string $url = '', $probing = true)
73 if ($type == self::HASHTAG) {
74 // Trim Unicode non-word characters
75 $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
77 $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
78 if (count($tags) > 1) {
79 foreach ($tags as $tag) {
80 self::store($uriid, $type, $tag, $url, $probing);
93 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
95 // No mention without a contact url
99 if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
100 Logger::notice('Wrong scheme in url', ['url' => $url, 'callstack' => System::callstack(20)]);
104 $condition = ['nurl' => Strings::normaliseLink($url), 'uid' => 0, 'deleted' => false];
105 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
106 if (DBA::isResult($contact)) {
107 $cid = $contact['id'];
108 Logger::info('Got id for contact url', ['cid' => $cid, 'url' => $url]);
112 $ssl_url = str_replace('http://', 'https://', $url);
113 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, 0];
114 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
115 if (DBA::isResult($contact)) {
116 $cid = $contact['id'];
117 Logger::info('Got id for contact alias', ['cid' => $cid, 'url' => $url]);
121 $cid = Contact::getIdForURL($url, 0, false);
122 Logger::info('Got id by probing', ['cid' => $cid, 'url' => $url]);
126 // The contact wasn't found in the system (most likely some dead account)
127 // We ensure that we only store a single entry by overwriting the previous name
128 Logger::info('Contact not found, updating tag', ['url' => $url, 'name' => $name]);
129 if (!DBA::exists('tag', ['name' => substr($name, 0, 96), 'url' => $url])) {
130 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
136 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
137 $url = strtolower($url);
142 $tagid = self::getID($name, $url);
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::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
165 * Get a tag id for a given tag name and url
167 * @param string $name
171 public static function getID(string $name, string $url = '')
173 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
175 $tag = DBA::selectFirst('tag', ['id'], $fields);
176 if (DBA::isResult($tag)) {
180 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
181 $tid = DBA::lastInsertId();
186 Logger::error('No tag id created', $fields);
191 * Store tag/mention elements
193 * @param integer $uriid
194 * @param string $hash
195 * @param string $name
197 * @param boolean $probing
199 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
201 $type = self::getTypeForHash($hash);
202 if ($type == self::UNKNOWN) {
206 self::store($uriid, $type, $name, $url, $probing);
210 * Get tags and mentions from the body
212 * @param string $body Body of the post
213 * @param string $tags Accepted tags
215 * @return array Tag list
217 public static function getFromBody(string $body, string $tags = null)
219 if (is_null($tags)) {
220 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
223 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
231 * Store tags and mentions from the body
233 * @param integer $uriid URI-Id
234 * @param string $body Body of the post
235 * @param string $tags Accepted tags
236 * @param boolean $probing Perform a probing for contacts, adding them if needed
238 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
240 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
242 $result = self::getFromBody($body, $tags);
243 if (empty($result)) {
247 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
249 foreach ($result as $tag) {
250 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
255 * Store raw tags (not encapsulated in links) from the body
256 * This function is needed in the intermediate phase.
257 * Later we can call item::setHashtags in advance to have all tags converted.
259 * @param integer $uriid URI-Id
260 * @param string $body Body of the post
262 public static function storeRawTagsFromBody(int $uriid, string $body)
264 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
266 $result = BBCode::getTags($body);
267 if (empty($result)) {
271 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
273 foreach ($result as $tag) {
274 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
277 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
282 * Checks for stored hashtags and mentions for the given post
284 * @param integer $uriid
287 public static function existsForPost(int $uriid)
289 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
295 * @param integer $uriid
296 * @param integer $type
297 * @param string $name
300 public static function remove(int $uriid, int $type, string $name, string $url = '')
302 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
303 if ($type == self::HASHTAG) {
304 $condition['name'] = $name;
307 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
308 if (!DBA::isResult($tag)) {
312 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
313 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
319 * @param integer $uriid
320 * @param string $hash
321 * @param string $name
324 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
326 $type = self::getTypeForHash($hash);
327 if ($type == self::UNKNOWN) {
331 self::remove($uriid, $type, $name, $url);
335 * Get the type for the given hash
337 * @param string $hash
338 * @return integer type
340 private static function getTypeForHash(string $hash)
342 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
343 return self::MENTION;
344 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
345 return self::EXCLUSIVE_MENTION;
346 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
347 return self::IMPLICIT_MENTION;
348 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
349 return self::HASHTAG;
351 return self::UNKNOWN;
356 * Create implicit mentions for a given post
358 * @param integer $uri_id
359 * @param integer $parent_uri_id
361 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
363 // Always mention the direct parent author
364 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
365 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
367 if (DI::config()->get('system', 'disable_implicit_mentions')) {
371 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id]);
372 while ($tag = DBA::fetch($tags)) {
373 self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
379 * Retrieves the terms from the provided type(s) associated with the provided item ID.
381 * @param int $item_id
382 * @param int|array $type
386 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
388 $condition = ['uri-id' => $uri_id, 'type' => $type];
389 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
393 * Return a string with all tags and mentions
395 * @param integer $uri_id
397 * @return string tags and mentions
400 public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
403 $tags = self::getByURIId($uri_id, $type);
404 foreach ($tags as $tag) {
405 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
408 return implode(',', $tag_list);
412 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
413 * provided item's body with them.
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 * @throws \ImagickException
420 public static function populateFromItem(&$item)
426 'implicit_mentions' => [],
429 $searchpath = DI::baseUrl() . "/search?tag=";
431 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
432 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
433 while ($tag = DBA::fetch($taglist)) {
434 if ($tag['url'] == '') {
435 $tag['url'] = $searchpath . rawurlencode($tag['name']);
438 $orig_tag = $tag['url'];
440 $prefix = self::TAG_CHARACTER[$tag['type']];
441 switch($tag['type']) {
443 if ($orig_tag != $tag['url']) {
444 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
447 $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
448 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
451 case self::EXCLUSIVE_MENTION:
452 if (!empty($tag['cid'])) {
453 $tag['url'] = Contact::magicLinkById($tag['cid']);
455 $tag['url'] = Contact::magicLink($tag['url']);
457 $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
458 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
460 case self::IMPLICIT_MENTION:
461 $return['implicit_mentions'][] = $prefix . $tag['name'];
465 DBA::close($taglist);
471 * Counts posts for given tag
473 * @param string $search
474 * @param integer $uid
475 * @return integer number of posts
477 public static function countByTag(string $search, int $uid = 0)
479 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
480 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
481 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
483 return DBA::count('tag-search-view', $condition);
487 * Search posts for given tag
489 * @param string $search
490 * @param integer $uid
491 * @param integer $start
492 * @param integer $limit
493 * @param integer $last_uriid
494 * @return array with URI-ID
496 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
498 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
499 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
500 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
502 if (!empty($last_uriid)) {
503 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
507 'order' => ['uri-id' => true],
508 'limit' => [$start, $limit]
511 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
514 while ($tag = DBA::fetch($tags)) {
515 $uriids[] = $tag['uri-id'];
523 * Returns a list of the most frequent global hashtags over the given period
525 * @param int $period Period in hours to consider posts
526 * @param int $limit Number of returned tags
530 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
532 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
536 return self::setGlobalTrendingHashtags($period, $limit);
541 * Fetch the blocked tags as SQL
545 private static function getBlockedSQL()
547 $blocked_txt = DI::config()->get('system', 'blocked_tags');
548 if (empty($blocked_txt)) {
552 $blocked = explode(',', $blocked_txt);
553 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
554 return " AND NOT `name` IN (" . implode(',', $blocked) . ")";
558 * Creates a list of the most frequent global hashtags over the given period
560 * @param int $period Period in hours to consider posts
561 * @param int $limit Number of returned tags
565 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
567 // Get a uri-id that is at least X hours old.
568 // We use the uri-id in the query for the hash tags since this is much faster
569 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
570 ['order' => ['received' => true]]);
571 if (empty($post['uri-id'])) {
575 $block_sql = self::getBlockedSQL();
577 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
578 FROM `tag-search-view`
579 WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
580 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
581 Item::PUBLIC, 0, $post['uri-id'], $limit);
583 if (DBA::isResult($tagsStmt)) {
584 $tags = DBA::toArray($tagsStmt);
585 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
593 * Returns a list of the most frequent local hashtags over the given period
595 * @param int $period Period in hours to consider posts
596 * @param int $limit Number of returned tags
600 public static function getLocalTrendingHashtags(int $period, $limit = 10)
602 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
606 return self::setLocalTrendingHashtags($period, $limit);
611 * Returns a list of the most frequent local hashtags over the given period
613 * @param int $period Period in hours to consider posts
614 * @param int $limit Number of returned tags
618 public static function setLocalTrendingHashtags(int $period, int $limit = 10)
620 // Get a uri-id that is at least X hours old.
621 // We use the uri-id in the query for the hash tags since this is much faster
622 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
623 ['order' => ['received' => true]]);
624 if (empty($post['uri-id'])) {
628 $block_sql = self::getBlockedSQL();
630 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
631 FROM `tag-search-view`
632 WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
633 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
634 Item::PUBLIC, $post['uri-id'], $limit);
636 if (DBA::isResult($tagsStmt)) {
637 $tags = DBA::toArray($tagsStmt);
638 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
646 * Check if the provided tag is of one of the provided term types.
649 * @param int ...$types
652 public static function isType($tag, ...$types)
655 foreach ($types as $type) {
656 if (array_key_exists($type, self::TAG_CHARACTER)) {
657 $tag_chars[] = self::TAG_CHARACTER[$type];
661 return Strings::startsWithChars($tag, $tag_chars);
665 * Fetch user who subscribed to the given tag
668 * @return array User list
670 private static function getUIDListByTag(string $tag)
673 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
674 while ($search = DBA::fetch($searches)) {
675 $uids[] = $search['uid'];
677 DBA::close($searches);
683 * Fetch user who subscribed to the tags of the given item
685 * @param integer $uri_id
686 * @return array User list
688 public static function getUIDListByURIId(int $uri_id)
691 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
693 foreach ($tags as $tag) {
694 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
697 return array_unique($uids);