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\Database\DBA;
17 use Friendica\Model\Item;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\Feed;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\ParseUrl;
24 use Friendica\Util\Strings;
25 use Friendica\Util\Temporal;
27 require_once __DIR__ . '/../mod/share.php';
29 function add_page_info_data(array $data, $no_photos = false)
31 Hook::callAll('page_info_data', $data);
33 if (empty($data['type'])) {
37 // It maybe is a rich content, but if it does have everything that a link has,
38 // then treat it that way
39 if (($data["type"] == "rich") && is_string($data["title"]) &&
40 is_string($data["text"]) && !empty($data["images"])) {
41 $data["type"] = "link";
44 $data["title"] = defaults($data, "title", "");
46 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
50 if ($no_photos && ($data["type"] == "photo")) {
54 // Escape some bad characters
55 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
56 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
58 $text = "[attachment type='".$data["type"]."'";
60 if (empty($data["text"])) {
61 $data["text"] = $data["title"];
64 if (empty($data["text"])) {
65 $data["text"] = $data["url"];
68 if (!empty($data["url"])) {
69 $text .= " url='".$data["url"]."'";
72 if (!empty($data["title"])) {
73 $text .= " title='".$data["title"]."'";
76 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
77 if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
78 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
79 // if the preview picture is larger than 500 pixels then show it in a larger mode
80 // But only, if the picture isn't higher than large (To prevent huge posts)
81 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
82 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
83 $text .= " image='".$preview."'";
85 $text .= " preview='".$preview."'";
89 $text .= "]".$data["text"]."[/attachment]";
92 if (isset($data["keywords"]) && count($data["keywords"])) {
94 foreach ($data["keywords"] as $keyword) {
95 /// @TODO make a positive list of allowed characters
96 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
97 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
98 $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url] ";
102 return "\n".$text.$hashtags;
105 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
107 $data = ParseUrl::getSiteinfoCached($url, true);
110 $data["images"][0]["src"] = $photo;
113 Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
115 if (!$keywords && isset($data["keywords"])) {
116 unset($data["keywords"]);
119 if (($keyword_blacklist != "") && isset($data["keywords"])) {
120 $list = explode(", ", $keyword_blacklist);
122 foreach ($list as $keyword) {
123 $keyword = trim($keyword);
125 $index = array_search($keyword, $data["keywords"]);
126 if ($index !== false) {
127 unset($data["keywords"][$index]);
135 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
137 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
140 if (isset($data["keywords"]) && count($data["keywords"])) {
141 foreach ($data["keywords"] as $keyword) {
142 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
143 ["", "", "", "", "", ""], $keyword);
149 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
156 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
158 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
162 if (is_array($data)) {
163 $text = add_page_info_data($data, $no_photos);
169 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
171 Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
173 $URLSearchString = "^\[\]";
175 // Fix for Mastodon where the mentions are in a different format
176 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
177 '$2[url=$1]$3[/url]', $body);
179 // Adding these spaces is a quick hack due to my problems with regular expressions :)
180 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
183 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
186 // Convert urls without bbcode elements
187 if (!$matches && $texturl) {
188 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
190 // Yeah, a hack. I really hate regular expressions :)
192 $matches[1] = $matches[2];
197 $footer = add_page_info($matches[1], $no_photos);
200 // Remove the link from the body if the link is attached at the end of the post
201 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
202 $removedlink = trim(str_replace($matches[1], "", $body));
203 if (($removedlink == "") || strstr($body, $removedlink)) {
204 $body = $removedlink;
207 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
208 if (($removedlink == "") || strstr($body, $removedlink)) {
209 $body = $removedlink;
213 // Add the page information to the bottom
214 if (isset($footer) && (trim($footer) != "")) {
223 * consume_feed - process atom feed and update anything/everything we might need to update
225 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
227 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
228 * It is this person's stuff that is going to be updated.
229 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
230 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
231 * have a contact record.
232 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
233 * might not) try and subscribe to it.
234 * $datedir sorts in reverse order
235 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
236 * imported prior to its children being seen in the stream unless we are certain
237 * of how the feed is arranged/ordered.
238 * With $pass = 1, we only pull parent items out of the stream.
239 * With $pass = 2, we only pull children (comments/likes).
241 * So running this twice, first with pass 1 and then with pass 2 will do the right
242 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
243 * model where comments can have sub-threads. That would require some massive sorting
244 * to get all the feed items into a mostly linear ordering, and might still require
248 * @param array $importer
249 * @param array $contact
251 * @throws ImagickException
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 function consume_feed($xml, array $importer, array $contact, &$hub)
256 if ($contact['network'] === Protocol::OSTATUS) {
257 Logger::log("Consume OStatus messages ", Logger::DEBUG);
258 OStatus::import($xml, $importer, $contact, $hub);
263 if ($contact['network'] === Protocol::FEED) {
264 Logger::log("Consume feeds", Logger::DEBUG);
265 Feed::import($xml, $importer, $contact, $hub);
270 if ($contact['network'] === Protocol::DFRN) {
271 Logger::log("Consume DFRN messages", Logger::DEBUG);
272 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
273 if (!empty($dfrn_importer)) {
274 Logger::log("Now import the DFRN feed");
275 DFRN::import($xml, $dfrn_importer, true);
281 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
284 * Diaspora has different message-ids in feeds than they do
285 * through the direct Diaspora protocol. If we try and use
286 * the feed, we'll get duplicates. So don't.
288 if ($contact['network'] === Protocol::DIASPORA) {
292 // Without an importer we don't have a user id - so we quit
293 if (empty($importer)) {
297 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
299 // No user, no nickname, we quit
300 if (!DBA::isResult($user)) {
304 $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
306 // Use a single verify token, even if multiple hubs
307 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
309 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
311 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
313 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
314 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
317 $postResult = Network::post($url, $params);
319 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
325 function drop_items(array $items)
329 if (!local_user() && !remote_user()) {
333 if (!empty($items)) {
334 foreach ($items as $item) {
335 $owner = Item::deleteForUser(['id' => $item], local_user());
337 if ($owner && !$uid) {
344 function drop_item($id, $return = '')
346 $a = BaseObject::getApp();
348 // locate item to be deleted
350 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
351 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
353 if (!DBA::isResult($item)) {
354 notice(L10n::t('Item not found.') . EOL);
355 $a->internalRedirect('network');
358 if ($item['deleted']) {
364 // check if logged in user is either the author or owner of this item
366 if (!empty($_SESSION['remote'])) {
367 foreach ($_SESSION['remote'] as $visitor) {
368 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
369 $contact_id = $visitor['cid'];
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($a->query_string);
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' => L10n::t('Do you really want to delete this item?'),
393 '$extra_inputs' => $inputs,
394 '$confirm' => L10n::t('Yes'),
395 '$confirm_url' => $query['base'],
396 '$confirm_name' => 'confirmed',
397 '$cancel' => L10n::t('Cancel'),
400 // Now check how the user responded to the confirmation query
401 if (!empty($_REQUEST['canceled'])) {
402 $a->internalRedirect('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 $a->internalRedirect('display/' . $parentitem['guid']);
427 // In case something goes wrong
429 $a->internalRedirect('network');
434 // if unknown location or deleting top level post called from display
435 if (empty($return_url) || strpos($return_url, 'display') !== false) {
436 $a->internalRedirect('network');
439 $a->internalRedirect($return_url);
444 notice(L10n::t('Permission denied.') . EOL);
445 $a->internalRedirect('display/' . $item['guid']);