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\Logger;
25 use Friendica\Database\DBA;
27 use Friendica\Util\Strings;
32 * This Model class handles term table interactions.
33 * This tables stores relevant terms related to posts, photos and searches, like hashtags, mentions and
34 * user-applied categories.
44 * An implicit mention is a mention in a comment body that is redundant with the threading information.
46 const IMPLICIT_MENTION = 8;
48 * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
50 const EXCLUSIVE_MENTION = 9;
52 const TAG_CHARACTER = [
55 self::IMPLICIT_MENTION => '%',
56 self::EXCLUSIVE_MENTION => '!',
59 const OBJECT_TYPE_POST = 1;
60 const OBJECT_TYPE_PHOTO = 2;
63 * Generates the legacy item.tag field comma-separated BBCode string from an item ID.
64 * Includes only hashtags, implicit and explicit mentions.
70 public static function tagTextFromItemId($item_id)
73 $tags = self::getByItemId($item_id, [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION]);
74 foreach ($tags as $tag) {
75 $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
78 return implode(',', $tag_list);
82 * Retrieves the terms from the provided type(s) associated with the provided item ID.
85 * @param int|array $type
89 private static function getByItemId($item_id, $type = [self::HASHTAG, self::MENTION])
91 $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type];
92 $tags = DBA::select('term', ['type', 'term', 'url'], $condition);
93 if (!DBA::isResult($tags)) {
97 return DBA::toArray($tags);
101 * Generates the legacy item.file field string from an item ID.
102 * Includes only file and category terms.
104 * @param int $item_id
108 public static function fileTextFromItemId($item_id)
111 $tags = self::getByItemId($item_id, [self::FILE, self::CATEGORY]);
112 foreach ($tags as $tag) {
113 if ($tag['type'] == self::CATEGORY) {
114 $file_text .= '<' . $tag['term'] . '>';
116 $file_text .= '[' . $tag['term'] . ']';
124 * Inserts new terms for the provided item ID based on the legacy item.tag field BBCode content.
125 * Deletes all previous tag terms for the same item ID.
126 * Sets both the item.mention and thread.mentions field flags if a mention concerning the item UID is found.
128 * @param int $item_id
129 * @param string $tag_str
130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
132 public static function insertFromTagFieldByItemId($item_id, $tag_str)
134 $profile_base = DI::baseUrl();
135 $profile_data = parse_url($profile_base);
136 $profile_path = $profile_data['path'] ?? '';
137 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
138 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
140 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
141 $item = Item::selectFirst($fields, ['id' => $item_id]);
142 if (!DBA::isResult($item)) {
146 $item['tag'] = $tag_str;
149 self::deleteByItemId($item_id);
151 if ($item['deleted']) {
155 $taglist = explode(',', $item['tag']);
158 foreach ($taglist as $tag) {
159 if (Strings::startsWith($tag, self::TAG_CHARACTER)) {
160 $tags_string .= ' ' . trim($tag);
162 $tags_string .= ' #' . trim($tag);
166 $data = ' ' . $item['title'] . ' ' . $item['body'] . ' ' . $tags_string . ' ';
168 // ignore anything in a code block
169 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
173 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
174 if (preg_match_all($pattern, $data, $matches)) {
175 foreach ($matches[1] as $match) {
176 $tags['#' . $match] = '';
180 $pattern = '/\W([\#@!%])\[url\=(.*?)\](.*?)\[\/url\]/ism';
181 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
182 foreach ($matches as $match) {
184 if (in_array($match[1], [
185 self::TAG_CHARACTER[self::MENTION],
186 self::TAG_CHARACTER[self::IMPLICIT_MENTION],
187 self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]
189 $contact = Contact::getDetailsByURL($match[2], 0);
190 if (!empty($contact['addr'])) {
191 $match[3] = $contact['addr'];
194 if (!empty($contact['url'])) {
195 $match[2] = $contact['url'];
199 $tags[$match[2]] = $match[1] . trim($match[3], ',.:;[]/\"?!');
203 foreach ($tags as $link => $tag) {
204 if (Tag::isType($tag, self::HASHTAG)) {
205 // try to ignore #039 or #1 or anything like that
206 if (ctype_digit(substr(trim($tag), 1))) {
210 // try to ignore html hex escapes, e.g. #x2317
211 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
215 $type = self::HASHTAG;
216 $term = substr($tag, 1);
218 } elseif (Tag::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION)) {
219 if (Tag::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)) {
220 $type = self::MENTION;
222 $type = self::IMPLICIT_MENTION;
225 $contact = Contact::getDetailsByURL($link, 0);
226 if (!empty($contact['name'])) {
227 $term = $contact['name'];
229 $term = substr($tag, 1);
231 } else { // This shouldn't happen
232 $type = self::HASHTAG;
236 Logger::notice('Unknown term type', ['tag' => $tag]);
239 if (DBA::exists('term', ['uid' => $item['uid'], 'otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'term' => $term, 'type' => $type])) {
247 if ($item['uid'] == 0) {
249 DBA::update('term', ['global' => true], ['otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
251 $global = DBA::exists('term', ['uid' => 0, 'otype' => self::OBJECT_TYPE_POST, 'guid' => $item['guid']]);
254 DBA::insert('term', [
255 'uid' => $item['uid'],
257 'otype' => self::OBJECT_TYPE_POST,
259 'term' => substr($term, 0, 255),
261 'guid' => $item['guid'],
262 'created' => $item['created'],
263 'received' => $item['received'],
267 // Search for mentions
268 if (Tag::isType($tag, self::MENTION, self::EXCLUSIVE_MENTION)
270 strpos($link, $profile_base_friendica) !== false
271 || strpos($link, $profile_base_diaspora) !== false
274 $users_stmt = DBA::p("SELECT `uid` FROM `contact` WHERE self AND (`url` = ? OR `nurl` = ?)", $link, $link);
275 $users = DBA::toArray($users_stmt);
276 foreach ($users AS $user) {
277 if ($user['uid'] == $item['uid']) {
278 /// @todo This function is called from Item::update - so we mustn't call that function here
279 DBA::update('item', ['mention' => true], ['id' => $item_id]);
280 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
288 * Inserts new terms for the provided item ID based on the legacy item.file field BBCode content.
289 * Deletes all previous file terms for the same item ID.
291 * @param integer $item_id item id
296 public static function insertFromFileFieldByItemId($item_id, $files)
298 $message = Item::selectFirst(['uid', 'deleted'], ['id' => $item_id]);
299 if (!DBA::isResult($message)) {
304 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [self::FILE, self::CATEGORY]]);
306 if ($message["deleted"]) {
310 $message['file'] = $files;
312 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
313 foreach ($files[1] as $file) {
314 DBA::insert('term', [
315 'uid' => $message["uid"],
317 'otype' => self::OBJECT_TYPE_POST,
318 'type' => self::FILE,
324 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
325 foreach ($files[1] as $file) {
326 DBA::insert('term', [
327 'uid' => $message["uid"],
329 'otype' => self::OBJECT_TYPE_POST,
330 'type' => self::CATEGORY,
338 * Delete tags of the specific type(s) from an item
340 * @param int $item_id
341 * @param int|array $type
344 public static function deleteByItemId($item_id, $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION])
346 if (empty($item_id)) {
351 DBA::delete('term', ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => $type]);