]> git.mxchange.org Git - friendica.git/blobdiff - mod/ping.php
Merge pull request #8841 from MrPetovan/task/8839-httpsignature-hs2019
[friendica.git] / mod / ping.php
index 06d83a1d9a073d8870dc2f2570ca004c391c71e6..6b3b015ac80e32bcc09839dad0d5e534ea826061 100644 (file)
@@ -1,30 +1,44 @@
 <?php
 /**
- * @file include/ping.php
+ * @copyright Copyright (C) 2020, Friendica
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ *
  */
 
 use Friendica\App;
-use Friendica\Content\Feature;
 use Friendica\Content\ForumManager;
 use Friendica\Content\Text\BBCode;
-use Friendica\Core\Addon;
-use Friendica\Core\Cache;
-use Friendica\Core\L10n;
-use Friendica\Core\PConfig;
-use Friendica\Core\System;
-use Friendica\Database\DBM;
+use Friendica\Core\Cache\Duration;
+use Friendica\Core\Hook;
+use Friendica\Database\DBA;
+use Friendica\DI;
 use Friendica\Model\Contact;
 use Friendica\Model\Group;
 use Friendica\Model\Item;
+use Friendica\Model\Notify\Type;
+use Friendica\Model\Verb;
+use Friendica\Protocol\Activity;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Temporal;
+use Friendica\Util\Proxy as ProxyUtils;
 use Friendica\Util\XML;
 
-require_once 'mod/proxy.php';
-require_once 'include/enotify.php';
-
 /**
- * @brief Outputs the counts and the lists of various notifications
+ * Outputs the counts and the lists of various notifications
  *
  * The output format can be controlled via the GET parameter 'format'. It can be
  * - xml (deprecated legacy default)
@@ -32,30 +46,31 @@ require_once 'include/enotify.php';
  *
  * Expected JSON structure:
  * {
- *             "result": {
- *                     "intro": 0,
- *                     "mail": 0,
- *                     "net": 0,
- *                     "home": 0,
- *                     "register": 0,
- *                     "all-events": 0,
- *                     "all-events-today": 0,
- *                     "events": 0,
- *                     "events-today": 0,
- *                     "birthdays": 0,
- *                     "birthdays-today": 0,
- *                     "groups": [ ],
- *                     "forums": [ ],
- *                     "notify": 0,
- *                     "notifications": [ ],
- *                     "sysmsgs": {
- *                             "notice": [ ],
- *                             "info": [ ]
- *                     }
- *             }
- *     }
+ *        "result": {
+ *            "intro": 0,
+ *            "mail": 0,
+ *            "net": 0,
+ *            "home": 0,
+ *            "register": 0,
+ *            "all-events": 0,
+ *            "all-events-today": 0,
+ *            "events": 0,
+ *            "events-today": 0,
+ *            "birthdays": 0,
+ *            "birthdays-today": 0,
+ *            "groups": [ ],
+ *            "forums": [ ],
+ *            "notification": 0,
+ *            "notifications": [ ],
+ *            "sysmsgs": {
+ *                "notice": [ ],
+ *                "info": [ ]
+ *            }
+ *        }
+ *    }
  *
  * @param App $a The Friendica App instance
+ * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  */
 function ping_init(App $a)
 {
@@ -65,14 +80,7 @@ function ping_init(App $a)
                $format = 'json';
        }
 
-       $tags          = [];
-       $comments      = [];
-       $likes         = [];
-       $dislikes      = [];
-       $friends       = [];
-       $posts         = [];
        $regs          = [];
-       $mails         = [];
        $notifications = [];
 
        $intro_count    = 0;
@@ -107,7 +115,7 @@ function ping_init(App $a)
 
        if (local_user()) {
                // Different login session than the page that is calling us.
-               if (intval($_GET['uid']) && intval($_GET['uid']) != local_user()) {
+               if (!empty($_GET['uid']) && intval($_GET['uid']) != local_user()) {
                        $data = ['result' => ['invalid' => 1]];
 
                        if ($format == 'json') {
@@ -123,21 +131,22 @@ function ping_init(App $a)
                                header("Content-type: text/xml");
                                echo XML::fromArray($data, $xml);
                        }
-                       killme();
+                       exit();
                }
 
                $notifs = ping_get_notifications(local_user());
 
-               $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ?", local_user(), local_user()];
+               $condition = ["`unseen` AND `uid` = ? AND `contact-id` != ? AND (`vid` != ? OR `vid` IS NULL)",
+                       local_user(), local_user(), Verb::getID(Activity::FOLLOW)];
                $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
-                       'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
-               $params = ['order' => ['created' => true]];
+                       'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'wall', 'activity'];
+               $params = ['order' => ['received' => true]];
                $items = Item::selectForUser(local_user(), $fields, $condition, $params);
 
-               if (DBM::is_result($items)) {
-                       $items_unseen = dba::inArray($items);
+               if (DBA::isResult($items)) {
+                       $items_unseen = Item::inArray($items);
                        $arr = ['items' => $items_unseen];
-                       Addon::callHooks('network_ping', $arr);
+                       Hook::callAll('network_ping', $arr);
 
                        foreach ($items_unseen as $item) {
                                if ($item['wall']) {
@@ -149,25 +158,21 @@ function ping_init(App $a)
                }
 
                if ($network_count) {
-                       if (intval(Feature::isEnabled(local_user(), 'groups'))) {
-                               // Find out how unseen network posts are spread across groups
-                               $group_counts = Group::countUnseen();
-                               if (DBM::is_result($group_counts)) {
-                                       foreach ($group_counts as $group_count) {
-                                               if ($group_count['count'] > 0) {
-                                                       $groups_unseen[] = $group_count;
-                                               }
+                       // Find out how unseen network posts are spread across groups
+                       $group_counts = Group::countUnseen();
+                       if (DBA::isResult($group_counts)) {
+                               foreach ($group_counts as $group_count) {
+                                       if ($group_count['count'] > 0) {
+                                               $groups_unseen[] = $group_count;
                                        }
                                }
                        }
 
-                       if (intval(Feature::isEnabled(local_user(), 'forumlist_widget'))) {
-                               $forum_counts = ForumManager::countUnseenItems();
-                               if (DBM::is_result($forum_counts)) {
-                                       foreach ($forum_counts as $forum_count) {
-                                               if ($forum_count['count'] > 0) {
-                                                       $forums_unseen[] = $forum_count;
-                                               }
+                       $forum_counts = ForumManager::countUnseenItems();
+                       if (DBA::isResult($forum_counts)) {
+                               foreach ($forum_counts as $forum_count) {
+                                       if ($forum_count['count'] > 0) {
+                                               $forums_unseen[] = $forum_count;
                                        }
                                }
                        }
@@ -191,44 +196,40 @@ function ping_init(App $a)
                $intro_count = count($intros1) + count($intros2);
                $intros = $intros1 + $intros2;
 
-               $myurl = System::baseUrl() . '/profile/' . $a->user['nickname'] ;
+               $myurl = DI::baseUrl() . '/profile/' . $a->user['nickname'];
                $mails = q(
                        "SELECT `id`, `from-name`, `from-url`, `from-photo`, `created` FROM `mail`
                        WHERE `uid` = %d AND `seen` = 0 AND `from-url` != '%s' ",
                        intval(local_user()),
-                       dbesc($myurl)
+                       DBA::escape($myurl)
                );
                $mail_count = count($mails);
 
-               if ($a->config['register_policy'] == REGISTER_APPROVE && is_site_admin()) {
-                       $regs = q(
-                               "SELECT `contact`.`name`, `contact`.`url`, `contact`.`micro`, `register`.`created`
-                               FROM `contact` RIGHT JOIN `register` ON `register`.`uid` = `contact`.`uid`
-                               WHERE `contact`.`self` = 1"
-                       );
+               if (intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::APPROVE && is_site_admin()) {
+                       $regs = Friendica\Model\Register::getPending();
 
-                       if (DBM::is_result($regs)) {
+                       if (DBA::isResult($regs)) {
                                $register_count = count($regs);
                        }
                }
 
                $cachekey = "ping_init:".local_user();
-               $ev = Cache::get($cachekey);
+               $ev = DI::cache()->get($cachekey);
                if (is_null($ev)) {
                        $ev = q(
                                "SELECT type, start, adjust FROM `event`
                                WHERE `event`.`uid` = %d AND `start` < '%s' AND `finish` > '%s' and `ignore` = 0
                                ORDER BY `start` ASC ",
                                intval(local_user()),
-                               dbesc(DateTimeFormat::utc('now + 7 days')),
-                               dbesc(DateTimeFormat::utcNow())
+                               DBA::escape(DateTimeFormat::utc('now + 7 days')),
+                               DBA::escape(DateTimeFormat::utcNow())
                        );
-                       if (DBM::is_result($ev)) {
-                               Cache::set($cachekey, $ev, CACHE_HOUR);
+                       if (DBA::isResult($ev)) {
+                               DI::cache()->set($cachekey, $ev, Duration::HOUR);
                        }
                }
 
-               if (DBM::is_result($ev)) {
+               if (DBA::isResult($ev)) {
                        $all_events = count($ev);
 
                        if ($all_events) {
@@ -266,7 +267,7 @@ function ping_init(App $a)
                $data['birthdays']        = $birthdays;
                $data['birthdays-today']  = $birthdays_today;
 
-               if (DBM::is_result($notifs)) {
+               if (DBA::isResult($notifs)) {
                        foreach ($notifs as $notif) {
                                if ($notif['seen'] == 0) {
                                        $sysnotify_count ++;
@@ -275,46 +276,33 @@ function ping_init(App $a)
                }
 
                // merge all notification types in one array
-               if (DBM::is_result($intros)) {
+               if (DBA::isResult($intros)) {
                        foreach ($intros as $intro) {
                                $notif = [
-                                       'href'    => System::baseUrl() . '/notifications/intros/' . $intro['id'],
+                                       'id'      => 0,
+                                       'href'    => DI::baseUrl() . '/notifications/intros/' . $intro['id'],
                                        'name'    => $intro['name'],
                                        'url'     => $intro['url'],
                                        'photo'   => $intro['photo'],
                                        'date'    => $intro['datetime'],
                                        'seen'    => false,
-                                       'message' => L10n::t('{0} wants to be your friend'),
+                                       'message' => DI::l10n()->t('{0} wants to be your friend'),
                                ];
                                $notifs[] = $notif;
                        }
                }
 
-               if (DBM::is_result($mails)) {
-                       foreach ($mails as $mail) {
-                               $notif = [
-                                       'href'    => System::baseUrl() . '/message/' . $mail['id'],
-                                       'name'    => $mail['from-name'],
-                                       'url'     => $mail['from-url'],
-                                       'photo'   => $mail['from-photo'],
-                                       'date'    => $mail['created'],
-                                       'seen'    => false,
-                                       'message' => L10n::t('{0} sent you a message'),
-                               ];
-                               $notifs[] = $notif;
-                       }
-               }
-
-               if (DBM::is_result($regs)) {
+               if (DBA::isResult($regs)) {
                        foreach ($regs as $reg) {
                                $notif = [
-                                       'href'    => System::baseUrl() . '/admin/users/',
+                                       'id'      => 0,
+                                       'href'    => DI::baseUrl() . '/admin/users/',
                                        'name'    => $reg['name'],
                                        'url'     => $reg['url'],
                                        'photo'   => $reg['micro'],
                                        'date'    => $reg['created'],
                                        'seen'    => false,
-                                       'message' => L10n::t('{0} requested registration'),
+                                       'message' => DI::l10n()->t('{0} requested registration'),
                                ];
                                $notifs[] = $notif;
                        }
@@ -341,20 +329,13 @@ function ping_init(App $a)
                };
                usort($notifs, $sort_function);
 
-               if (DBM::is_result($notifs)) {
-                       // Are the nofications called from the regular process or via the friendica app?
-                       $regularnotifications = (intval($_GET['uid']) && intval($_GET['_']));
-
+               if (DBA::isResult($notifs)) {
                        foreach ($notifs as $notif) {
-                               if ($a->is_friendica_app() || !$regularnotifications) {
-                                       $notif['message'] = str_replace("{0}", $notif['name'], $notif['message']);
-                               }
-
                                $contact = Contact::getDetailsByURL($notif['url']);
                                if (isset($contact['micro'])) {
-                                       $notif['photo'] = proxy_url($contact['micro'], false, PROXY_SIZE_MICRO);
+                                       $notif['photo'] = ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO);
                                } else {
-                                       $notif['photo'] = proxy_url($notif['photo'], false, PROXY_SIZE_MICRO);
+                                       $notif['photo'] = ProxyUtils::proxifyUrl($notif['photo'], false, ProxyUtils::SIZE_MICRO);
                                }
 
                                $local_time = DateTimeFormat::local($notif['date']);
@@ -377,12 +358,12 @@ function ping_init(App $a)
        $sysmsgs = [];
        $sysmsgs_info = [];
 
-       if (x($_SESSION, 'sysmsg')) {
+       if (!empty($_SESSION['sysmsg'])) {
                $sysmsgs = $_SESSION['sysmsg'];
                unset($_SESSION['sysmsg']);
        }
 
-       if (x($_SESSION, 'sysmsg_info')) {
+       if (!empty($_SESSION['sysmsg_info'])) {
                $sysmsgs_info = $_SESSION['sysmsg_info'];
                unset($_SESSION['sysmsg_info']);
        }
@@ -390,7 +371,7 @@ function ping_init(App $a)
        if ($format == 'json') {
                $data['groups'] = $groups_unseen;
                $data['forums'] = $forums_unseen;
-               $data['notify'] = $sysnotify_count + $intro_count + $mail_count + $register_count;
+               $data['notification'] = $sysnotify_count + $intro_count + $register_count;
                $data['notifications'] = $notifications;
                $data['sysmsgs'] = [
                        'notice' => $sysmsgs,
@@ -415,14 +396,15 @@ function ping_init(App $a)
                echo XML::fromArray(["result" => $data], $xml);
        }
 
-       killme();
+       exit();
 }
 
 /**
- * @brief Retrieves the notifications array for the given user ID
+ * Retrieves the notifications array for the given user ID
  *
  * @param int $uid User id
  * @return array Associative array of notifications
+ * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  */
 function ping_get_notifications($uid)
 {
@@ -433,8 +415,6 @@ function ping_get_notifications($uid)
        $order   = "DESC";
        $quit    = false;
 
-       $a = get_app();
-
        do {
                $r = q(
                        "SELECT `notify`.*, `item`.`visible`, `item`.`deleted`
@@ -443,8 +423,8 @@ function ping_get_notifications($uid)
                        AND NOT (`notify`.`type` IN (%d, %d))
                        AND $seensql `notify`.`seen` ORDER BY `notify`.`date` $order LIMIT %d, 50",
                        intval($uid),
-                       intval(NOTIFY_INTRO),
-                       intval(NOTIFY_MAIL),
+                       intval(Type::INTRO),
+                       intval(Type::MAIL),
                        intval($offset)
                );
 
@@ -473,27 +453,27 @@ function ping_get_notifications($uid)
                                $notification["message"] = $notification["msg_cache"];
                        } else {
                                $notification["name"] = strip_tags(BBCode::convert($notification["name"]));
-                               $notification["message"] = format_notification_message($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
+                               $notification["message"] = Friendica\Model\Notify::formatMessage($notification["name"], strip_tags(BBCode::convert($notification["msg"])));
 
                                q(
                                        "UPDATE `notify` SET `name_cache` = '%s', `msg_cache` = '%s' WHERE `id` = %d",
-                                       dbesc($notification["name"]),
-                                       dbesc($notification["message"]),
+                                       DBA::escape($notification["name"]),
+                                       DBA::escape($notification["message"]),
                                        intval($notification["id"])
                                );
                        }
 
-                       $notification["href"] = System::baseUrl() . "/notify/view/" . $notification["id"];
+                       $notification["href"] = DI::baseUrl() . "/notification/" . $notification["id"];
 
                        if ($notification["visible"]
                                && !$notification["deleted"]
-                               && !(x($result, $notification["parent"]) && is_array($result[$notification["parent"]]))
+                               && empty($result[$notification['parent']])
                        ) {
                                // Should we condense the notifications or show them all?
-                               if (PConfig::get(local_user(), 'system', 'detailed_notif')) {
+                               if (DI::pConfig()->get(local_user(), 'system', 'detailed_notif')) {
                                        $result[$notification["id"]] = $notification;
                                } else {
-                                       $result[$notification["parent"]] = $notification;
+                                       $result[$notification['parent']] = $notification;
                                }
                        }
                }
@@ -503,19 +483,20 @@ function ping_get_notifications($uid)
 }
 
 /**
- * @brief Backward-compatible XML formatting for ping.php output
+ * Backward-compatible XML formatting for ping.php output
  * @deprecated
  *
- * @param array $data          The initial ping data array
- * @param int   $sysnotify     Number of unseen system notifications
- * @param array $notifs        Complete list of notification
- * @param array $sysmsgs       List of system notice messages
- * @param array $sysmsgs_info  List of system info messages
- * @param int   $groups_unseen Number of unseen group items
- * @param int   $forums_unseen Number of unseen forum items
+ * @param array $data            The initial ping data array
+ * @param int   $sysnotify_count Number of unseen system notifications
+ * @param array $notifs          Complete list of notification
+ * @param array $sysmsgs         List of system notice messages
+ * @param array $sysmsgs_info    List of system info messages
+ * @param array $groups_unseen   List of unseen group items
+ * @param array $forums_unseen   List of unseen forum items
+ *
  * @return array XML-transform ready data array
  */
-function ping_format_xml_data($data, $sysnotify, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
+function ping_format_xml_data($data, $sysnotify_count, $notifs, $sysmsgs, $sysmsgs_info, $groups_unseen, $forums_unseen)
 {
        $notifications = [];
        foreach ($notifs as $key => $notif) {