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\System;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
31 use Friendica\Util\Strings;
36 * This Model class handles tag table interactions.
37 * This tables stores relevant tags related to posts, like hashtags and mentions.
45 * An implicit mention is a mention in a comment body that is redundant with the threading information.
47 const IMPLICIT_MENTION = 8;
49 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
51 const EXCLUSIVE_MENTION = 9;
53 const TAG_CHARACTER = [
56 self::IMPLICIT_MENTION => '%',
57 self::EXCLUSIVE_MENTION => '!',
61 * Store tag/mention elements
63 * @param integer $uriid
64 * @param integer $type
67 * @param boolean $probing
69 public static function store(int $uriid, int $type, string $name, string $url = '', $probing = true)
71 if ($type == self::HASHTAG) {
72 // Remove some common "garbarge" from tags
73 $name = trim($name, "\x00..\x20\xFF#!@,;.:'/?!^°$%".'"');
75 $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
76 if (count($tags) > 1) {
77 foreach ($tags as $tag) {
78 self::store($uriid, $type, $tag, $url, $probing);
91 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
93 // No mention without a contact url
97 if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
98 Logger::notice('Wrong scheme in url', ['url' => $url, 'callstack' => System::callstack(20)]);
102 $condition = ['nurl' => Strings::normaliseLink($url), 'uid' => 0, 'deleted' => false];
103 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
104 if (DBA::isResult($contact)) {
105 $cid = $contact['id'];
106 Logger::info('Got id for contact url', ['cid' => $cid, 'url' => $url]);
110 $ssl_url = str_replace('http://', 'https://', $url);
111 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, 0];
112 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
113 if (DBA::isResult($contact)) {
114 $cid = $contact['id'];
115 Logger::info('Got id for contact alias', ['cid' => $cid, 'url' => $url]);
119 $cid = Contact::getIdForURL($url, 0, false);
120 Logger::info('Got id by probing', ['cid' => $cid, 'url' => $url]);
124 // The contact wasn't found in the system (most likely some dead account)
125 // We ensure that we only store a single entry by overwriting the previous name
126 Logger::info('Contact not found, updating tag', ['url' => $url, 'name' => $name]);
127 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
132 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
133 $url = strtolower($url);
138 $tagid = self::getID($name, $url);
144 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
146 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
147 $condition = $fields;
148 $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
149 if (DBA::exists('post-tag', $condition)) {
150 Logger::info('Tag already exists', $fields);
155 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
157 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
161 * Get a tag id for a given tag name and url
163 * @param string $name
167 public static function getID(string $name, string $url = '')
169 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
171 $tag = DBA::selectFirst('tag', ['id'], $fields);
172 if (DBA::isResult($tag)) {
176 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
177 $tid = DBA::lastInsertId();
182 Logger::error('No tag id created', $fields);
187 * Store tag/mention elements
189 * @param integer $uriid
190 * @param string $hash
191 * @param string $name
193 * @param boolean $probing
195 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
197 $type = self::getTypeForHash($hash);
198 if ($type == self::UNKNOWN) {
202 self::store($uriid, $type, $name, $url, $probing);
206 * Store tags and mentions from the body
208 * @param integer $uriid URI-Id
209 * @param string $body Body of the post
210 * @param string $tags Accepted tags
211 * @param boolean $probing Perform a probing for contacts, adding them if needed
213 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
215 if (is_null($tags)) {
216 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
219 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
221 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
225 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
227 foreach ($result as $tag) {
228 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
233 * Store raw tags (not encapsulated in links) from the body
234 * This function is needed in the intermediate phase.
235 * Later we can call item::setHashtags in advance to have all tags converted.
237 * @param integer $uriid URI-Id
238 * @param string $body Body of the post
240 public static function storeRawTagsFromBody(int $uriid, string $body)
242 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
244 $result = BBCode::getTags($body);
245 if (empty($result)) {
249 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
251 foreach ($result as $tag) {
252 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
255 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
260 * Checks for stored hashtags and mentions for the given post
262 * @param integer $uriid
265 public static function existsForPost(int $uriid)
267 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
273 * @param integer $uriid
274 * @param integer $type
275 * @param string $name
278 public static function remove(int $uriid, int $type, string $name, string $url = '')
280 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
281 if ($type == self::HASHTAG) {
282 $condition['name'] = $name;
285 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
286 if (!DBA::isResult($tag)) {
290 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
291 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
297 * @param integer $uriid
298 * @param string $hash
299 * @param string $name
302 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
304 $type = self::getTypeForHash($hash);
305 if ($type == self::UNKNOWN) {
309 self::remove($uriid, $type, $name, $url);
313 * Get the type for the given hash
315 * @param string $hash
316 * @return integer type
318 private static function getTypeForHash(string $hash)
320 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
321 return self::MENTION;
322 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
323 return self::EXCLUSIVE_MENTION;
324 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
325 return self::IMPLICIT_MENTION;
326 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
327 return self::HASHTAG;
329 return self::UNKNOWN;
334 * Create implicit mentions for a given post
336 * @param integer $uri_id
337 * @param integer $parent_uri_id
339 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
341 // Always mention the direct parent author
342 $parent = Item::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
343 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
345 if (DI::config()->get('system', 'disable_implicit_mentions')) {
349 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id]);
350 while ($tag = DBA::fetch($tags)) {
351 self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
357 * Retrieves the terms from the provided type(s) associated with the provided item ID.
359 * @param int $item_id
360 * @param int|array $type
364 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
366 $condition = ['uri-id' => $uri_id, 'type' => $type];
367 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
371 * Return a string with all tags and mentions
373 * @param integer $uri_id
375 * @return string tags and mentions
378 public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
381 $tags = self::getByURIId($uri_id, $type);
382 foreach ($tags as $tag) {
383 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
386 return implode(',', $tag_list);
390 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
391 * provided item's body with them.
395 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
396 * @throws \ImagickException
398 public static function populateFromItem(&$item)
404 'implicit_mentions' => [],
407 $searchpath = DI::baseUrl() . "/search?tag=";
409 $taglist = DBA::select('tag-view', ['type', 'name', 'url'],
410 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
411 while ($tag = DBA::fetch($taglist)) {
412 if ($tag['url'] == '') {
413 $tag['url'] = $searchpath . rawurlencode($tag['name']);
416 $orig_tag = $tag['url'];
418 $prefix = self::TAG_CHARACTER[$tag['type']];
419 switch($tag['type']) {
421 if ($orig_tag != $tag['url']) {
422 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
425 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
426 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
429 case self::EXCLUSIVE_MENTION:
430 $tag['url'] = Contact::magicLink($tag['url']);
431 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
432 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
434 case self::IMPLICIT_MENTION:
435 $return['implicit_mentions'][] = $prefix . $tag['name'];
439 DBA::close($taglist);
445 * Counts posts for given tag
447 * @param string $search
448 * @param integer $uid
449 * @return integer number of posts
451 public static function countByTag(string $search, int $uid = 0)
453 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $search, $uid];
454 $params = ['group_by' => ['uri-id']];
456 return DBA::count('tag-search-view', $condition, $params);
460 * Search posts for given tag
462 * @param string $search
463 * @param integer $uid
464 * @param integer $start
465 * @param integer $limit
466 * @param integer $last_uriid
467 * @return array with URI-ID
469 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
471 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $search, $uid];
473 if (!empty($last_uriid)) {
474 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
478 'order' => ['uri-id' => true],
479 'group_by' => ['uri-id'],
480 'limit' => [$start, $limit]
483 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
486 while ($tag = DBA::fetch($tags)) {
487 $uriids[] = $tag['uri-id'];
495 * Returns a list of the most frequent global hashtags over the given period
497 * @param int $period Period in hours to consider posts
498 * @param int $limit Number of returned tags
502 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
504 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
508 return self::setGlobalTrendingHashtags($period, $limit);
513 * Creates a list of the most frequent global hashtags over the given period
515 * @param int $period Period in hours to consider posts
516 * @param int $limit Number of returned tags
520 public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
522 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
523 FROM `tag-search-view`
524 WHERE `private` = ? AND `uid` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
525 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
526 Item::PUBLIC, 0, $period, $limit);
528 if (DBA::isResult($tagsStmt)) {
529 $tags = DBA::toArray($tagsStmt);
530 DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
538 * Returns a list of the most frequent local hashtags over the given period
540 * @param int $period Period in hours to consider posts
541 * @param int $limit Number of returned tags
545 public static function getLocalTrendingHashtags(int $period, $limit = 10)
547 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
551 return self::setLocalTrendingHashtags($period, $limit);
556 * Returns a list of the most frequent local hashtags over the given period
558 * @param int $period Period in hours to consider posts
559 * @param int $limit Number of returned tags
563 public static function setLocalTrendingHashtags(int $period, int $limit = 10)
565 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
566 FROM `tag-search-view`
567 WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
568 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
569 Item::PUBLIC, $period, $limit);
571 if (DBA::isResult($tagsStmt)) {
572 $tags = DBA::toArray($tagsStmt);
573 DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
581 * Check if the provided tag is of one of the provided term types.
584 * @param int ...$types
587 public static function isType($tag, ...$types)
590 foreach ($types as $type) {
591 if (array_key_exists($type, self::TAG_CHARACTER)) {
592 $tag_chars[] = self::TAG_CHARACTER[$type];
596 return Strings::startsWithChars($tag, $tag_chars);
600 * Fetch user who subscribed to the given tag
603 * @return array User list
605 private static function getUIDListByTag(string $tag)
608 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
609 while ($search = DBA::fetch($searches)) {
610 $uids[] = $search['uid'];
612 DBA::close($searches);
618 * Fetch user who subscribed to the tags of the given item
620 * @param integer $uri_id
621 * @return array User list
623 public static function getUIDListByURIId(int $uri_id)
626 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
628 foreach ($tags as $tag) {
629 $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
632 return array_unique($uids);