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