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\Core\Cache\Duration;
25 use Friendica\Core\Logger;
26 use Friendica\Database\DBA;
28 use Friendica\Util\Strings;
33 * This Model class handles term table interactions.
34 * This tables stores relevant terms related to posts, photos and searches, like hashtags, mentions and
35 * user-applied categories.
45 const SAVEDSEARCH = 6;
46 const CONVERSATION = 7;
48 * An implicit mention is a mention in a comment body that is redundant with the threading information.
50 const IMPLICIT_MENTION = 8;
52 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
54 const EXCLUSIVE_MENTION = 9;
56 const TAG_CHARACTER = [
59 self::IMPLICIT_MENTION => '%',
60 self::EXCLUSIVE_MENTION => '!',
63 const OBJECT_TYPE_POST = 1;
64 const OBJECT_TYPE_PHOTO = 2;
67 * Returns a list of the most frequent global hashtags over the given period
69 * @param int $period Period in hours to consider posts
73 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
75 $tags = DI::cache()->get('global_trending_tags');
78 $tagsStmt = DBA::p("SELECT t.`term`, COUNT(*) AS `score`
80 JOIN `item` i ON i.`id` = t.`oid` AND i.`uid` = t.`uid`
81 JOIN `thread` ON `thread`.`iid` = i.`id`
82 WHERE `thread`.`visible`
83 AND NOT `thread`.`deleted`
84 AND NOT `thread`.`moderated`
85 AND `thread`.`private` = ?
90 AND i.`received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
95 Term::OBJECT_TYPE_POST,
101 if (DBA::isResult($tagsStmt)) {
102 $tags = DBA::toArray($tagsStmt);
103 DI::cache()->set('global_trending_tags', $tags, Duration::HOUR);
111 * Returns a list of the most frequent local hashtags over the given period
113 * @param int $period Period in hours to consider posts
117 public static function getLocalTrendingHashtags(int $period, $limit = 10)
119 $tags = DI::cache()->get('local_trending_tags');
122 $tagsStmt = DBA::p("SELECT t.`term`, COUNT(*) AS `score`
124 JOIN `item` i ON i.`id` = t.`oid` AND i.`uid` = t.`uid`
125 JOIN `thread` ON `thread`.`iid` = i.`id`
126 WHERE `thread`.`visible`
127 AND NOT `thread`.`deleted`
128 AND NOT `thread`.`moderated`
129 AND `thread`.`private` = ?
131 AND `thread`.`origin`
135 AND i.`received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
137 ORDER BY `score` DESC
140 Term::OBJECT_TYPE_POST,
146 if (DBA::isResult($tagsStmt)) {
147 $tags = DBA::toArray($tagsStmt);
148 DI::cache()->set('local_trending_tags', $tags, Duration::HOUR);
156 * Generates the legacy item.tag field comma-separated BBCode string from an item ID.
157 * Includes only hashtags, implicit and explicit mentions.
159 * @param int $item_id
163 public static function tagTextFromItemId($item_id)
166 $tags = self::tagArrayFromItemId($item_id, [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]);
167 foreach ($tags as $tag) {
168 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
171 return implode(',', $tag_list);
175 * Retrieves the terms from the provided type(s) associated with the provided item ID.
177 * @param int $item_id
178 * @param int|array $type
182 public static function tagArrayFromItemId($item_id, $type = [self::HASHTAG, self::MENTION])
184 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type];
185 $tags = DBA::select('term', ['type', 'term', 'url'], $condition);
186 if (!DBA::isResult($tags)) {
190 return DBA::toArray($tags);
194 * Generates the legacy item.file field string from an item ID.
195 * Includes only file and category terms.
197 * @param int $item_id
201 public static function fileTextFromItemId($item_id)
204 $tags = self::tagArrayFromItemId($item_id, [self::FILE, self::CATEGORY]);
205 foreach ($tags as $tag) {
206 if ($tag['type'] == self::CATEGORY) {
207 $file_text .= '<' . $tag['term'] . '>';
209 $file_text .= '[' . $tag['term'] . ']';
217 * Inserts new terms for the provided item ID based on the legacy item.tag field BBCode content.
218 * Deletes all previous tag terms for the same item ID.
219 * Sets both the item.mention and thread.mentions field flags if a mention concerning the item UID is found.
221 * @param int $item_id
222 * @param string $tag_str
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225 public static function insertFromTagFieldByItemId($item_id, $tag_str)
227 $profile_base = DI::baseUrl();
228 $profile_data = parse_url($profile_base);
229 $profile_path = $profile_data['path'] ?? '';
230 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
231 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
233 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
234 $item = Item::selectFirst($fields, ['id' => $item_id]);
235 if (!DBA::isResult($item)) {
239 $item['tag'] = $tag_str;
242 self::deleteByItemId($item_id);
244 if ($item['deleted']) {
248 $taglist = explode(',', $item['tag']);
251 foreach ($taglist as $tag) {
252 if (Strings::startsWith($tag, self::TAG_CHARACTER)) {
253 $tags_string .= ' ' . trim($tag);
255 $tags_string .= ' #' . trim($tag);
259 $data = ' ' . $item['title'] . ' ' . $item['body'] . ' ' . $tags_string . ' ';
261 // ignore anything in a code block
262 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
266 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
267 if (preg_match_all($pattern, $data, $matches)) {
268 foreach ($matches[1] as $match) {
269 $tags['#' . $match] = '';
273 $pattern = '/\W([\#@!%])\[url\=(.*?)\](.*?)\[\/url\]/ism';
274 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
275 foreach ($matches as $match) {
277 if (in_array($match[1], [
278 self::TAG_CHARACTER[self::MENTION],
279 self::TAG_CHARACTER[self::IMPLICIT_MENTION],
280 self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]
282 $contact = Contact::getDetailsByURL($match[2], 0);
283 if (!empty($contact['addr'])) {
284 $match[3] = $contact['addr'];
287 if (!empty($contact['url'])) {
288 $match[2] = $contact['url'];
292 $tags[$match[2]] = $match[1] . trim($match[3], ',.:;[]/\"?!');
296 foreach ($tags as $link => $tag) {
297 if (self::isType($tag, self::HASHTAG)) {
298 // try to ignore #039 or #1 or anything like that
299 if (ctype_digit(substr(trim($tag), 1))) {
303 // try to ignore html hex escapes, e.g. #x2317
304 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
308 $type = self::HASHTAG;
309 $term = substr($tag, 1);
311 } elseif (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION)) {
312 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)) {
313 $type = self::MENTION;
315 $type = self::IMPLICIT_MENTION;
318 $contact = Contact::getDetailsByURL($link, 0);
319 if (!empty($contact['name'])) {
320 $term = $contact['name'];
322 $term = substr($tag, 1);
324 } else { // This shouldn't happen
325 $type = self::HASHTAG;
329 Logger::notice('Unknown term type', ['tag' => $tag]);
332 if (DBA::exists('term', ['uid' => $item['uid'], 'otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'term' => $term, 'type' => $type])) {
336 if ($item['uid'] == 0) {
338 DBA::update('term', ['global' => true], ['otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
340 $global = DBA::exists('term', ['uid' => 0, 'otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
343 DBA::insert('term', [
344 'uid' => $item['uid'],
346 'otype' => self::OBJECT_TYPE_POST,
350 'guid' => $item['guid'],
351 'created' => $item['created'],
352 'received' => $item['received'],
356 // Search for mentions
357 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)
359 strpos($link, $profile_base_friendica) !== false
360 || strpos($link, $profile_base_diaspora) !== false
363 $users_stmt = DBA::p("SELECT `uid` FROM `contact` WHERE self AND (`url` = ? OR `nurl` = ?)", $link, $link);
364 $users = DBA::toArray($users_stmt);
365 foreach ($users AS $user) {
366 if ($user['uid'] == $item['uid']) {
367 /// @todo This function is called from Item::update - so we mustn't call that function here
368 DBA::update('item', ['mention' => true], ['id' => $item_id]);
369 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
377 * Inserts new terms for the provided item ID based on the legacy item.file field BBCode content.
378 * Deletes all previous file terms for the same item ID.
380 * @param integer $item_id item id
385 public static function insertFromFileFieldByItemId($item_id, $files)
387 $message = Item::selectFirst(['uid', 'deleted'], ['id' => $item_id]);
388 if (!DBA::isResult($message)) {
393 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [self::FILE, self::CATEGORY]]);
395 if ($message["deleted"]) {
399 $message['file'] = $files;
401 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
402 foreach ($files[1] as $file) {
403 DBA::insert('term', [
404 'uid' => $message["uid"],
406 'otype' => self::OBJECT_TYPE_POST,
407 'type' => self::FILE,
413 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
414 foreach ($files[1] as $file) {
415 DBA::insert('term', [
416 'uid' => $message["uid"],
418 'otype' => self::OBJECT_TYPE_POST,
419 'type' => self::CATEGORY,
427 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
428 * provided item's body with them.
432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
433 * @throws \ImagickException
435 public static function populateTagsFromItem(&$item)
441 'implicit_mentions' => [],
444 $searchpath = DI::baseUrl() . "/search?tag=";
446 $taglist = DBA::select(
448 ['type', 'term', 'url'],
449 ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item['id'], 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]],
452 while ($tag = DBA::fetch($taglist)) {
453 if ($tag['url'] == '') {
454 $tag['url'] = $searchpath . rawurlencode($tag['term']);
457 $orig_tag = $tag['url'];
459 $prefix = self::TAG_CHARACTER[$tag['type']];
460 switch($tag['type']) {
462 if ($orig_tag != $tag['url']) {
463 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
466 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['term']) . '</a>';
467 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['term']) . '</a>';
470 $tag['url'] = Contact::magicLink($tag['url']);
471 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['term']) . '</a>';
472 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['term']) . '</a>';
474 case self::IMPLICIT_MENTION:
475 $return['implicit_mentions'][] = $prefix . $tag['term'];
479 DBA::close($taglist);
485 * Delete tags of the specific type(s) from an item
487 * @param int $item_id
488 * @param int|array $type
491 public static function deleteByItemId($item_id, $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION])
493 if (empty($item_id)) {
498 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type]);
502 * Check if the provided tag is of one of the provided term types.
505 * @param int ...$types
508 public static function isType($tag, ...$types)
511 foreach ($types as $type) {
512 if (array_key_exists($type, self::TAG_CHARACTER)) {
513 $tag_chars[] = self::TAG_CHARACTER[$type];
517 return Strings::startsWith($tag, $tag_chars);