Merge pull request #7266 from MrPetovan/bug/notices
[friendica.git/.git] / include / items.php
1 <?php
2 /**
3  * @file include/items.php
4  */
5
6 use Friendica\BaseObject;
7 use Friendica\Content\Feature;
8 use Friendica\Core\Config;
9 use Friendica\Core\Hook;
10 use Friendica\Core\L10n;
11 use Friendica\Core\Logger;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Item;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\Feed;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\ParseUrl;
24 use Friendica\Util\Strings;
25 use Friendica\Util\Temporal;
26
27 require_once __DIR__ . '/../mod/share.php';
28
29 function add_page_info_data(array $data, $no_photos = false)
30 {
31         Hook::callAll('page_info_data', $data);
32
33         if (empty($data['type'])) {
34                 return '';
35         }
36
37         // It maybe is a rich content, but if it does have everything that a link has,
38         // then treat it that way
39         if (($data["type"] == "rich") && is_string($data["title"]) &&
40                 is_string($data["text"]) && !empty($data["images"])) {
41                 $data["type"] = "link";
42         }
43
44         $data["title"] = defaults($data, "title", "");
45
46         if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
47                 return "";
48         }
49
50         if ($no_photos && ($data["type"] == "photo")) {
51                 return "";
52         }
53
54         // Escape some bad characters
55         $data["url"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
56         $data["title"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
57
58         $text = "[attachment type='".$data["type"]."'";
59
60         if (empty($data["text"])) {
61                 $data["text"] = $data["title"];
62         }
63
64         if (empty($data["text"])) {
65                 $data["text"] = $data["url"];
66         }
67
68         if (!empty($data["url"])) {
69                 $text .= " url='".$data["url"]."'";
70         }
71
72         if (!empty($data["title"])) {
73                 $text .= " title='".$data["title"]."'";
74         }
75
76         // Only embedd a picture link when it seems to be a valid picture ("width" is set)
77         if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
78                 $preview = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
79                 // if the preview picture is larger than 500 pixels then show it in a larger mode
80                 // But only, if the picture isn't higher than large (To prevent huge posts)
81                 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
82                         && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
83                         $text .= " image='".$preview."'";
84                 } else {
85                         $text .= " preview='".$preview."'";
86                 }
87         }
88
89         $text .= "]".$data["text"]."[/attachment]";
90
91         $hashtags = "";
92         if (isset($data["keywords"]) && count($data["keywords"])) {
93                 $hashtags = "\n";
94                 foreach ($data["keywords"] as $keyword) {
95                         /// @TODO make a positive list of allowed characters
96                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
97                                                 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
98                         $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url] ";
99                 }
100         }
101
102         return "\n".$text.$hashtags;
103 }
104
105 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
106 {
107         $data = ParseUrl::getSiteinfoCached($url, true);
108
109         if ($photo != "") {
110                 $data["images"][0]["src"] = $photo;
111         }
112
113         Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
114
115         if (!$keywords && isset($data["keywords"])) {
116                 unset($data["keywords"]);
117         }
118
119         if (($keyword_blacklist != "") && isset($data["keywords"])) {
120                 $list = explode(", ", $keyword_blacklist);
121
122                 foreach ($list as $keyword) {
123                         $keyword = trim($keyword);
124
125                         $index = array_search($keyword, $data["keywords"]);
126                         if ($index !== false) {
127                                 unset($data["keywords"][$index]);
128                         }
129                 }
130         }
131
132         return $data;
133 }
134
135 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
136 {
137         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
138
139         $tags = "";
140         if (isset($data["keywords"]) && count($data["keywords"])) {
141                 foreach ($data["keywords"] as $keyword) {
142                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
143                                 ["", "", "", "", "", ""], $keyword);
144
145                         if ($tags != "") {
146                                 $tags .= ", ";
147                         }
148
149                         $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
150                 }
151         }
152
153         return $tags;
154 }
155
156 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
157 {
158         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
159
160         $text = '';
161
162         if (is_array($data)) {
163                 $text = add_page_info_data($data, $no_photos);
164         }
165
166         return $text;
167 }
168
169 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
170 {
171         Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
172
173         $URLSearchString = "^\[\]";
174
175         // Fix for Mastodon where the mentions are in a different format
176         $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
177                 '$2[url=$1]$3[/url]', $body);
178
179         // Adding these spaces is a quick hack due to my problems with regular expressions :)
180         preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
181
182         if (!$matches) {
183                 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
184         }
185
186         // Convert urls without bbcode elements
187         if (!$matches && $texturl) {
188                 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
189
190                 // Yeah, a hack. I really hate regular expressions :)
191                 if ($matches) {
192                         $matches[1] = $matches[2];
193                 }
194         }
195
196         if ($matches) {
197                 $footer = add_page_info($matches[1], $no_photos);
198         }
199
200         // Remove the link from the body if the link is attached at the end of the post
201         if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
202                 $removedlink = trim(str_replace($matches[1], "", $body));
203                 if (($removedlink == "") || strstr($body, $removedlink)) {
204                         $body = $removedlink;
205                 }
206
207                 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
208                 if (($removedlink == "") || strstr($body, $removedlink)) {
209                         $body = $removedlink;
210                 }
211         }
212
213         // Add the page information to the bottom
214         if (isset($footer) && (trim($footer) != "")) {
215                 $body .= $footer;
216         }
217
218         return $body;
219 }
220
221 /**
222  *
223  * consume_feed - process atom feed and update anything/everything we might need to update
224  *
225  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
226  *
227  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
228  *             It is this person's stuff that is going to be updated.
229  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
230  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
231  *             have a contact record.
232  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
233  *        might not) try and subscribe to it.
234  * $datedir sorts in reverse order
235  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
236  *      imported prior to its children being seen in the stream unless we are certain
237  *      of how the feed is arranged/ordered.
238  * With $pass = 1, we only pull parent items out of the stream.
239  * With $pass = 2, we only pull children (comments/likes).
240  *
241  * So running this twice, first with pass 1 and then with pass 2 will do the right
242  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
243  * model where comments can have sub-threads. That would require some massive sorting
244  * to get all the feed items into a mostly linear ordering, and might still require
245  * recursion.
246  *
247  * @param       $xml
248  * @param array $importer
249  * @param array $contact
250  * @param       $hub
251  * @throws ImagickException
252  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253  */
254 function consume_feed($xml, array $importer, array $contact, &$hub)
255 {
256         if ($contact['network'] === Protocol::OSTATUS) {
257                 Logger::log("Consume OStatus messages ", Logger::DEBUG);
258                 OStatus::import($xml, $importer, $contact, $hub);
259
260                 return;
261         }
262
263         if ($contact['network'] === Protocol::FEED) {
264                 Logger::log("Consume feeds", Logger::DEBUG);
265                 Feed::import($xml, $importer, $contact, $hub);
266
267                 return;
268         }
269
270         if ($contact['network'] === Protocol::DFRN) {
271                 Logger::log("Consume DFRN messages", Logger::DEBUG);
272                 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
273                 if (!empty($dfrn_importer)) {
274                         Logger::log("Now import the DFRN feed");
275                         DFRN::import($xml, $dfrn_importer, true);
276                         return;
277                 }
278         }
279 }
280
281 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
282 {
283         /*
284          * Diaspora has different message-ids in feeds than they do
285          * through the direct Diaspora protocol. If we try and use
286          * the feed, we'll get duplicates. So don't.
287          */
288         if ($contact['network'] === Protocol::DIASPORA) {
289                 return;
290         }
291
292         // Without an importer we don't have a user id - so we quit
293         if (empty($importer)) {
294                 return;
295         }
296
297         $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
298
299         // No user, no nickname, we quit
300         if (!DBA::isResult($user)) {
301                 return;
302         }
303
304         $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
305
306         // Use a single verify token, even if multiple hubs
307         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
308
309         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
310
311         Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
312
313         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
314                 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
315         }
316
317         $postResult = Network::post($url, $params);
318
319         Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
320
321         return;
322
323 }
324
325 function drop_items(array $items)
326 {
327         $uid = 0;
328
329         if (!local_user() && !remote_user()) {
330                 return;
331         }
332
333         if (!empty($items)) {
334                 foreach ($items as $item) {
335                         $owner = Item::deleteForUser(['id' => $item], local_user());
336
337                         if ($owner && !$uid) {
338                                 $uid = $owner;
339                         }
340                 }
341         }
342 }
343
344 function drop_item($id, $return = '')
345 {
346         $a = BaseObject::getApp();
347
348         // locate item to be deleted
349
350         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
351         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
352
353         if (!DBA::isResult($item)) {
354                 notice(L10n::t('Item not found.') . EOL);
355                 $a->internalRedirect('network');
356         }
357
358         if ($item['deleted']) {
359                 return 0;
360         }
361
362         $contact_id = 0;
363
364         // check if logged in user is either the author or owner of this item
365
366         if (!empty($_SESSION['remote'])) {
367                 foreach ($_SESSION['remote'] as $visitor) {
368                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
369                                 $contact_id = $visitor['cid'];
370                                 break;
371                         }
372                 }
373         }
374
375         if ((local_user() == $item['uid']) || $contact_id) {
376                 // Check if we should do HTML-based delete confirmation
377                 if (!empty($_REQUEST['confirm'])) {
378                         // <form> can't take arguments in its "action" parameter
379                         // so add any arguments as hidden inputs
380                         $query = explode_querystring($a->query_string);
381                         $inputs = [];
382
383                         foreach ($query['args'] as $arg) {
384                                 if (strpos($arg, 'confirm=') === false) {
385                                         $arg_parts = explode('=', $arg);
386                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
387                                 }
388                         }
389
390                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
391                                 '$method' => 'get',
392                                 '$message' => L10n::t('Do you really want to delete this item?'),
393                                 '$extra_inputs' => $inputs,
394                                 '$confirm' => L10n::t('Yes'),
395                                 '$confirm_url' => $query['base'],
396                                 '$confirm_name' => 'confirmed',
397                                 '$cancel' => L10n::t('Cancel'),
398                         ]);
399                 }
400                 // Now check how the user responded to the confirmation query
401                 if (!empty($_REQUEST['canceled'])) {
402                         $a->internalRedirect('display/' . $item['guid']);
403                 }
404
405                 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
406                 $parentitem = null;
407                 if (!empty($item['parent'])){
408                         $fields = ['guid'];
409                         $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
410                 }
411
412                 // delete the item
413                 Item::deleteForUser(['id' => $item['id']], local_user());
414
415                 $return_url = hex2bin($return);
416
417                 // removes update_* from return_url to ignore Ajax refresh
418                 $return_url = str_replace("update_", "", $return_url);
419
420                 // Check if delete a comment
421                 if ($is_comment) {
422                         // Return to parent guid
423                         if (!empty($parentitem)) {
424                                 $a->internalRedirect('display/' . $parentitem['guid']);
425                                 //NOTREACHED
426                         }
427                         // In case something goes wrong
428                         else {
429                                 $a->internalRedirect('network');
430                                 //NOTREACHED
431                         }
432                 }
433                 else {
434                         // if unknown location or deleting top level post called from display
435                         if (empty($return_url) || strpos($return_url, 'display') !== false) {
436                                 $a->internalRedirect('network');
437                                 //NOTREACHED
438                         } else {
439                                 $a->internalRedirect($return_url);
440                                 //NOTREACHED
441                         }
442                 }
443         } else {
444                 notice(L10n::t('Permission denied.') . EOL);
445                 $a->internalRedirect('display/' . $item['guid']);
446                 //NOTREACHED
447         }
448 }