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