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\Temporal;
26 require_once 'include/text.php';
27 require_once 'mod/share.php';
28 require_once 'include/enotify.php';
30 function add_page_info_data(array $data, $no_photos = false)
32 Addon::callHooks('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"] = defaults($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=" . rawurlencode($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=" . rawurlencode($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 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
209 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
210 if (($removedlink == "") || strstr($body, $removedlink)) {
211 $body = $removedlink;
215 // Add the page information to the bottom
216 if (isset($footer) && (trim($footer) != "")) {
225 * consume_feed - process atom feed and update anything/everything we might need to update
227 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
229 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
230 * It is this person's stuff that is going to be updated.
231 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
232 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
233 * have a contact record.
234 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
235 * might not) try and subscribe to it.
236 * $datedir sorts in reverse order
237 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
238 * imported prior to its children being seen in the stream unless we are certain
239 * of how the feed is arranged/ordered.
240 * With $pass = 1, we only pull parent items out of the stream.
241 * With $pass = 2, we only pull children (comments/likes).
243 * So running this twice, first with pass 1 and then with pass 2 will do the right
244 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
245 * model where comments can have sub-threads. That would require some massive sorting
246 * to get all the feed items into a mostly linear ordering, and might still require
249 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
251 if ($contact['network'] === Protocol::OSTATUS) {
253 // Test - remove before flight
254 //$tempfile = tempnam(get_temppath(), "ostatus2");
255 //file_put_contents($tempfile, $xml);
256 Logger::log("Consume OStatus messages ", Logger::DEBUG);
257 OStatus::import($xml, $importer, $contact, $hub);
263 if ($contact['network'] === Protocol::FEED) {
265 Logger::log("Consume feeds", Logger::DEBUG);
266 Feed::import($xml, $importer, $contact, $hub);
272 if ($contact['network'] === Protocol::DFRN) {
273 Logger::log("Consume DFRN messages", Logger::DEBUG);
274 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
275 if (!empty($dfrn_importer)) {
276 Logger::log("Now import the DFRN feed");
277 DFRN::import($xml, $dfrn_importer, true);
283 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
286 * Diaspora has different message-ids in feeds than they do
287 * through the direct Diaspora protocol. If we try and use
288 * the feed, we'll get duplicates. So don't.
290 if ($contact['network'] === Protocol::DIASPORA) {
294 // Without an importer we don't have a user id - so we quit
295 if (empty($importer)) {
299 $a = BaseObject::getApp();
301 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
303 // No user, no nickname, we quit
304 if (!DBA::isResult($user)) {
308 $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
310 // Use a single verify token, even if multiple hubs
311 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
313 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
315 Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
317 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
318 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
321 $postResult = Network::post($url, $params);
323 Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
329 function drop_items(array $items)
333 if (!local_user() && !remote_user()) {
337 if (!empty($items)) {
338 foreach ($items as $item) {
339 $owner = Item::deleteForUser(['id' => $item], local_user());
341 if ($owner && !$uid) {
348 function drop_item($id, $return)
350 $a = BaseObject::getApp();
352 // locate item to be deleted
354 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted'];
355 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
357 if (!DBA::isResult($item)) {
358 notice(L10n::t('Item not found.') . EOL);
359 $a->internalRedirect('network');
362 if ($item['deleted']) {
368 // check if logged in user is either the author or owner of this item
370 if (!empty($_SESSION['remote'])) {
371 foreach ($_SESSION['remote'] as $visitor) {
372 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
373 $contact_id = $visitor['cid'];
379 if ((local_user() == $item['uid']) || $contact_id) {
380 // Check if we should do HTML-based delete confirmation
381 if (!empty($_REQUEST['confirm'])) {
382 // <form> can't take arguments in its "action" parameter
383 // so add any arguments as hidden inputs
384 $query = explode_querystring($a->query_string);
387 foreach ($query['args'] as $arg) {
388 if (strpos($arg, 'confirm=') === false) {
389 $arg_parts = explode('=', $arg);
390 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
394 return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
396 '$message' => L10n::t('Do you really want to delete this item?'),
397 '$extra_inputs' => $inputs,
398 '$confirm' => L10n::t('Yes'),
399 '$confirm_url' => $query['base'],
400 '$confirm_name' => 'confirmed',
401 '$cancel' => L10n::t('Cancel'),
404 // Now check how the user responded to the confirmation query
405 if (!empty($_REQUEST['canceled'])) {
406 $a->internalRedirect('display/' . $item['guid']);
410 Item::deleteForUser(['id' => $item['id']], local_user());
412 $return_url = hex2bin($return);
413 notice("RETURN: " + $return_url);
414 if (empty($return_url) || strpos($return_url, 'display') ) {
415 $a->internalRedirect('network');
419 $a->internalRedirect($return_url);
423 notice(L10n::t('Permission denied.') . EOL);
424 $a->internalRedirect('display/' . $item['guid']);
429 /* arrange the list in years */
430 function list_post_dates($uid, $wall)
432 $dnow = DateTimeFormat::localNow('Y-m-d');
434 $dthen = Item::firstPostDate($uid, $wall);
439 // Set the start and end date to the beginning of the month
440 $dnow = substr($dnow, 0, 8) . '01';
441 $dthen = substr($dthen, 0, 8) . '01';
446 * Starting with the current month, get the first and last days of every
447 * month down to and including the month of the first post
449 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
450 $dyear = intval(substr($dnow, 0, 4));
451 $dstart = substr($dnow, 0, 8) . '01';
452 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
453 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
454 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
455 $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
457 if (empty($ret[$dyear])) {
461 $ret[$dyear][] = [$str, $end_month, $start_month];
462 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
467 function posted_date_widget($url, $uid, $wall)
471 if (!Feature::isEnabled($uid, 'archives')) {
475 // For former Facebook folks that left because of "timeline"
477 * @TODO old-lost code?
478 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
482 $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
484 $ret = list_post_dates($uid, $wall);
486 if (!DBA::isResult($ret)) {
490 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
491 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
493 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('posted_date_widget.tpl'),[
494 '$title' => L10n::t('Archives'),
495 '$size' => $visible_years,
496 '$cutoff_year' => $cutoff_year,
497 '$cutoff' => $cutoff,
500 '$showmore' => L10n::t('show more')