3 * @file include/items.php
6 use Friendica\BaseObject;
7 use Friendica\Content\Feature;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
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 'include/text.php';
28 require_once 'mod/share.php';
29 require_once 'include/enotify.php';
31 function add_page_info_data(array $data, $no_photos = false)
33 Addon::callHooks('page_info_data', $data);
35 if (empty($data['type'])) {
39 // It maybe is a rich content, but if it does have everything that a link has,
40 // then treat it that way
41 if (($data["type"] == "rich") && is_string($data["title"]) &&
42 is_string($data["text"]) && !empty($data["images"])) {
43 $data["type"] = "link";
46 $data["title"] = defaults($data, "title", "");
48 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
52 if ($no_photos && ($data["type"] == "photo")) {
56 // Escape some bad characters
57 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
58 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
60 $text = "[attachment type='".$data["type"]."'";
62 if (empty($data["text"])) {
63 $data["text"] = $data["title"];
66 if (empty($data["text"])) {
67 $data["text"] = $data["url"];
70 if (!empty($data["url"])) {
71 $text .= " url='".$data["url"]."'";
74 if (!empty($data["title"])) {
75 $text .= " title='".$data["title"]."'";
78 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
79 if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
80 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
81 // if the preview picture is larger than 500 pixels then show it in a larger mode
82 // But only, if the picture isn't higher than large (To prevent huge posts)
83 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
84 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
85 $text .= " image='".$preview."'";
87 $text .= " preview='".$preview."'";
91 $text .= "]".$data["text"]."[/attachment]";
94 if (isset($data["keywords"]) && count($data["keywords"])) {
96 foreach ($data["keywords"] as $keyword) {
97 /// @TODO make a positive list of allowed characters
98 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
99 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
100 $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
104 return "\n".$text.$hashtags;
107 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
109 $data = ParseUrl::getSiteinfoCached($url, true);
112 $data["images"][0]["src"] = $photo;
115 Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
117 if (!$keywords && isset($data["keywords"])) {
118 unset($data["keywords"]);
121 if (($keyword_blacklist != "") && isset($data["keywords"])) {
122 $list = explode(", ", $keyword_blacklist);
124 foreach ($list as $keyword) {
125 $keyword = trim($keyword);
127 $index = array_search($keyword, $data["keywords"]);
128 if ($index !== false) {
129 unset($data["keywords"][$index]);
137 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
139 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
142 if (isset($data["keywords"]) && count($data["keywords"])) {
143 foreach ($data["keywords"] as $keyword) {
144 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
145 ["", "", "", "", "", ""], $keyword);
151 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
158 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
160 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
164 if (is_array($data)) {
165 $text = add_page_info_data($data, $no_photos);
171 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
173 Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
175 $URLSearchString = "^\[\]";
177 // Fix for Mastodon where the mentions are in a different format
178 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
179 '$2[url=$1]$3[/url]', $body);
181 // Adding these spaces is a quick hack due to my problems with regular expressions :)
182 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
185 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
188 // Convert urls without bbcode elements
189 if (!$matches && $texturl) {
190 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
192 // Yeah, a hack. I really hate regular expressions :)
194 $matches[1] = $matches[2];
199 $footer = add_page_info($matches[1], $no_photos);
202 // Remove the link from the body if the link is attached at the end of the post
203 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
204 $removedlink = trim(str_replace($matches[1], "", $body));
205 if (($removedlink == "") || strstr($body, $removedlink)) {
206 $body = $removedlink;
209 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
210 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
211 if (($removedlink == "") || strstr($body, $removedlink)) {
212 $body = $removedlink;
216 // Add the page information to the bottom
217 if (isset($footer) && (trim($footer) != "")) {
226 * consume_feed - process atom feed and update anything/everything we might need to update
228 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
230 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
231 * It is this person's stuff that is going to be updated.
232 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
233 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
234 * have a contact record.
235 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
236 * might not) try and subscribe to it.
237 * $datedir sorts in reverse order
238 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
239 * imported prior to its children being seen in the stream unless we are certain
240 * of how the feed is arranged/ordered.
241 * With $pass = 1, we only pull parent items out of the stream.
242 * With $pass = 2, we only pull children (comments/likes).
244 * So running this twice, first with pass 1 and then with pass 2 will do the right
245 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
246 * model where comments can have sub-threads. That would require some massive sorting
247 * to get all the feed items into a mostly linear ordering, and might still require
250 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
252 if ($contact['network'] === Protocol::OSTATUS) {
254 // Test - remove before flight
255 //$tempfile = tempnam(get_temppath(), "ostatus2");
256 //file_put_contents($tempfile, $xml);
257 Logger::log("Consume OStatus messages ", Logger::DEBUG);
258 OStatus::import($xml, $importer, $contact, $hub);
264 if ($contact['network'] === Protocol::FEED) {
266 Logger::log("Consume feeds", Logger::DEBUG);
267 Feed::import($xml, $importer, $contact, $hub);
273 if ($contact['network'] === Protocol::DFRN) {
274 Logger::log("Consume DFRN messages", Logger::DEBUG);
275 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
276 if (!empty($dfrn_importer)) {
277 Logger::log("Now import the DFRN feed");
278 DFRN::import($xml, $dfrn_importer, true);
284 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
287 * Diaspora has different message-ids in feeds than they do
288 * through the direct Diaspora protocol. If we try and use
289 * the feed, we'll get duplicates. So don't.
291 if ($contact['network'] === Protocol::DIASPORA) {
295 // Without an importer we don't have a user id - so we quit
296 if (empty($importer)) {
300 $a = BaseObject::getApp();
302 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
304 // No user, no nickname, we quit
305 if (!DBA::isResult($user)) {
309 $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
311 // Use a single verify token, even if multiple hubs
312 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
314 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
316 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
318 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
319 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
322 $postResult = Network::post($url, $params);
324 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
330 function drop_items(array $items)
334 if (!local_user() && !remote_user()) {
338 if (!empty($items)) {
339 foreach ($items as $item) {
340 $owner = Item::deleteForUser(['id' => $item], local_user());
342 if ($owner && !$uid) {
349 function drop_item($id, $return = '')
351 $a = BaseObject::getApp();
353 // locate item to be deleted
355 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted'];
356 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
358 if (!DBA::isResult($item)) {
359 notice(L10n::t('Item not found.') . EOL);
360 $a->internalRedirect('network');
363 if ($item['deleted']) {
369 // check if logged in user is either the author or owner of this item
371 if (!empty($_SESSION['remote'])) {
372 foreach ($_SESSION['remote'] as $visitor) {
373 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
374 $contact_id = $visitor['cid'];
380 if ((local_user() == $item['uid']) || $contact_id) {
381 // Check if we should do HTML-based delete confirmation
382 if (!empty($_REQUEST['confirm'])) {
383 // <form> can't take arguments in its "action" parameter
384 // so add any arguments as hidden inputs
385 $query = explode_querystring($a->query_string);
388 foreach ($query['args'] as $arg) {
389 if (strpos($arg, 'confirm=') === false) {
390 $arg_parts = explode('=', $arg);
391 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
395 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
397 '$message' => L10n::t('Do you really want to delete this item?'),
398 '$extra_inputs' => $inputs,
399 '$confirm' => L10n::t('Yes'),
400 '$confirm_url' => $query['base'],
401 '$confirm_name' => 'confirmed',
402 '$cancel' => L10n::t('Cancel'),
405 // Now check how the user responded to the confirmation query
406 if (!empty($_REQUEST['canceled'])) {
407 $a->internalRedirect('display/' . $item['guid']);
411 Item::deleteForUser(['id' => $item['id']], local_user());
413 $return_url = hex2bin($return);
415 // removes update_* from return_url to ignore Ajax refresh
416 $return_url = str_replace("update_", "", $return_url);
418 if (empty($return_url) || strpos($return_url, 'display') !== false) {
419 $a->internalRedirect('network');
423 $a->internalRedirect($return_url);
427 notice(L10n::t('Permission denied.') . EOL);
428 $a->internalRedirect('display/' . $item['guid']);
433 /* arrange the list in years */
434 function list_post_dates($uid, $wall)
436 $dnow = DateTimeFormat::localNow('Y-m-d');
438 $dthen = Item::firstPostDate($uid, $wall);
443 // Set the start and end date to the beginning of the month
444 $dnow = substr($dnow, 0, 8) . '01';
445 $dthen = substr($dthen, 0, 8) . '01';
450 * Starting with the current month, get the first and last days of every
451 * month down to and including the month of the first post
453 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
454 $dyear = intval(substr($dnow, 0, 4));
455 $dstart = substr($dnow, 0, 8) . '01';
456 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
457 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
458 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
459 $str = L10n::getDay(DateTimeFormat::utc($dnow, 'F'));
461 if (empty($ret[$dyear])) {
465 $ret[$dyear][] = [$str, $end_month, $start_month];
466 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
471 function posted_date_widget($url, $uid, $wall)
475 if (!Feature::isEnabled($uid, 'archives')) {
479 // For former Facebook folks that left because of "timeline"
481 * @TODO old-lost code?
482 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
486 $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
488 $ret = list_post_dates($uid, $wall);
490 if (!DBA::isResult($ret)) {
494 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
495 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
497 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('posted_date_widget.tpl'),[
498 '$title' => L10n::t('Archives'),
499 '$size' => $visible_years,
500 '$cutoff_year' => $cutoff_year,
501 '$cutoff' => $cutoff,
504 '$showmore' => L10n::t('show more')