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\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Item;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Feed;
18 use Friendica\Protocol\OStatus;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\ParseUrl;
22 use Friendica\Util\Temporal;
24 require_once 'include/text.php';
25 require_once 'mod/share.php';
26 require_once 'include/enotify.php';
28 function add_page_info_data(array $data, $no_photos = false)
30 Addon::callHooks('page_info_data', $data);
32 if (empty($data['type'])) {
36 // It maybe is a rich content, but if it does have everything that a link has,
37 // then treat it that way
38 if (($data["type"] == "rich") && is_string($data["title"]) &&
39 is_string($data["text"]) && !empty($data["images"])) {
40 $data["type"] = "link";
43 $data["title"] = defaults($data, "title", "");
45 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
49 if ($no_photos && ($data["type"] == "photo")) {
53 // Escape some bad characters
54 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
55 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
57 $text = "[attachment type='".$data["type"]."'";
59 if (empty($data["text"])) {
60 $data["text"] = $data["title"];
63 if (empty($data["text"])) {
64 $data["text"] = $data["url"];
67 if (!empty($data["url"])) {
68 $text .= " url='".$data["url"]."'";
71 if (!empty($data["title"])) {
72 $text .= " title='".$data["title"]."'";
75 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
76 if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
77 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
78 // if the preview picture is larger than 500 pixels then show it in a larger mode
79 // But only, if the picture isn't higher than large (To prevent huge posts)
80 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
81 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
82 $text .= " image='".$preview."'";
84 $text .= " preview='".$preview."'";
88 $text .= "]".$data["text"]."[/attachment]";
91 if (isset($data["keywords"]) && count($data["keywords"])) {
93 foreach ($data["keywords"] as $keyword) {
94 /// @TODO make a positive list of allowed characters
95 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
96 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
97 $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
101 return "\n".$text.$hashtags;
104 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
106 $data = ParseUrl::getSiteinfoCached($url, true);
109 $data["images"][0]["src"] = $photo;
112 logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
114 if (!$keywords && isset($data["keywords"])) {
115 unset($data["keywords"]);
118 if (($keyword_blacklist != "") && isset($data["keywords"])) {
119 $list = explode(", ", $keyword_blacklist);
121 foreach ($list as $keyword) {
122 $keyword = trim($keyword);
124 $index = array_search($keyword, $data["keywords"]);
125 if ($index !== false) {
126 unset($data["keywords"][$index]);
134 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
136 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
139 if (isset($data["keywords"]) && count($data["keywords"])) {
140 foreach ($data["keywords"] as $keyword) {
141 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
142 ["", "", "", "", "", ""], $keyword);
148 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
155 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
157 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
161 if (is_array($data)) {
162 $text = add_page_info_data($data, $no_photos);
168 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
170 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
172 $URLSearchString = "^\[\]";
174 // Fix for Mastodon where the mentions are in a different format
175 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
176 '$2[url=$1]$3[/url]', $body);
178 // Adding these spaces is a quick hack due to my problems with regular expressions :)
179 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
182 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
185 // Convert urls without bbcode elements
186 if (!$matches && $texturl) {
187 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
189 // Yeah, a hack. I really hate regular expressions :)
191 $matches[1] = $matches[2];
196 $footer = add_page_info($matches[1], $no_photos);
199 // Remove the link from the body if the link is attached at the end of the post
200 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
201 $removedlink = trim(str_replace($matches[1], "", $body));
202 if (($removedlink == "") || strstr($body, $removedlink)) {
203 $body = $removedlink;
206 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
207 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/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
247 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
249 if ($contact['network'] === Protocol::OSTATUS) {
251 // Test - remove before flight
252 //$tempfile = tempnam(get_temppath(), "ostatus2");
253 //file_put_contents($tempfile, $xml);
254 logger("Consume OStatus messages ", LOGGER_DEBUG);
255 OStatus::import($xml, $importer, $contact, $hub);
261 if ($contact['network'] === Protocol::FEED) {
263 logger("Consume feeds", LOGGER_DEBUG);
264 Feed::import($xml, $importer, $contact, $hub);
270 if ($contact['network'] === Protocol::DFRN) {
271 logger("Consume DFRN messages", LOGGER_DEBUG);
272 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
273 if (!empty($dfrn_importer)) {
274 logger("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 $a = BaseObject::getApp();
299 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
301 // No user, no nickname, we quit
302 if (!DBA::isResult($user)) {
306 $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
308 // Use a single verify token, even if multiple hubs
309 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
311 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
313 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
315 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
316 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
319 Network::post($url, $params);
321 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
327 function drop_items(array $items)
331 if (!local_user() && !remote_user()) {
335 if (!empty($items)) {
336 foreach ($items as $item) {
337 $owner = Item::deleteForUser(['id' => $item], local_user());
339 if ($owner && !$uid) {
346 function drop_item($id)
348 $a = BaseObject::getApp();
350 // locate item to be deleted
352 $fields = ['id', 'uid', 'contact-id', 'deleted'];
353 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
355 if (!DBA::isResult($item)) {
356 notice(L10n::t('Item not found.') . EOL);
357 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
360 if ($item['deleted']) {
366 // check if logged in user is either the author or owner of this item
368 if (!empty($_SESSION['remote'])) {
369 foreach ($_SESSION['remote'] as $visitor) {
370 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
371 $contact_id = $visitor['cid'];
377 if ((local_user() == $item['uid']) || $contact_id) {
378 // Check if we should do HTML-based delete confirmation
379 if (!empty($_REQUEST['confirm'])) {
380 // <form> can't take arguments in its "action" parameter
381 // so add any arguments as hidden inputs
382 $query = explode_querystring($a->query_string);
385 foreach ($query['args'] as $arg) {
386 if (strpos($arg, 'confirm=') === false) {
387 $arg_parts = explode('=', $arg);
388 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
392 return replace_macros(get_markup_template('confirm.tpl'), [
394 '$message' => L10n::t('Do you really want to delete this item?'),
395 '$extra_inputs' => $inputs,
396 '$confirm' => L10n::t('Yes'),
397 '$confirm_url' => $query['base'],
398 '$confirm_name' => 'confirmed',
399 '$cancel' => L10n::t('Cancel'),
402 // Now check how the user responded to the confirmation query
403 if (!empty($_REQUEST['canceled'])) {
404 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
408 Item::deleteForUser(['id' => $item['id']], local_user());
410 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
413 notice(L10n::t('Permission denied.') . EOL);
414 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
419 /* arrange the list in years */
420 function list_post_dates($uid, $wall)
422 $dnow = DateTimeFormat::localNow('Y-m-d');
424 $dthen = Item::firstPostDate($uid, $wall);
429 // Set the start and end date to the beginning of the month
430 $dnow = substr($dnow, 0, 8) . '01';
431 $dthen = substr($dthen, 0, 8) . '01';
436 * Starting with the current month, get the first and last days of every
437 * month down to and including the month of the first post
439 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
440 $dyear = intval(substr($dnow, 0, 4));
441 $dstart = substr($dnow, 0, 8) . '01';
442 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
443 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
444 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
445 $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
447 if (empty($ret[$dyear])) {
451 $ret[$dyear][] = [$str, $end_month, $start_month];
452 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
457 function posted_date_widget($url, $uid, $wall)
461 if (!Feature::isEnabled($uid, 'archives')) {
465 // For former Facebook folks that left because of "timeline"
467 * @TODO old-lost code?
468 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
472 $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
474 $ret = list_post_dates($uid, $wall);
476 if (!DBA::isResult($ret)) {
480 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
481 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
483 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
484 '$title' => L10n::t('Archives'),
485 '$size' => $visible_years,
486 '$cutoff_year' => $cutoff_year,
487 '$cutoff' => $cutoff,
490 '$showmore' => L10n::t('show more')