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 $fields = ['name' => substr($name, 0, 96), 'url' => ''];
129 if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
130 $fields['url'] = strtolower($url);
133 $tag = DBA::selectFirst('tag', ['id'], $fields);
134 if (!DBA::isResult($tag)) {
135 DBA::insert('tag', $fields, true);
136 $tagid = DBA::lastInsertId();
142 Logger::error('No tag id created', $fields);
147 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
149 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
150 $condition = $fields;
151 $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
152 if (DBA::exists('post-tag', $condition)) {
153 Logger::info('Tag already exists', $fields);
158 DBA::insert('post-tag', $fields, true);
160 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
164 * Store tag/mention elements
166 * @param integer $uriid
167 * @param string $hash
168 * @param string $name
170 * @param boolean $probing
172 public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
174 $type = self::getTypeForHash($hash);
175 if ($type == self::UNKNOWN) {
179 self::store($uriid, $type, $name, $url, $probing);
183 * Store tags and mentions from the body
185 * @param integer $uriid URI-Id
186 * @param string $body Body of the post
187 * @param string $tags Accepted tags
188 * @param boolean $probing Perform a probing for contacts, adding them if needed
190 public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
192 if (is_null($tags)) {
193 $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
196 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
198 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
202 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
204 foreach ($result as $tag) {
205 self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
210 * Store raw tags (not encapsulated in links) from the body
211 * This function is needed in the intermediate phase.
212 * Later we can call item::setHashtags in advance to have all tags converted.
214 * @param integer $uriid URI-Id
215 * @param string $body Body of the post
217 public static function storeRawTagsFromBody(int $uriid, string $body)
219 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
221 $result = BBCode::getTags($body);
222 if (empty($result)) {
226 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
228 foreach ($result as $tag) {
229 if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
232 self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
237 * Checks for stored hashtags and mentions for the given post
239 * @param integer $uriid
242 public static function existsForPost(int $uriid)
244 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
250 * @param integer $uriid
251 * @param integer $type
252 * @param string $name
255 public static function remove(int $uriid, int $type, string $name, string $url = '')
257 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
258 if ($type == self::HASHTAG) {
259 $condition['name'] = $name;
262 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
263 if (!DBA::isResult($tag)) {
267 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
268 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
274 * @param integer $uriid
275 * @param string $hash
276 * @param string $name
279 public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
281 $type = self::getTypeForHash($hash);
282 if ($type == self::UNKNOWN) {
286 self::remove($uriid, $type, $name, $url);
290 * Get the type for the given hash
292 * @param string $hash
293 * @return integer type
295 private static function getTypeForHash(string $hash)
297 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
298 return self::MENTION;
299 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
300 return self::EXCLUSIVE_MENTION;
301 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
302 return self::IMPLICIT_MENTION;
303 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
304 return self::HASHTAG;
306 return self::UNKNOWN;
311 * Retrieves the terms from the provided type(s) associated with the provided item ID.
313 * @param int $item_id
314 * @param int|array $type
318 public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
320 $condition = ['uri-id' => $uri_id, 'type' => $type];
321 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
325 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
326 * provided item's body with them.
330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 public static function populateFromItem(&$item)
339 'implicit_mentions' => [],
342 $searchpath = DI::baseUrl() . "/search?tag=";
344 $taglist = DBA::select('tag-view', ['type', 'name', 'url'],
345 ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
346 while ($tag = DBA::fetch($taglist)) {
347 if ($tag['url'] == '') {
348 $tag['url'] = $searchpath . rawurlencode($tag['name']);
351 $orig_tag = $tag['url'];
353 $prefix = self::TAG_CHARACTER[$tag['type']];
354 switch($tag['type']) {
356 if ($orig_tag != $tag['url']) {
357 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
360 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
361 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
364 case self::EXCLUSIVE_MENTION:
365 $tag['url'] = Contact::magicLink($tag['url']);
366 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
367 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
369 case self::IMPLICIT_MENTION:
370 $return['implicit_mentions'][] = $prefix . $tag['name'];
374 DBA::close($taglist);
380 * Search posts for given tag
382 * @param string $search
383 * @param integer $uid
384 * @param integer $start
385 * @param integer $limit
386 * @return array with URI-ID
388 public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100)
390 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $search, $uid];
392 'order' => ['uri-id' => true],
393 'group_by' => ['uri-id'],
394 'limit' => [$start, $limit]
397 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
400 while ($tag = DBA::fetch($tags)) {
401 $uriids[] = $tag['uri-id'];
409 * Returns a list of the most frequent global hashtags over the given period
411 * @param int $period Period in hours to consider posts
415 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
417 $tags = DI::cache()->get('global_trending_tags');
420 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
421 FROM `tag-search-view`
422 WHERE `private` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
423 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
424 Item::PUBLIC, $period, $limit);
426 if (DBA::isResult($tagsStmt)) {
427 $tags = DBA::toArray($tagsStmt);
428 DI::cache()->set('global_trending_tags', $tags, Duration::HOUR);
436 * Returns a list of the most frequent local hashtags over the given period
438 * @param int $period Period in hours to consider posts
442 public static function getLocalTrendingHashtags(int $period, $limit = 10)
444 $tags = DI::cache()->get('local_trending_tags');
447 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
448 FROM `tag-search-view`
449 WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
450 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
451 Item::PUBLIC, $period, $limit);
453 if (DBA::isResult($tagsStmt)) {
454 $tags = DBA::toArray($tagsStmt);
455 DI::cache()->set('local_trending_tags', $tags, Duration::HOUR);
463 * Check if the provided tag is of one of the provided term types.
466 * @param int ...$types
469 public static function isType($tag, ...$types)
472 foreach ($types as $type) {
473 if (array_key_exists($type, self::TAG_CHARACTER)) {
474 $tag_chars[] = self::TAG_CHARACTER[$type];
478 return Strings::startsWith($tag, $tag_chars);