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);
153 $text = add_page_info_data($data, $no_photos);
158 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
160 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
162 $URLSearchString = "^\[\]";
164 // Fix for Mastodon where the mentions are in a different format
165 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
166 '$2[url=$1]$3[/url]', $body);
168 // Adding these spaces is a quick hack due to my problems with regular expressions :)
169 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
172 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
175 // Convert urls without bbcode elements
176 if (!$matches && $texturl) {
177 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
179 // Yeah, a hack. I really hate regular expressions :)
181 $matches[1] = $matches[2];
186 $footer = add_page_info($matches[1], $no_photos);
189 // Remove the link from the body if the link is attached at the end of the post
190 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
191 $removedlink = trim(str_replace($matches[1], "", $body));
192 if (($removedlink == "") || strstr($body, $removedlink)) {
193 $body = $removedlink;
196 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
197 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
198 if (($removedlink == "") || strstr($body, $removedlink)) {
199 $body = $removedlink;
203 // Add the page information to the bottom
204 if (isset($footer) && (trim($footer) != "")) {
213 * consume_feed - process atom feed and update anything/everything we might need to update
215 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
217 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
218 * It is this person's stuff that is going to be updated.
219 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
220 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
221 * have a contact record.
222 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
223 * might not) try and subscribe to it.
224 * $datedir sorts in reverse order
225 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
226 * imported prior to its children being seen in the stream unless we are certain
227 * of how the feed is arranged/ordered.
228 * With $pass = 1, we only pull parent items out of the stream.
229 * With $pass = 2, we only pull children (comments/likes).
231 * So running this twice, first with pass 1 and then with pass 2 will do the right
232 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
233 * model where comments can have sub-threads. That would require some massive sorting
234 * to get all the feed items into a mostly linear ordering, and might still require
237 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
239 if ($contact['network'] === NETWORK_OSTATUS) {
241 // Test - remove before flight
242 //$tempfile = tempnam(get_temppath(), "ostatus2");
243 //file_put_contents($tempfile, $xml);
244 logger("Consume OStatus messages ", LOGGER_DEBUG);
245 OStatus::import($xml, $importer, $contact, $hub);
251 if ($contact['network'] === NETWORK_FEED) {
253 logger("Consume feeds", LOGGER_DEBUG);
254 Feed::import($xml, $importer, $contact, $hub);
260 if ($contact['network'] === NETWORK_DFRN) {
261 logger("Consume DFRN messages", LOGGER_DEBUG);
263 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
264 `contact`.`pubkey` AS `cpubkey`,
265 `contact`.`prvkey` AS `cprvkey`,
266 `contact`.`thumb` AS `thumb`,
267 `contact`.`url` as `url`,
268 `contact`.`name` as `senderName`,
271 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
272 WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
273 DBA::escape($contact["id"]), DBA::escape($importer["uid"])
276 if (DBA::isResult($r)) {
277 logger("Now import the DFRN feed");
278 DFRN::import($xml, $r[0], true);
284 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
286 $a = BaseObject::getApp();
289 if (!empty($importer)) {
290 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
291 intval($importer['uid'])
296 * Diaspora has different message-ids in feeds than they do
297 * through the direct Diaspora protocol. If we try and use
298 * the feed, we'll get duplicates. So don't.
300 if ((!DBA::isResult($r)) || $contact['network'] === NETWORK_DIASPORA) {
304 $push_url = System::baseUrl() . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
306 // Use a single verify token, even if multiple hubs
307 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
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('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 Network::post($url, $params);
319 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), 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)
346 $a = BaseObject::getApp();
348 // locate item to be deleted
350 $fields = ['id', 'uid', 'contact-id', 'deleted'];
351 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
353 if (!DBA::isResult($item)) {
354 notice(L10n::t('Item not found.') . EOL);
355 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
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 ($_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 replace_macros(get_markup_template('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 ($_REQUEST['canceled']) {
402 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
406 Item::deleteForUser(['id' => $item['id']], local_user());
408 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
411 notice(L10n::t('Permission denied.') . EOL);
412 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
417 /* arrange the list in years */
418 function list_post_dates($uid, $wall)
420 $dnow = DateTimeFormat::localNow('Y-m-d');
422 $dthen = Item::firstPostDate($uid, $wall);
427 // Set the start and end date to the beginning of the month
428 $dnow = substr($dnow, 0, 8) . '01';
429 $dthen = substr($dthen, 0, 8) . '01';
434 * Starting with the current month, get the first and last days of every
435 * month down to and including the month of the first post
437 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
438 $dyear = intval(substr($dnow, 0, 4));
439 $dstart = substr($dnow, 0, 8) . '01';
440 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
441 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
442 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
443 $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
445 if (empty($ret[$dyear])) {
449 $ret[$dyear][] = [$str, $end_month, $start_month];
450 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
455 function posted_date_widget($url, $uid, $wall)
459 if (!Feature::isEnabled($uid, 'archives')) {
463 // For former Facebook folks that left because of "timeline"
465 * @TODO old-lost code?
466 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
470 $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
472 $ret = list_post_dates($uid, $wall);
474 if (!DBA::isResult($ret)) {
478 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
479 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
481 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
482 '$title' => L10n::t('Archives'),
483 '$size' => $visible_years,
484 '$cutoff_year' => $cutoff_year,
485 '$cutoff' => $cutoff,
488 '$showmore' => L10n::t('show more')