]> git.mxchange.org Git - friendica.git/blob - src/Model/Term.php
Merge remote-tracking branch 'upstream/develop' into diasppora-delivery
[friendica.git] / src / Model / Term.php
1 <?php
2 /**
3  * @file src/Model/Term
4  */
5 namespace Friendica\Model;
6
7 use Friendica\Core\System;
8 use Friendica\Database\DBA;
9
10 require_once 'boot.php';
11 require_once 'include/conversation.php';
12 require_once 'include/dba.php';
13
14 class Term
15 {
16         public static function tagTextFromItemId($itemid)
17         {
18                 $tag_text = '';
19                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => [TERM_HASHTAG, TERM_MENTION]];
20                 $tags = DBA::select('term', [], $condition);
21                 while ($tag = DBA::fetch($tags)) {
22                         if ($tag_text != '') {
23                                 $tag_text .= ',';
24                         }
25
26                         if ($tag['type'] == 1) {
27                                 $tag_text .= '#';
28                         } else {
29                                 $tag_text .= '@';
30                         }
31                         $tag_text .= '[url=' . $tag['url'] . ']' . $tag['term'] . '[/url]';
32                 }
33                 return $tag_text;
34         }
35
36         public static function tagArrayFromItemId($itemid, $type = [TERM_HASHTAG, TERM_MENTION])
37         {
38                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => $type];
39                 $tags = DBA::select('term', ['type', 'term', 'url'], $condition);
40                 if (!DBA::isResult($tags)) {
41                         return [];
42                 }
43
44                 return DBA::toArray($tags);
45         }
46
47         public static function fileTextFromItemId($itemid)
48         {
49                 $file_text = '';
50                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => [TERM_FILE, TERM_CATEGORY]];
51                 $tags = DBA::select('term', [], $condition);
52                 while ($tag = DBA::fetch($tags)) {
53                         if ($tag['type'] == TERM_CATEGORY) {
54                                 $file_text .= '<' . $tag['term'] . '>';
55                         } else {
56                                 $file_text .= '[' . $tag['term'] . ']';
57                         }
58                 }
59                 return $file_text;
60         }
61
62         public static function insertFromTagFieldByItemId($itemid, $tags)
63         {
64                 $profile_base = System::baseUrl();
65                 $profile_data = parse_url($profile_base);
66                 $profile_path = defaults($profile_data, 'path', '');
67                 $profile_base_friendica = $profile_data['host'] . $profile_path . '/profile/';
68                 $profile_base_diaspora = $profile_data['host'] . $profile_path . '/u/';
69
70                 $fields = ['guid', 'uid', 'id', 'edited', 'deleted', 'created', 'received', 'title', 'body', 'parent'];
71                 $message = Item::selectFirst($fields, ['id' => $itemid]);
72                 if (!DBA::isResult($message)) {
73                         return;
74                 }
75
76                 $message['tag'] = $tags;
77
78                 // Clean up all tags
79                 self::deleteByItemId($itemid);
80
81                 if ($message['deleted']) {
82                         return;
83                 }
84
85                 $taglist = explode(',', $message['tag']);
86
87                 $tags_string = '';
88                 foreach ($taglist as $tag) {
89                         if ((substr(trim($tag), 0, 1) == '#') || (substr(trim($tag), 0, 1) == '@') || (substr(trim($tag), 0, 1) == '!')) {
90                                 $tags_string .= ' ' . trim($tag);
91                         } else {
92                                 $tags_string .= ' #' . trim($tag);
93                         }
94                 }
95
96                 $data = ' ' . $message['title'] . ' ' . $message['body'] . ' ' . $tags_string . ' ';
97
98                 // ignore anything in a code block
99                 $data = preg_replace('/\[code\](.*?)\[\/code\]/sm', '', $data);
100
101                 $tags = [];
102
103                 $pattern = '/\W\#([^\[].*?)[\s\'".,:;\?!\[\]\/]/ism';
104                 if (preg_match_all($pattern, $data, $matches)) {
105                         foreach ($matches[1] as $match) {
106                                 $tags['#' . $match] = '';
107                         }
108                 }
109
110                 $pattern = '/\W([\#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism';
111                 if (preg_match_all($pattern, $data, $matches, PREG_SET_ORDER)) {
112                         foreach ($matches as $match) {
113
114                                 if (($match[1] == '@') || ($match[1] == '!')) {
115                                         $contact = Contact::getDetailsByURL($match[2], 0);
116                                         if (!empty($contact['addr'])) {
117                                                 $match[3] = $contact['addr'];
118                                         }
119
120                                         if (!empty($contact['url'])) {
121                                                 $match[2] = $contact['url'];
122                                         }
123                                 }
124
125                                 $tags[$match[1] . trim($match[3], ',.:;[]/\"?!')] = $match[2];
126                         }
127                 }
128
129                 foreach ($tags as $tag => $link) {
130                         if (substr(trim($tag), 0, 1) == '#') {
131                                 // try to ignore #039 or #1 or anything like that
132                                 if (ctype_digit(substr(trim($tag), 1))) {
133                                         continue;
134                                 }
135
136                                 // try to ignore html hex escapes, e.g. #x2317
137                                 if ((substr(trim($tag), 1, 1) == 'x' || substr(trim($tag), 1, 1) == 'X') && ctype_digit(substr(trim($tag), 2))) {
138                                         continue;
139                                 }
140
141                                 $type = TERM_HASHTAG;
142                                 $term = substr($tag, 1);
143                         } elseif ((substr(trim($tag), 0, 1) == '@') || (substr(trim($tag), 0, 1) == '!')) {
144                                 $type = TERM_MENTION;
145
146                                 $contact = Contact::getDetailsByURL($link, 0);
147                                 if (!empty($contact['name'])) {
148                                         $term = $contact['name'];
149                                 } else {
150                                         $term = substr($tag, 1);
151                                 }
152                         } else { // This shouldn't happen
153                                 $type = TERM_HASHTAG;
154                                 $term = $tag;
155                         }
156
157                         if (DBA::exists('term', ['uid' => $message['uid'], 'otype' => TERM_OBJ_POST, 'oid' => $itemid, 'url' => $link])) {
158                                 continue;
159                         }
160
161                         if ($message['uid'] == 0) {
162                                 $global = true;
163                                 DBA::update('term', ['global' => true], ['otype' => TERM_OBJ_POST, 'guid' => $message['guid']]);
164                         } else {
165                                 $global = DBA::exists('term', ['uid' => 0, 'otype' => TERM_OBJ_POST, 'guid' => $message['guid']]);
166                         }
167
168                         DBA::insert('term', [
169                                 'uid'      => $message['uid'],
170                                 'oid'      => $itemid,
171                                 'otype'    => TERM_OBJ_POST,
172                                 'type'     => $type,
173                                 'term'     => $term,
174                                 'url'      => $link,
175                                 'guid'     => $message['guid'],
176                                 'created'  => $message['created'],
177                                 'received' => $message['received'],
178                                 'global'   => $global
179                         ]);
180
181                         // Search for mentions
182                         if (((substr($tag, 0, 1) == '@') || (substr($tag, 0, 1) == '!')) && (strpos($link, $profile_base_friendica) || strpos($link, $profile_base_diaspora))) {
183                                 $users = q("SELECT `uid` FROM `contact` WHERE self AND (`url` = '%s' OR `nurl` = '%s')", $link, $link);
184                                 foreach ($users AS $user) {
185                                         if ($user['uid'] == $message['uid']) {
186                                                 /// @todo This function is called frim Item::update - so we mustn't call that function here
187                                                 DBA::update('item', ['mention' => true], ['id' => $itemid]);
188                                                 DBA::update('thread', ['mention' => true], ['iid' => $message['parent']]);
189                                         }
190                                 }
191                         }
192                 }
193         }
194
195         /**
196          * @param integer $itemid item id
197          * @return void
198          */
199         public static function insertFromFileFieldByItemId($itemid, $files)
200         {
201                 $message = Item::selectFirst(['uid', 'deleted'], ['id' => $itemid]);
202                 if (!DBA::isResult($message)) {
203                         return;
204                 }
205
206                 // Clean up all tags
207                 DBA::delete('term', ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => [TERM_FILE, TERM_CATEGORY]]);
208
209                 if ($message["deleted"]) {
210                         return;
211                 }
212
213                 $message['file'] = $files;
214
215                 if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) {
216                         foreach ($files[1] as $file) {
217                                 DBA::insert('term', [
218                                         'uid' => $message["uid"],
219                                         'oid' => $itemid,
220                                         'otype' => TERM_OBJ_POST,
221                                         'type' => TERM_FILE,
222                                         'term' => $file
223                                 ]);
224                         }
225                 }
226
227                 if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) {
228                         foreach ($files[1] as $file) {
229                                 DBA::insert('term', [
230                                         'uid' => $message["uid"],
231                                         'oid' => $itemid,
232                                         'otype' => TERM_OBJ_POST,
233                                         'type' => TERM_CATEGORY,
234                                         'term' => $file
235                                 ]);
236                         }
237                 }
238         }
239
240         /**
241          * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
242          * provided item's body with them.
243          *
244          * @param array $item
245          * @return array
246          */
247         public static function populateTagsFromItem(&$item)
248         {
249                 $return = [
250                         'tags' => [],
251                         'hashtags' => [],
252                         'mentions' => [],
253                 ];
254
255                 $searchpath = System::baseUrl() . "/search?tag=";
256
257                 $taglist = DBA::select(
258                         'term',
259                         ['type', 'term', 'url'],
260                         ["`otype` = ? AND `oid` = ? AND `type` IN (?, ?)", TERM_OBJ_POST, $item['id'], TERM_HASHTAG, TERM_MENTION],
261                         ['order' => ['tid']]
262                 );
263
264                 while ($tag = DBA::fetch($taglist)) {
265                         if ($tag["url"] == "") {
266                                 $tag["url"] = $searchpath . $tag["term"];
267                         }
268
269                         $orig_tag = $tag["url"];
270
271                         $author = ['uid' => 0, 'id' => $item['author-id'],
272                                 'network' => $item['author-network'], 'url' => $item['author-link']];
273                         $tag["url"] = Contact::magicLinkByContact($author, $tag['url']);
274
275                         if ($tag["type"] == TERM_HASHTAG) {
276                                 if ($orig_tag != $tag["url"]) {
277                                         $item['body'] = str_replace($orig_tag, $tag["url"], $item['body']);
278                                 }
279
280                                 $return['hashtags'][] = "#<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
281                                 $prefix = "#";
282                         } elseif ($tag["type"] == TERM_MENTION) {
283                                 $return['mentions'][] = "@<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
284                                 $prefix = "@";
285                         }
286
287                         $return['tags'][] = $prefix . "<a href=\"" . $tag["url"] . "\" target=\"_blank\">" . $tag["term"] . "</a>";
288                 }
289                 DBA::close($taglist);
290
291                 return $return;
292         }
293
294         /**
295          * Delete all tags from an item
296          * @param int itemid - choose from which item the tags will be removed
297          * @param array type - items type. default is [TERM_HASHTAG, TERM_MENTION]
298          */
299         public static function deleteByItemId($itemid, $type = [TERM_HASHTAG, TERM_MENTION])
300         {
301                 if (empty($itemid)) {
302                         return;
303                 }
304
305                 // Clean up all tags
306                 DBA::delete('term', ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => $type]);
307
308         }
309 }