]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Add notification clear on private message display
[friendica.git] / mod / ping.php
1 <?php
2 /**
3  * @file include/ping.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\Feature;
8 use Friendica\Content\ForumManager;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Group;
19 use Friendica\Model\Item;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Temporal;
22 use Friendica\Util\Proxy as ProxyUtils;
23 use Friendica\Util\XML;
24
25 /**
26  * @brief Outputs the counts and the lists of various notifications
27  *
28  * The output format can be controlled via the GET parameter 'format'. It can be
29  * - xml (deprecated legacy default)
30  * - json (outputs JSONP with the 'callback' GET parameter)
31  *
32  * Expected JSON structure:
33  * {
34  *              "result": {
35  *                      "intro": 0,
36  *                      "mail": 0,
37  *                      "net": 0,
38  *                      "home": 0,
39  *                      "register": 0,
40  *                      "all-events": 0,
41  *                      "all-events-today": 0,
42  *                      "events": 0,
43  *                      "events-today": 0,
44  *                      "birthdays": 0,
45  *                      "birthdays-today": 0,
46  *                      "groups": [ ],
47  *                      "forums": [ ],
48  *                      "notify": 0,
49  *                      "notifications": [ ],
50  *                      "sysmsgs": {
51  *                              "notice": [ ],
52  *                              "info": [ ]
53  *                      }
54  *              }
55  *      }
56  *
57  * @param App $a The Friendica App instance
58  */
59 function ping_init(App $a)
60 {
61         $format = 'xml';
62
63         if (isset($_GET['format']) && $_GET['format'] == 'json') {
64                 $format = 'json';
65         }
66
67         $regs          = [];
68         $notifications = [];
69
70         $intro_count    = 0;
71         $mail_count     = 0;
72         $home_count     = 0;
73         $network_count  = 0;
74         $register_count = 0;
75         $sysnotify_count = 0;
76         $groups_unseen  = [];
77         $forums_unseen  = [];
78
79         $all_events       = 0;
80         $all_events_today = 0;
81         $events           = 0;
82         $events_today     = 0;
83         $birthdays        = 0;
84         $birthdays_today  = 0;
85
86         $data = [];
87         $data['intro']    = $intro_count;
88         $data['mail']     = $mail_count;
89         $data['net']      = $network_count;
90         $data['home']     = $home_count;
91         $data['register'] = $register_count;
92
93         $data['all-events']       = $all_events;
94         $data['all-events-today'] = $all_events_today;
95         $data['events']           = $events;
96         $data['events-today']     = $events_today;
97         $data['birthdays']        = $birthdays;
98         $data['birthdays-today']  = $birthdays_today;
99
100         if (local_user()) {
101                 // Different login session than the page that is calling us.
102                 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
103                         $data = ['result' => ['invalid' => 1]];
104
105                         if ($format == 'json') {
106                                 if (isset($_GET['callback'])) {
107                                         // JSONP support
108                                         header("Content-type: application/javascript");
109                                         echo $_GET['callback'] . '(' . json_encode($data) . ')';
110                                 } else {
111                                         header("Content-type: application/json");
112                                         echo json_encode($data);
113                                 }
114                         } else {
115                                 header("Content-type: text/xml");
116                                 echo XML::fromArray($data, $xml);
117                         }
118                         killme();
119                 }
120
121                 $notifs = ping_get_notifications(local_user());
122
123                 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
124                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
125                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
126                 $params = ['order' => ['created' => true]];
127                 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
128
129                 if (DBA::isResult($items)) {
130                         $items_unseen = Item::inArray($items);
131                         $arr = ['items' => $items_unseen];
132                         Addon::callHooks('network_ping', $arr);
133
134                         foreach ($items_unseen as $item) {
135                                 if ($item['wall']) {
136                                         $home_count++;
137                                 } else {
138                                         $network_count++;
139                                 }
140                         }
141                 }
142
143                 if ($network_count) {
144                         // Find out how unseen network posts are spread across groups
145                         $group_counts = Group::countUnseen();
146                         if (DBA::isResult($group_counts)) {
147                                 foreach ($group_counts as $group_count) {
148                                         if ($group_count['count'] > 0) {
149                                                 $groups_unseen[] = $group_count;
150                                         }
151                                 }
152                         }
153
154                         $forum_counts = ForumManager::countUnseenItems();
155                         if (DBA::isResult($forum_counts)) {
156                                 foreach ($forum_counts as $forum_count) {
157                                         if ($forum_count['count'] > 0) {
158                                                 $forums_unseen[] = $forum_count;
159                                         }
160                                 }
161                         }
162                 }
163
164                 $intros1 = q(
165                         "SELECT  `intro`.`id`, `intro`.`datetime`,
166                         `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
167                         FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
168                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
169                         intval(local_user())
170                 );
171                 $intros2 = q(
172                         "SELECT `intro`.`id`, `intro`.`datetime`,
173                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
174                         FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
175                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
176                         intval(local_user())
177                 );
178
179                 $intro_count = count($intros1) + count($intros2);
180                 $intros = $intros1 + $intros2;
181
182                 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'];
183                 $mails = q(
184                         "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
185                         WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
186                         intval(local_user()),
187                         DBA::escape($myurl)
188                 );
189                 $mail_count = count($mails);
190
191                 if (intval(Config::get('config', 'register_policy')) === REGISTER_APPROVE && is_site_admin()) {
192                         $regs = Friendica\Model\Register::getPending();
193
194                         if (DBA::isResult($regs)) {
195                                 $register_count = count($regs);
196                         }
197                 }
198
199                 $cachekey = "ping_init:".local_user();
200                 $ev = Cache::get($cachekey);
201                 if (is_null($ev)) {
202                         $ev = q(
203                                 "SELECT type, start, adjust FROM `event`
204                                 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
205                                 ORDER BY `start` ASC ",
206                                 intval(local_user()),
207                                 DBA::escape(DateTimeFormat::utc('now + 7 days')),
208                                 DBA::escape(DateTimeFormat::utcNow())
209                         );
210                         if (DBA::isResult($ev)) {
211                                 Cache::set($cachekey, $ev, Cache::HOUR);
212                         }
213                 }
214
215                 if (DBA::isResult($ev)) {
216                         $all_events = count($ev);
217
218                         if ($all_events) {
219                                 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
220                                 foreach ($ev as $x) {
221                                         $bd = false;
222                                         if ($x['type'] === 'birthday') {
223                                                 $birthdays ++;
224                                                 $bd = true;
225                                         } else {
226                                                 $events ++;
227                                         }
228                                         if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
229                                                 $all_events_today ++;
230                                                 if ($bd) {
231                                                         $birthdays_today ++;
232                                                 } else {
233                                                         $events_today ++;
234                                                 }
235                                         }
236                                 }
237                         }
238                 }
239
240                 $data['intro']    = $intro_count;
241                 $data['mail']     = $mail_count;
242                 $data['net']      = $network_count;
243                 $data['home']     = $home_count;
244                 $data['register'] = $register_count;
245
246                 $data['all-events']       = $all_events;
247                 $data['all-events-today'] = $all_events_today;
248                 $data['events']           = $events;
249                 $data['events-today']     = $events_today;
250                 $data['birthdays']        = $birthdays;
251                 $data['birthdays-today']  = $birthdays_today;
252
253                 if (DBA::isResult($notifs)) {
254                         foreach ($notifs as $notif) {
255                                 if ($notif['seen'] == 0) {
256                                         $sysnotify_count ++;
257                                 }
258                         }
259                 }
260
261                 // merge all notification types in one array
262                 if (DBA::isResult($intros)) {
263                         foreach ($intros as $intro) {
264                                 $notif = [
265                                         'id'      => 0,
266                                         'href'    => System::baseUrl() . '/notifications/intros/' . $intro['id'],
267                                         'name'    => $intro['name'],
268                                         'url'     => $intro['url'],
269                                         'photo'   => $intro['photo'],
270                                         'date'    => $intro['datetime'],
271                                         'seen'    => false,
272                                         'message' => L10n::t('{0} wants to be your friend'),
273                                 ];
274                                 $notifs[] = $notif;
275                         }
276                 }
277
278                 if (DBA::isResult($mails)) {
279                         foreach ($mails as $mail) {
280                                 $notif = [
281                                         'id'      => 0,
282                                         'href'    => System::baseUrl() . '/message/' . $mail['id'],
283                                         'name'    => $mail['from-name'],
284                                         'url'     => $mail['from-url'],
285                                         'photo'   => $mail['from-photo'],
286                                         'date'    => $mail['created'],
287                                         'seen'    => false,
288                                         'message' => L10n::t('{0} sent you a message'),
289                                 ];
290                                 $notifs[] = $notif;
291                         }
292                 }
293
294                 if (DBA::isResult($regs)) {
295                         foreach ($regs as $reg) {
296                                 $notif = [
297                                         'id'      => 0,
298                                         'href'    => System::baseUrl() . '/admin/users/',
299                                         'name'    => $reg['name'],
300                                         'url'     => $reg['url'],
301                                         'photo'   => $reg['micro'],
302                                         'date'    => $reg['created'],
303                                         'seen'    => false,
304                                         'message' => L10n::t('{0} requested registration'),
305                                 ];
306                                 $notifs[] = $notif;
307                         }
308                 }
309
310                 // sort notifications by $[]['date']
311                 $sort_function = function ($a, $b) {
312                         $adate = strtotime($a['date']);
313                         $bdate = strtotime($b['date']);
314
315                         // Unseen messages are kept at the top
316                         // The value 31536000 means one year. This should be enough :-)
317                         if (!$a['seen']) {
318                                 $adate += 31536000;
319                         }
320                         if (!$b['seen']) {
321                                 $bdate += 31536000;
322                         }
323
324                         if ($adate == $bdate) {
325                                 return 0;
326                         }
327                         return ($adate < $bdate) ? 1 : -1;
328                 };
329                 usort($notifs, $sort_function);
330
331                 if (DBA::isResult($notifs)) {
332                         // Are the nofications called from the regular process or via the friendica app?
333                         $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
334
335                         foreach ($notifs as $notif) {
336                                 if ($a->isFriendicaApp() || !$regularnotifications) {
337                                         $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
338                                 }
339
340                                 $contact = Contact::getDetailsByURL($notif['url']);
341                                 if (isset($contact['micro'])) {
342                                         $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
343                                 } else {
344                                         $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
345                                 }
346
347                                 $local_time = DateTimeFormat::local($notif['date']);
348
349                                 $notifications[] = [
350                                         'id'        => $notif['id'],
351                                         'href'      => $notif['href'],
352                                         'name'      => $notif['name'],
353                                         'url'       => $notif['url'],
354                                         'photo'     => $notif['photo'],
355                                         'date'      => Temporal::getRelativeDate($notif['date']),
356                                         'message'   => $notif['message'],
357                                         'seen'      => $notif['seen'],
358                                         'timestamp' => strtotime($local_time)
359                                 ];
360                         }
361                 }
362         }
363
364         $sysmsgs = [];
365         $sysmsgs_info = [];
366
367         if (!empty($_SESSION['sysmsg'])) {
368                 $sysmsgs = $_SESSION['sysmsg'];
369                 unset($_SESSION['sysmsg']);
370         }
371
372         if (!empty($_SESSION['sysmsg_info'])) {
373                 $sysmsgs_info = $_SESSION['sysmsg_info'];
374                 unset($_SESSION['sysmsg_info']);
375         }
376
377         if ($format == 'json') {
378                 $data['groups'] = $groups_unseen;
379                 $data['forums'] = $forums_unseen;
380                 $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
381                 $data['notifications'] = $notifications;
382                 $data['sysmsgs'] = [
383                         'notice' => $sysmsgs,
384                         'info' => $sysmsgs_info
385                 ];
386
387                 $json_payload = json_encode(["result" => $data]);
388
389                 if (isset($_GET['callback'])) {
390                         // JSONP support
391                         header("Content-type: application/javascript");
392                         echo $_GET['callback'] . '(' . $json_payload . ')';
393                 } else {
394                         header("Content-type: application/json");
395                         echo $json_payload;
396                 }
397         } else {
398                 // Legacy slower XML format output
399                 $data = ping_format_xml_data($data, $sysnotify_count, $notifications, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen);
400
401                 header("Content-type: text/xml");
402                 echo XML::fromArray(["result" => $data], $xml);
403         }
404
405         killme();
406 }
407
408 /**
409  * @brief Retrieves the notifications array for the given user ID
410  *
411  * @param int $uid User id
412  * @return array Associative array of notifications
413  */
414 function ping_get_notifications($uid)
415 {
416         $result  = [];
417         $offset  = 0;
418         $seen    = false;
419         $seensql = "NOT";
420         $order   = "DESC";
421         $quit    = false;
422
423         do {
424                 $r = q(
425                         "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
426                         FROM `notify` LEFT JOIN `item` ON `item`.`id` = `notify`.`iid`
427                         WHERE `notify`.`uid` = %d AND `notify`.`msg` != ''
428                         AND NOT (`notify`.`type` IN (%d, %d))
429                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
430                         intval($uid),
431                         intval(NOTIFY_INTRO),
432                         intval(NOTIFY_MAIL),
433                         intval($offset)
434                 );
435
436                 if (!$r && !$seen) {
437                         $seen = true;
438                         $seensql = "";
439                         $order = "DESC";
440                         $offset = 0;
441                 } elseif (!$r) {
442                         $quit = true;
443                 } else {
444                         $offset += 50;
445                 }
446
447                 foreach ($r as $notification) {
448                         if (is_null($notification["visible"])) {
449                                 $notification["visible"] = true;
450                         }
451
452                         if (is_null($notification["deleted"])) {
453                                 $notification["deleted"] = 0;
454                         }
455
456                         if ($notification["msg_cache"]) {
457                                 $notification["name"] = $notification["name_cache"];
458                                 $notification["message"] = $notification["msg_cache"];
459                         } else {
460                                 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
461                                 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
462
463                                 q(
464                                         "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
465                                         DBA::escape($notification["name"]),
466                                         DBA::escape($notification["message"]),
467                                         intval($notification["id"])
468                                 );
469                         }
470
471                         $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
472
473                         if ($notification["visible"]
474                                 && !$notification["deleted"]
475                                 && empty($result[$notification["parent"]])
476                         ) {
477                                 // Should we condense the notifications or show them all?
478                                 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
479                                         $result[$notification["id"]] = $notification;
480                                 } else {
481                                         $result[$notification["parent"]] = $notification;
482                                 }
483                         }
484                 }
485         } while ((count($result) < 50) && !$quit);
486
487         return($result);
488 }
489
490 /**
491  * @brief Backward-compatible XML formatting for ping.php output
492  * @deprecated
493  *
494  * @param array $data            The initial ping data array
495  * @param int   $sysnotify_count Number of unseen system notifications
496  * @param array $notifs          Complete list of notification
497  * @param array $sysmsgs         List of system notice messages
498  * @param array $sysmsgs_info    List of system info messages
499  * @param array $groups_unseen   List of unseen group messages
500  * @param array $forums_unseen   List of unseen forum messages
501  *
502  * @return array XML-transform ready data array
503  */
504 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
505 {
506         $notifications = [];
507         foreach ($notifs as $key => $notif) {
508                 $notifications[$key . ':note'] = $notif['message'];
509
510                 $notifications[$key . ':@attributes'] = [
511                         'id'        => $notif['id'],
512                         'href'      => $notif['href'],
513                         'name'      => $notif['name'],
514                         'url'       => $notif['url'],
515                         'photo'     => $notif['photo'],
516                         'date'      => $notif['date'],
517                         'seen'      => $notif['seen'],
518                         'timestamp' => $notif['timestamp']
519                 ];
520         }
521
522         $sysmsg = [];
523         foreach ($sysmsgs as $key => $m) {
524                 $sysmsg[$key . ':notice'] = $m;
525         }
526         foreach ($sysmsgs_info as $key => $m) {
527                 $sysmsg[$key . ':info'] = $m;
528         }
529
530         $data['notif'] = $notifications;
531         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
532         $data['sysmsgs'] = $sysmsg;
533
534         if ($data['register'] == 0) {
535                 unset($data['register']);
536         }
537
538         $groups = [];
539         if (count($groups_unseen)) {
540                 foreach ($groups_unseen as $key => $item) {
541                         $groups[$key . ':group'] = $item['count'];
542                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
543                 }
544                 $data['groups'] = $groups;
545         }
546
547         $forums = [];
548         if (count($forums_unseen)) {
549                 foreach ($forums_unseen as $key => $item) {
550                         $forums[$key . ':forum'] = $item['count'];
551                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
552                 }
553                 $data['forums'] = $forums;
554         }
555
556         return $data;
557 }