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