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 * An implicit mention is a mention in a comment body that is redundant with the threading information.
47 const IMPLICIT_MENTION = 8;
49 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
51 const EXCLUSIVE_MENTION = 9;
53 const TAG_CHARACTER = [
56 self::IMPLICIT_MENTION => '%',
57 self::EXCLUSIVE_MENTION => '!',
60 const OBJECT_TYPE_POST = 1;
61 const OBJECT_TYPE_PHOTO = 2;
64 * Generates the legacy item.tag field comma-separated BBCode string from an item ID.
65 * Includes only hashtags, implicit and explicit mentions.
71 public static function tagTextFromItemId($item_id)
74 $tags = self::tagArrayFromItemId($item_id, [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]);
75 foreach ($tags as $tag) {
76 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
79 return implode(',', $tag_list);
83 * Retrieves the terms from the provided type(s) associated with the provided item ID.
86 * @param int|array $type
90 private static function tagArrayFromItemId($item_id, $type = [self::HASHTAG, self::MENTION])
92 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type];
93 $tags = DBA::select('term', ['type', 'term', 'url'], $condition);
94 if (!DBA::isResult($tags)) {
98 return DBA::toArray($tags);
102 * Generates the legacy item.file field string from an item ID.
103 * Includes only file and category terms.
105 * @param int $item_id
109 public static function fileTextFromItemId($item_id)
112 $tags = self::tagArrayFromItemId($item_id, [self::FILE, self::CATEGORY]);
113 foreach ($tags as $tag) {
114 if ($tag['type'] == self::CATEGORY) {
115 $file_text .= '<' . $tag['term'] . '>';
117 $file_text .= '[' . $tag['term'] . ']';
125 * Inserts new terms for the provided item ID based on the legacy item.tag field BBCode content.
126 * Deletes all previous tag terms for the same item ID.
127 * Sets both the item.mention and thread.mentions field flags if a mention concerning the item UID is found.
129 * @param int $item_id
130 * @param string $tag_str
131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
133 public static function insertFromTagFieldByItemId($item_id, $tag_str)
135 $profile_base = DI::baseUrl();
136 $profile_data = parse_url($profile_base);
137 $profile_path = $profile_data['path'] ?? '';
138 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
139 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
141 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
142 $item = Item::selectFirst($fields, ['id' => $item_id]);
143 if (!DBA::isResult($item)) {
147 $item['tag'] = $tag_str;
150 self::deleteByItemId($item_id);
152 if ($item['deleted']) {
156 $taglist = explode(',', $item['tag']);
159 foreach ($taglist as $tag) {
160 if (Strings::startsWith($tag, self::TAG_CHARACTER)) {
161 $tags_string .= ' ' . trim($tag);
163 $tags_string .= ' #' . trim($tag);
167 $data = ' ' . $item['title'] . ' ' . $item['body'] . ' ' . $tags_string . ' ';
169 // ignore anything in a code block
170 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
174 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
175 if (preg_match_all($pattern, $data, $matches)) {
176 foreach ($matches[1] as $match) {
177 $tags['#' . $match] = '';
181 $pattern = '/\W([\#@!%])\[url\=(.*?)\](.*?)\[\/url\]/ism';
182 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
183 foreach ($matches as $match) {
185 if (in_array($match[1], [
186 self::TAG_CHARACTER[self::MENTION],
187 self::TAG_CHARACTER[self::IMPLICIT_MENTION],
188 self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]
190 $contact = Contact::getDetailsByURL($match[2], 0);
191 if (!empty($contact['addr'])) {
192 $match[3] = $contact['addr'];
195 if (!empty($contact['url'])) {
196 $match[2] = $contact['url'];
200 $tags[$match[2]] = $match[1] . trim($match[3], ',.:;[]/\"?!');
204 foreach ($tags as $link => $tag) {
205 if (self::isType($tag, self::HASHTAG)) {
206 // try to ignore #039 or #1 or anything like that
207 if (ctype_digit(substr(trim($tag), 1))) {
211 // try to ignore html hex escapes, e.g. #x2317
212 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
216 $type = self::HASHTAG;
217 $term = substr($tag, 1);
219 } elseif (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION)) {
220 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)) {
221 $type = self::MENTION;
223 $type = self::IMPLICIT_MENTION;
226 $contact = Contact::getDetailsByURL($link, 0);
227 if (!empty($contact['name'])) {
228 $term = $contact['name'];
230 $term = substr($tag, 1);
232 } else { // This shouldn't happen
233 $type = self::HASHTAG;
237 Logger::notice('Unknown term type', ['tag' => $tag]);
240 if (DBA::exists('term', ['uid' => $item['uid'], 'otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'term' => $term, 'type' => $type])) {
248 if ($item['uid'] == 0) {
250 DBA::update('term', ['global' => true], ['otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
252 $global = DBA::exists('term', ['uid' => 0, 'otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
255 DBA::insert('term', [
256 'uid' => $item['uid'],
258 'otype' => self::OBJECT_TYPE_POST,
260 'term' => substr($term, 0, 255),
262 'guid' => $item['guid'],
263 'created' => $item['created'],
264 'received' => $item['received'],
268 // Search for mentions
269 if (self::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)
271 strpos($link, $profile_base_friendica) !== false
272 || strpos($link, $profile_base_diaspora) !== false
275 $users_stmt = DBA::p("SELECT `uid` FROM `contact` WHERE self AND (`url` = ? OR `nurl` = ?)", $link, $link);
276 $users = DBA::toArray($users_stmt);
277 foreach ($users AS $user) {
278 if ($user['uid'] == $item['uid']) {
279 /// @todo This function is called from Item::update - so we mustn't call that function here
280 DBA::update('item', ['mention' => true], ['id' => $item_id]);
281 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
289 * Inserts new terms for the provided item ID based on the legacy item.file field BBCode content.
290 * Deletes all previous file terms for the same item ID.
292 * @param integer $item_id item id
297 public static function insertFromFileFieldByItemId($item_id, $files)
299 $message = Item::selectFirst(['uid', 'deleted'], ['id' => $item_id]);
300 if (!DBA::isResult($message)) {
305 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [self::FILE, self::CATEGORY]]);
307 if ($message["deleted"]) {
311 $message['file'] = $files;
313 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
314 foreach ($files[1] as $file) {
315 DBA::insert('term', [
316 'uid' => $message["uid"],
318 'otype' => self::OBJECT_TYPE_POST,
319 'type' => self::FILE,
325 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
326 foreach ($files[1] as $file) {
327 DBA::insert('term', [
328 'uid' => $message["uid"],
330 'otype' => self::OBJECT_TYPE_POST,
331 'type' => self::CATEGORY,
339 * Delete tags of the specific type(s) from an item
341 * @param int $item_id
342 * @param int|array $type
345 public static function deleteByItemId($item_id, $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION])
347 if (empty($item_id)) {
352 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type]);
356 * Check if the provided tag is of one of the provided term types.
359 * @param int ...$types
362 public static function isType($tag, ...$types)
365 foreach ($types as $type) {
366 if (array_key_exists($type, self::TAG_CHARACTER)) {
367 $tag_chars[] = self::TAG_CHARACTER[$type];
371 return Strings::startsWith($tag, $tag_chars);