3 * @copyright Copyright (C) 2010-2021, 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 * Store tags and mentions from the body
212 * @param integer $uriid URI-Id
213 * @param string $body Body of the post
214 * @param string $tags Accepted tags
215 * @param boolean $probing Perform a probing for contacts, adding them if needed
217 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
219 if (is_null($tags)) {
220 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
223 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
225 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
229 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
231 foreach ($result as $tag) {
232 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
237 * Store raw tags (not encapsulated in links) from the body
238 * This function is needed in the intermediate phase.
239 * Later we can call item::setHashtags in advance to have all tags converted.
241 * @param integer $uriid URI-Id
242 * @param string $body Body of the post
244 public static function storeRawTagsFromBody(int $uriid, string $body)
246 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
248 $result = BBCode::getTags($body);
249 if (empty($result)) {
253 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
255 foreach ($result as $tag) {
256 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
259 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
264 * Checks for stored hashtags and mentions for the given post
266 * @param integer $uriid
269 public static function existsForPost(int $uriid)
271 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
277 * @param integer $uriid
278 * @param integer $type
279 * @param string $name
282 public static function remove(int $uriid, int $type, string $name, string $url = '')
284 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
285 if ($type == self::HASHTAG) {
286 $condition['name'] = $name;
289 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
290 if (!DBA::isResult($tag)) {
294 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
295 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
301 * @param integer $uriid
302 * @param string $hash
303 * @param string $name
306 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
308 $type = self::getTypeForHash($hash);
309 if ($type == self::UNKNOWN) {
313 self::remove($uriid, $type, $name, $url);
317 * Get the type for the given hash
319 * @param string $hash
320 * @return integer type
322 private static function getTypeForHash(string $hash)
324 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
325 return self::MENTION;
326 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
327 return self::EXCLUSIVE_MENTION;
328 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
329 return self::IMPLICIT_MENTION;
330 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
331 return self::HASHTAG;
333 return self::UNKNOWN;
338 * Create implicit mentions for a given post
340 * @param integer $uri_id
341 * @param integer $parent_uri_id
343 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
345 // Always mention the direct parent author
346 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
347 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
349 if (DI::config()->get('system', 'disable_implicit_mentions')) {
353 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id]);
354 while ($tag = DBA::fetch($tags)) {
355 self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
361 * Retrieves the terms from the provided type(s) associated with the provided item ID.
363 * @param int $item_id
364 * @param int|array $type
368 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
370 $condition = ['uri-id' => $uri_id, 'type' => $type];
371 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
375 * Return a string with all tags and mentions
377 * @param integer $uri_id
379 * @return string tags and mentions
382 public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
385 $tags = self::getByURIId($uri_id, $type);
386 foreach ($tags as $tag) {
387 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
390 return implode(',', $tag_list);
394 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
395 * provided item's body with them.
399 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
400 * @throws \ImagickException
402 public static function populateFromItem(&$item)
408 'implicit_mentions' => [],
411 $searchpath = DI::baseUrl() . "/search?tag=";
413 $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
414 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
415 while ($tag = DBA::fetch($taglist)) {
416 if ($tag['url'] == '') {
417 $tag['url'] = $searchpath . rawurlencode($tag['name']);
420 $orig_tag = $tag['url'];
422 $prefix = self::TAG_CHARACTER[$tag['type']];
423 switch($tag['type']) {
425 if ($orig_tag != $tag['url']) {
426 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
429 $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
430 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
433 case self::EXCLUSIVE_MENTION:
434 if (!empty($tag['cid'])) {
435 $tag['url'] = Contact::magicLinkById($tag['cid']);
437 $tag['url'] = Contact::magicLink($tag['url']);
439 $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
440 $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
442 case self::IMPLICIT_MENTION:
443 $return['implicit_mentions'][] = $prefix . $tag['name'];
447 DBA::close($taglist);
453 * Counts posts for given tag
455 * @param string $search
456 * @param integer $uid
457 * @return integer number of posts
459 public static function countByTag(string $search, int $uid = 0)
461 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
462 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
463 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
465 return DBA::count('tag-search-view', $condition);
469 * Search posts for given tag
471 * @param string $search
472 * @param integer $uid
473 * @param integer $start
474 * @param integer $limit
475 * @param integer $last_uriid
476 * @return array with URI-ID
478 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
480 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
481 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
482 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
484 if (!empty($last_uriid)) {
485 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
489 'order' => ['uri-id' => true],
490 'limit' => [$start, $limit]
493 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
496 while ($tag = DBA::fetch($tags)) {
497 $uriids[] = $tag['uri-id'];
505 * Returns a list of the most frequent global hashtags over the given period
507 * @param int $period Period in hours to consider posts
508 * @param int $limit Number of returned tags
512 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
514 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
518 return self::setGlobalTrendingHashtags($period, $limit);
523 * Fetch the blocked tags as SQL
527 private static function getBlockedSQL()
529 $blocked_txt = DI::config()->get('system', 'blocked_tags');
530 if (empty($blocked_txt)) {
534 $blocked = explode(',', $blocked_txt);
535 array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
536 return " AND NOT `name` IN (" . implode(',', $blocked) . ")";
540 * Creates a list of the most frequent global hashtags over the given period
542 * @param int $period Period in hours to consider posts
543 * @param int $limit Number of returned tags
547 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
549 // Get a uri-id that is at least X hours old.
550 // We use the uri-id in the query for the hash tags since this is much faster
551 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
552 ['order' => ['received' => true]]);
553 if (empty($post['uri-id'])) {
557 $block_sql = self::getBlockedSQL();
559 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
560 FROM `tag-search-view`
561 WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
562 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
563 Item::PUBLIC, 0, $post['uri-id'], $limit);
565 if (DBA::isResult($tagsStmt)) {
566 $tags = DBA::toArray($tagsStmt);
567 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
575 * Returns a list of the most frequent local hashtags over the given period
577 * @param int $period Period in hours to consider posts
578 * @param int $limit Number of returned tags
582 public static function getLocalTrendingHashtags(int $period, $limit = 10)
584 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
588 return self::setLocalTrendingHashtags($period, $limit);
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 setLocalTrendingHashtags(int $period, int $limit = 10)
602 // Get a uri-id that is at least X hours old.
603 // We use the uri-id in the query for the hash tags since this is much faster
604 $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
605 ['order' => ['received' => true]]);
606 if (empty($post['uri-id'])) {
610 $block_sql = self::getBlockedSQL();
612 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`, COUNT(DISTINCT(`author-id`)) as `authors`
613 FROM `tag-search-view`
614 WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
615 GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
616 Item::PUBLIC, $post['uri-id'], $limit);
618 if (DBA::isResult($tagsStmt)) {
619 $tags = DBA::toArray($tagsStmt);
620 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
628 * Check if the provided tag is of one of the provided term types.
631 * @param int ...$types
634 public static function isType($tag, ...$types)
637 foreach ($types as $type) {
638 if (array_key_exists($type, self::TAG_CHARACTER)) {
639 $tag_chars[] = self::TAG_CHARACTER[$type];
643 return Strings::startsWithChars($tag, $tag_chars);
647 * Fetch user who subscribed to the given tag
650 * @return array User list
652 private static function getUIDListByTag(string $tag)
655 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
656 while ($search = DBA::fetch($searches)) {
657 $uids[] = $search['uid'];
659 DBA::close($searches);
665 * Fetch user who subscribed to the tags of the given item
667 * @param integer $uri_id
668 * @return array User list
670 public static function getUIDListByURIId(int $uri_id)
673 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
675 foreach ($tags as $tag) {
676 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
679 return array_unique($uids);