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