]> git.mxchange.org Git - friendica.git/blob - mod/ping.php
Deprecated the notify table/classes
[friendica.git] / mod / ping.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 use Friendica\App;
23 use Friendica\Content\ForumManager;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Cache\Enum\Duration;
26 use Friendica\Core\Hook;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Group;
31 use Friendica\Model\Notification;
32 use Friendica\Model\Post;
33 use Friendica\Model\Verb;
34 use Friendica\Protocol\Activity;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Proxy;
37 use Friendica\Util\Temporal;
38 use Friendica\Util\XML;
39
40 /**
41  * Outputs the counts and the lists of various notifications
42  *
43  * The output format can be controlled via the GET parameter 'format'. It can be
44  * - xml (deprecated legacy default)
45  * - json (outputs JSONP with the 'callback' GET parameter)
46  *
47  * Expected JSON structure:
48  * {
49  *        "result": {
50  *            "intro": 0,
51  *            "mail": 0,
52  *            "net": 0,
53  *            "home": 0,
54  *            "register": 0,
55  *            "all-events": 0,
56  *            "all-events-today": 0,
57  *            "events": 0,
58  *            "events-today": 0,
59  *            "birthdays": 0,
60  *            "birthdays-today": 0,
61  *            "groups": [ ],
62  *            "forums": [ ],
63  *            "notification": 0,
64  *            "notifications": [ ],
65  *            "sysmsgs": {
66  *                "notice": [ ],
67  *                "info": [ ]
68  *            }
69  *        }
70  *    }
71  *
72  * @param App $a The Friendica App instance
73  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
74  */
75 function ping_init(App $a)
76 {
77         $format = 'xml';
78
79         if (isset($_GET['format']) && $_GET['format'] == 'json') {
80                 $format = 'json';
81         }
82
83         $regs          = [];
84         $notifications = [];
85
86         $intro_count    = 0;
87         $mail_count     = 0;
88         $home_count     = 0;
89         $network_count  = 0;
90         $register_count = 0;
91         $sysnotify_count = 0;
92         $groups_unseen  = [];
93         $forums_unseen  = [];
94
95         $all_events       = 0;
96         $all_events_today = 0;
97         $events           = 0;
98         $events_today     = 0;
99         $birthdays        = 0;
100         $birthdays_today  = 0;
101
102         $data = [];
103         $data['intro']    = $intro_count;
104         $data['mail']     = $mail_count;
105         $data['net']      = $network_count;
106         $data['home']     = $home_count;
107         $data['register'] = $register_count;
108
109         $data['all-events']       = $all_events;
110         $data['all-events-today'] = $all_events_today;
111         $data['events']           = $events;
112         $data['events-today']     = $events_today;
113         $data['birthdays']        = $birthdays;
114         $data['birthdays-today']  = $birthdays_today;
115
116         if (local_user()) {
117                 // Different login session than the page that is calling us.
118                 if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
119                         $data = ['result' => ['invalid' => 1]];
120
121                         if ($format == 'json') {
122                                 if (isset($_GET['callback'])) {
123                                         // JSONP support
124                                         header("Content-type: application/javascript");
125                                         echo $_GET['callback'] . '(' . json_encode($data) . ')';
126                                 } else {
127                                         header("Content-type: application/json");
128                                         echo json_encode($data);
129                                 }
130                         } else {
131                                 header("Content-type: text/xml");
132                                 echo XML::fromArray($data, $xml);
133                         }
134                         exit();
135                 }
136
137                 $notifications = ping_get_notifications(local_user());
138
139                 $condition = ["`unseen` AND `uid` = ? AND NOT `origin` AND (`vid` != ? OR `vid` IS NULL)",
140                         local_user(), Verb::getID(Activity::FOLLOW)];
141                 $items = Post::selectForUser(local_user(), ['wall', 'uid', 'uri-id'], $condition, ['limit' => 1000]);
142                 if (DBA::isResult($items)) {
143                         $items_unseen = Post::toArray($items, false);
144                         $arr = ['items' => $items_unseen];
145                         Hook::callAll('network_ping', $arr);
146
147                         foreach ($items_unseen as $item) {
148                                 if ($item['wall']) {
149                                         $home_count++;
150                                 } else {
151                                         $network_count++;
152                                 }
153                         }
154                 }
155                 DBA::close($items);
156
157                 if ($network_count) {
158                         // Find out how unseen network posts are spread across groups
159                         $group_counts = Group::countUnseen();
160                         if (DBA::isResult($group_counts)) {
161                                 foreach ($group_counts as $group_count) {
162                                         if ($group_count['count'] > 0) {
163                                                 $groups_unseen[] = $group_count;
164                                         }
165                                 }
166                         }
167
168                         $forum_counts = ForumManager::countUnseenItems();
169                         if (DBA::isResult($forum_counts)) {
170                                 foreach ($forum_counts as $forum_count) {
171                                         if ($forum_count['count'] > 0) {
172                                                 $forums_unseen[] = $forum_count;
173                                         }
174                                 }
175                         }
176                 }
177
178                 $intros1 = DBA::toArray(DBA::p(
179                         "SELECT  `intro`.`id`, `intro`.`datetime`,
180                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
181                         FROM `intro` INNER JOIN `contact` ON `intro`.`suggest-cid` = `contact`.`id`
182                         WHERE `intro`.`uid` = ? AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`suggest-cid` != 0",
183                         local_user()
184                 ));
185                 $intros2 = DBA::toArray(DBA::p(
186                         "SELECT `intro`.`id`, `intro`.`datetime`,
187                         `contact`.`name`, `contact`.`url`, `contact`.`photo`
188                         FROM `intro` INNER JOIN `contact` ON `intro`.`contact-id` = `contact`.`id`
189                         WHERE `intro`.`uid` = ? AND NOT `intro`.`blocked` AND NOT `intro`.`ignore` AND `intro`.`contact-id` != 0 AND (`intro`.`suggest-cid` = 0 OR `intro`.`suggest-cid` IS NULL)",
190                         local_user()
191                 ));
192
193                 $intro_count = count($intros1) + count($intros2);
194                 $intros = $intros1 + $intros2;
195
196                 $myurl = DI::baseUrl() . '/profile/' . $a->getLoggedInUserNickname();
197                 $mail_count = DBA::count('mail', ["`uid` = ? AND NOT `seen` AND `from-url` != ?", local_user(), $myurl]);
198
199                 if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && $a->isSiteAdmin()) {
200                         $regs = Friendica\Model\Register::getPending();
201
202                         if (DBA::isResult($regs)) {
203                                 $register_count = count($regs);
204                         }
205                 }
206
207                 $cachekey = "ping_init:".local_user();
208                 $ev = DI::cache()->get($cachekey);
209                 if (is_null($ev)) {
210                         $ev = DBA::selectToArray('event', ['type', 'start'],
211                                 ["`uid` = ? AND `start` < ? AND `finish` > ? AND NOT `ignore`",
212                                 local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utcNow()]);
213                         if (DBA::isResult($ev)) {
214                                 DI::cache()->set($cachekey, $ev, Duration::HOUR);
215                         }
216                 }
217
218                 if (DBA::isResult($ev)) {
219                         $all_events = count($ev);
220
221                         if ($all_events) {
222                                 $str_now = DateTimeFormat::localNow('Y-m-d');
223                                 foreach ($ev as $x) {
224                                         $bd = false;
225                                         if ($x['type'] === 'birthday') {
226                                                 $birthdays ++;
227                                                 $bd = true;
228                                         } else {
229                                                 $events ++;
230                                         }
231                                         if (DateTimeFormat::local($x['start'], 'Y-m-d') === $str_now) {
232                                                 $all_events_today ++;
233                                                 if ($bd) {
234                                                         $birthdays_today ++;
235                                                 } else {
236                                                         $events_today ++;
237                                                 }
238                                         }
239                                 }
240                         }
241                 }
242
243                 $data['intro']    = $intro_count;
244                 $data['mail']     = $mail_count;
245                 $data['net']      = ($network_count < 1000) ? $network_count : '999+';
246                 $data['home']     = ($home_count < 1000) ? $home_count : '999+';
247                 $data['register'] = $register_count;
248
249                 $data['all-events']       = $all_events;
250                 $data['all-events-today'] = $all_events_today;
251                 $data['events']           = $events;
252                 $data['events-today']     = $events_today;
253                 $data['birthdays']        = $birthdays;
254                 $data['birthdays-today']  = $birthdays_today;
255
256                 if (DBA::isResult($notifications)) {
257                         foreach ($notifications as $notif) {
258                                 if ($notif['seen'] == 0) {
259                                         $sysnotify_count ++;
260                                 }
261                         }
262                 }
263
264                 // merge all notification types in one array
265                 if (DBA::isResult($intros)) {
266                         foreach ($intros as $intro) {
267                                 $notif = [
268                                         'id'      => 0,
269                                         'href'    => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
270                                         'name'    => BBCode::convert($intro['name']),
271                                         'url'     => $intro['url'],
272                                         'photo'   => $intro['photo'],
273                                         'date'    => $intro['datetime'],
274                                         'seen'    => false,
275                                         'message' => DI::l10n()->t('{0} wants to be your friend'),
276                                 ];
277                                 $notifications[] = $notif;
278                         }
279                 }
280
281                 if (DBA::isResult($regs)) {
282                         if (count($regs) <= 1 || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
283                                 foreach ($regs as $reg) {
284                                         $notif = [
285                                                 'id'      => 0,
286                                                 'href'    => DI::baseUrl()->get(true) . '/admin/users/pending',
287                                                 'name'    => $reg['name'],
288                                                 'url'     => $reg['url'],
289                                                 'photo'   => $reg['micro'],
290                                                 'date'    => $reg['created'],
291                                                 'seen'    => false,
292                                                 'message' => DI::l10n()->t('{0} requested registration'),
293                                         ];
294                                         $notifications[] = $notif;
295                                 }
296                         } else {
297                                 $notif = [
298                                         'id'      => 0,
299                                         'href'    => DI::baseUrl()->get(true) . '/admin/users/pending',
300                                         'name'    => $regs[0]['name'],
301                                         'url'     => $regs[0]['url'],
302                                         'photo'   => $regs[0]['micro'],
303                                         'date'    => $regs[0]['created'],
304                                         'seen'    => false,
305                                         'message' => DI::l10n()->t('{0} and %d others requested registration', count($regs) - 1),
306                                 ];
307                                 $notifications[] = $notif;
308                         }
309                 }
310
311                 // sort notifications by $[]['date']
312                 $sort_function = function ($a, $b) {
313                         $adate = strtotime($a['date']);
314                         $bdate = strtotime($b['date']);
315
316                         // Unseen messages are kept at the top
317                         // The value 31536000 means one year. This should be enough :-)
318                         if (!$a['seen']) {
319                                 $adate += 31536000;
320                         }
321                         if (!$b['seen']) {
322                                 $bdate += 31536000;
323                         }
324
325                         if ($adate == $bdate) {
326                                 return 0;
327                         }
328                         return ($adate < $bdate) ? 1 : -1;
329                 };
330                 usort($notifications, $sort_function);
331
332                 array_walk($notifications, function (&$notification) {
333                         $notification['photo']     = Contact::getAvatarUrlForUrl($notification['url'], local_user(), Proxy::SIZE_MICRO);
334                         $notification['timestamp'] = DateTimeFormat::local($notification['date']);
335                         $notification['date']      = Temporal::getRelativeDate($notification['date']);
336                 });
337         }
338
339         $sysmsgs = [];
340         $sysmsgs_info = [];
341
342         if (!empty($_SESSION['sysmsg'])) {
343                 $sysmsgs = $_SESSION['sysmsg'];
344                 unset($_SESSION['sysmsg']);
345         }
346
347         if (!empty($_SESSION['sysmsg_info'])) {
348                 $sysmsgs_info = $_SESSION['sysmsg_info'];
349                 unset($_SESSION['sysmsg_info']);
350         }
351
352         if ($format == 'json') {
353                 $notification_count = $sysnotify_count + $intro_count + $register_count;
354                 
355                 $data['groups'] = $groups_unseen;
356                 $data['forums'] = $forums_unseen;
357                 $data['notification'] = ($notification_count < 50) ? $notification_count : '49+';
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  * 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 = DBA::toArray(DBA::p(
403                         "SELECT `notify`.*, `post`.`visible`, `post`.`deleted`
404                         FROM `notify` LEFT JOIN `post` ON `post`.`uri-id` = `notify`.`uri-id`
405                         WHERE `notify`.`uid` = ? AND `notify`.`msg` != ''
406                         AND NOT (`notify`.`type` IN (?, ?))
407                         AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT ?, 50",
408                         $uid,
409                         Notification\Type::INTRO,
410                         Notification\Type::MAIL,
411                         $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"] = \Friendica\Navigation\Notifications\Entity\Notify::formatMessage($notification["name"], BBCode::toPlaintext($notification["msg"]));
440
441                                 // @todo Replace this with a call of the Notify model class
442                                 DBA::update('notify', ['name_cache' => $notification["name"], 'msg_cache' => $notification["message"]], ['id' => $notification["id"]]);
443                         }
444
445                         $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
446
447                         if ($notification["visible"]
448                                 && !$notification["deleted"]
449                                 && empty($result['p:' . $notification['parent']])
450                         ) {
451                                 // Should we condense the notifications or show them all?
452                                 if (($notification['verb'] != Activity::POST) || DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
453                                         $result[] = $notification;
454                                 } else {
455                                         $result['p:' . $notification['parent']] = $notification;
456                                 }
457                         }
458                 }
459         } while ((count($result) < 50) && !$quit);
460
461         return($result);
462 }
463
464 /**
465  * Backward-compatible XML formatting for ping.php output
466  * @deprecated
467  *
468  * @param array $data            The initial ping data array
469  * @param int   $sysnotify_count Number of unseen system notifications
470  * @param array $notifs          Complete list of notification
471  * @param array $sysmsgs         List of system notice messages
472  * @param array $sysmsgs_info    List of system info messages
473  * @param array $groups_unseen   List of unseen group items
474  * @param array $forums_unseen   List of unseen forum items
475  *
476  * @return array XML-transform ready data array
477  */
478 function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
479 {
480         $notifications = [];
481         foreach ($notifs as $key => $notif) {
482                 $notifications[$key . ':note'] = $notif['message'];
483
484                 $notifications[$key . ':@attributes'] = [
485                         'id'        => $notif['id'],
486                         'href'      => $notif['href'],
487                         'name'      => $notif['name'],
488                         'url'       => $notif['url'],
489                         'photo'     => $notif['photo'],
490                         'date'      => $notif['date'],
491                         'seen'      => $notif['seen'],
492                         'timestamp' => $notif['timestamp']
493                 ];
494         }
495
496         $sysmsg = [];
497         foreach ($sysmsgs as $key => $m) {
498                 $sysmsg[$key . ':notice'] = $m;
499         }
500         foreach ($sysmsgs_info as $key => $m) {
501                 $sysmsg[$key . ':info'] = $m;
502         }
503
504         $data['notif'] = $notifications;
505         $data['@attributes'] = ['count' => $sysnotify_count + $data['intro'] + $data['mail'] + $data['register']];
506         $data['sysmsgs'] = $sysmsg;
507
508         if ($data['register'] == 0) {
509                 unset($data['register']);
510         }
511
512         $groups = [];
513         if (count($groups_unseen)) {
514                 foreach ($groups_unseen as $key => $item) {
515                         $groups[$key . ':group'] = $item['count'];
516                         $groups[$key . ':@attributes'] = ['id' => $item['id']];
517                 }
518                 $data['groups'] = $groups;
519         }
520
521         $forums = [];
522         if (count($forums_unseen)) {
523                 foreach ($forums_unseen as $key => $item) {
524                         $forums[$key . ':forum'] = $item['count'];
525                         $forums[$key . ':@attributes'] = ['id' => $item['id']];
526                 }
527                 $data['forums'] = $forums;
528         }
529
530         return $data;
531 }