]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Merge pull request #5963 from MrPetovan/bug/5956-catch-more-diaspora-magic-links
[friendica.git] / mod / ping.php
1 <?php
2 /**
3  * @file include/ping.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\Feature;
8 use Friendica\Content\ForumManager;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Group;
19 use Friendica\Model\Item;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Temporal;
22 use Friendica\Util\Proxy as ProxyUtils;
23 use Friendica\Util\XML;
24
25 require_once 'include/enotify.php';
26
27 /**
28  * @brief Outputs the counts and the lists of various notifications
29  *
30  * The output format can be controlled via the GET parameter 'format'. It can be
31  * - xml (deprecated legacy default)
32  * - json (outputs JSONP with the 'callback' GET parameter)
33  *
34  * Expected JSON structure:
35  * {
36  *              "result": {
37  *                      "intro": 0,
38  *                      "mail": 0,
39  *                      "net": 0,
40  *                      "home": 0,
41  *                      "register": 0,
42  *                      "all-events": 0,
43  *                      "all-events-today": 0,
44  *                      "events": 0,
45  *                      "events-today": 0,
46  *                      "birthdays": 0,
47  *                      "birthdays-today": 0,
48  *                      "groups": [ ],
49  *                      "forums": [ ],
50  *                      "notify": 0,
51  *                      "notifications": [ ],
52  *                      "sysmsgs": {
53  *                              "notice": [ ],
54  *                              "info": [ ]
55  *                      }
56  *              }
57  *      }
58  *
59  * @param App $a The Friendica App instance
60  */
61 function ping_init(App $a)
62 {
63         $format = 'xml';
64
65         if (isset($_GET['format']) && $_GET['format'] == 'json') {
66                 $format = 'json';
67         }
68
69         $tags          = [];
70         $comments      = [];
71         $likes         = [];
72         $dislikes      = [];
73         $friends       = [];
74         $posts         = [];
75         $regs          = [];
76         $mails         = [];
77         $notifications = [];
78
79         $intro_count    = 0;
80         $mail_count     = 0;
81         $home_count     = 0;
82         $network_count  = 0;
83         $register_count = 0;
84         $sysnotify_count = 0;
85         $groups_unseen  = [];
86         $forums_unseen  = [];
87
88         $all_events       = 0;
89         $all_events_today = 0;
90         $events           = 0;
91         $events_today     = 0;
92         $birthdays        = 0;
93         $birthdays_today  = 0;
94
95         $data = [];
96         $data['intro']    = $intro_count;
97         $data['mail']     = $mail_count;
98         $data['net']      = $network_count;
99         $data['home']     = $home_count;
100         $data['register'] = $register_count;
101
102         $data['all-events']       = $all_events;
103         $data['all-events-today'] = $all_events_today;
104         $data['events']           = $events;
105         $data['events-today']     = $events_today;
106         $data['birthdays']        = $birthdays;
107         $data['birthdays-today']  = $birthdays_today;
108
109         if (local_user()) {
110                 // Different login session than the page that is calling us.
111                 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
112                         $data = ['result' => ['invalid' => 1]];
113
114                         if ($format == 'json') {
115                                 if (isset($_GET['callback'])) {
116                                         // JSONP support
117                                         header("Content-type: application/javascript");
118                                         echo $_GET['callback'] . '(' . json_encode($data) . ')';
119                                 } else {
120                                         header("Content-type: application/json");
121                                         echo json_encode($data);
122                                 }
123                         } else {
124                                 header("Content-type: text/xml");
125                                 echo XML::fromArray($data, $xml);
126                         }
127                         killme();
128                 }
129
130                 $notifs = ping_get_notifications(local_user());
131
132                 $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
133                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
134                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall'];
135                 $params = ['order' => ['created' => true]];
136                 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
137
138                 if (DBA::isResult($items)) {
139                         $items_unseen = Item::inArray($items);
140                         $arr = ['items' => $items_unseen];
141                         Addon::callHooks('network_ping', $arr);
142
143                         foreach ($items_unseen as $item) {
144                                 if ($item['wall']) {
145                                         $home_count++;
146                                 } else {
147                                         $network_count++;
148                                 }
149                         }
150                 }
151
152                 if ($network_count) {
153                         if (intval(Feature::isEnabled(local_user(), 'groups'))) {
154                                 // Find out how unseen network posts are spread across groups
155                                 $group_counts = Group::countUnseen();
156                                 if (DBA::isResult($group_counts)) {
157                                         foreach ($group_counts as $group_count) {
158                                                 if ($group_count['count'] > 0) {
159                                                         $groups_unseen[] = $group_count;
160                                                 }
161                                         }
162                                 }
163                         }
164
165                         if (intval(Feature::isEnabled(local_user(), 'forumlist_widget'))) {
166                                 $forum_counts = ForumManager::countUnseenItems();
167                                 if (DBA::isResult($forum_counts)) {
168                                         foreach ($forum_counts as $forum_count) {
169                                                 if ($forum_count['count'] > 0) {
170                                                         $forums_unseen[] = $forum_count;
171                                                 }
172                                         }
173                                 }
174                         }
175                 }
176
177                 $intros1 = q(
178                         "SELECT  `intro`.`id`, `intro`.`datetime`,
179                         `fcontact`.`name`, `fcontact`.`url`, `fcontact`.`photo`
180                         FROM `intro` LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
181                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`fid` != 0",
182                         intval(local_user())
183                 );
184                 $intros2 = q(
185                         "SELECT `intro`.`id`, `intro`.`datetime`,
186                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
187                         FROM `intro` LEFT JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
188                         WHERE `intro`.`uid` = %d  AND `intro`.`blocked` = 0 AND `intro`.`ignore` = 0 AND `intro`.`contact-id` != 0",
189                         intval(local_user())
190                 );
191
192                 $intro_count = count($intros1) + count($intros2);
193                 $intros = $intros1 + $intros2;
194
195                 $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'] ;
196                 $mails = q(
197                         "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
198                         WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
199                         intval(local_user()),
200                         DBA::escape($myurl)
201                 );
202                 $mail_count = count($mails);
203
204                 if (intval(Config::get('config', 'register_policy')) === REGISTER_APPROVE && is_site_admin()) {
205                         $regs = Friendica\Model\Register::getPending();
206
207                         if (DBA::isResult($regs)) {
208                                 $register_count = count($regs);
209                         }
210                 }
211
212                 $cachekey = "ping_init:".local_user();
213                 $ev = Cache::get($cachekey);
214                 if (is_null($ev)) {
215                         $ev = q(
216                                 "SELECT type, start, adjust FROM `event`
217                                 WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
218                                 ORDER BY `start` ASC ",
219                                 intval(local_user()),
220                                 DBA::escape(DateTimeFormat::utc('now + 7 days')),
221                                 DBA::escape(DateTimeFormat::utcNow())
222                         );
223                         if (DBA::isResult($ev)) {
224                                 Cache::set($cachekey, $ev, CACHE_HOUR);
225                         }
226                 }
227
228                 if (DBA::isResult($ev)) {
229                         $all_events = count($ev);
230
231                         if ($all_events) {
232                                 $str_now = DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d');
233                                 foreach ($ev as $x) {
234                                         $bd = false;
235                                         if ($x['type'] === 'birthday') {
236                                                 $birthdays ++;
237                                                 $bd = true;
238                                         } else {
239                                                 $events ++;
240                                         }
241                                         if (DateTimeFormat::convert($x['start'], ((intval($x['adjust'])) ? $a->timezone : 'UTC'), 'UTC', 'Y-m-d') === $str_now) {
242                                                 $all_events_today ++;
243                                                 if ($bd) {
244                                                         $birthdays_today ++;
245                                                 } else {
246                                                         $events_today ++;
247                                                 }
248                                         }
249                                 }
250                         }
251                 }
252
253                 $data['intro']    = $intro_count;
254                 $data['mail']     = $mail_count;
255                 $data['net']      = $network_count;
256                 $data['home']     = $home_count;
257                 $data['register'] = $register_count;
258
259                 $data['all-events']       = $all_events;
260                 $data['all-events-today'] = $all_events_today;
261                 $data['events']           = $events;
262                 $data['events-today']     = $events_today;
263                 $data['birthdays']        = $birthdays;
264                 $data['birthdays-today']  = $birthdays_today;
265
266                 if (DBA::isResult($notifs)) {
267                         foreach ($notifs as $notif) {
268                                 if ($notif['seen'] == 0) {
269                                         $sysnotify_count ++;
270                                 }
271                         }
272                 }
273
274                 // merge all notification types in one array
275                 if (DBA::isResult($intros)) {
276                         foreach ($intros as $intro) {
277                                 $notif = [
278                                         'id'      => 0,
279                                         'href'    => System::baseUrl() . '/notifications/intros/' . $intro['id'],
280                                         'name'    => $intro['name'],
281                                         'url'     => $intro['url'],
282                                         'photo'   => $intro['photo'],
283                                         'date'    => $intro['datetime'],
284                                         'seen'    => false,
285                                         'message' => L10n::t('{0} wants to be your friend'),
286                                 ];
287                                 $notifs[] = $notif;
288                         }
289                 }
290
291                 if (DBA::isResult($mails)) {
292                         foreach ($mails as $mail) {
293                                 $notif = [
294                                         'id'      => 0,
295                                         'href'    => System::baseUrl() . '/message/' . $mail['id'],
296                                         'name'    => $mail['from-name'],
297                                         'url'     => $mail['from-url'],
298                                         'photo'   => $mail['from-photo'],
299                                         'date'    => $mail['created'],
300                                         'seen'    => false,
301                                         'message' => L10n::t('{0} sent you a message'),
302                                 ];
303                                 $notifs[] = $notif;
304                         }
305                 }
306
307                 if (DBA::isResult($regs)) {
308                         foreach ($regs as $reg) {
309                                 $notif = [
310                                         'id'      => 0,
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' => L10n::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 (DBA::isResult($notifs)) {
345                         // Are the nofications called from the regular process or via the friendica app?
346                         $regularnotifications = (!empty($_GET['uid']) && !empty($_GET['_']));
347
348                         foreach ($notifs as $notif) {
349                                 if ($a->isFriendicaApp() || !$regularnotifications) {
350                                         $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
351                                 }
352
353                                 $contact = Contact::getDetailsByURL($notif['url']);
354                                 if (isset($contact['micro'])) {
355                                         $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
356                                 } else {
357                                         $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
358                                 }
359
360                                 $local_time = DateTimeFormat::local($notif['date']);
361
362                                 $notifications[] = [
363                                         'id'        => $notif['id'],
364                                         'href'      => $notif['href'],
365                                         'name'      => $notif['name'],
366                                         'url'       => $notif['url'],
367                                         'photo'     => $notif['photo'],
368                                         'date'      => Temporal::getRelativeDate($notif['date']),
369                                         'message'   => $notif['message'],
370                                         'seen'      => $notif['seen'],
371                                         'timestamp' => strtotime($local_time)
372                                 ];
373                         }
374                 }
375         }
376
377         $sysmsgs = [];
378         $sysmsgs_info = [];
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'] = [
396                         'notice' => $sysmsgs,
397                         'info' => $sysmsgs_info
398                 ];
399
400                 $json_payload = json_encode(["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::fromArray(["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  = [];
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`.`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["deleted"])) {
468                                 $notification["deleted"] = 0;
469                         }
470
471                         if ($notification["msg_cache"]) {
472                                 $notification["name"] = $notification["name_cache"];
473                                 $notification["message"] = $notification["msg_cache"];
474                         } else {
475                                 $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
476                                 $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
477
478                                 q(
479                                         "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
480                                         DBA::escape($notification["name"]),
481                                         DBA::escape($notification["message"]),
482                                         intval($notification["id"])
483                                 );
484                         }
485
486                         $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
487
488                         if ($notification["visible"]
489                                 && !$notification["deleted"]
490                                 && !(x($result, $notification["parent"]) && !empty($result[$notification["parent"]]))
491                         ) {
492                                 // Should we condense the notifications or show them all?
493                                 if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
494                                         $result[$notification["id"]] = $notification;
495                                 } else {
496                                         $result[$notification["parent"]] = $notification;
497                                 }
498                         }
499                 }
500         } while ((count($result) < 50) && !$quit);
501
502         return($result);
503 }
504
505 /**
506  * @brief Backward-compatible XML formatting for ping.php output
507  * @deprecated
508  *
509  * @param array $data            The initial ping data array
510  * @param int   $sysnotify_count Number of unseen system notifications
511  * @param array $notifs          Complete list of notification
512  * @param array $sysmsgs         List of system notice messages
513  * @param array $sysmsgs_info    List of system info messages
514  * @param int   $groups_unseen   Number of unseen group items
515  * @param int   $forums_unseen   Number of unseen forum items
516  *
517  * @return array XML-transform ready data array
518  */
519 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
520 {
521         $notifications = [];
522         foreach ($notifs as $key => $notif) {
523                 $notifications[$key . ':note'] = $notif['message'];
524
525                 $notifications[$key . ':@attributes'] = [
526                         'id'        => $notif['id'],
527                         'href'      => $notif['href'],
528                         'name'      => $notif['name'],
529                         'url'       => $notif['url'],
530                         'photo'     => $notif['photo'],
531                         'date'      => $notif['date'],
532                         'seen'      => $notif['seen'],
533                         'timestamp' => $notif['timestamp']
534                 ];
535         }
536
537         $sysmsg = [];
538         foreach ($sysmsgs as $key => $m) {
539                 $sysmsg[$key . ':notice'] = $m;
540         }
541         foreach ($sysmsgs_info as $key => $m) {
542                 $sysmsg[$key . ':info'] = $m;
543         }
544
545         $data['notif'] = $notifications;
546         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
547         $data['sysmsgs'] = $sysmsg;
548
549         if ($data['register'] == 0) {
550                 unset($data['register']);
551         }
552
553         $groups = [];
554         if (count($groups_unseen)) {
555                 foreach ($groups_unseen as $key => $item) {
556                         $groups[$key . ':group'] = $item['count'];
557                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
558                 }
559                 $data['groups'] = $groups;
560         }
561
562         $forums = [];
563         if (count($forums_unseen)) {
564                 foreach ($forums_unseen as $key => $item) {
565                         $forums[$key . ':forum'] = $item['count'];
566                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
567                 }
568                 $data['forums'] = $forums;
569         }
570
571         return $data;
572 }