3 * @file include/items.php
6 use Friendica\BaseObject;
7 use Friendica\Content\Feature;
8 use Friendica\Core\Config;
9 use Friendica\Core\Hook;
10 use Friendica\Core\L10n;
11 use Friendica\Core\Logger;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\System;
16 use Friendica\Core\Session;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Item;
19 use Friendica\Protocol\DFRN;
20 use Friendica\Protocol\Feed;
21 use Friendica\Protocol\OStatus;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Util\ParseUrl;
25 use Friendica\Util\Strings;
26 use Friendica\Util\Temporal;
28 require_once __DIR__ . '/../mod/share.php';
30 function add_page_info_data(array $data, $no_photos = false)
32 Hook::callAll('page_info_data', $data);
34 if (empty($data['type'])) {
38 // It maybe is a rich content, but if it does have everything that a link has,
39 // then treat it that way
40 if (($data["type"] == "rich") && is_string($data["title"]) &&
41 is_string($data["text"]) && !empty($data["images"])) {
42 $data["type"] = "link";
45 $data["title"] = $data["title"] ?? '';
47 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
51 if ($no_photos && ($data["type"] == "photo")) {
55 // Escape some bad characters
56 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
57 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
59 $text = "[attachment type='".$data["type"]."'";
61 if (empty($data["text"])) {
62 $data["text"] = $data["title"];
65 if (empty($data["text"])) {
66 $data["text"] = $data["url"];
69 if (!empty($data["url"])) {
70 $text .= " url='".$data["url"]."'";
73 if (!empty($data["title"])) {
74 $text .= " title='".$data["title"]."'";
77 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
78 if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
79 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
80 // if the preview picture is larger than 500 pixels then show it in a larger mode
81 // But only, if the picture isn't higher than large (To prevent huge posts)
82 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
83 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
84 $text .= " image='".$preview."'";
86 $text .= " preview='".$preview."'";
90 $text .= "]".$data["text"]."[/attachment]";
93 if (isset($data["keywords"]) && count($data["keywords"])) {
95 foreach ($data["keywords"] as $keyword) {
96 /// @TODO make a positive list of allowed characters
97 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
98 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
99 $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url] ";
103 return "\n".$text.$hashtags;
106 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
108 $data = ParseUrl::getSiteinfoCached($url, true);
111 $data["images"][0]["src"] = $photo;
114 Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
116 if (!$keywords && isset($data["keywords"])) {
117 unset($data["keywords"]);
120 if (($keyword_blacklist != "") && isset($data["keywords"])) {
121 $list = explode(", ", $keyword_blacklist);
123 foreach ($list as $keyword) {
124 $keyword = trim($keyword);
126 $index = array_search($keyword, $data["keywords"]);
127 if ($index !== false) {
128 unset($data["keywords"][$index]);
136 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
138 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
141 if (isset($data["keywords"]) && count($data["keywords"])) {
142 foreach ($data["keywords"] as $keyword) {
143 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
144 ["", "", "", "", "", ""], $keyword);
150 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
157 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
159 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
163 if (is_array($data)) {
164 $text = add_page_info_data($data, $no_photos);
170 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
172 Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
174 $URLSearchString = "^\[\]";
176 // Fix for Mastodon where the mentions are in a different format
177 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
178 '$2[url=$1]$3[/url]', $body);
180 // Adding these spaces is a quick hack due to my problems with regular expressions :)
181 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
184 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
187 // Convert urls without bbcode elements
188 if (!$matches && $texturl) {
189 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
191 // Yeah, a hack. I really hate regular expressions :)
193 $matches[1] = $matches[2];
198 $footer = add_page_info($matches[1], $no_photos);
201 // Remove the link from the body if the link is attached at the end of the post
202 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
203 $removedlink = trim(str_replace($matches[1], "", $body));
204 if (($removedlink == "") || strstr($body, $removedlink)) {
205 $body = $removedlink;
208 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
209 if (($removedlink == "") || strstr($body, $removedlink)) {
210 $body = $removedlink;
214 // Add the page information to the bottom
215 if (isset($footer) && (trim($footer) != "")) {
224 * consume_feed - process atom feed and update anything/everything we might need to update
226 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
228 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
229 * It is this person's stuff that is going to be updated.
230 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
231 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
232 * have a contact record.
233 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
234 * might not) try and subscribe to it.
235 * $datedir sorts in reverse order
236 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
237 * imported prior to its children being seen in the stream unless we are certain
238 * of how the feed is arranged/ordered.
239 * With $pass = 1, we only pull parent items out of the stream.
240 * With $pass = 2, we only pull children (comments/likes).
242 * So running this twice, first with pass 1 and then with pass 2 will do the right
243 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
244 * model where comments can have sub-threads. That would require some massive sorting
245 * to get all the feed items into a mostly linear ordering, and might still require
249 * @param array $importer
250 * @param array $contact
252 * @throws ImagickException
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 function consume_feed($xml, array $importer, array $contact, &$hub)
257 if ($contact['network'] === Protocol::OSTATUS) {
258 Logger::log("Consume OStatus messages ", Logger::DEBUG);
259 OStatus::import($xml, $importer, $contact, $hub);
264 if ($contact['network'] === Protocol::FEED) {
265 Logger::log("Consume feeds", Logger::DEBUG);
266 Feed::import($xml, $importer, $contact, $hub);
271 if ($contact['network'] === Protocol::DFRN) {
272 Logger::log("Consume DFRN messages", Logger::DEBUG);
273 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
274 if (!empty($dfrn_importer)) {
275 Logger::log("Now import the DFRN feed");
276 DFRN::import($xml, $dfrn_importer, true);
282 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
285 * Diaspora has different message-ids in feeds than they do
286 * through the direct Diaspora protocol. If we try and use
287 * the feed, we'll get duplicates. So don't.
289 if ($contact['network'] === Protocol::DIASPORA) {
293 // Without an importer we don't have a user id - so we quit
294 if (empty($importer)) {
298 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
300 // No user, no nickname, we quit
301 if (!DBA::isResult($user)) {
305 $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
307 // Use a single verify token, even if multiple hubs
308 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
310 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
312 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
314 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
315 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
318 $postResult = Network::post($url, $params);
320 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
326 function drop_items(array $items)
330 if (!Session::isAuthenticated()) {
334 if (!empty($items)) {
335 foreach ($items as $item) {
336 $owner = Item::deleteForUser(['id' => $item], local_user());
338 if ($owner && !$uid) {
345 function drop_item($id, $return = '')
347 $a = BaseObject::getApp();
349 // locate item to be deleted
351 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
352 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
354 if (!DBA::isResult($item)) {
355 notice(L10n::t('Item not found.') . EOL);
356 $a->internalRedirect('network');
359 if ($item['deleted']) {
365 // check if logged in user is either the author or owner of this item
366 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
367 $contact_id = $item['contact-id'];
370 if ((local_user() == $item['uid']) || $contact_id) {
371 // Check if we should do HTML-based delete confirmation
372 if (!empty($_REQUEST['confirm'])) {
373 // <form> can't take arguments in its "action" parameter
374 // so add any arguments as hidden inputs
375 $query = explode_querystring($a->query_string);
378 foreach ($query['args'] as $arg) {
379 if (strpos($arg, 'confirm=') === false) {
380 $arg_parts = explode('=', $arg);
381 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
385 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
387 '$message' => L10n::t('Do you really want to delete this item?'),
388 '$extra_inputs' => $inputs,
389 '$confirm' => L10n::t('Yes'),
390 '$confirm_url' => $query['base'],
391 '$confirm_name' => 'confirmed',
392 '$cancel' => L10n::t('Cancel'),
395 // Now check how the user responded to the confirmation query
396 if (!empty($_REQUEST['canceled'])) {
397 $a->internalRedirect('display/' . $item['guid']);
400 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
402 if (!empty($item['parent'])){
404 $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
408 Item::deleteForUser(['id' => $item['id']], local_user());
410 $return_url = hex2bin($return);
412 // removes update_* from return_url to ignore Ajax refresh
413 $return_url = str_replace("update_", "", $return_url);
415 // Check if delete a comment
417 // Return to parent guid
418 if (!empty($parentitem)) {
419 $a->internalRedirect('display/' . $parentitem['guid']);
422 // In case something goes wrong
424 $a->internalRedirect('network');
429 // if unknown location or deleting top level post called from display
430 if (empty($return_url) || strpos($return_url, 'display') !== false) {
431 $a->internalRedirect('network');
434 $a->internalRedirect($return_url);
439 notice(L10n::t('Permission denied.') . EOL);
440 $a->internalRedirect('display/' . $item['guid']);