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