3 * @file include/items.php
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\Session;
13 use Friendica\Database\DBA;
15 use Friendica\Model\Item;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Feed;
18 use Friendica\Protocol\OStatus;
19 use Friendica\Util\Network;
20 use Friendica\Util\ParseUrl;
21 use Friendica\Util\Strings;
23 require_once __DIR__ . '/../mod/share.php';
25 function add_page_info_data(array $data, $no_photos = false)
27 Hook::callAll('page_info_data', $data);
29 if (empty($data['type'])) {
33 // It maybe is a rich content, but if it does have everything that a link has,
34 // then treat it that way
35 if (($data["type"] == "rich") && is_string($data["title"]) &&
36 is_string($data["text"]) && !empty($data["images"])) {
37 $data["type"] = "link";
40 $data["title"] = $data["title"] ?? '';
42 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
46 if ($no_photos && ($data["type"] == "photo")) {
50 // Escape some bad characters
51 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
52 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
54 $text = "[attachment type='".$data["type"]."'";
56 if (empty($data["text"])) {
57 $data["text"] = $data["title"];
60 if (empty($data["text"])) {
61 $data["text"] = $data["url"];
64 if (!empty($data["url"])) {
65 $text .= " url='".$data["url"]."'";
68 if (!empty($data["title"])) {
69 $text .= " title='".$data["title"]."'";
72 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
73 if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
74 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
75 // if the preview picture is larger than 500 pixels then show it in a larger mode
76 // But only, if the picture isn't higher than large (To prevent huge posts)
77 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
78 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
79 $text .= " image='".$preview."'";
81 $text .= " preview='".$preview."'";
85 $text .= "]".$data["text"]."[/attachment]";
88 if (isset($data["keywords"]) && count($data["keywords"])) {
90 foreach ($data["keywords"] as $keyword) {
91 /// @TODO make a positive list of allowed characters
92 $hashtag = str_replace([' ', '+', '/', '.', '#', '@', "'", '"', '’', '`', '(', ')', '„', '“'], '', $keyword);
93 $hashtags .= "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url] ";
97 return "\n".$text.$hashtags;
100 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
102 $data = ParseUrl::getSiteinfoCached($url, true);
105 $data["images"][0]["src"] = $photo;
108 Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
110 if (!$keywords && isset($data["keywords"])) {
111 unset($data["keywords"]);
114 if (($keyword_blacklist != "") && isset($data["keywords"])) {
115 $list = explode(", ", $keyword_blacklist);
117 foreach ($list as $keyword) {
118 $keyword = trim($keyword);
120 $index = array_search($keyword, $data["keywords"]);
121 if ($index !== false) {
122 unset($data["keywords"][$index]);
130 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
132 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
135 if (isset($data["keywords"]) && count($data["keywords"])) {
136 foreach ($data["keywords"] as $keyword) {
137 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
138 ["", "", "", "", "", ""], $keyword);
144 $tags .= "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
151 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
153 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
157 if (is_array($data)) {
158 $text = add_page_info_data($data, $no_photos);
164 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
166 Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
168 $URLSearchString = "^\[\]";
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);
174 // Adding these spaces is a quick hack due to my problems with regular expressions :)
175 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
178 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
181 // Convert urls without bbcode elements
182 if (!$matches && $texturl) {
183 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
185 // Yeah, a hack. I really hate regular expressions :)
187 $matches[1] = $matches[2];
192 $footer = add_page_info($matches[1], $no_photos);
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;
202 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
203 if (($removedlink == "") || strstr($body, $removedlink)) {
204 $body = $removedlink;
208 // Add the page information to the bottom
209 if (isset($footer) && (trim($footer) != "")) {
218 * consume_feed - process atom feed and update anything/everything we might need to update
220 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
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).
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
243 * @param array $importer
244 * @param array $contact
246 * @throws ImagickException
247 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249 function consume_feed($xml, array $importer, array $contact, &$hub)
251 if ($contact['network'] === Protocol::OSTATUS) {
252 Logger::log("Consume OStatus messages ", Logger::DEBUG);
253 OStatus::import($xml, $importer, $contact, $hub);
258 if ($contact['network'] === Protocol::FEED) {
259 Logger::log("Consume feeds", Logger::DEBUG);
260 Feed::import($xml, $importer, $contact);
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);
276 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
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.
283 if ($contact['network'] === Protocol::DIASPORA) {
287 // Without an importer we don't have a user id - so we quit
288 if (empty($importer)) {
292 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
294 // No user, no nickname, we quit
295 if (!DBA::isResult($user)) {
299 $push_url = DI::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
301 // Use a single verify token, even if multiple hubs
302 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
304 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
306 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
308 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
309 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
312 $postResult = Network::post($url, $params);
314 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
320 function drop_items(array $items)
324 if (!Session::isAuthenticated()) {
328 if (!empty($items)) {
329 foreach ($items as $item) {
330 $owner = Item::deleteForUser(['id' => $item], local_user());
332 if ($owner && !$uid) {
339 function drop_item($id, $return = '')
343 // locate item to be deleted
345 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
346 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
348 if (!DBA::isResult($item)) {
349 notice(L10n::t('Item not found.') . EOL);
350 DI::baseUrl()->redirect('network');
353 if ($item['deleted']) {
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'];
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());
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]];
379 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
381 '$message' => L10n::t('Do you really want to delete this item?'),
382 '$extra_inputs' => $inputs,
383 '$confirm' => L10n::t('Yes'),
384 '$confirm_url' => $query['base'],
385 '$confirm_name' => 'confirmed',
386 '$cancel' => L10n::t('Cancel'),
389 // Now check how the user responded to the confirmation query
390 if (!empty($_REQUEST['canceled'])) {
391 DI::baseUrl()->redirect('display/' . $item['guid']);
394 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
396 if (!empty($item['parent'])){
398 $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
402 Item::deleteForUser(['id' => $item['id']], local_user());
404 $return_url = hex2bin($return);
406 // removes update_* from return_url to ignore Ajax refresh
407 $return_url = str_replace("update_", "", $return_url);
409 // Check if delete a comment
411 // Return to parent guid
412 if (!empty($parentitem)) {
413 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
416 // In case something goes wrong
418 DI::baseUrl()->redirect('network');
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');
428 DI::baseUrl()->redirect($return_url);
433 notice(L10n::t('Permission denied.') . EOL);
434 DI::baseUrl()->redirect('display/' . $item['guid']);