3 * @file include/items.php
6 use Friendica\Content\Feature;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Item;
14 use Friendica\Protocol\DFRN;
15 use Friendica\Protocol\Feed;
16 use Friendica\Protocol\OStatus;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
19 use Friendica\Util\ParseUrl;
21 require_once 'include/bbcode.php';
22 require_once 'include/tags.php';
23 require_once 'include/text.php';
24 require_once 'include/threads.php';
25 require_once 'mod/share.php';
26 require_once 'include/enotify.php';
28 function add_page_info_data($data) {
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"]) && (sizeof($data["images"]) > 0)) {
35 $data["type"] = "link";
38 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
42 if ($no_photos && ($data["type"] == "photo")) {
46 // Escape some bad characters
47 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
48 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
50 $text = "[attachment type='".$data["type"]."'";
52 if ($data["text"] == "") {
53 $data["text"] = $data["title"];
56 if ($data["text"] == "") {
57 $data["text"] = $data["url"];
60 if ($data["url"] != "") {
61 $text .= " url='".$data["url"]."'";
64 if ($data["title"] != "") {
65 $text .= " title='".$data["title"]."'";
68 if (sizeof($data["images"]) > 0) {
69 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
70 // if the preview picture is larger than 500 pixels then show it in a larger mode
71 // But only, if the picture isn't higher than large (To prevent huge posts)
72 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
73 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
74 $text .= " image='".$preview."'";
76 $text .= " preview='".$preview."'";
80 $text .= "]".$data["text"]."[/attachment]";
83 if (isset($data["keywords"]) && count($data["keywords"])) {
85 foreach ($data["keywords"] AS $keyword) {
86 /// @TODO make a positive list of allowed characters
87 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
88 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
89 $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
93 return "\n".$text.$hashtags;
96 function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
98 $data = ParseUrl::getSiteinfoCached($url, true);
101 $data["images"][0]["src"] = $photo;
104 logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
106 if (!$keywords && isset($data["keywords"])) {
107 unset($data["keywords"]);
110 if (($keyword_blacklist != "") && isset($data["keywords"])) {
111 $list = explode(", ", $keyword_blacklist);
112 foreach ($list AS $keyword) {
113 $keyword = trim($keyword);
114 $index = array_search($keyword, $data["keywords"]);
115 if ($index !== false) {
116 unset($data["keywords"][$index]);
124 function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
125 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
128 if (isset($data["keywords"]) && count($data["keywords"])) {
129 foreach ($data["keywords"] AS $keyword) {
130 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
131 ["", "", "", "", "", ""], $keyword);
137 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
144 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
145 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
147 $text = add_page_info_data($data);
152 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
154 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
156 $URLSearchString = "^\[\]";
158 // Fix for Mastodon where the mentions are in a different format
159 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
160 '$2[url=$1]$3[/url]', $body);
162 // Adding these spaces is a quick hack due to my problems with regular expressions :)
163 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
166 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
169 // Convert urls without bbcode elements
170 if (!$matches && $texturl) {
171 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
173 // Yeah, a hack. I really hate regular expressions :)
175 $matches[1] = $matches[2];
180 $footer = add_page_info($matches[1], $no_photos);
183 // Remove the link from the body if the link is attached at the end of the post
184 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
185 $removedlink = trim(str_replace($matches[1], "", $body));
186 if (($removedlink == "") || strstr($body, $removedlink)) {
187 $body = $removedlink;
190 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
191 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
192 if (($removedlink == "") || strstr($body, $removedlink)) {
193 $body = $removedlink;
197 // Add the page information to the bottom
198 if (isset($footer) && (trim($footer) != "")) {
207 * consume_feed - process atom feed and update anything/everything we might need to update
209 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
211 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
212 * It is this person's stuff that is going to be updated.
213 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
214 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
215 * have a contact record.
216 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
217 * might not) try and subscribe to it.
218 * $datedir sorts in reverse order
219 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
220 * imported prior to its children being seen in the stream unless we are certain
221 * of how the feed is arranged/ordered.
222 * With $pass = 1, we only pull parent items out of the stream.
223 * With $pass = 2, we only pull children (comments/likes).
225 * So running this twice, first with pass 1 and then with pass 2 will do the right
226 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
227 * model where comments can have sub-threads. That would require some massive sorting
228 * to get all the feed items into a mostly linear ordering, and might still require
231 * @TODO find proper type-hints
233 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
234 if ($contact['network'] === NETWORK_OSTATUS) {
236 // Test - remove before flight
237 //$tempfile = tempnam(get_temppath(), "ostatus2");
238 //file_put_contents($tempfile, $xml);
239 logger("Consume OStatus messages ", LOGGER_DEBUG);
240 OStatus::import($xml, $importer, $contact, $hub);
245 if ($contact['network'] === NETWORK_FEED) {
247 logger("Consume feeds", LOGGER_DEBUG);
248 Feed::import($xml, $importer, $contact, $hub);
253 if ($contact['network'] === NETWORK_DFRN) {
254 logger("Consume DFRN messages", LOGGER_DEBUG);
256 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
257 `contact`.`pubkey` AS `cpubkey`,
258 `contact`.`prvkey` AS `cprvkey`,
259 `contact`.`thumb` AS `thumb`,
260 `contact`.`url` as `url`,
261 `contact`.`name` as `senderName`,
264 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
265 WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
266 dbesc($contact["id"]), dbesc($importer["uid"])
268 if (DBM::is_result($r)) {
269 logger("Now import the DFRN feed");
270 DFRN::import($xml, $r[0], true);
276 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
280 if (is_array($importer)) {
281 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
282 intval($importer['uid'])
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 ((!DBM::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
295 $push_url = Config::get('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
297 // Use a single verify token, even if multiple hubs
298 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
300 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
302 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
304 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
305 dba::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
308 Network::post($url, $params);
310 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
316 /// @TODO type-hint is array
317 function drop_items($items) {
320 if (!local_user() && !remote_user()) {
325 foreach ($items as $item) {
326 $owner = Item::delete($item);
333 function drop_item($id) {
337 // locate item to be deleted
339 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
343 if (!DBM::is_result($r)) {
344 notice(L10n::t('Item not found.') . EOL);
345 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
350 if ($item['deleted']) {
356 // check if logged in user is either the author or owner of this item
358 if (is_array($_SESSION['remote'])) {
359 foreach ($_SESSION['remote'] as $visitor) {
360 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
361 $contact_id = $visitor['cid'];
367 if ((local_user() == $item['uid']) || $contact_id) {
369 // Check if we should do HTML-based delete confirmation
370 if ($_REQUEST['confirm']) {
371 // <form> can't take arguments in its "action" parameter
372 // so add any arguments as hidden inputs
373 $query = explode_querystring($a->query_string);
375 foreach ($query['args'] as $arg) {
376 if (strpos($arg, 'confirm=') === false) {
377 $arg_parts = explode('=', $arg);
378 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
382 return replace_macros(get_markup_template('confirm.tpl'), [
384 '$message' => L10n::t('Do you really want to delete this item?'),
385 '$extra_inputs' => $inputs,
386 '$confirm' => L10n::t('Yes'),
387 '$confirm_url' => $query['base'],
388 '$confirm_name' => 'confirmed',
389 '$cancel' => L10n::t('Cancel'),
392 // Now check how the user responded to the confirmation query
393 if ($_REQUEST['canceled']) {
394 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
398 Item::delete($item['id']);
400 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
403 notice(L10n::t('Permission denied.') . EOL);
404 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
409 /* arrange the list in years */
410 function list_post_dates($uid, $wall) {
411 $dnow = DateTimeFormat::localNow('Y-m-d');
413 $dthen = Item::firstPostDate($uid, $wall);
418 // Set the start and end date to the beginning of the month
419 $dnow = substr($dnow, 0, 8) . '01';
420 $dthen = substr($dthen, 0, 8) . '01';
425 * Starting with the current month, get the first and last days of every
426 * month down to and including the month of the first post
428 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
429 $dyear = intval(substr($dnow, 0, 4));
430 $dstart = substr($dnow, 0, 8) . '01';
431 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
432 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
433 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
434 $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
438 $ret[$dyear][] = [$str, $end_month, $start_month];
439 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
444 function posted_date_widget($url, $uid, $wall) {
447 if (!Feature::isEnabled($uid, 'archives')) {
451 // For former Facebook folks that left because of "timeline"
453 * @TODO old-lost code?
454 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
458 $visible_years = PConfig::get($uid,'system','archive_visible_years');
459 if (!$visible_years) {
463 $ret = list_post_dates($uid, $wall);
465 if (!DBM::is_result($ret)) {
469 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
470 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
472 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
473 '$title' => L10n::t('Archives'),
474 '$size' => $visible_years,
475 '$cutoff_year' => $cutoff_year,
476 '$cutoff' => $cutoff,
479 '$showmore' => L10n::t('show more')