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