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