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