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\Worker;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Group;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Model\Item;
20 use Friendica\Model\Conversation;
21 use Friendica\Object\Image;
22 use Friendica\Protocol\DFRN;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\Feed;
25 use Friendica\Util\Network;
26 use Friendica\Util\ParseUrl;
28 require_once 'include/bbcode.php';
29 require_once 'include/tags.php';
30 require_once 'include/text.php';
31 require_once 'include/threads.php';
32 require_once 'mod/share.php';
33 require_once 'include/enotify.php';
35 function add_page_info_data($data) {
36 Addon::callHooks('page_info_data', $data);
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"]) && (sizeof($data["images"]) > 0)) {
42 $data["type"] = "link";
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 ($data["text"] == "") {
60 $data["text"] = $data["title"];
63 if ($data["text"] == "") {
64 $data["text"] = $data["url"];
67 if ($data["url"] != "") {
68 $text .= " url='".$data["url"]."'";
71 if ($data["title"] != "") {
72 $text .= " title='".$data["title"]."'";
75 if (sizeof($data["images"]) > 0) {
76 $preview = str_replace(["[", "]"], ["[", "]"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
77 // if the preview picture is larger than 500 pixels then show it in a larger mode
78 // But only, if the picture isn't higher than large (To prevent huge posts)
79 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
80 && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
81 $text .= " image='".$preview."'";
83 $text .= " preview='".$preview."'";
87 $text .= "]".$data["text"]."[/attachment]";
90 if (isset($data["keywords"]) && count($data["keywords"])) {
92 foreach ($data["keywords"] AS $keyword) {
93 /// @TODO make a positive list of allowed characters
94 $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
95 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
96 $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
100 return "\n".$text.$hashtags;
103 function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
105 $data = ParseUrl::getSiteinfoCached($url, true);
108 $data["images"][0]["src"] = $photo;
111 logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
113 if (!$keywords && isset($data["keywords"])) {
114 unset($data["keywords"]);
117 if (($keyword_blacklist != "") && isset($data["keywords"])) {
118 $list = explode(", ", $keyword_blacklist);
119 foreach ($list AS $keyword) {
120 $keyword = trim($keyword);
121 $index = array_search($keyword, $data["keywords"]);
122 if ($index !== false) {
123 unset($data["keywords"][$index]);
131 function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
132 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
135 if (isset($data["keywords"]) && count($data["keywords"])) {
136 foreach ($data["keywords"] AS $keyword) {
137 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
138 ["", "", "", "", "", ""], $keyword);
144 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
151 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
152 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
154 $text = add_page_info_data($data);
159 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
161 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
163 $URLSearchString = "^\[\]";
165 // Fix for Mastodon where the mentions are in a different format
166 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
167 '$2[url=$1]$3[/url]', $body);
169 // Adding these spaces is a quick hack due to my problems with regular expressions :)
170 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
173 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
176 // Convert urls without bbcode elements
177 if (!$matches && $texturl) {
178 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
180 // Yeah, a hack. I really hate regular expressions :)
182 $matches[1] = $matches[2];
187 $footer = add_page_info($matches[1], $no_photos);
190 // Remove the link from the body if the link is attached at the end of the post
191 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
192 $removedlink = trim(str_replace($matches[1], "", $body));
193 if (($removedlink == "") || strstr($body, $removedlink)) {
194 $body = $removedlink;
197 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
198 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
199 if (($removedlink == "") || strstr($body, $removedlink)) {
200 $body = $removedlink;
204 // Add the page information to the bottom
205 if (isset($footer) && (trim($footer) != "")) {
214 * consume_feed - process atom feed and update anything/everything we might need to update
216 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
218 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
219 * It is this person's stuff that is going to be updated.
220 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
221 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
222 * have a contact record.
223 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
224 * might not) try and subscribe to it.
225 * $datedir sorts in reverse order
226 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
227 * imported prior to its children being seen in the stream unless we are certain
228 * of how the feed is arranged/ordered.
229 * With $pass = 1, we only pull parent items out of the stream.
230 * With $pass = 2, we only pull children (comments/likes).
232 * So running this twice, first with pass 1 and then with pass 2 will do the right
233 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
234 * model where comments can have sub-threads. That would require some massive sorting
235 * to get all the feed items into a mostly linear ordering, and might still require
238 * @TODO find proper type-hints
240 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
241 if ($contact['network'] === NETWORK_OSTATUS) {
243 // Test - remove before flight
244 //$tempfile = tempnam(get_temppath(), "ostatus2");
245 //file_put_contents($tempfile, $xml);
246 logger("Consume OStatus messages ", LOGGER_DEBUG);
247 OStatus::import($xml, $importer, $contact, $hub);
252 if ($contact['network'] === NETWORK_FEED) {
254 logger("Consume feeds", LOGGER_DEBUG);
255 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 dbesc($contact["id"]), dbesc($importer["uid"])
275 if (DBM::is_result($r)) {
276 logger("Now import the DFRN feed");
277 DFRN::import($xml, $r[0], true);
283 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
287 if (is_array($importer)) {
288 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
289 intval($importer['uid'])
294 * Diaspora has different message-ids in feeds than they do
295 * through the direct Diaspora protocol. If we try and use
296 * the feed, we'll get duplicates. So don't.
298 if ((!DBM::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
302 $push_url = Config::get('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
304 // Use a single verify token, even if multiple hubs
305 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
307 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
309 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
311 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
312 dba::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
315 Network::post($url, $params);
317 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
323 /// @TODO type-hint is array
324 function drop_items($items) {
327 if (!local_user() && !remote_user()) {
332 foreach ($items as $item) {
333 $owner = Item::delete($item);
340 function drop_item($id) {
344 // locate item to be deleted
346 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
350 if (!DBM::is_result($r)) {
351 notice(L10n::t('Item not found.') . EOL);
352 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
357 if ($item['deleted']) {
363 // check if logged in user is either the author or owner of this item
365 if (is_array($_SESSION['remote'])) {
366 foreach ($_SESSION['remote'] as $visitor) {
367 if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
368 $contact_id = $visitor['cid'];
374 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);
382 foreach ($query['args'] as $arg) {
383 if (strpos($arg, 'confirm=') === false) {
384 $arg_parts = explode('=', $arg);
385 $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
389 return replace_macros(get_markup_template('confirm.tpl'), [
391 '$message' => L10n::t('Do you really want to delete this item?'),
392 '$extra_inputs' => $inputs,
393 '$confirm' => L10n::t('Yes'),
394 '$confirm_url' => $query['base'],
395 '$confirm_name' => 'confirmed',
396 '$cancel' => L10n::t('Cancel'),
399 // Now check how the user responded to the confirmation query
400 if ($_REQUEST['canceled']) {
401 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
405 Item::delete($item['id']);
407 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
410 notice(L10n::t('Permission denied.') . EOL);
411 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
416 /* arrange the list in years */
417 function list_post_dates($uid, $wall) {
418 $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
420 $dthen = Item::firstPostDate($uid, $wall);
425 // Set the start and end date to the beginning of the month
426 $dnow = substr($dnow, 0, 8) . '01';
427 $dthen = substr($dthen, 0, 8) . '01';
432 * Starting with the current month, get the first and last days of every
433 * month down to and including the month of the first post
435 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
436 $dyear = intval(substr($dnow, 0, 4));
437 $dstart = substr($dnow, 0, 8) . '01';
438 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
439 $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
440 $end_month = datetime_convert('', '', $dend, 'Y-m-d');
441 $str = day_translate(datetime_convert('', '', $dnow, 'F'));
445 $ret[$dyear][] = [$str, $end_month, $start_month];
446 $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
451 function posted_date_widget($url, $uid, $wall) {
454 if (!Feature::isEnabled($uid, 'archives')) {
458 // For former Facebook folks that left because of "timeline"
460 * @TODO old-lost code?
461 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
465 $visible_years = PConfig::get($uid,'system','archive_visible_years');
466 if (!$visible_years) {
470 $ret = list_post_dates($uid, $wall);
472 if (!DBM::is_result($ret)) {
476 $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
477 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
479 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
480 '$title' => L10n::t('Archives'),
481 '$size' => $visible_years,
482 '$cutoff_year' => $cutoff_year,
483 '$cutoff' => $cutoff,
486 '$showmore' => L10n::t('show more')