3 * @file src/Model/Term.php
5 namespace Friendica\Model;
7 use Friendica\Core\Cache\Cache;
8 use Friendica\Core\Logger;
9 use Friendica\Database\DBA;
11 use Friendica\Util\Strings;
16 * This Model class handles term table interactions.
17 * This tables stores relevant terms related to posts, photos and searches, like hashtags, mentions and
18 * user-applied categories.
20 * @package Friendica\Model
30 const SAVEDSEARCH = 6;
31 const CONVERSATION = 7;
33 * An implicit mention is a mention in a comment body that is redundant with the threading information.
35 const IMPLICIT_MENTION = 8;
37 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
39 const EXCLUSIVE_MENTION = 9;
41 const TAG_CHARACTER = [
44 self::IMPLICIT_MENTION => '%',
45 self::EXCLUSIVE_MENTION => '!',
48 const OBJECT_TYPE_POST = 1;
49 const OBJECT_TYPE_PHOTO = 2;
52 * Returns a list of the most frequent global hashtags over the given period
54 * @param int $period Period in hours to consider posts
58 public static function getGlobalTrendingHashtags(int $period, $limit = 10)
60 $tags = DI::cache()->get('global_trending_tags');
63 $tagsStmt = DBA::p("SELECT t.`term`, COUNT(*) AS `score`
65 JOIN `item` i ON i.`id` = t.`oid` AND i.`uid` = t.`uid`
66 JOIN `thread` ON `thread`.`iid` = i.`id`
67 WHERE `thread`.`visible`
68 AND NOT `thread`.`deleted`
69 AND NOT `thread`.`moderated`
70 AND NOT `thread`.`private`
75 AND i.`received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
79 Term::OBJECT_TYPE_POST,
85 if (DBA::isResult($tagsStmt)) {
86 $tags = DBA::toArray($tagsStmt);
87 DI::cache()->set('global_trending_tags', $tags, Cache::HOUR);
95 * Returns a list of the most frequent local hashtags over the given period
97 * @param int $period Period in hours to consider posts
101 public static function getLocalTrendingHashtags(int $period, $limit = 10)
103 $tags = DI::cache()->get('local_trending_tags');
106 $tagsStmt = DBA::p("SELECT t.`term`, COUNT(*) AS `score`
108 JOIN `item` i ON i.`id` = t.`oid` AND i.`uid` = t.`uid`
109 JOIN `thread` ON `thread`.`iid` = i.`id`
110 JOIN `user` ON `user`.`uid` = `thread`.`uid` AND NOT `user`.`hidewall`
111 WHERE `thread`.`visible`
112 AND NOT `thread`.`deleted`
113 AND NOT `thread`.`moderated`
114 AND NOT `thread`.`private`
116 AND `thread`.`origin`
120 AND i.`received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
122 ORDER BY `score` DESC
124 Term::OBJECT_TYPE_POST,
130 if (DBA::isResult($tagsStmt)) {
131 $tags = DBA::toArray($tagsStmt);
132 DI::cache()->set('local_trending_tags', $tags, Cache::HOUR);
140 * Generates the legacy item.tag field comma-separated BBCode string from an item ID.
141 * Includes only hashtags, implicit and explicit mentions.
143 * @param int $item_id
147 public static function tagTextFromItemId($item_id)
150 $tags = self::tagArrayFromItemId($item_id, [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]);
151 foreach ($tags as $tag) {
152 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
155 return implode(',', $tag_list);
159 * Retrieves the terms from the provided type(s) associated with the provided item ID.
161 * @param int $item_id
162 * @param int|array $type
166 public static function tagArrayFromItemId($item_id, $type = [self::HASHTAG, self::MENTION])
168 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type];
169 $tags = DBA::select('term', ['type', 'term', 'url'], $condition);
170 if (!DBA::isResult($tags)) {
174 return DBA::toArray($tags);
178 * Generates the legacy item.file field string from an item ID.
179 * Includes only file and category terms.
181 * @param int $item_id
185 public static function fileTextFromItemId($item_id)
188 $tags = self::tagArrayFromItemId($item_id, [self::FILE, self::CATEGORY]);
189 foreach ($tags as $tag) {
190 if ($tag['type'] == self::CATEGORY) {
191 $file_text .= '<' . $tag['term'] . '>';
193 $file_text .= '[' . $tag['term'] . ']';
201 * Inserts new terms for the provided item ID based on the legacy item.tag field BBCode content.
202 * Deletes all previous tag terms for the same item ID.
203 * Sets both the item.mention and thread.mentions field flags if a mention concerning the item UID is found.
205 * @param int $item_id
206 * @param string $tag_str
207 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
209 public static function insertFromTagFieldByItemId($item_id, $tag_str)
211 $profile_base = DI::baseUrl();
212 $profile_data = parse_url($profile_base);
213 $profile_path = $profile_data['path'] ?? '';
214 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
215 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
217 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
218 $item = Item::selectFirst($fields, ['id' => $item_id]);
219 if (!DBA::isResult($item)) {
223 $item['tag'] = $tag_str;
226 self::deleteByItemId($item_id);
228 if ($item['deleted']) {
232 $taglist = explode(',', $item['tag']);
235 foreach ($taglist as $tag) {
236 if (Strings::startsWith($tag, self::TAG_CHARACTER)) {
237 $tags_string .= ' ' . trim($tag);
239 $tags_string .= ' #' . trim($tag);
243 $data = ' ' . $item['title'] . ' ' . $item['body'] . ' ' . $tags_string . ' ';
245 // ignore anything in a code block
246 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
250 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
251 if (preg_match_all($pattern, $data, $matches)) {
252 foreach ($matches[1] as $match) {
253 $tags['#' . $match] = '';
257 $pattern = '/\W([\#@!%])\[url\=(.*?)\](.*?)\[\/url\]/ism';
258 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
259 foreach ($matches as $match) {
261 if (in_array($match[1], [
262 self::TAG_CHARACTER[self::MENTION],
263 self::TAG_CHARACTER[self::IMPLICIT_MENTION],
264 self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]
266 $contact = Contact::getDetailsByURL($match[2], 0);
267 if (!empty($contact['addr'])) {
268 $match[3] = $contact['addr'];
271 if (!empty($contact['url'])) {
272 $match[2] = $contact['url'];
276 $tags[$match[2]] = $match[1] . trim($match[3], ',.:;[]/\"?!');
280 foreach ($tags as $link => $tag) {
281 if (self::isType($tag, self::HASHTAG)) {
282 // try to ignore #039 or #1 or anything like that
283 if (ctype_digit(substr(trim($tag), 1))) {
287 // try to ignore html hex escapes, e.g. #x2317
288 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
292 $type = self::HASHTAG;
293 $term = substr($tag, 1);
295 } elseif (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION)) {
296 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)) {
297 $type = self::MENTION;
299 $type = self::IMPLICIT_MENTION;
302 $contact = Contact::getDetailsByURL($link, 0);
303 if (!empty($contact['name'])) {
304 $term = $contact['name'];
306 $term = substr($tag, 1);
308 } else { // This shouldn't happen
309 $type = self::HASHTAG;
313 Logger::notice('Unknown term type', ['tag' => $tag]);
316 if (DBA::exists('term', ['uid' => $item['uid'], 'otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'term' => $term, 'type' => $type])) {
320 if ($item['uid'] == 0) {
322 DBA::update('term', ['global' => true], ['otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
324 $global = DBA::exists('term', ['uid' => 0, 'otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
327 DBA::insert('term', [
328 'uid' => $item['uid'],
330 'otype' => self::OBJECT_TYPE_POST,
334 'guid' => $item['guid'],
335 'created' => $item['created'],
336 'received' => $item['received'],
340 // Search for mentions
341 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)
343 strpos($link, $profile_base_friendica) !== false
344 || strpos($link, $profile_base_diaspora) !== false
347 $users_stmt = DBA::p("SELECT `uid` FROM `contact` WHERE self AND (`url` = ? OR `nurl` = ?)", $link, $link);
348 $users = DBA::toArray($users_stmt);
349 foreach ($users AS $user) {
350 if ($user['uid'] == $item['uid']) {
351 /// @todo This function is called from Item::update - so we mustn't call that function here
352 DBA::update('item', ['mention' => true], ['id' => $item_id]);
353 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
361 * Inserts new terms for the provided item ID based on the legacy item.file field BBCode content.
362 * Deletes all previous file terms for the same item ID.
364 * @param integer $item_id item id
369 public static function insertFromFileFieldByItemId($item_id, $files)
371 $message = Item::selectFirst(['uid', 'deleted'], ['id' => $item_id]);
372 if (!DBA::isResult($message)) {
377 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [self::FILE, self::CATEGORY]]);
379 if ($message["deleted"]) {
383 $message['file'] = $files;
385 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
386 foreach ($files[1] as $file) {
387 DBA::insert('term', [
388 'uid' => $message["uid"],
390 'otype' => self::OBJECT_TYPE_POST,
391 'type' => self::FILE,
397 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
398 foreach ($files[1] as $file) {
399 DBA::insert('term', [
400 'uid' => $message["uid"],
402 'otype' => self::OBJECT_TYPE_POST,
403 'type' => self::CATEGORY,
411 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
412 * provided item's body with them.
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
417 * @throws \ImagickException
419 public static function populateTagsFromItem(&$item)
425 'implicit_mentions' => [],
428 $searchpath = DI::baseUrl() . "/search?tag=";
430 $taglist = DBA::select(
432 ['type', 'term', 'url'],
433 ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item['id'], 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]],
436 while ($tag = DBA::fetch($taglist)) {
437 if ($tag['url'] == '') {
438 $tag['url'] = $searchpath . rawurlencode($tag['term']);
441 $orig_tag = $tag['url'];
443 $prefix = self::TAG_CHARACTER[$tag['type']];
444 switch($tag['type']) {
446 if ($orig_tag != $tag['url']) {
447 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
450 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
451 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
454 $tag['url'] = Contact::magicLink($tag['url']);
455 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
456 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
458 case self::IMPLICIT_MENTION:
459 $return['implicit_mentions'][] = $prefix . $tag['term'];
463 DBA::close($taglist);
469 * Delete tags of the specific type(s) from an item
471 * @param int $item_id
472 * @param int|array $type
475 public static function deleteByItemId($item_id, $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION])
477 if (empty($item_id)) {
482 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type]);
486 * Check if the provided tag is of one of the provided term types.
489 * @param int ...$types
492 public static function isType($tag, ...$types)
495 foreach ($types as $type) {
496 if (array_key_exists($type, self::TAG_CHARACTER)) {
497 $tag_chars[] = self::TAG_CHARACTER[$type];
501 return Strings::startsWith($tag, $tag_chars);