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