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\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Item;
15 use Friendica\Protocol\DFRN;
16 use Friendica\Protocol\Feed;
17 use Friendica\Protocol\OStatus;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\ParseUrl;
21 use Friendica\Util\Temporal;
23 require_once 'include/text.php';
24 require_once 'mod/share.php';
25 require_once 'include/enotify.php';
27 function add_page_info_data(array $data, $no_photos = false)
29 Addon::callHooks('page_info_data', $data);
31 // It maybe is a rich content, but if it does have everything that a link has,
32 // then treat it that way
33 if (($data["type"] == "rich") && is_string($data["title"]) &&
34 is_string($data["text"]) && !empty($data["images"])) {
35 $data["type"] = "link";
38 $data["title"] = defaults($data, "title", "");
40 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
44 if ($no_photos && ($data["type"] == "photo")) {
48 // Escape some bad characters
49 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
50 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
52 $text = "[attachment type='".$data["type"]."'";
54 if (empty($data["text"])) {
55 $data["text"] = $data["title"];
58 if (empty($data["text"])) {
59 $data["text"] = $data["url"];
62 if (!empty($data["url"])) {
63 $text .= " url='".$data["url"]."'";
66 if (!empty($data["title"])) {
67 $text .= " title='".$data["title"]."'";
70 if (!empty($data["images"])) {
71 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
72 // if the preview picture is larger than 500 pixels then show it in a larger mode
73 // But only, if the picture isn't higher than large (To prevent huge posts)
74 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
75 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
76 $text .= " image='".$preview."'";
78 $text .= " preview='".$preview."'";
82 $text .= "]".$data["text"]."[/attachment]";
85 if (isset($data["keywords"]) && count($data["keywords"])) {
87 foreach ($data["keywords"] as $keyword) {
88 /// @TODO make a positive list of allowed characters
89 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
90 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
91 $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
95 return "\n".$text.$hashtags;
98 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
100 $data = ParseUrl::getSiteinfoCached($url, true);
103 $data["images"][0]["src"] = $photo;
106 logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
108 if (!$keywords && isset($data["keywords"])) {
109 unset($data["keywords"]);
112 if (($keyword_blacklist != "") && isset($data["keywords"])) {
113 $list = explode(", ", $keyword_blacklist);
115 foreach ($list as $keyword) {
116 $keyword = trim($keyword);
118 $index = array_search($keyword, $data["keywords"]);
119 if ($index !== false) {
120 unset($data["keywords"][$index]);
128 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
130 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
133 if (isset($data["keywords"]) && count($data["keywords"])) {
134 foreach ($data["keywords"] as $keyword) {
135 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
136 ["", "", "", "", "", ""], $keyword);
142 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
149 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
151 $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
155 if (is_array($data)) {
156 $text = add_page_info_data($data, $no_photos);
162 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
164 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
166 $URLSearchString = "^\[\]";
168 // Fix for Mastodon where the mentions are in a different format
169 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
170 '$2[url=$1]$3[/url]', $body);
172 // Adding these spaces is a quick hack due to my problems with regular expressions :)
173 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
176 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
179 // Convert urls without bbcode elements
180 if (!$matches && $texturl) {
181 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
183 // Yeah, a hack. I really hate regular expressions :)
185 $matches[1] = $matches[2];
190 $footer = add_page_info($matches[1], $no_photos);
193 // Remove the link from the body if the link is attached at the end of the post
194 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
195 $removedlink = trim(str_replace($matches[1], "", $body));
196 if (($removedlink == "") || strstr($body, $removedlink)) {
197 $body = $removedlink;
200 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
201 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
202 if (($removedlink == "") || strstr($body, $removedlink)) {
203 $body = $removedlink;
207 // Add the page information to the bottom
208 if (isset($footer) && (trim($footer) != "")) {
217 * consume_feed - process atom feed and update anything/everything we might need to update
219 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
221 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
222 * It is this person's stuff that is going to be updated.
223 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
224 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
225 * have a contact record.
226 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
227 * might not) try and subscribe to it.
228 * $datedir sorts in reverse order
229 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
230 * imported prior to its children being seen in the stream unless we are certain
231 * of how the feed is arranged/ordered.
232 * With $pass = 1, we only pull parent items out of the stream.
233 * With $pass = 2, we only pull children (comments/likes).
235 * So running this twice, first with pass 1 and then with pass 2 will do the right
236 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
237 * model where comments can have sub-threads. That would require some massive sorting
238 * to get all the feed items into a mostly linear ordering, and might still require
241 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
243 if ($contact['network'] === NETWORK_OSTATUS) {
245 // Test - remove before flight
246 //$tempfile = tempnam(get_temppath(), "ostatus2");
247 //file_put_contents($tempfile, $xml);
248 logger("Consume OStatus messages ", LOGGER_DEBUG);
249 OStatus::import($xml, $importer, $contact, $hub);
255 if ($contact['network'] === NETWORK_FEED) {
257 logger("Consume feeds", LOGGER_DEBUG);
258 Feed::import($xml, $importer, $contact, $hub);
264 if ($contact['network'] === NETWORK_DFRN) {
265 logger("Consume DFRN messages", LOGGER_DEBUG);
267 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
268 `contact`.`pubkey` AS `cpubkey`,
269 `contact`.`prvkey` AS `cprvkey`,
270 `contact`.`thumb` AS `thumb`,
271 `contact`.`url` as `url`,
272 `contact`.`name` as `senderName`,
275 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
276 WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
277 DBA::escape($contact["id"]), DBA::escape($importer["uid"])
280 if (DBA::isResult($r)) {
281 logger("Now import the DFRN feed");
282 DFRN::import($xml, $r[0], true);
288 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
290 $a = BaseObject::getApp();
293 if (!empty($importer)) {
294 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
295 intval($importer['uid'])
300 * Diaspora has different message-ids in feeds than they do
301 * through the direct Diaspora protocol. If we try and use
302 * the feed, we'll get duplicates. So don't.
304 if ((!DBA::isResult($r)) || $contact['network'] === NETWORK_DIASPORA) {
308 $push_url = System::baseUrl() . '/pubsub/' . $r[0]['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('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 Network::post($url, $params);
323 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), 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)
350 $a = BaseObject::getApp();
352 // locate item to be deleted
354 $fields = ['id', 'uid', '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 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
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 ($_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 replace_macros(get_markup_template('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 ($_REQUEST['canceled']) {
406 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
410 Item::deleteForUser(['id' => $item['id']], local_user());
412 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
415 notice(L10n::t('Permission denied.') . EOL);
416 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
421 /* arrange the list in years */
422 function list_post_dates($uid, $wall)
424 $dnow = DateTimeFormat::localNow('Y-m-d');
426 $dthen = Item::firstPostDate($uid, $wall);
431 // Set the start and end date to the beginning of the month
432 $dnow = substr($dnow, 0, 8) . '01';
433 $dthen = substr($dthen, 0, 8) . '01';
438 * Starting with the current month, get the first and last days of every
439 * month down to and including the month of the first post
441 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
442 $dyear = intval(substr($dnow, 0, 4));
443 $dstart = substr($dnow, 0, 8) . '01';
444 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
445 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
446 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
447 $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
449 if (empty($ret[$dyear])) {
453 $ret[$dyear][] = [$str, $end_month, $start_month];
454 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
459 function posted_date_widget($url, $uid, $wall)
463 if (!Feature::isEnabled($uid, 'archives')) {
467 // For former Facebook folks that left because of "timeline"
469 * @TODO old-lost code?
470 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
474 $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
476 $ret = list_post_dates($uid, $wall);
478 if (!DBA::isResult($ret)) {
482 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
483 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
485 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
486 '$title' => L10n::t('Archives'),
487 '$size' => $visible_years,
488 '$cutoff_year' => $cutoff_year,
489 '$cutoff' => $cutoff,
492 '$showmore' => L10n::t('show more')