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