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\Core\Worker;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Group;
18 use Friendica\Model\Item;
19 use Friendica\Model\Term;
20 use Friendica\Model\User;
21 use Friendica\Object\Image;
22 use Friendica\Protocol\DFRN;
23 use Friendica\Protocol\Feed;
24 use Friendica\Util\Network;
25 use Friendica\Protocol\OStatus;
26 use Friendica\Util\ParseUrl;
27 use Friendica\Util\Temporal;
29 require_once 'include/bbcode.php';
30 require_once 'include/tags.php';
31 require_once 'include/text.php';
32 require_once 'include/threads.php';
33 require_once 'mod/share.php';
34 require_once 'include/enotify.php';
36 function add_page_info_data($data) {
37 Addon::callHooks('page_info_data', $data);
39 // It maybe is a rich content, but if it does have everything that a link has,
40 // then treat it that way
41 if (($data["type"] == "rich") && is_string($data["title"]) &&
42 is_string($data["text"]) && (sizeof($data["images"]) > 0)) {
43 $data["type"] = "link";
46 if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
50 if ($no_photos && ($data["type"] == "photo")) {
54 // Escape some bad characters
55 $data["url"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
56 $data["title"] = str_replace(["[", "]"], ["[", "]"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
58 $text = "[attachment type='".$data["type"]."'";
60 if ($data["text"] == "") {
61 $data["text"] = $data["title"];
64 if ($data["text"] == "") {
65 $data["text"] = $data["url"];
68 if ($data["url"] != "") {
69 $text .= " url='".$data["url"]."'";
72 if ($data["title"] != "") {
73 $text .= " title='".$data["title"]."'";
76 if (sizeof($data["images"]) > 0) {
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, $no_photos = false, $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);
120 foreach ($list AS $keyword) {
121 $keyword = trim($keyword);
122 $index = array_search($keyword, $data["keywords"]);
123 if ($index !== false) {
124 unset($data["keywords"][$index]);
132 function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
133 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
136 if (isset($data["keywords"]) && count($data["keywords"])) {
137 foreach ($data["keywords"] AS $keyword) {
138 $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
139 ["", "", "", "", "", ""], $keyword);
145 $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
152 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
153 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
155 $text = add_page_info_data($data);
160 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
162 logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
164 $URLSearchString = "^\[\]";
166 // Fix for Mastodon where the mentions are in a different format
167 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
168 '$2[url=$1]$3[/url]', $body);
170 // Adding these spaces is a quick hack due to my problems with regular expressions :)
171 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
174 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
177 // Convert urls without bbcode elements
178 if (!$matches && $texturl) {
179 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
181 // Yeah, a hack. I really hate regular expressions :)
183 $matches[1] = $matches[2];
188 $footer = add_page_info($matches[1], $no_photos);
191 // Remove the link from the body if the link is attached at the end of the post
192 if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
193 $removedlink = trim(str_replace($matches[1], "", $body));
194 if (($removedlink == "") || strstr($body, $removedlink)) {
195 $body = $removedlink;
198 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
199 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
200 if (($removedlink == "") || strstr($body, $removedlink)) {
201 $body = $removedlink;
205 // Add the page information to the bottom
206 if (isset($footer) && (trim($footer) != "")) {
215 * consume_feed - process atom feed and update anything/everything we might need to update
217 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
219 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
220 * It is this person's stuff that is going to be updated.
221 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
222 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
223 * have a contact record.
224 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
225 * might not) try and subscribe to it.
226 * $datedir sorts in reverse order
227 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
228 * imported prior to its children being seen in the stream unless we are certain
229 * of how the feed is arranged/ordered.
230 * With $pass = 1, we only pull parent items out of the stream.
231 * With $pass = 2, we only pull children (comments/likes).
233 * So running this twice, first with pass 1 and then with pass 2 will do the right
234 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
235 * model where comments can have sub-threads. That would require some massive sorting
236 * to get all the feed items into a mostly linear ordering, and might still require
239 * @TODO find proper type-hints
241 function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
242 if ($contact['network'] === NETWORK_OSTATUS) {
244 // Test - remove before flight
245 //$tempfile = tempnam(get_temppath(), "ostatus2");
246 //file_put_contents($tempfile, $xml);
247 logger("Consume OStatus messages ", LOGGER_DEBUG);
248 OStatus::import($xml, $importer, $contact, $hub);
253 if ($contact['network'] === NETWORK_FEED) {
255 logger("Consume feeds", LOGGER_DEBUG);
256 Feed::import($xml, $importer, $contact, $hub);
261 if ($contact['network'] === NETWORK_DFRN) {
262 logger("Consume DFRN messages", LOGGER_DEBUG);
264 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
265 `contact`.`pubkey` AS `cpubkey`,
266 `contact`.`prvkey` AS `cprvkey`,
267 `contact`.`thumb` AS `thumb`,
268 `contact`.`url` as `url`,
269 `contact`.`name` as `senderName`,
272 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
273 WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
274 dbesc($contact["id"]), dbesc($importer["uid"])
276 if (DBM::is_result($r)) {
277 logger("Now import the DFRN feed");
278 DFRN::import($xml, $r[0], true);
284 function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
288 if (is_array($importer)) {
289 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
290 intval($importer['uid'])
295 * Diaspora has different message-ids in feeds than they do
296 * through the direct Diaspora protocol. If we try and use
297 * the feed, we'll get duplicates. So don't.
299 if ((!DBM::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
303 $push_url = Config::get('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
305 // Use a single verify token, even if multiple hubs
306 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
308 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
310 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
312 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
313 dba::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
316 Network::post($url, $params);
318 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
324 /// @TODO type-hint is array
325 function drop_items($items) {
328 if (!local_user() && !remote_user()) {
333 foreach ($items as $item) {
334 $owner = Item::delete($item);
341 function drop_item($id) {
345 // locate item to be deleted
347 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
351 if (!DBM::is_result($r)) {
352 notice(L10n::t('Item not found.') . EOL);
353 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 (is_array($_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) {
377 // Check if we should do HTML-based delete confirmation
378 if ($_REQUEST['confirm']) {
379 // <form> can't take arguments in its "action" parameter
380 // so add any arguments as hidden inputs
381 $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::delete($item['id']);
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) {
419 $dnow = Temporal::convert('now', date_default_timezone_get(), 'UTC', 'Y-m-d');
421 $dthen = Item::firstPostDate($uid, $wall);
426 // Set the start and end date to the beginning of the month
427 $dnow = substr($dnow, 0, 8) . '01';
428 $dthen = substr($dthen, 0, 8) . '01';
433 * Starting with the current month, get the first and last days of every
434 * month down to and including the month of the first post
436 while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
437 $dyear = intval(substr($dnow, 0, 4));
438 $dstart = substr($dnow, 0, 8) . '01';
439 $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
440 $start_month = Temporal::convert($dstart, 'UTC', 'UTC', 'Y-m-d');
441 $end_month = Temporal::convert($dend, 'UTC', 'UTC', 'Y-m-d');
442 $str = day_translate(Temporal::convert($dnow, 'UTC', 'UTC', 'F'));
446 $ret[$dyear][] = [$str, $end_month, $start_month];
447 $dnow = Temporal::convert($dnow . ' -1 month', 'UTC', 'UTC', 'Y-m-d');
452 function posted_date_widget($url, $uid, $wall) {
455 if (!Feature::isEnabled($uid, 'archives')) {
459 // For former Facebook folks that left because of "timeline"
461 * @TODO old-lost code?
462 if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
466 $visible_years = PConfig::get($uid,'system','archive_visible_years');
467 if (!$visible_years) {
471 $ret = list_post_dates($uid, $wall);
473 if (!DBM::is_result($ret)) {
477 $cutoff_year = intval(Temporal::convert('now', date_default_timezone_get(), 'UTC', 'Y')) - $visible_years;
478 $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
480 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
481 '$title' => L10n::t('Archives'),
482 '$size' => $visible_years,
483 '$cutoff_year' => $cutoff_year,
484 '$cutoff' => $cutoff,
487 '$showmore' => L10n::t('show more')