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\System;
13 use Friendica\Core\Session;
14 use Friendica\Database\DBA;
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;
24 require_once __DIR__ . '/../mod/share.php';
26 function add_page_info_data(array $data, $no_photos = false)
28 Hook::callAll('page_info_data', $data);
30 if (empty($data['type'])) {
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";
41 $data["title"] = $data["title"] ?? '';
43 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
47 if ($no_photos && ($data["type"] == "photo")) {
51 // Escape some bad characters
52 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
53 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
55 $text = "[attachment type='".$data["type"]."'";
57 if (empty($data["text"])) {
58 $data["text"] = $data["title"];
61 if (empty($data["text"])) {
62 $data["text"] = $data["url"];
65 if (!empty($data["url"])) {
66 $text .= " url='".$data["url"]."'";
69 if (!empty($data["title"])) {
70 $text .= " title='".$data["title"]."'";
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(["[", "]"], ["[", "]"], 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."'";
82 $text .= " preview='".$preview."'";
86 $text .= "]".$data["text"]."[/attachment]";
89 if (isset($data["keywords"]) && count($data["keywords"])) {
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] ";
99 return "\n".$text.$hashtags;
102 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
104 $data = ParseUrl::getSiteinfoCached($url, true);
107 $data["images"][0]["src"] = $photo;
110 Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
112 if (!$keywords && isset($data["keywords"])) {
113 unset($data["keywords"]);
116 if (($keyword_blacklist != "") && isset($data["keywords"])) {
117 $list = explode(", ", $keyword_blacklist);
119 foreach ($list as $keyword) {
120 $keyword = trim($keyword);
122 $index = array_search($keyword, $data["keywords"]);
123 if ($index !== false) {
124 unset($data["keywords"][$index]);
132 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
134 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
137 if (isset($data["keywords"]) && count($data["keywords"])) {
138 foreach ($data["keywords"] as $keyword) {
139 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
140 ["", "", "", "", "", ""], $keyword);
146 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
153 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
155 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
159 if (is_array($data)) {
160 $text = add_page_info_data($data, $no_photos);
166 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
168 Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
170 $URLSearchString = "^\[\]";
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);
176 // Adding these spaces is a quick hack due to my problems with regular expressions :)
177 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
180 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
183 // Convert urls without bbcode elements
184 if (!$matches && $texturl) {
185 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
187 // Yeah, a hack. I really hate regular expressions :)
189 $matches[1] = $matches[2];
194 $footer = add_page_info($matches[1], $no_photos);
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;
204 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
205 if (($removedlink == "") || strstr($body, $removedlink)) {
206 $body = $removedlink;
210 // Add the page information to the bottom
211 if (isset($footer) && (trim($footer) != "")) {
220 * consume_feed - process atom feed and update anything/everything we might need to update
222 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
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).
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
245 * @param array $importer
246 * @param array $contact
248 * @throws ImagickException
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 function consume_feed($xml, array $importer, array $contact, &$hub)
253 if ($contact['network'] === Protocol::OSTATUS) {
254 Logger::log("Consume OStatus messages ", Logger::DEBUG);
255 OStatus::import($xml, $importer, $contact, $hub);
260 if ($contact['network'] === Protocol::FEED) {
261 Logger::log("Consume feeds", Logger::DEBUG);
262 Feed::import($xml, $importer, $contact, $hub);
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);
278 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
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.
285 if ($contact['network'] === Protocol::DIASPORA) {
289 // Without an importer we don't have a user id - so we quit
290 if (empty($importer)) {
294 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
296 // No user, no nickname, we quit
297 if (!DBA::isResult($user)) {
301 $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
303 // Use a single verify token, even if multiple hubs
304 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
306 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
308 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
310 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
311 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
314 $postResult = Network::post($url, $params);
316 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
322 function drop_items(array $items)
326 if (!Session::isAuthenticated()) {
330 if (!empty($items)) {
331 foreach ($items as $item) {
332 $owner = Item::deleteForUser(['id' => $item], local_user());
334 if ($owner && !$uid) {
341 function drop_item($id, $return = '')
345 // locate item to be deleted
347 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
348 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
350 if (!DBA::isResult($item)) {
351 notice(L10n::t('Item not found.') . EOL);
352 DI::baseUrl()->redirect('network');
355 if ($item['deleted']) {
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'];
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());
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]];
381 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
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'),
391 // Now check how the user responded to the confirmation query
392 if (!empty($_REQUEST['canceled'])) {
393 DI::baseUrl()->redirect('display/' . $item['guid']);
396 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
398 if (!empty($item['parent'])){
400 $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
404 Item::deleteForUser(['id' => $item['id']], local_user());
406 $return_url = hex2bin($return);
408 // removes update_* from return_url to ignore Ajax refresh
409 $return_url = str_replace("update_", "", $return_url);
411 // Check if delete a comment
413 // Return to parent guid
414 if (!empty($parentitem)) {
415 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
418 // In case something goes wrong
420 DI::baseUrl()->redirect('network');
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');
430 DI::baseUrl()->redirect($return_url);
435 notice(L10n::t('Permission denied.') . EOL);
436 DI::baseUrl()->redirect('display/' . $item['guid']);