3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
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;
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;
37 require_once __DIR__ . '/../mod/share.php';
39 function add_page_info_data(array $data, $no_photos = false)
41 Hook::callAll('page_info_data', $data);
43 if (empty($data['type'])) {
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";
54 $data["title"] = $data["title"] ?? '';
56 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
60 if ($no_photos && ($data["type"] == "photo")) {
64 // Escape some bad characters
65 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
66 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
68 $text = "[attachment type='".$data["type"]."'";
70 if (empty($data["text"])) {
71 $data["text"] = $data["title"];
74 if (empty($data["text"])) {
75 $data["text"] = $data["url"];
78 if (!empty($data["url"])) {
79 $text .= " url='".$data["url"]."'";
82 if (!empty($data["title"])) {
83 $text .= " title='".$data["title"]."'";
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(["[", "]"], ["[", "]"], 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."'";
95 $text .= " preview='".$preview."'";
99 $text .= "]".$data["text"]."[/attachment]";
102 if (isset($data["keywords"]) && count($data["keywords"])) {
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] ";
111 return "\n".$text.$hashtags;
114 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
116 $data = ParseUrl::getSiteinfoCached($url, true);
119 $data["images"][0]["src"] = $photo;
122 Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
124 if (!$keywords && isset($data["keywords"])) {
125 unset($data["keywords"]);
128 if (($keyword_blacklist != "") && isset($data["keywords"])) {
129 $list = explode(", ", $keyword_blacklist);
131 foreach ($list as $keyword) {
132 $keyword = trim($keyword);
134 $index = array_search($keyword, $data["keywords"]);
135 if ($index !== false) {
136 unset($data["keywords"][$index]);
144 function get_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
146 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
147 if (empty($data["keywords"]) || !is_array($data["keywords"])) {
152 foreach ($data['keywords'] as $keyword) {
153 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
154 ["", "", "", "", "", ""], $keyword);
156 $taglist[] = $hashtag;
162 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
164 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
168 if (is_array($data)) {
169 $text = add_page_info_data($data, $no_photos);
175 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
177 Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
179 $URLSearchString = "^\[\]";
181 // Fix for Mastodon where the mentions are in a different format
182 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
183 '$2[url=$1]$3[/url]', $body);
185 // Adding these spaces is a quick hack due to my problems with regular expressions :)
186 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
189 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
192 // Convert urls without bbcode elements
193 if (!$matches && $texturl) {
194 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
196 // Yeah, a hack. I really hate regular expressions :)
198 $matches[1] = $matches[2];
203 $footer = add_page_info($matches[1], $no_photos);
206 // Remove the link from the body if the link is attached at the end of the post
207 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
208 $removedlink = trim(str_replace($matches[1], "", $body));
209 if (($removedlink == "") || strstr($body, $removedlink)) {
210 $body = $removedlink;
213 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
214 if (($removedlink == "") || strstr($body, $removedlink)) {
215 $body = $removedlink;
219 // Add the page information to the bottom
220 if (isset($footer) && (trim($footer) != "")) {
229 * consume_feed - process atom feed and update anything/everything we might need to update
231 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
233 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
234 * It is this person's stuff that is going to be updated.
235 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
236 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
237 * have a contact record.
238 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
239 * might not) try and subscribe to it.
240 * $datedir sorts in reverse order
241 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
242 * imported prior to its children being seen in the stream unless we are certain
243 * of how the feed is arranged/ordered.
244 * With $pass = 1, we only pull parent items out of the stream.
245 * With $pass = 2, we only pull children (comments/likes).
247 * So running this twice, first with pass 1 and then with pass 2 will do the right
248 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
249 * model where comments can have sub-threads. That would require some massive sorting
250 * to get all the feed items into a mostly linear ordering, and might still require
254 * @param array $importer
255 * @param array $contact
257 * @throws ImagickException
258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260 function consume_feed($xml, array $importer, array $contact, &$hub)
262 if ($contact['network'] === Protocol::OSTATUS) {
263 Logger::log("Consume OStatus messages ", Logger::DEBUG);
264 OStatus::import($xml, $importer, $contact, $hub);
269 if ($contact['network'] === Protocol::FEED) {
270 Logger::log("Consume feeds", Logger::DEBUG);
271 Feed::import($xml, $importer, $contact);
276 if ($contact['network'] === Protocol::DFRN) {
277 Logger::log("Consume DFRN messages", Logger::DEBUG);
278 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
279 if (!empty($dfrn_importer)) {
280 Logger::log("Now import the DFRN feed");
281 DFRN::import($xml, $dfrn_importer, true);
287 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
290 * Diaspora has different message-ids in feeds than they do
291 * through the direct Diaspora protocol. If we try and use
292 * the feed, we'll get duplicates. So don't.
294 if ($contact['network'] === Protocol::DIASPORA) {
298 // Without an importer we don't have a user id - so we quit
299 if (empty($importer)) {
303 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
305 // No user, no nickname, we quit
306 if (!DBA::isResult($user)) {
310 $push_url = DI::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
312 // Use a single verify token, even if multiple hubs
313 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
315 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
317 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
319 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
320 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
323 $postResult = Network::post($url, $params);
325 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
331 function drop_items(array $items)
335 if (!Session::isAuthenticated()) {
339 if (!empty($items)) {
340 foreach ($items as $item) {
341 $owner = Item::deleteForUser(['id' => $item], local_user());
343 if ($owner && !$uid) {
350 function drop_item($id, $return = '')
354 // locate item to be deleted
356 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
357 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
359 if (!DBA::isResult($item)) {
360 notice(DI::l10n()->t('Item not found.') . EOL);
361 DI::baseUrl()->redirect('network');
364 if ($item['deleted']) {
370 // check if logged in user is either the author or owner of this item
371 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
372 $contact_id = $item['contact-id'];
375 if ((local_user() == $item['uid']) || $contact_id) {
376 // Check if we should do HTML-based delete confirmation
377 if (!empty($_REQUEST['confirm'])) {
378 // <form> can't take arguments in its "action" parameter
379 // so add any arguments as hidden inputs
380 $query = explode_querystring(DI::args()->getQueryString());
383 foreach ($query['args'] as $arg) {
384 if (strpos($arg, 'confirm=') === false) {
385 $arg_parts = explode('=', $arg);
386 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
390 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
392 '$message' => DI::l10n()->t('Do you really want to delete this item?'),
393 '$extra_inputs' => $inputs,
394 '$confirm' => DI::l10n()->t('Yes'),
395 '$confirm_url' => $query['base'],
396 '$confirm_name' => 'confirmed',
397 '$cancel' => DI::l10n()->t('Cancel'),
400 // Now check how the user responded to the confirmation query
401 if (!empty($_REQUEST['canceled'])) {
402 DI::baseUrl()->redirect('display/' . $item['guid']);
405 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
407 if (!empty($item['parent'])){
409 $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
413 Item::deleteForUser(['id' => $item['id']], local_user());
415 $return_url = hex2bin($return);
417 // removes update_* from return_url to ignore Ajax refresh
418 $return_url = str_replace("update_", "", $return_url);
420 // Check if delete a comment
422 // Return to parent guid
423 if (!empty($parentitem)) {
424 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
427 // In case something goes wrong
429 DI::baseUrl()->redirect('network');
434 // if unknown location or deleting top level post called from display
435 if (empty($return_url) || strpos($return_url, 'display') !== false) {
436 DI::baseUrl()->redirect('network');
439 DI::baseUrl()->redirect($return_url);
444 notice(DI::l10n()->t('Permission denied.') . EOL);
445 DI::baseUrl()->redirect('display/' . $item['guid']);