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