3 * @copyright Copyright (C) 2020, Friendica
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\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\Strings;
37 * This Model class handles tag table interactions.
38 * This tables stores relevant tags related to posts, like hashtags and mentions.
46 * An implicit mention is a mention in a comment body that is redundant with the threading information.
48 const IMPLICIT_MENTION = 8;
50 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
52 const EXCLUSIVE_MENTION = 9;
54 const TAG_CHARACTER = [
57 self::IMPLICIT_MENTION => '%',
58 self::EXCLUSIVE_MENTION => '!',
62 * Store tag/mention elements
64 * @param integer $uriid
65 * @param integer $type
68 * @param boolean $probing
70 public static function store(int $uriid, int $type, string $name, string $url = '', $probing = true)
72 if ($type == self::HASHTAG) {
73 // Trim Unicode non-word characters
74 $name = preg_replace('/(^\W+)|(\W+$)/us', '', $name);
76 $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
77 if (count($tags) > 1) {
78 foreach ($tags as $tag) {
79 self::store($uriid, $type, $tag, $url, $probing);
92 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
94 // No mention without a contact url
98 if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
99 Logger::notice('Wrong scheme in url', ['url' => $url, 'callstack' => System::callstack(20)]);
103 $condition = ['nurl' => Strings::normaliseLink($url), 'uid' => 0, 'deleted' => false];
104 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
105 if (DBA::isResult($contact)) {
106 $cid = $contact['id'];
107 Logger::info('Got id for contact url', ['cid' => $cid, 'url' => $url]);
111 $ssl_url = str_replace('http://', 'https://', $url);
112 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, 0];
113 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
114 if (DBA::isResult($contact)) {
115 $cid = $contact['id'];
116 Logger::info('Got id for contact alias', ['cid' => $cid, 'url' => $url]);
120 $cid = Contact::getIdForURL($url, 0, false);
121 Logger::info('Got id by probing', ['cid' => $cid, 'url' => $url]);
125 // The contact wasn't found in the system (most likely some dead account)
126 // We ensure that we only store a single entry by overwriting the previous name
127 Logger::info('Contact not found, updating tag', ['url' => $url, 'name' => $name]);
128 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
133 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
134 $url = strtolower($url);
139 $tagid = self::getID($name, $url);
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 * Get a tag id for a given tag name and url
164 * @param string $name
168 public static function getID(string $name, string $url = '')
170 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
172 $tag = DBA::selectFirst('tag', ['id'], $fields);
173 if (DBA::isResult($tag)) {
177 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
178 $tid = DBA::lastInsertId();
183 Logger::error('No tag id created', $fields);
188 * Store tag/mention elements
190 * @param integer $uriid
191 * @param string $hash
192 * @param string $name
194 * @param boolean $probing
196 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
198 $type = self::getTypeForHash($hash);
199 if ($type == self::UNKNOWN) {
203 self::store($uriid, $type, $name, $url, $probing);
207 * Store tags and mentions from the body
209 * @param integer $uriid URI-Id
210 * @param string $body Body of the post
211 * @param string $tags Accepted tags
212 * @param boolean $probing Perform a probing for contacts, adding them if needed
214 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
216 if (is_null($tags)) {
217 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
220 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
222 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
226 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
228 foreach ($result as $tag) {
229 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
234 * Store raw tags (not encapsulated in links) from the body
235 * This function is needed in the intermediate phase.
236 * Later we can call item::setHashtags in advance to have all tags converted.
238 * @param integer $uriid URI-Id
239 * @param string $body Body of the post
241 public static function storeRawTagsFromBody(int $uriid, string $body)
243 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
245 $result = BBCode::getTags($body);
246 if (empty($result)) {
250 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
252 foreach ($result as $tag) {
253 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
256 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
261 * Checks for stored hashtags and mentions for the given post
263 * @param integer $uriid
266 public static function existsForPost(int $uriid)
268 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
274 * @param integer $uriid
275 * @param integer $type
276 * @param string $name
279 public static function remove(int $uriid, int $type, string $name, string $url = '')
281 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
282 if ($type == self::HASHTAG) {
283 $condition['name'] = $name;
286 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
287 if (!DBA::isResult($tag)) {
291 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
292 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
298 * @param integer $uriid
299 * @param string $hash
300 * @param string $name
303 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
305 $type = self::getTypeForHash($hash);
306 if ($type == self::UNKNOWN) {
310 self::remove($uriid, $type, $name, $url);
314 * Get the type for the given hash
316 * @param string $hash
317 * @return integer type
319 private static function getTypeForHash(string $hash)
321 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
322 return self::MENTION;
323 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
324 return self::EXCLUSIVE_MENTION;
325 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
326 return self::IMPLICIT_MENTION;
327 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
328 return self::HASHTAG;
330 return self::UNKNOWN;
335 * Create implicit mentions for a given post
337 * @param integer $uri_id
338 * @param integer $parent_uri_id
340 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
342 // Always mention the direct parent author
343 $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
344 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
346 if (DI::config()->get('system', 'disable_implicit_mentions')) {
350 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id]);
351 while ($tag = DBA::fetch($tags)) {
352 self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
358 * Retrieves the terms from the provided type(s) associated with the provided item ID.
360 * @param int $item_id
361 * @param int|array $type
365 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
367 $condition = ['uri-id' => $uri_id, 'type' => $type];
368 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
372 * Return a string with all tags and mentions
374 * @param integer $uri_id
376 * @return string tags and mentions
379 public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
382 $tags = self::getByURIId($uri_id, $type);
383 foreach ($tags as $tag) {
384 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
387 return implode(',', $tag_list);
391 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
392 * provided item's body with them.
396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
397 * @throws \ImagickException
399 public static function populateFromItem(&$item)
405 'implicit_mentions' => [],
408 $searchpath = DI::baseUrl() . "/search?tag=";
410 $taglist = DBA::select('tag-view', ['type', 'name', 'url'],
411 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
412 while ($tag = DBA::fetch($taglist)) {
413 if ($tag['url'] == '') {
414 $tag['url'] = $searchpath . rawurlencode($tag['name']);
417 $orig_tag = $tag['url'];
419 $prefix = self::TAG_CHARACTER[$tag['type']];
420 switch($tag['type']) {
422 if ($orig_tag != $tag['url']) {
423 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
426 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
427 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
430 case self::EXCLUSIVE_MENTION:
431 $tag['url'] = Contact::magicLink($tag['url']);
432 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
433 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
435 case self::IMPLICIT_MENTION:
436 $return['implicit_mentions'][] = $prefix . $tag['name'];
440 DBA::close($taglist);
446 * Counts posts for given tag
448 * @param string $search
449 * @param integer $uid
450 * @return integer number of posts
452 public static function countByTag(string $search, int $uid = 0)
454 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))
455 AND `uri-id` IN (SELECT `uri-id` FROM `post-view` WHERE `network` IN (?, ?, ?, ?))",
456 $search, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
457 $params = ['group_by' => ['uri-id']];
459 return DBA::count('tag-search-view', $condition, $params);
463 * Search posts for given tag
465 * @param string $search
466 * @param integer $uid
467 * @param integer $start
468 * @param integer $limit
469 * @param integer $last_uriid
470 * @return array with URI-ID
472 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
474 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))
475 AND `uri-id` IN (SELECT `uri-id` FROM `post-view` WHERE `network` IN (?, ?, ?, ?))",
476 $search, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
478 if (!empty($last_uriid)) {
479 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
483 'order' => ['uri-id' => true],
484 'group_by' => ['uri-id'],
485 'limit' => [$start, $limit]
488 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
491 while ($tag = DBA::fetch($tags)) {
492 $uriids[] = $tag['uri-id'];
500 * Returns a list of the most frequent global hashtags over the given period
502 * @param int $period Period in hours to consider posts
503 * @param int $limit Number of returned tags
507 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
509 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
513 return self::setGlobalTrendingHashtags($period, $limit);
518 * Creates a list of the most frequent global hashtags over the given period
520 * @param int $period Period in hours to consider posts
521 * @param int $limit Number of returned tags
525 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
527 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
528 FROM `tag-search-view`
529 WHERE `private` = ? AND `uid` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
530 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
531 Item::PUBLIC, 0, $period, $limit);
533 if (DBA::isResult($tagsStmt)) {
534 $tags = DBA::toArray($tagsStmt);
535 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
543 * Returns a list of the most frequent local hashtags over the given period
545 * @param int $period Period in hours to consider posts
546 * @param int $limit Number of returned tags
550 public static function getLocalTrendingHashtags(int $period, $limit = 10)
552 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
556 return self::setLocalTrendingHashtags($period, $limit);
561 * Returns a list of the most frequent local hashtags over the given period
563 * @param int $period Period in hours to consider posts
564 * @param int $limit Number of returned tags
568 public static function setLocalTrendingHashtags(int $period, int $limit = 10)
570 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
571 FROM `tag-search-view`
572 WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
573 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
574 Item::PUBLIC, $period, $limit);
576 if (DBA::isResult($tagsStmt)) {
577 $tags = DBA::toArray($tagsStmt);
578 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
586 * Check if the provided tag is of one of the provided term types.
589 * @param int ...$types
592 public static function isType($tag, ...$types)
595 foreach ($types as $type) {
596 if (array_key_exists($type, self::TAG_CHARACTER)) {
597 $tag_chars[] = self::TAG_CHARACTER[$type];
601 return Strings::startsWithChars($tag, $tag_chars);
605 * Fetch user who subscribed to the given tag
608 * @return array User list
610 private static function getUIDListByTag(string $tag)
613 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
614 while ($search = DBA::fetch($searches)) {
615 $uids[] = $search['uid'];
617 DBA::close($searches);
623 * Fetch user who subscribed to the tags of the given item
625 * @param integer $uri_id
626 * @return array User list
628 public static function getUIDListByURIId(int $uri_id)
631 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
633 foreach ($tags as $tag) {
634 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
637 return array_unique($uids);