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