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', 'cid'],
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 if (!empty($tag['cid'])) {
432 $tag['url'] = Contact::magicLinkById($tag['cid']);
434 $tag['url'] = Contact::magicLink($tag['url']);
436 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
437 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
439 case self::IMPLICIT_MENTION:
440 $return['implicit_mentions'][] = $prefix . $tag['name'];
444 DBA::close($taglist);
450 * Counts posts for given tag
452 * @param string $search
453 * @param integer $uid
454 * @return integer number of posts
456 public static function countByTag(string $search, int $uid = 0)
458 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
459 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
460 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
462 return DBA::count('tag-search-view', $condition);
466 * Search posts for given tag
468 * @param string $search
469 * @param integer $uid
470 * @param integer $start
471 * @param integer $limit
472 * @param integer $last_uriid
473 * @return array with URI-ID
475 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
477 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
478 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
479 $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
481 if (!empty($last_uriid)) {
482 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
486 'order' => ['uri-id' => true],
487 'limit' => [$start, $limit]
490 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
493 while ($tag = DBA::fetch($tags)) {
494 $uriids[] = $tag['uri-id'];
502 * Returns a list of the most frequent global hashtags over the given period
504 * @param int $period Period in hours to consider posts
505 * @param int $limit Number of returned tags
509 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
511 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
515 return self::setGlobalTrendingHashtags($period, $limit);
520 * Creates a list of the most frequent global hashtags over the given period
522 * @param int $period Period in hours to consider posts
523 * @param int $limit Number of returned tags
527 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
529 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
530 FROM `tag-search-view`
531 WHERE `private` = ? AND `uid` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
532 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
533 Item::PUBLIC, 0, $period, $limit);
535 if (DBA::isResult($tagsStmt)) {
536 $tags = DBA::toArray($tagsStmt);
537 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
545 * Returns a list of the most frequent local 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 getLocalTrendingHashtags(int $period, $limit = 10)
554 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
558 return self::setLocalTrendingHashtags($period, $limit);
563 * Returns a list of the most frequent local hashtags over the given period
565 * @param int $period Period in hours to consider posts
566 * @param int $limit Number of returned tags
570 public static function setLocalTrendingHashtags(int $period, int $limit = 10)
572 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
573 FROM `tag-search-view`
574 WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
575 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
576 Item::PUBLIC, $period, $limit);
578 if (DBA::isResult($tagsStmt)) {
579 $tags = DBA::toArray($tagsStmt);
580 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
588 * Check if the provided tag is of one of the provided term types.
591 * @param int ...$types
594 public static function isType($tag, ...$types)
597 foreach ($types as $type) {
598 if (array_key_exists($type, self::TAG_CHARACTER)) {
599 $tag_chars[] = self::TAG_CHARACTER[$type];
603 return Strings::startsWithChars($tag, $tag_chars);
607 * Fetch user who subscribed to the given tag
610 * @return array User list
612 private static function getUIDListByTag(string $tag)
615 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
616 while ($search = DBA::fetch($searches)) {
617 $uids[] = $search['uid'];
619 DBA::close($searches);
625 * Fetch user who subscribed to the tags of the given item
627 * @param integer $uri_id
628 * @return array User list
630 public static function getUIDListByURIId(int $uri_id)
633 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
635 foreach ($tags as $tag) {
636 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
639 return array_unique($uids);