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