3 * @file include/items.php
6 use Friendica\Core\Hook;
7 use Friendica\Core\Logger;
8 use Friendica\Core\Protocol;
9 use Friendica\Core\Renderer;
10 use Friendica\Core\Session;
11 use Friendica\Database\DBA;
13 use Friendica\Model\Item;
14 use Friendica\Protocol\DFRN;
15 use Friendica\Protocol\Feed;
16 use Friendica\Protocol\OStatus;
17 use Friendica\Util\Network;
18 use Friendica\Util\ParseUrl;
19 use Friendica\Util\Strings;
21 require_once __DIR__ . '/../mod/share.php';
23 function add_page_info_data(array $data, $no_photos = false)
25 Hook::callAll('page_info_data', $data);
27 if (empty($data['type'])) {
31 // It maybe is a rich content, but if it does have everything that a link has,
32 // then treat it that way
33 if (($data["type"] == "rich") && is_string($data["title"]) &&
34 is_string($data["text"]) && !empty($data["images"])) {
35 $data["type"] = "link";
38 $data["title"] = $data["title"] ?? '';
40 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
44 if ($no_photos && ($data["type"] == "photo")) {
48 // Escape some bad characters
49 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
50 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
52 $text = "[attachment type='".$data["type"]."'";
54 if (empty($data["text"])) {
55 $data["text"] = $data["title"];
58 if (empty($data["text"])) {
59 $data["text"] = $data["url"];
62 if (!empty($data["url"])) {
63 $text .= " url='".$data["url"]."'";
66 if (!empty($data["title"])) {
67 $text .= " title='".$data["title"]."'";
70 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
71 if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
72 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
73 // if the preview picture is larger than 500 pixels then show it in a larger mode
74 // But only, if the picture isn't higher than large (To prevent huge posts)
75 if (!DI::config()->get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
76 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
77 $text .= " image='".$preview."'";
79 $text .= " preview='".$preview."'";
83 $text .= "]".$data["text"]."[/attachment]";
86 if (isset($data["keywords"]) && count($data["keywords"])) {
88 foreach ($data["keywords"] as $keyword) {
89 /// @TODO make a positive list of allowed characters
90 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
91 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
92 $hashtags .= "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url] ";
96 return "\n".$text.$hashtags;
99 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
101 $data = ParseUrl::getSiteinfoCached($url, true);
104 $data["images"][0]["src"] = $photo;
107 Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
109 if (!$keywords && isset($data["keywords"])) {
110 unset($data["keywords"]);
113 if (($keyword_blacklist != "") && isset($data["keywords"])) {
114 $list = explode(", ", $keyword_blacklist);
116 foreach ($list as $keyword) {
117 $keyword = trim($keyword);
119 $index = array_search($keyword, $data["keywords"]);
120 if ($index !== false) {
121 unset($data["keywords"][$index]);
129 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
131 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
134 if (isset($data["keywords"]) && count($data["keywords"])) {
135 foreach ($data["keywords"] as $keyword) {
136 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
137 ["", "", "", "", "", ""], $keyword);
143 $tags .= "#[url=" . DI::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
150 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
152 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
156 if (is_array($data)) {
157 $text = add_page_info_data($data, $no_photos);
163 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
165 Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
167 $URLSearchString = "^\[\]";
169 // Fix for Mastodon where the mentions are in a different format
170 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
171 '$2[url=$1]$3[/url]', $body);
173 // Adding these spaces is a quick hack due to my problems with regular expressions :)
174 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
177 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
180 // Convert urls without bbcode elements
181 if (!$matches && $texturl) {
182 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
184 // Yeah, a hack. I really hate regular expressions :)
186 $matches[1] = $matches[2];
191 $footer = add_page_info($matches[1], $no_photos);
194 // Remove the link from the body if the link is attached at the end of the post
195 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
196 $removedlink = trim(str_replace($matches[1], "", $body));
197 if (($removedlink == "") || strstr($body, $removedlink)) {
198 $body = $removedlink;
201 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
202 if (($removedlink == "") || strstr($body, $removedlink)) {
203 $body = $removedlink;
207 // Add the page information to the bottom
208 if (isset($footer) && (trim($footer) != "")) {
217 * consume_feed - process atom feed and update anything/everything we might need to update
219 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
221 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
222 * It is this person's stuff that is going to be updated.
223 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
224 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
225 * have a contact record.
226 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
227 * might not) try and subscribe to it.
228 * $datedir sorts in reverse order
229 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
230 * imported prior to its children being seen in the stream unless we are certain
231 * of how the feed is arranged/ordered.
232 * With $pass = 1, we only pull parent items out of the stream.
233 * With $pass = 2, we only pull children (comments/likes).
235 * So running this twice, first with pass 1 and then with pass 2 will do the right
236 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
237 * model where comments can have sub-threads. That would require some massive sorting
238 * to get all the feed items into a mostly linear ordering, and might still require
242 * @param array $importer
243 * @param array $contact
245 * @throws ImagickException
246 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
248 function consume_feed($xml, array $importer, array $contact, &$hub)
250 if ($contact['network'] === Protocol::OSTATUS) {
251 Logger::log("Consume OStatus messages ", Logger::DEBUG);
252 OStatus::import($xml, $importer, $contact, $hub);
257 if ($contact['network'] === Protocol::FEED) {
258 Logger::log("Consume feeds", Logger::DEBUG);
259 Feed::import($xml, $importer, $contact);
264 if ($contact['network'] === Protocol::DFRN) {
265 Logger::log("Consume DFRN messages", Logger::DEBUG);
266 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
267 if (!empty($dfrn_importer)) {
268 Logger::log("Now import the DFRN feed");
269 DFRN::import($xml, $dfrn_importer, true);
275 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
278 * Diaspora has different message-ids in feeds than they do
279 * through the direct Diaspora protocol. If we try and use
280 * the feed, we'll get duplicates. So don't.
282 if ($contact['network'] === Protocol::DIASPORA) {
286 // Without an importer we don't have a user id - so we quit
287 if (empty($importer)) {
291 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
293 // No user, no nickname, we quit
294 if (!DBA::isResult($user)) {
298 $push_url = DI::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
300 // Use a single verify token, even if multiple hubs
301 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
303 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
305 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
307 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
308 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
311 $postResult = Network::post($url, $params);
313 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
319 function drop_items(array $items)
323 if (!Session::isAuthenticated()) {
327 if (!empty($items)) {
328 foreach ($items as $item) {
329 $owner = Item::deleteForUser(['id' => $item], local_user());
331 if ($owner && !$uid) {
338 function drop_item($id, $return = '')
342 // locate item to be deleted
344 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
345 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
347 if (!DBA::isResult($item)) {
348 notice(DI::l10n()->t('Item not found.') . EOL);
349 DI::baseUrl()->redirect('network');
352 if ($item['deleted']) {
358 // check if logged in user is either the author or owner of this item
359 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
360 $contact_id = $item['contact-id'];
363 if ((local_user() == $item['uid']) || $contact_id) {
364 // Check if we should do HTML-based delete confirmation
365 if (!empty($_REQUEST['confirm'])) {
366 // <form> can't take arguments in its "action" parameter
367 // so add any arguments as hidden inputs
368 $query = explode_querystring(DI::args()->getQueryString());
371 foreach ($query['args'] as $arg) {
372 if (strpos($arg, 'confirm=') === false) {
373 $arg_parts = explode('=', $arg);
374 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
378 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
380 '$message' => DI::l10n()->t('Do you really want to delete this item?'),
381 '$extra_inputs' => $inputs,
382 '$confirm' => DI::l10n()->t('Yes'),
383 '$confirm_url' => $query['base'],
384 '$confirm_name' => 'confirmed',
385 '$cancel' => DI::l10n()->t('Cancel'),
388 // Now check how the user responded to the confirmation query
389 if (!empty($_REQUEST['canceled'])) {
390 DI::baseUrl()->redirect('display/' . $item['guid']);
393 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
395 if (!empty($item['parent'])){
397 $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
401 Item::deleteForUser(['id' => $item['id']], local_user());
403 $return_url = hex2bin($return);
405 // removes update_* from return_url to ignore Ajax refresh
406 $return_url = str_replace("update_", "", $return_url);
408 // Check if delete a comment
410 // Return to parent guid
411 if (!empty($parentitem)) {
412 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
415 // In case something goes wrong
417 DI::baseUrl()->redirect('network');
422 // if unknown location or deleting top level post called from display
423 if (empty($return_url) || strpos($return_url, 'display') !== false) {
424 DI::baseUrl()->redirect('network');
427 DI::baseUrl()->redirect($return_url);
432 notice(DI::l10n()->t('Permission denied.') . EOL);
433 DI::baseUrl()->redirect('display/' . $item['guid']);