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