Restore display when there aren't unread notifications
[friendica.git/.git] / include / items.php
1 <?php
2 /**
3  * @file include/items.php
4  */
5
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\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Item;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Feed;
18 use Friendica\Protocol\OStatus;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\ParseUrl;
22 use Friendica\Util\Temporal;
23
24 require_once 'include/text.php';
25 require_once 'mod/share.php';
26 require_once 'include/enotify.php';
27
28 function add_page_info_data(array $data, $no_photos = false)
29 {
30         Addon::callHooks('page_info_data', $data);
31
32         if (empty($data['type'])) {
33                 return '';
34         }
35
36         // It maybe is a rich content, but if it does have everything that a link has,
37         // then treat it that way
38         if (($data["type"] == "rich") && is_string($data["title"]) &&
39                 is_string($data["text"]) && !empty($data["images"])) {
40                 $data["type"] = "link";
41         }
42
43         $data["title"] = defaults($data, "title", "");
44
45         if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
46                 return "";
47         }
48
49         if ($no_photos && ($data["type"] == "photo")) {
50                 return "";
51         }
52
53         // Escape some bad characters
54         $data["url"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
55         $data["title"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
56
57         $text = "[attachment type='".$data["type"]."'";
58
59         if (empty($data["text"])) {
60                 $data["text"] = $data["title"];
61         }
62
63         if (empty($data["text"])) {
64                 $data["text"] = $data["url"];
65         }
66
67         if (!empty($data["url"])) {
68                 $text .= " url='".$data["url"]."'";
69         }
70
71         if (!empty($data["title"])) {
72                 $text .= " title='".$data["title"]."'";
73         }
74
75         // Only embedd a picture link when it seems to be a valid picture ("width" is set)
76         if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
77                 $preview = str_replace(["[", "]"], ["&#91;", "&#93;"], 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."'";
83                 } else {
84                         $text .= " preview='".$preview."'";
85                 }
86         }
87
88         $text .= "]".$data["text"]."[/attachment]";
89
90         $hashtags = "";
91         if (isset($data["keywords"]) && count($data["keywords"])) {
92                 $hashtags = "\n";
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] ";
98                 }
99         }
100
101         return "\n".$text.$hashtags;
102 }
103
104 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
105 {
106         $data = ParseUrl::getSiteinfoCached($url, true);
107
108         if ($photo != "") {
109                 $data["images"][0]["src"] = $photo;
110         }
111
112         logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
113
114         if (!$keywords && isset($data["keywords"])) {
115                 unset($data["keywords"]);
116         }
117
118         if (($keyword_blacklist != "") && isset($data["keywords"])) {
119                 $list = explode(", ", $keyword_blacklist);
120
121                 foreach ($list as $keyword) {
122                         $keyword = trim($keyword);
123
124                         $index = array_search($keyword, $data["keywords"]);
125                         if ($index !== false) {
126                                 unset($data["keywords"][$index]);
127                         }
128                 }
129         }
130
131         return $data;
132 }
133
134 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
135 {
136         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
137
138         $tags = "";
139         if (isset($data["keywords"]) && count($data["keywords"])) {
140                 foreach ($data["keywords"] as $keyword) {
141                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
142                                 ["", "", "", "", "", ""], $keyword);
143
144                         if ($tags != "") {
145                                 $tags .= ", ";
146                         }
147
148                         $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
149                 }
150         }
151
152         return $tags;
153 }
154
155 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
156 {
157         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
158
159         $text = '';
160
161         if (is_array($data)) {
162                 $text = add_page_info_data($data, $no_photos);
163         }
164
165         return $text;
166 }
167
168 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
169 {
170         logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
171
172         $URLSearchString = "^\[\]";
173
174         // Fix for Mastodon where the mentions are in a different format
175         $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
176                 '$2[url=$1]$3[/url]', $body);
177
178         // Adding these spaces is a quick hack due to my problems with regular expressions :)
179         preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
180
181         if (!$matches) {
182                 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
183         }
184
185         // Convert urls without bbcode elements
186         if (!$matches && $texturl) {
187                 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
188
189                 // Yeah, a hack. I really hate regular expressions :)
190                 if ($matches) {
191                         $matches[1] = $matches[2];
192                 }
193         }
194
195         if ($matches) {
196                 $footer = add_page_info($matches[1], $no_photos);
197         }
198
199         // Remove the link from the body if the link is attached at the end of the post
200         if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
201                 $removedlink = trim(str_replace($matches[1], "", $body));
202                 if (($removedlink == "") || strstr($body, $removedlink)) {
203                         $body = $removedlink;
204                 }
205
206                 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
207                 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
208                 if (($removedlink == "") || strstr($body, $removedlink)) {
209                         $body = $removedlink;
210                 }
211         }
212
213         // Add the page information to the bottom
214         if (isset($footer) && (trim($footer) != "")) {
215                 $body .= $footer;
216         }
217
218         return $body;
219 }
220
221 /**
222  *
223  * consume_feed - process atom feed and update anything/everything we might need to update
224  *
225  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
226  *
227  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
228  *             It is this person's stuff that is going to be updated.
229  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
230  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
231  *             have a contact record.
232  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
233  *        might not) try and subscribe to it.
234  * $datedir sorts in reverse order
235  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
236  *      imported prior to its children being seen in the stream unless we are certain
237  *      of how the feed is arranged/ordered.
238  * With $pass = 1, we only pull parent items out of the stream.
239  * With $pass = 2, we only pull children (comments/likes).
240  *
241  * So running this twice, first with pass 1 and then with pass 2 will do the right
242  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
243  * model where comments can have sub-threads. That would require some massive sorting
244  * to get all the feed items into a mostly linear ordering, and might still require
245  * recursion.
246  */
247 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
248 {
249         if ($contact['network'] === Protocol::OSTATUS) {
250                 if ($pass < 2) {
251                         // Test - remove before flight
252                         //$tempfile = tempnam(get_temppath(), "ostatus2");
253                         //file_put_contents($tempfile, $xml);
254                         logger("Consume OStatus messages ", LOGGER_DEBUG);
255                         OStatus::import($xml, $importer, $contact, $hub);
256                 }
257
258                 return;
259         }
260
261         if ($contact['network'] === Protocol::FEED) {
262                 if ($pass < 2) {
263                         logger("Consume feeds", LOGGER_DEBUG);
264                         Feed::import($xml, $importer, $contact, $hub);
265                 }
266
267                 return;
268         }
269
270         if ($contact['network'] === Protocol::DFRN) {
271                 logger("Consume DFRN messages", LOGGER_DEBUG);
272                 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
273                 if (!empty($dfrn_importer)) {
274                         logger("Now import the DFRN feed");
275                         DFRN::import($xml, $dfrn_importer, true);
276                         return;
277                 }
278         }
279 }
280
281 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
282 {
283         /*
284          * Diaspora has different message-ids in feeds than they do
285          * through the direct Diaspora protocol. If we try and use
286          * the feed, we'll get duplicates. So don't.
287          */
288         if ($contact['network'] === Protocol::DIASPORA) {
289                 return;
290         }
291
292         // Without an importer we don't have a user id - so we quit
293         if (empty($importer)) {
294                 return;
295         }
296
297         $a = BaseObject::getApp();
298
299         $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
300
301         // No user, no nickname, we quit
302         if (!DBA::isResult($user)) {
303                 return;
304         }
305
306         $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
307
308         // Use a single verify token, even if multiple hubs
309         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
310
311         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
312
313         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
314
315         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
316                 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
317         }
318
319         Network::post($url, $params);
320
321         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
322
323         return;
324
325 }
326
327 function drop_items(array $items)
328 {
329         $uid = 0;
330
331         if (!local_user() && !remote_user()) {
332                 return;
333         }
334
335         if (!empty($items)) {
336                 foreach ($items as $item) {
337                         $owner = Item::deleteForUser(['id' => $item], local_user());
338
339                         if ($owner && !$uid) {
340                                 $uid = $owner;
341                         }
342                 }
343         }
344 }
345
346 function drop_item($id)
347 {
348         $a = BaseObject::getApp();
349
350         // locate item to be deleted
351
352         $fields = ['id', 'uid', 'contact-id', 'deleted'];
353         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
354
355         if (!DBA::isResult($item)) {
356                 notice(L10n::t('Item not found.') . EOL);
357                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
358         }
359
360         if ($item['deleted']) {
361                 return 0;
362         }
363
364         $contact_id = 0;
365
366         // check if logged in user is either the author or owner of this item
367
368         if (!empty($_SESSION['remote'])) {
369                 foreach ($_SESSION['remote'] as $visitor) {
370                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
371                                 $contact_id = $visitor['cid'];
372                                 break;
373                         }
374                 }
375         }
376
377         if ((local_user() == $item['uid']) || $contact_id) {
378                 // Check if we should do HTML-based delete confirmation
379                 if (!empty($_REQUEST['confirm'])) {
380                         // <form> can't take arguments in its "action" parameter
381                         // so add any arguments as hidden inputs
382                         $query = explode_querystring($a->query_string);
383                         $inputs = [];
384
385                         foreach ($query['args'] as $arg) {
386                                 if (strpos($arg, 'confirm=') === false) {
387                                         $arg_parts = explode('=', $arg);
388                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
389                                 }
390                         }
391
392                         return replace_macros(get_markup_template('confirm.tpl'), [
393                                 '$method' => 'get',
394                                 '$message' => L10n::t('Do you really want to delete this item?'),
395                                 '$extra_inputs' => $inputs,
396                                 '$confirm' => L10n::t('Yes'),
397                                 '$confirm_url' => $query['base'],
398                                 '$confirm_name' => 'confirmed',
399                                 '$cancel' => L10n::t('Cancel'),
400                         ]);
401                 }
402                 // Now check how the user responded to the confirmation query
403                 if (!empty($_REQUEST['canceled'])) {
404                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
405                 }
406
407                 // delete the item
408                 Item::deleteForUser(['id' => $item['id']], local_user());
409
410                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
411                 //NOTREACHED
412         } else {
413                 notice(L10n::t('Permission denied.') . EOL);
414                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
415                 //NOTREACHED
416         }
417 }
418
419 /* arrange the list in years */
420 function list_post_dates($uid, $wall)
421 {
422         $dnow = DateTimeFormat::localNow('Y-m-d');
423
424         $dthen = Item::firstPostDate($uid, $wall);
425         if (!$dthen) {
426                 return [];
427         }
428
429         // Set the start and end date to the beginning of the month
430         $dnow = substr($dnow, 0, 8) . '01';
431         $dthen = substr($dthen, 0, 8) . '01';
432
433         $ret = [];
434
435         /*
436          * Starting with the current month, get the first and last days of every
437          * month down to and including the month of the first post
438          */
439         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
440                 $dyear = intval(substr($dnow, 0, 4));
441                 $dstart = substr($dnow, 0, 8) . '01';
442                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
443                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
444                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
445                 $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
446
447                 if (empty($ret[$dyear])) {
448                         $ret[$dyear] = [];
449                 }
450
451                 $ret[$dyear][] = [$str, $end_month, $start_month];
452                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
453         }
454         return $ret;
455 }
456
457 function posted_date_widget($url, $uid, $wall)
458 {
459         $o = '';
460
461         if (!Feature::isEnabled($uid, 'archives')) {
462                 return $o;
463         }
464
465         // For former Facebook folks that left because of "timeline"
466         /*
467          * @TODO old-lost code?
468         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
469                 return $o;
470         */
471
472         $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
473
474         $ret = list_post_dates($uid, $wall);
475
476         if (!DBA::isResult($ret)) {
477                 return $o;
478         }
479
480         $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
481         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
482
483         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
484                 '$title' => L10n::t('Archives'),
485                 '$size' => $visible_years,
486                 '$cutoff_year' => $cutoff_year,
487                 '$cutoff' => $cutoff,
488                 '$url' => $url,
489                 '$dates' => $ret,
490                 '$showmore' => L10n::t('show more')
491
492         ]);
493         return $o;
494 }