3 * @file src/Model/Term.php
5 namespace Friendica\Model;
7 use Friendica\Core\Logger;
8 use Friendica\Core\System;
9 use Friendica\Database\DBA;
10 use Friendica\Util\Strings;
15 * This Model class handles term table interactions.
16 * This tables stores relevant terms related to posts, photos and searches, like hashtags, mentions and
17 * user-applied categories.
19 * @package Friendica\Model
29 const SAVEDSEARCH = 6;
30 const CONVERSATION = 7;
32 * An implicit mention is a mention in a comment body that is redundant with the threading information.
34 const IMPLICIT_MENTION = 8;
36 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
38 const EXCLUSIVE_MENTION = 9;
40 const TAG_CHARACTER = [
43 self::IMPLICIT_MENTION => '%',
44 self::EXCLUSIVE_MENTION => '!',
47 const OBJECT_TYPE_POST = 1;
48 const OBJECT_TYPE_PHOTO = 2;
51 * Generates the legacy item.tag field comma-separated BBCode string from an item ID.
52 * Includes only hashtags, implicit and explicit mentions.
58 public static function tagTextFromItemId($item_id)
61 $tags = self::tagArrayFromItemId($item_id, [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]);
62 foreach ($tags as $tag) {
63 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
66 return implode(',', $tag_list);
70 * Retrieves the terms from the provided type(s) associated with the provided item ID.
73 * @param int|array $type
77 public static function tagArrayFromItemId($item_id, $type = [self::HASHTAG, self::MENTION])
79 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type];
80 $tags = DBA::select('term', ['type', 'term', 'url'], $condition);
81 if (!DBA::isResult($tags)) {
85 return DBA::toArray($tags);
89 * Generates the legacy item.file field string from an item ID.
90 * Includes only file and category terms.
96 public static function fileTextFromItemId($item_id)
99 $tags = self::tagArrayFromItemId($item_id, [self::FILE, self::CATEGORY]);
100 foreach ($tags as $tag) {
101 if ($tag['type'] == self::CATEGORY) {
102 $file_text .= '<' . $tag['term'] . '>';
104 $file_text .= '[' . $tag['term'] . ']';
112 * Inserts new terms for the provided item ID based on the legacy item.tag field BBCode content.
113 * Deletes all previous tag terms for the same item ID.
114 * Sets both the item.mention and thread.mentions field flags if a mention concerning the item UID is found.
116 * @param int $item_id
117 * @param string $tag_str
118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120 public static function insertFromTagFieldByItemId($item_id, $tag_str)
122 $profile_base = System::baseUrl();
123 $profile_data = parse_url($profile_base);
124 $profile_path = defaults($profile_data, 'path', '');
125 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
126 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
128 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
129 $item = Item::selectFirst($fields, ['id' => $item_id]);
130 if (!DBA::isResult($item)) {
134 $item['tag'] = $tag_str;
137 self::deleteByItemId($item_id);
139 if ($item['deleted']) {
143 $taglist = explode(',', $item['tag']);
146 foreach ($taglist as $tag) {
147 if (Strings::startsWith($tag, self::TAG_CHARACTER)) {
148 $tags_string .= ' ' . trim($tag);
150 $tags_string .= ' #' . trim($tag);
154 $data = ' ' . $item['title'] . ' ' . $item['body'] . ' ' . $tags_string . ' ';
156 // ignore anything in a code block
157 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
161 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
162 if (preg_match_all($pattern, $data, $matches)) {
163 foreach ($matches[1] as $match) {
164 $tags['#' . $match] = '';
168 $pattern = '/\W([\#@!%])\[url\=(.*?)\](.*?)\[\/url\]/ism';
169 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
170 foreach ($matches as $match) {
172 if (in_array($match[1], [
173 self::TAG_CHARACTER[self::MENTION],
174 self::TAG_CHARACTER[self::IMPLICIT_MENTION],
175 self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]
177 $contact = Contact::getDetailsByURL($match[2], 0);
178 if (!empty($contact['addr'])) {
179 $match[3] = $contact['addr'];
182 if (!empty($contact['url'])) {
183 $match[2] = $contact['url'];
187 $tags[$match[2]] = $match[1] . trim($match[3], ',.:;[]/\"?!');
191 foreach ($tags as $link => $tag) {
192 if (self::isType($tag, self::HASHTAG)) {
193 // try to ignore #039 or #1 or anything like that
194 if (ctype_digit(substr(trim($tag), 1))) {
198 // try to ignore html hex escapes, e.g. #x2317
199 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
203 $type = self::HASHTAG;
204 $term = substr($tag, 1);
206 } elseif (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION)) {
207 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)) {
208 $type = self::MENTION;
210 $type = self::IMPLICIT_MENTION;
213 $contact = Contact::getDetailsByURL($link, 0);
214 if (!empty($contact['name'])) {
215 $term = $contact['name'];
217 $term = substr($tag, 1);
219 } else { // This shouldn't happen
220 $type = self::HASHTAG;
224 Logger::notice('Unknown term type', ['tag' => $tag]);
227 if (DBA::exists('term', ['uid' => $item['uid'], 'otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'term' => $term, 'type' => $type])) {
231 if ($item['uid'] == 0) {
233 DBA::update('term', ['global' => true], ['otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
235 $global = DBA::exists('term', ['uid' => 0, 'otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
238 DBA::insert('term', [
239 'uid' => $item['uid'],
241 'otype' => self::OBJECT_TYPE_POST,
245 'guid' => $item['guid'],
246 'created' => $item['created'],
247 'received' => $item['received'],
251 // Search for mentions
252 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)
254 strpos($link, $profile_base_friendica) !== false
255 || strpos($link, $profile_base_diaspora) !== false
258 $users_stmt = DBA::p("SELECT `uid` FROM `contact` WHERE self AND (`url` = ? OR `nurl` = ?)", $link, $link);
259 $users = DBA::toArray($users_stmt);
260 foreach ($users AS $user) {
261 if ($user['uid'] == $item['uid']) {
262 /// @todo This function is called from Item::update - so we mustn't call that function here
263 DBA::update('item', ['mention' => true], ['id' => $item_id]);
264 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
272 * Inserts new terms for the provided item ID based on the legacy item.file field BBCode content.
273 * Deletes all previous file terms for the same item ID.
275 * @param integer $item_id item id
280 public static function insertFromFileFieldByItemId($item_id, $files)
282 $message = Item::selectFirst(['uid', 'deleted'], ['id' => $item_id]);
283 if (!DBA::isResult($message)) {
288 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [self::FILE, self::CATEGORY]]);
290 if ($message["deleted"]) {
294 $message['file'] = $files;
296 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
297 foreach ($files[1] as $file) {
298 DBA::insert('term', [
299 'uid' => $message["uid"],
301 'otype' => self::OBJECT_TYPE_POST,
302 'type' => self::FILE,
308 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
309 foreach ($files[1] as $file) {
310 DBA::insert('term', [
311 'uid' => $message["uid"],
313 'otype' => self::OBJECT_TYPE_POST,
314 'type' => self::CATEGORY,
322 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
323 * provided item's body with them.
327 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
328 * @throws \ImagickException
330 public static function populateTagsFromItem(&$item)
336 'implicit_mentions' => [],
339 $searchpath = System::baseUrl() . "/search?tag=";
341 $taglist = DBA::select(
343 ['type', 'term', 'url'],
344 ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item['id'], 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]],
347 while ($tag = DBA::fetch($taglist)) {
348 if ($tag['url'] == '') {
349 $tag['url'] = $searchpath . rawurlencode($tag['term']);
352 $orig_tag = $tag['url'];
354 $prefix = self::TAG_CHARACTER[$tag['type']];
355 switch($tag['type']) {
357 if ($orig_tag != $tag['url']) {
358 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
361 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
362 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
365 $tag['url'] = Contact::magicLink($tag['url']);
366 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
367 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
369 case self::IMPLICIT_MENTION:
370 $return['implicit_mentions'][] = $prefix . $tag['term'];
374 DBA::close($taglist);
380 * Delete tags of the specific type(s) from an item
382 * @param int $item_id
383 * @param int|array $type
386 public static function deleteByItemId($item_id, $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION])
388 if (empty($item_id)) {
393 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type]);
397 * Check if the provided tag is of one of the provided term types.
400 * @param int ...$types
403 public static function isType($tag, ...$types)
406 foreach ($types as $type) {
407 if (isset(self::TAG_CHARACTER[$type])) {
408 $tag_chars[] = self::TAG_CHARACTER[$type];
412 return Strings::startsWith($tag, $tag_chars);