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\DBA;
30 use Friendica\Util\Strings;
35 * This Model class handles tag table interactions.
36 * This tables stores relevant tags related to posts, like hashtags and mentions.
44 * An implicit mention is a mention in a comment body that is redundant with the threading information.
46 const IMPLICIT_MENTION = 8;
48 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
50 const EXCLUSIVE_MENTION = 9;
52 const TAG_CHARACTER = [
55 self::IMPLICIT_MENTION => '%',
56 self::EXCLUSIVE_MENTION => '!',
60 * Store tag/mention elements
62 * @param integer $uriid
63 * @param integer $type
66 * @param boolean $probing
68 public static function store(int $uriid, int $type, string $name, string $url = '', $probing = true)
70 if ($type == self::HASHTAG) {
71 // Remove some common "garbarge" from tags
72 $name = trim($name, "\x00..\x20\xFF#!@,;.:'/?!^°$%".'"');
74 $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
75 if (count($tags) > 1) {
76 foreach ($tags as $tag) {
77 self::store($uriid, $type, $tag, $url, $probing);
90 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
92 // No mention without a contact url
97 $condition = ['nurl' => Strings::normaliseLink($url), 'uid' => 0, 'deleted' => false];
98 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
99 if (DBA::isResult($contact)) {
100 $cid = $contact['id'];
101 Logger::info('Got id for contact url', ['cid' => $cid, 'url' => $url]);
105 $ssl_url = str_replace('http://', 'https://', $url);
106 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, 0];
107 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
108 if (DBA::isResult($contact)) {
109 $cid = $contact['id'];
110 Logger::info('Got id for contact alias', ['cid' => $cid, 'url' => $url]);
114 $cid = Contact::getIdForURL($url, 0, true);
115 Logger::info('Got id by probing', ['cid' => $cid, 'url' => $url]);
119 // The contact wasn't found in the system (most likely some dead account)
120 // We ensure that we only store a single entry by overwriting the previous name
121 Logger::info('Contact not found, updating tag', ['url' => $url, 'name' => $name]);
122 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
127 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
128 $url = strtolower($url);
133 $tagid = self::getID($name, $url);
139 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
141 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
142 $condition = $fields;
143 $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
144 if (DBA::exists('post-tag', $condition)) {
145 Logger::info('Tag already exists', $fields);
150 DBA::insert('post-tag', $fields, true);
152 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
156 * Get a tag id for a given tag name and url
158 * @param string $name
162 public static function getID(string $name, string $url = '')
164 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
166 $tag = DBA::selectFirst('tag', ['id'], $fields);
167 if (DBA::isResult($tag)) {
171 DBA::insert('tag', $fields, true);
172 $tid = DBA::lastInsertId();
177 Logger::error('No tag id created', $fields);
182 * Store tag/mention elements
184 * @param integer $uriid
185 * @param string $hash
186 * @param string $name
188 * @param boolean $probing
190 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
192 $type = self::getTypeForHash($hash);
193 if ($type == self::UNKNOWN) {
197 self::store($uriid, $type, $name, $url, $probing);
201 * Store tags and mentions from the body
203 * @param integer $uriid URI-Id
204 * @param string $body Body of the post
205 * @param string $tags Accepted tags
206 * @param boolean $probing Perform a probing for contacts, adding them if needed
208 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
210 if (is_null($tags)) {
211 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
214 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
216 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
220 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
222 foreach ($result as $tag) {
223 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
228 * Store raw tags (not encapsulated in links) from the body
229 * This function is needed in the intermediate phase.
230 * Later we can call item::setHashtags in advance to have all tags converted.
232 * @param integer $uriid URI-Id
233 * @param string $body Body of the post
235 public static function storeRawTagsFromBody(int $uriid, string $body)
237 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
239 $result = BBCode::getTags($body);
240 if (empty($result)) {
244 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
246 foreach ($result as $tag) {
247 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
250 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
255 * Checks for stored hashtags and mentions for the given post
257 * @param integer $uriid
260 public static function existsForPost(int $uriid)
262 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
268 * @param integer $uriid
269 * @param integer $type
270 * @param string $name
273 public static function remove(int $uriid, int $type, string $name, string $url = '')
275 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
276 if ($type == self::HASHTAG) {
277 $condition['name'] = $name;
280 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
281 if (!DBA::isResult($tag)) {
285 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
286 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
292 * @param integer $uriid
293 * @param string $hash
294 * @param string $name
297 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
299 $type = self::getTypeForHash($hash);
300 if ($type == self::UNKNOWN) {
304 self::remove($uriid, $type, $name, $url);
308 * Get the type for the given hash
310 * @param string $hash
311 * @return integer type
313 private static function getTypeForHash(string $hash)
315 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
316 return self::MENTION;
317 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
318 return self::EXCLUSIVE_MENTION;
319 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
320 return self::IMPLICIT_MENTION;
321 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
322 return self::HASHTAG;
324 return self::UNKNOWN;
329 * Create implicit mentions for a given post
331 * @param integer $uri_id
332 * @param integer $parent_uri_id
334 public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
336 if ($uri_id == $parent_uri_id) {
340 // Always mention the direct parent author
341 $parent = Item::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
342 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
344 if (DI::config()->get('system', 'disable_implicit_mentions')) {
348 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id]);
349 while ($tag = DBA::fetch($tags)) {
350 self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
355 * Retrieves the terms from the provided type(s) associated with the provided item ID.
357 * @param int $item_id
358 * @param int|array $type
362 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
364 $condition = ['uri-id' => $uri_id, 'type' => $type];
365 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
369 * Return a string with all tags and mentions
371 * @param integer $uri_id
372 * @return string tags and mentions
374 public static function getCSVByURIId(int $uri_id)
377 $tags = self::getByURIId($uri_id);
378 foreach ($tags as $tag) {
379 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
382 return implode(',', $tag_list);
386 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
387 * provided item's body with them.
391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
392 * @throws \ImagickException
394 public static function populateFromItem(&$item)
400 'implicit_mentions' => [],
403 $searchpath = DI::baseUrl() . "/search?tag=";
405 $taglist = DBA::select('tag-view', ['type', 'name', 'url'],
406 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
407 while ($tag = DBA::fetch($taglist)) {
408 if ($tag['url'] == '') {
409 $tag['url'] = $searchpath . rawurlencode($tag['name']);
412 $orig_tag = $tag['url'];
414 $prefix = self::TAG_CHARACTER[$tag['type']];
415 switch($tag['type']) {
417 if ($orig_tag != $tag['url']) {
418 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
421 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
422 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
425 case self::EXCLUSIVE_MENTION:
426 $tag['url'] = Contact::magicLink($tag['url']);
427 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
428 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
430 case self::IMPLICIT_MENTION:
431 $return['implicit_mentions'][] = $prefix . $tag['name'];
435 DBA::close($taglist);
441 * Search posts for given tag
443 * @param string $search
444 * @param integer $uid
445 * @param integer $start
446 * @param integer $limit
447 * @return array with URI-ID
449 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100)
451 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $search, $uid];
453 'order' => ['uri-id' => true],
454 'group_by' => ['uri-id'],
455 'limit' => [$start, $limit]
458 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
461 while ($tag = DBA::fetch($tags)) {
462 $uriids[] = $tag['uri-id'];
470 * Returns a list of the most frequent global hashtags over the given period
472 * @param int $period Period in hours to consider posts
476 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
478 $tags = DI::cache()->get('global_trending_tags');
481 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
482 FROM `tag-search-view`
483 WHERE `private` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
484 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
485 Item::PUBLIC, $period, $limit);
487 if (DBA::isResult($tagsStmt)) {
488 $tags = DBA::toArray($tagsStmt);
489 DI::cache()->set('global_trending_tags', $tags, Duration::HOUR);
497 * Returns a list of the most frequent local hashtags over the given period
499 * @param int $period Period in hours to consider posts
503 public static function getLocalTrendingHashtags(int $period, $limit = 10)
505 $tags = DI::cache()->get('local_trending_tags');
508 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
509 FROM `tag-search-view`
510 WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
511 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
512 Item::PUBLIC, $period, $limit);
514 if (DBA::isResult($tagsStmt)) {
515 $tags = DBA::toArray($tagsStmt);
516 DI::cache()->set('local_trending_tags', $tags, Duration::HOUR);
524 * Check if the provided tag is of one of the provided term types.
527 * @param int ...$types
530 public static function isType($tag, ...$types)
533 foreach ($types as $type) {
534 if (array_key_exists($type, self::TAG_CHARACTER)) {
535 $tag_chars[] = self::TAG_CHARACTER[$type];
539 return Strings::startsWith($tag, $tag_chars);