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