5 namespace Friendica\Model;
7 use Friendica\Core\System;
8 use Friendica\Database\DBA;
9 use Friendica\Util\Strings;
19 const SAVEDSEARCH = 6;
20 const CONVERSATION = 7;
21 const IMPLICIT_MENTION = 8;
22 const EXCLUSIVE_MENTION = 9;
24 const TAG_CHARACTER = [
27 self::IMPLICIT_MENTION => '%',
28 self::EXCLUSIVE_MENTION => '!',
31 const OBJECT_TYPE_POST = 1;
32 const OBJECT_TYPE_PHOTO = 2;
35 * Generates the legacy item.tag field comma-separated BBCode string from an item ID.
36 * Includes only hashtags, implicit and explicit mentions.
42 public static function tagTextFromItemId($item_id)
45 $tags = self::tagArrayFromItemId($item_id, [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]);
46 foreach ($tags as $tag) {
47 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
50 return implode(',', $tag_list);
54 * Retrieves the terms from the provided type(s) associated with the provided item ID.
57 * @param int|array $type
61 public static function tagArrayFromItemId($item_id, $type = [self::HASHTAG, self::MENTION])
63 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type];
64 $tags = DBA::select('term', ['type', 'term', 'url'], $condition);
65 if (!DBA::isResult($tags)) {
69 return DBA::toArray($tags);
73 * Generates the legacy item.file field string from an item ID.
74 * Includes only file and category terms.
80 public static function fileTextFromItemId($item_id)
83 $tags = self::tagArrayFromItemId($item_id, [self::FILE, self::CATEGORY]);
84 foreach ($tags as $tag) {
85 if ($tag['type'] == self::CATEGORY) {
86 $file_text .= '<' . $tag['term'] . '>';
88 $file_text .= '[' . $tag['term'] . ']';
96 * Inserts new terms for the provided item ID based on the legacy item.tag field BBCode content.
97 * Deletes all previous tag terms for the same item ID.
98 * Sets both the item.mention and thread.mentions field flags if a mention concerning the item UID is found.
100 * @param int $item_id
101 * @param string $tag_str
102 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
104 public static function insertFromTagFieldByItemId($item_id, $tag_str)
106 $profile_base = System::baseUrl();
107 $profile_data = parse_url($profile_base);
108 $profile_path = defaults($profile_data, 'path', '');
109 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
110 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
112 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
113 $item = Item::selectFirst($fields, ['id' => $item_id]);
114 if (!DBA::isResult($item)) {
118 $item['tag'] = $tag_str;
121 self::deleteByItemId($item_id);
123 if ($item['deleted']) {
127 $taglist = explode(',', $item['tag']);
130 foreach ($taglist as $tag) {
131 if (Strings::startsWith($tag, self::TAG_CHARACTER)) {
132 $tags_string .= ' ' . trim($tag);
134 $tags_string .= ' #' . trim($tag);
138 $data = ' ' . $item['title'] . ' ' . $item['body'] . ' ' . $tags_string . ' ';
140 // ignore anything in a code block
141 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
145 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
146 if (preg_match_all($pattern, $data, $matches)) {
147 foreach ($matches[1] as $match) {
148 $tags['#' . $match] = '';
152 $pattern = '/\W([\#@!%])\[url\=(.*?)\](.*?)\[\/url\]/ism';
153 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
154 foreach ($matches as $match) {
156 if (in_array($match[1], [
157 self::TAG_CHARACTER[self::MENTION],
158 self::TAG_CHARACTER[self::IMPLICIT_MENTION],
159 self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]
161 $contact = Contact::getDetailsByURL($match[2], 0);
162 if (!empty($contact['addr'])) {
163 $match[3] = $contact['addr'];
166 if (!empty($contact['url'])) {
167 $match[2] = $contact['url'];
171 $tags[$match[2]] = $match[1] . trim($match[3], ',.:;[]/\"?!');
175 foreach ($tags as $link => $tag) {
176 if (self::isType($tag, self::HASHTAG)) {
177 // try to ignore #039 or #1 or anything like that
178 if (ctype_digit(substr(trim($tag), 1))) {
182 // try to ignore html hex escapes, e.g. #x2317
183 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
187 $type = self::HASHTAG;
188 $term = substr($tag, 1);
190 } elseif (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION)) {
191 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)) {
192 $type = self::MENTION;
194 $type = self::IMPLICIT_MENTION;
197 $contact = Contact::getDetailsByURL($link, 0);
198 if (!empty($contact['name'])) {
199 $term = $contact['name'];
201 $term = substr($tag, 1);
203 } else { // This shouldn't happen
204 $type = self::HASHTAG;
209 if (DBA::exists('term', ['uid' => $item['uid'], 'otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'term' => $term, 'type' => $type])) {
213 if ($item['uid'] == 0) {
215 DBA::update('term', ['global' => true], ['otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
217 $global = DBA::exists('term', ['uid' => 0, 'otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
220 DBA::insert('term', [
221 'uid' => $item['uid'],
223 'otype' => self::OBJECT_TYPE_POST,
227 'guid' => $item['guid'],
228 'created' => $item['created'],
229 'received' => $item['received'],
233 // Search for mentions
234 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)
236 strpos($link, $profile_base_friendica) !== false
237 || strpos($link, $profile_base_diaspora) !== false
240 $users_stmt = DBA::p("SELECT `uid` FROM `contact` WHERE self AND (`url` = ? OR `nurl` = ?)", $link, $link);
241 $users = DBA::toArray($users_stmt);
242 foreach ($users AS $user) {
243 if ($user['uid'] == $item['uid']) {
244 /// @todo This function is called from Item::update - so we mustn't call that function here
245 DBA::update('item', ['mention' => true], ['id' => $item_id]);
246 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
254 * Inserts new terms for the provided item ID based on the legacy item.file field BBCode content.
255 * Deletes all previous file terms for the same item ID.
257 * @param integer $item_id item id
262 public static function insertFromFileFieldByItemId($item_id, $files)
264 $message = Item::selectFirst(['uid', 'deleted'], ['id' => $item_id]);
265 if (!DBA::isResult($message)) {
270 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [self::FILE, self::CATEGORY]]);
272 if ($message["deleted"]) {
276 $message['file'] = $files;
278 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
279 foreach ($files[1] as $file) {
280 DBA::insert('term', [
281 'uid' => $message["uid"],
283 'otype' => self::OBJECT_TYPE_POST,
284 'type' => self::FILE,
290 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
291 foreach ($files[1] as $file) {
292 DBA::insert('term', [
293 'uid' => $message["uid"],
295 'otype' => self::OBJECT_TYPE_POST,
296 'type' => self::CATEGORY,
304 * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
305 * provided item's body with them.
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 public static function populateTagsFromItem(&$item)
318 'implicit_mentions' => [],
321 $searchpath = System::baseUrl() . "/search?tag=";
323 $taglist = DBA::select(
325 ['type', 'term', 'url'],
326 ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item['id'], 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]],
329 while ($tag = DBA::fetch($taglist)) {
330 if ($tag['url'] == '') {
331 $tag['url'] = $searchpath . rawurlencode($tag['term']);
334 $orig_tag = $tag['url'];
336 $prefix = self::TAG_CHARACTER[$tag['type']];
337 switch($tag['type']) {
339 if ($orig_tag != $tag['url']) {
340 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
343 $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
344 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
347 $tag['url'] = Contact::magicLink($tag['url']);
348 $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
349 $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
351 case self::IMPLICIT_MENTION:
352 $return['implicit_mentions'][] = $prefix . $tag['term'];
356 DBA::close($taglist);
362 * Delete tags of the specific type(s) from an item
364 * @param int $item_id
365 * @param int|array $type
368 public static function deleteByItemId($item_id, $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION])
370 if (empty($item_id)) {
375 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type]);
379 * Check if the provided tag is of one of the provided term types.
382 * @param int ...$types
385 public static function isType($tag, ...$types)
388 foreach ($types as $type) {
389 if (isset(self::TAG_CHARACTER[$type])) {
390 $tag_chars[] = self::TAG_CHARACTER[$type];
394 return Strings::startsWith($tag, $tag_chars);