]> git.mxchange.org Git - friendica.git/blob - src/Model/Term.php
Fix PHPDoc comments project-wide
[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          * @param         $files
196          * @return void
197          * @throws \Exception
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          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
247          * @throws \ImagickException
248          */
249         public static function populateTagsFromItem(&$item)
250         {
251                 $return = [
252                         'tags' => [],
253                         'hashtags' => [],
254                         'mentions' => [],
255                 ];
256
257                 $searchpath = System::baseUrl() . "/search?tag=";
258
259                 $taglist = DBA::select(
260                         'term',
261                         ['type', 'term', 'url'],
262                         ["`otype` = ? AND `oid` = ? AND `type` IN (?, ?)", TERM_OBJ_POST, $item['id'], TERM_HASHTAG, TERM_MENTION],
263                         ['order' => ['tid']]
264                 );
265
266                 while ($tag = DBA::fetch($taglist)) {
267                         if ($tag['url'] == '') {
268                                 $tag['url'] = $searchpath . rawurlencode($tag['term']);
269                         }
270
271                         $orig_tag = $tag['url'];
272
273                         $author = ['uid' => 0, 'id' => $item['author-id'],
274                                 'network' => $item['author-network'], 'url' => $item['author-link']];
275                         $tag['url'] = Contact::magicLinkByContact($author, $tag['url']);
276
277                         if ($tag['type'] == TERM_HASHTAG) {
278                                 if ($orig_tag != $tag['url']) {
279                                         $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
280                                 }
281
282                                 $return['hashtags'][] = '#<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
283                                 $prefix = '#';
284                         } elseif ($tag['type'] == TERM_MENTION) {
285                                 $return['mentions'][] = '@<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
286                                 $prefix = '@';
287                         }
288
289                         $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank">' . $tag['term'] . '</a>';
290                 }
291                 DBA::close($taglist);
292
293                 return $return;
294         }
295
296         /**
297          * Delete all tags from an item
298          *
299          * @param int itemid - choose from which item the tags will be removed
300          * @param array $type
301          * @throws \Exception
302          */
303         public static function deleteByItemId($itemid, $type = [TERM_HASHTAG, TERM_MENTION])
304         {
305                 if (empty($itemid)) {
306                         return;
307                 }
308
309                 // Clean up all tags
310                 DBA::delete('term', ['otype' => TERM_OBJ_POST, 'oid' => $itemid, 'type' => $type]);
311
312         }
313 }