]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/DFRN.php
Merge pull request #7184 from annando/add-tag
[friendica.git] / src / Protocol / DFRN.php
index c4355503137923dc9c662f38e626b040b2be20c3..01159b1baeea7c8cfea232462be993b0c78acaa3 100644 (file)
@@ -14,9 +14,9 @@ use Friendica\App;
 use Friendica\Content\OEmbed;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\HTML;
-use Friendica\Core\Addon;
 use Friendica\Core\Config;
-use Friendica\Core\L10n;
+use Friendica\Core\Hook;
+use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
 use Friendica\Core\System;
 use Friendica\Database\DBA;
@@ -25,23 +25,20 @@ use Friendica\Model\Conversation;
 use Friendica\Model\Event;
 use Friendica\Model\GContact;
 use Friendica\Model\Item;
+use Friendica\Model\Mail;
 use Friendica\Model\PermissionSet;
 use Friendica\Model\Profile;
 use Friendica\Model\User;
 use Friendica\Object\Image;
+use Friendica\Util\BaseURL;
 use Friendica\Util\Crypto;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
+use Friendica\Util\Strings;
 use Friendica\Util\XML;
 use HTMLPurifier;
 use HTMLPurifier_Config;
 
-require_once 'boot.php';
-require_once 'include/dba.php';
-require_once "include/enotify.php";
-require_once "include/items.php";
-require_once "include/text.php";
-
 /**
  * @brief This class contain functions to create and send DFRN XML files
  */
@@ -61,6 +58,7 @@ class DFRN
         * @param integer $uid User id
         *
         * @return array importer
+        * @throws \Exception
         */
        public static function getImporter($cid, $uid = 0)
        {
@@ -81,7 +79,8 @@ class DFRN
                                return [];
                        }
 
-                       $user['importer_uid']  = $user['uid'];
+                       $user['importer_uid'] = $user['uid'];
+                       $user['uprvkey'] = $user['prvkey'];
                } else {
                        $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
                                'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
@@ -100,7 +99,9 @@ class DFRN
         * @param array $owner Owner record
         *
         * @return string DFRN entries
-        * @todo Find proper type-hints
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
+        * @todo  Find proper type-hints
         */
        public static function entries($items, $owner)
        {
@@ -120,7 +121,9 @@ class DFRN
                        $item["entry:cid"] = defaults($item, "entry:cid", 0);
 
                        $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
-                       $root->appendChild($entry);
+                       if (isset($entry)) {
+                               $root->appendChild($entry);
+                       }
                }
 
                return trim($doc->saveXML());
@@ -138,10 +141,12 @@ class DFRN
         * @param boolean $onlyheader  Output only the header without content? (Default is "no")
         *
         * @return string DFRN feed entries
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
        {
-               $a = get_app();
+               $a = \get_app();
 
                $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
                $public_feed = (($dfrn_id) ? false : true);
@@ -174,30 +179,25 @@ class DFRN
                );
 
                if (! DBA::isResult($r)) {
-                       logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
-                       killme();
+                       Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
+                       exit();
                }
 
                $owner = $r[0];
                $owner_id = $owner['uid'];
-               $owner_nick = $owner['nickname'];
 
                $sql_post_table = "";
 
                if (! $public_feed) {
-                       $sql_extra = '';
                        switch ($direction) {
                                case (-1):
                                        $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
-                                       $my_id = $dfrn_id;
                                        break;
                                case 0:
                                        $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
-                                       $my_id = '1:' . $dfrn_id;
                                        break;
                                case 1:
                                        $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
-                                       $my_id = '0:' . $dfrn_id;
                                        break;
                                default:
                                        return false;
@@ -210,12 +210,11 @@ class DFRN
                        );
 
                        if (! DBA::isResult($r)) {
-                               logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
-                               killme();
+                               Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
+                               exit();
                        }
 
                        $contact = $r[0];
-                       include_once 'include/security.php';
 
                        $set = PermissionSet::get($owner_id, $contact['id']);
 
@@ -239,12 +238,11 @@ class DFRN
                if (isset($category)) {
                        $sql_post_table = sprintf(
                                "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
-                               DBA::escape(protect_sprintf($category)),
+                               DBA::escape(Strings::protectSprintf($category)),
                                intval(TERM_OBJ_POST),
                                intval(TERM_CATEGORY),
                                intval($owner_id)
                        );
-                       //$sql_extra .= file_tag_file_query('item',$category,'category');
                }
 
                if ($public_feed && ! $converse) {
@@ -258,7 +256,7 @@ class DFRN
                        FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
                        STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
                        WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
-                       $sql_extra
+                       AND `item`.`visible` $sql_extra
                        ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
                        intval($owner_id),
                        DBA::escape($check_date),
@@ -300,12 +298,12 @@ class DFRN
                $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
 
                /// @TODO This hook can't work anymore
-               //      Addon::callHooks('atom_feed', $atom);
+               //      \Friendica\Core\Hook::callAll('atom_feed', $atom);
 
                if (!DBA::isResult($items) || $onlyheader) {
                        $atom = trim($doc->saveXML());
 
-                       Addon::callHooks('atom_feed_end', $atom);
+                       Hook::callAll('atom_feed_end', $atom);
 
                        return $atom;
                }
@@ -329,12 +327,14 @@ class DFRN
                        }
 
                        $entry = self::entry($doc, $type, $item, $owner, true);
-                       $root->appendChild($entry);
+                       if (isset($entry)) {
+                               $root->appendChild($entry);
+                       }
                }
 
                $atom = trim($doc->saveXML());
 
-               Addon::callHooks('atom_feed_end', $atom);
+               Hook::callAll('atom_feed_end', $atom);
 
                return $atom;
        }
@@ -346,6 +346,8 @@ class DFRN
         * @param boolean $conversation Show the conversation. If false show the single post.
         *
         * @return string DFRN feed entry
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function itemFeed($item_id, $conversation = false)
        {
@@ -358,7 +360,7 @@ class DFRN
                $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
                $items = Item::inArray($ret);
                if (!DBA::isResult($items)) {
-                       killme();
+                       return '';
                }
 
                $item = $items[0];
@@ -366,7 +368,7 @@ class DFRN
                if ($item['uid'] != 0) {
                        $owner = User::getOwnerDataById($item['uid']);
                        if (!$owner) {
-                               killme();
+                               return '';
                        }
                } else {
                        $owner = ['uid' => 0, 'nick' => 'feed-item'];
@@ -394,10 +396,12 @@ class DFRN
 
                        foreach ($items as $item) {
                                $entry = self::entry($doc, $type, $item, $owner, true, 0);
-                               $root->appendChild($entry);
+                               if (isset($entry)) {
+                                       $root->appendChild($entry);
+                               }
                        }
                } else {
-                       $root = self::entry($doc, $type, $item, $owner, true, 0, true);
+                       self::entry($doc, $type, $item, $owner, true, 0, true);
                }
 
                $atom = trim($doc->saveXML());
@@ -411,7 +415,8 @@ class DFRN
         * @param array $owner Owner record
         *
         * @return string DFRN mail
-        * @todo Find proper type-hints
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find proper type-hints
         */
        public static function mail($item, $owner)
        {
@@ -447,7 +452,8 @@ class DFRN
         * @param array $owner Owner record
         *
         * @return string DFRN suggestions
-        * @todo Find proper type-hints
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find proper type-hints
         */
        public static function fsuggest($item, $owner)
        {
@@ -476,7 +482,8 @@ class DFRN
         * @param int   $uid   User ID
         *
         * @return string DFRN relocations
-        * @todo Find proper type-hints
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find proper type-hints
         */
        public static function relocate($owner, $uid)
        {
@@ -530,16 +537,17 @@ class DFRN
        /**
         * @brief Adds the header elements for the DFRN protocol
         *
-        * @param object $doc           XML document
-        * @param array  $owner         Owner record
-        * @param string $authorelement Element name for the author
-        * @param string $alternatelink link to profile or category
-        * @param bool   $public        Is it a header for public posts?
+        * @param DOMDocument $doc           XML document
+        * @param array       $owner         Owner record
+        * @param string      $authorelement Element name for the author
+        * @param string      $alternatelink link to profile or category
+        * @param bool        $public        Is it a header for public posts?
         *
         * @return object XML root object
-        * @todo Find proper type-hints
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find proper type-hints
         */
-       private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
+       private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false)
        {
 
                if ($alternatelink == "") {
@@ -587,14 +595,14 @@ class DFRN
                }
 
                // For backward compatibility we keep this element
-               if ($owner['page-flags'] == Contact::PAGE_COMMUNITY) {
+               if ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
                        XML::addElement($doc, $root, "dfrn:community", 1);
                }
 
                // The former element is replaced by this one
                XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
 
-               /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
+               /// @todo We need a way to transmit the different page flags like "User::PAGE_FLAGS_PRVGROUP"
 
                XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
 
@@ -607,15 +615,16 @@ class DFRN
        /**
         * @brief Adds the author element in the header for the DFRN protocol
         *
-        * @param object  $doc           XML document
-        * @param array   $owner         Owner record
-        * @param string  $authorelement Element name for the author
-        * @param boolean $public        boolean
+        * @param DOMDocument $doc           XML document
+        * @param array       $owner         Owner record
+        * @param string      $authorelement Element name for the author
+        * @param boolean     $public        boolean
         *
-        * @return object XML author object
-        * @todo Find proper type-hints
+        * @return \DOMElement XML author object
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find proper type-hints
         */
-       private static function addAuthor($doc, $owner, $authorelement, $public)
+       private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public)
        {
                // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
                $r = q(
@@ -646,7 +655,7 @@ class DFRN
                XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
 
                $attributes = ["rel" => "photo", "type" => "image/jpeg",
-                                       "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
+                                       "media:width" => 300, "media:height" => 300, "href" => $owner['photo']];
 
                if (!$public || !$hidewall) {
                        $attributes["dfrn:updated"] = $picdate;
@@ -688,7 +697,7 @@ class DFRN
                        XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
                        XML::addElement($doc, $author, "poco:updated", $namdate);
 
-                       if (trim($profile["dob"]) > '0001-01-01') {
+                       if (trim($profile["dob"]) > DBA::NULL_DATE) {
                                XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
                        }
 
@@ -751,41 +760,44 @@ class DFRN
        /**
         * @brief Adds the author elements in the "entry" elements of the DFRN protocol
         *
-        * @param object $doc         XML document
+        * @param DOMDocument $doc         XML document
         * @param string $element     Element name for the author
         * @param string $contact_url Link of the contact
         * @param array  $item        Item elements
         *
-        * @return object XML author object
-        * @todo Find proper type-hints
+        * @return \DOMElement XML author object
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find proper type-hints
         */
-       private static function addEntryAuthor($doc, $element, $contact_url, $item)
+       private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item)
        {
-               $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
-
                $author = $doc->createElement($element);
-               XML::addElement($doc, $author, "name", $contact["name"]);
-               XML::addElement($doc, $author, "uri", $contact["url"]);
-               XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
 
-               /// @Todo
-               /// - Check real image type and image size
-               /// - Check which of these boths elements we should use
-               $attributes = [
+               $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
+               if (!empty($contact)) {
+                       XML::addElement($doc, $author, "name", $contact["name"]);
+                       XML::addElement($doc, $author, "uri", $contact["url"]);
+                       XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
+
+                       /// @Todo
+                       /// - Check real image type and image size
+                       /// - Check which of these boths elements we should use
+                       $attributes = [
                                "rel" => "photo",
                                "type" => "image/jpeg",
                                "media:width" => 80,
                                "media:height" => 80,
                                "href" => $contact["photo"]];
-               XML::addElement($doc, $author, "link", "", $attributes);
+                       XML::addElement($doc, $author, "link", "", $attributes);
 
-               $attributes = [
+                       $attributes = [
                                "rel" => "avatar",
                                "type" => "image/jpeg",
                                "media:width" => 80,
                                "media:height" => 80,
                                "href" => $contact["photo"]];
-               XML::addElement($doc, $author, "link", "", $attributes);
+                       XML::addElement($doc, $author, "link", "", $attributes);
+               }
 
                return $author;
        }
@@ -793,14 +805,15 @@ class DFRN
        /**
         * @brief Adds the activity elements
         *
-        * @param object $doc      XML document
-        * @param string $element  Element name for the activity
-        * @param string $activity activity value
+        * @param DOMDocument $doc      XML document
+        * @param string      $element  Element name for the activity
+        * @param string      $activity activity value
         *
-        * @return object XML activity object
-        * @todo Find proper type-hints
+        * @return \DOMElement XML activity object
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find proper type-hints
         */
-       private static function createActivity($doc, $element, $activity)
+       private static function createActivity(DOMDocument $doc, $element, $activity)
        {
                if ($activity) {
                        $entry = $doc->createElement($element);
@@ -863,8 +876,8 @@ class DFRN
         * @param object $root XML root
         * @param array  $item Item element
         *
-        * @return object XML attachment object
-        * @todo Find proper type-hints
+        * @return void XML attachment object
+        * @todo  Find proper type-hints
         */
        private static function getAttachment($doc, $root, $item)
        {
@@ -895,23 +908,26 @@ class DFRN
        /**
         * @brief Adds the "entry" elements for the DFRN protocol
         *
-        * @param object $doc     XML document
-        * @param string $type    "text" or "html"
-        * @param array  $item    Item element
-        * @param array  $owner   Owner record
-        * @param bool   $comment Trigger the sending of the "comment" element
-        * @param int    $cid     Contact ID of the recipient
-        * @param bool   $single  If set, the entry is created as an XML document with a single "entry" element
+        * @param DOMDocument $doc     XML document
+        * @param string      $type    "text" or "html"
+        * @param array       $item    Item element
+        * @param array       $owner   Owner record
+        * @param bool        $comment Trigger the sending of the "comment" element
+        * @param int         $cid     Contact ID of the recipient
+        * @param bool        $single  If set, the entry is created as an XML document with a single "entry" element
         *
-        * @return object XML entry object
-        * @todo Find proper type-hints
+        * @return null|\DOMElement XML entry object
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
+        * @todo  Find proper type-hints
         */
-       private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
+       private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
        {
                $mentioned = [];
 
                if (!$item['parent']) {
-                       return;
+                       Logger::notice('Item without parent found.', ['type' => $type, 'item' => $item]);
+                       return null;
                }
 
                if ($item['deleted']) {
@@ -972,7 +988,7 @@ class DFRN
                }
 
                // Add conversation data. This is used for OStatus
-               $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
+               $conversation_href = System::baseUrl()."/display/".$item["parent-guid"];
                $conversation_uri = $conversation_href;
 
                if (isset($parent_item)) {
@@ -1000,7 +1016,7 @@ class DFRN
                XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
 
                // "dfrn:env" is used to read the content
-               XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
+               XML::addElement($doc, $entry, "dfrn:env", Strings::base64UrlEncode($body, true));
 
                // The "content" field is not read by the receiver. We could remove it when the type is "text"
                // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
@@ -1095,7 +1111,7 @@ class DFRN
                }
 
                foreach ($mentioned as $mention) {
-                       $condition = ['uid' => $owner["uid"], 'nurl' => normalise_link($mention)];
+                       $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
                        $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
 
                        if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
@@ -1160,18 +1176,21 @@ class DFRN
         * @param string $atom     Content that will be transmitted
         * @param bool   $dissolve (to be documented)
         *
+        * @param bool   $legacy_transport
         * @return int Deliver status. Negative values mean an error.
-        * @todo Add array type-hint for $owner, $contact
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
+        * @todo  Add array type-hint for $owner, $contact
         */
-       public static function deliver($owner, $contact, $atom, $dissolve = false)
+       public static function deliver($owner, $contact, $atom, $dissolve = false, $legacy_transport = false)
        {
-               $a = get_app();
-
                // At first try the Diaspora transport layer
-               $ret = self::transmit($owner, $contact, $atom);
-               if ($ret >= 200) {
-                       logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
-                       return $ret;
+               if (!$dissolve && !$legacy_transport) {
+                       $curlResult = self::transmit($owner, $contact, $atom);
+                       if ($curlResult >= 200) {
+                               Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
+                               return $curlResult;
+                       }
                }
 
                $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
@@ -1186,19 +1205,18 @@ class DFRN
                $rino = Config::get('system', 'rino_encrypt');
                $rino = intval($rino);
 
-               logger("Local rino version: ". $rino, LOGGER_DEBUG);
+               Logger::log("Local rino version: ". $rino, Logger::DEBUG);
 
                $ssl_val = intval(Config::get('system', 'ssl_policy'));
-               $ssl_policy = '';
 
                switch ($ssl_val) {
-                       case SSL_POLICY_FULL:
+                       case BaseURL::SSL_POLICY_FULL:
                                $ssl_policy = 'full';
                                break;
-                       case SSL_POLICY_SELFSIGN:
+                       case BaseURL::SSL_POLICY_SELFSIGN:
                                $ssl_policy = 'self';
                                break;
-                       case SSL_POLICY_NONE:
+                       case BaseURL::SSL_POLICY_NONE:
                        default:
                                $ssl_policy = 'none';
                                break;
@@ -1206,24 +1224,24 @@ class DFRN
 
                $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
 
-               logger('dfrn_deliver: ' . $url);
+               Logger::log('dfrn_deliver: ' . $url);
 
-               $ret = Network::curl($url);
+               $curlResult = Network::curl($url);
 
-               if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
+               if ($curlResult->isTimeout()) {
                        Contact::markForArchival($contact);
                        return -2; // timed out
                }
 
-               $xml = $ret['body'];
+               $xml = $curlResult->getBody();
 
-               $curl_stat = $a->get_curl_code();
+               $curl_stat = $curlResult->getReturnCode();
                if (empty($curl_stat)) {
                        Contact::markForArchival($contact);
                        return -3; // timed out
                }
 
-               logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
+               Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
 
                if (empty($xml)) {
                        Contact::markForArchival($contact);
@@ -1231,8 +1249,8 @@ class DFRN
                }
 
                if (strpos($xml, '<?xml') === false) {
-                       logger('dfrn_deliver: no valid XML returned');
-                       logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
+                       Logger::log('dfrn_deliver: no valid XML returned');
+                       Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
                        Contact::markForArchival($contact);
                        return 3;
                }
@@ -1257,11 +1275,11 @@ class DFRN
                $perm         = (($res->perm) ? $res->perm : null);
                $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
                $rino_remote_version = intval($res->rino);
-               $page         = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
+               $page         = (($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? 1 : 0);
 
-               logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
+               Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
 
-               if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
+               if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
                        $page = 2;
                }
 
@@ -1278,7 +1296,7 @@ class DFRN
                }
 
                if (($contact['duplex'] && strlen($contact['pubkey']))
-                       || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
+                       || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
                        || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
                ) {
                        openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
@@ -1295,7 +1313,7 @@ class DFRN
                }
 
                if ($final_dfrn_id != $orig_id) {
-                       logger('dfrn_deliver: wrong dfrn_id.');
+                       Logger::log('dfrn_deliver: wrong dfrn_id.');
                        // did not decode properly - cannot trust this site
                        Contact::markForArchival($contact);
                        return 3;
@@ -1307,7 +1325,7 @@ class DFRN
                        $postvars['dissolve'] = '1';
                }
 
-               if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
+               if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
                        $postvars['data'] = $atom;
                        $postvars['perm'] = 'rw';
                } else {
@@ -1323,7 +1341,7 @@ class DFRN
 
 
                if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
-                       logger('rino version: '. $rino_remote_version);
+                       Logger::log('rino version: '. $rino_remote_version);
 
                        switch ($rino_remote_version) {
                                case 1:
@@ -1332,7 +1350,7 @@ class DFRN
                                        break;
 
                                default:
-                                       logger("rino: invalid requested version '$rino_remote_version'");
+                                       Logger::log("rino: invalid requested version '$rino_remote_version'");
                                        Contact::markForArchival($contact);
                                        return -8;
                        }
@@ -1342,7 +1360,7 @@ class DFRN
 
                        if ($dfrn_version >= 2.1) {
                                if (($contact['duplex'] && strlen($contact['pubkey']))
-                                       || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
+                                       || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY && strlen($contact['pubkey']))
                                        || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
                                ) {
                                        openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
@@ -1350,39 +1368,41 @@ class DFRN
                                        openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
                                }
                        } else {
-                               if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
+                               if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
                                        openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
                                } else {
                                        openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
                                }
                        }
 
-                       logger('md5 rawkey ' . md5($postvars['key']));
+                       Logger::log('md5 rawkey ' . md5($postvars['key']));
 
                        $postvars['key'] = bin2hex($postvars['key']);
                }
 
 
-               logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
+               Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
+
+               $postResult = Network::post($contact['notify'], $postvars);
 
-               $xml = Network::post($contact['notify'], $postvars);
+               $xml = $postResult->getBody();
 
-               logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
+               Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
 
-               $curl_stat = $a->get_curl_code();
+               $curl_stat = $postResult->getReturnCode();
                if (empty($curl_stat) || empty($xml)) {
                        Contact::markForArchival($contact);
                        return -9; // timed out
                }
 
-               if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
+               if (($curl_stat == 503) && stristr($postResult->getHeader(), 'retry-after')) {
                        Contact::markForArchival($contact);
                        return -10;
                }
 
                if (strpos($xml, '<?xml') === false) {
-                       logger('dfrn_deliver: phase 2: no valid XML returned');
-                       logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
+                       Logger::log('dfrn_deliver: phase 2: no valid XML returned');
+                       Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
                        Contact::markForArchival($contact);
                        return 3;
                }
@@ -1400,7 +1420,7 @@ class DFRN
                }
 
                if (!empty($res->message)) {
-                       logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
+                       Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
                }
 
                if (($res->status >= 200) && ($res->status <= 299)) {
@@ -1413,26 +1433,27 @@ class DFRN
        /**
         * @brief Transmits atom content to the contacts via the Diaspora transport layer
         *
-        * @param array  $owner    Owner record
-        * @param array  $contact  Contact record of the receiver
-        * @param string $atom     Content that will be transmitted
+        * @param array  $owner   Owner record
+        * @param array  $contact Contact record of the receiver
+        * @param string $atom    Content that will be transmitted
         *
+        * @param bool   $public_batch
         * @return int Deliver status. Negative values mean an error.
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function transmit($owner, $contact, $atom, $public_batch = false)
        {
-               $a = get_app();
-
                if (!$public_batch) {
                        if (empty($contact['addr'])) {
-                               logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
+                               Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
                                if (Contact::updateFromProbe($contact['id'])) {
                                        $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
                                        $contact['addr'] = $new_contact['addr'];
                                }
 
                                if (empty($contact['addr'])) {
-                                       logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
+                                       Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
                                        Contact::markForArchival($contact);
                                        return -21;
                                }
@@ -1440,7 +1461,7 @@ class DFRN
 
                        $fcontact = Diaspora::personByHandle($contact['addr']);
                        if (empty($fcontact)) {
-                               logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
+                               Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
                                Contact::markForArchival($contact);
                                return -22;
                        }
@@ -1464,23 +1485,24 @@ class DFRN
 
                $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
 
-               $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
+               $postResult = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
+               $xml = $postResult->getBody();
 
-               $curl_stat = $a->get_curl_code();
+               $curl_stat = $postResult->getReturnCode();
                if (empty($curl_stat) || empty($xml)) {
-                       logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
+                       Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
                        Contact::markForArchival($contact);
                        return -9; // timed out
                }
 
-               if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
+               if (($curl_stat == 503) && (stristr($postResult->getHeader(), 'retry-after'))) {
                        Contact::markForArchival($contact);
                        return -10;
                }
 
                if (strpos($xml, '<?xml') === false) {
-                       logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
-                       logger('Returned XML: ' . $xml, LOGGER_DATA);
+                       Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
+                       Logger::log('Returned XML: ' . $xml, Logger::DATA);
                        Contact::markForArchival($contact);
                        return 3;
                }
@@ -1493,7 +1515,7 @@ class DFRN
                }
 
                if (!empty($res->message)) {
-                       logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
+                       Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
                }
 
                if (($res->status >= 200) && ($res->status <= 299)) {
@@ -1503,43 +1525,6 @@ class DFRN
                return intval($res->status);
        }
 
-       /**
-        * @brief Add new birthday event for this person
-        *
-        * @param array  $contact  Contact record
-        * @param string $birthday Birthday of the contact
-        * @return void
-        * @todo Add array type-hint for $contact
-        */
-       private static function birthdayEvent($contact, $birthday)
-       {
-               // Check for duplicates
-               $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
-                       'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
-               if (DBA::exists('event', $condition)) {
-                       return;
-               }
-
-               logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
-
-               $bdtext = L10n::t('%s\'s birthday', $contact['name']);
-               $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
-
-               $r = q(
-                       "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
-                       VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
-                       intval($contact['uid']),
-                       intval($contact['id']),
-                       DBA::escape(DateTimeFormat::utcNow()),
-                       DBA::escape(DateTimeFormat::utcNow()),
-                       DBA::escape(DateTimeFormat::utc($birthday)),
-                       DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
-                       DBA::escape($bdtext),
-                       DBA::escape($bdtext2),
-                       DBA::escape('birthday')
-               );
-       }
-
        /**
         * @brief Fetch the author data from head or entry items
         *
@@ -1551,7 +1536,9 @@ class DFRN
         * @param string $xml       optional, default empty
         *
         * @return array Relevant data of the author
-        * @todo Find good type-hints for all parameter
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
+        * @todo  Find good type-hints for all parameter
         */
        private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
        {
@@ -1562,7 +1549,7 @@ class DFRN
                $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
                        'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
                $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
-                       $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
+                       $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
                $contact_old = DBA::selectFirst('contact', $fields, $condition);
 
                if (DBA::isResult($contact_old)) {
@@ -1570,7 +1557,7 @@ class DFRN
                        $author["network"] = $contact_old["network"];
                } else {
                        if (!$onlyfetch) {
-                               logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
+                               Logger::debug("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml);
                        }
 
                        $author["contact-unknown"] = true;
@@ -1619,11 +1606,12 @@ class DFRN
                }
 
                if (empty($author['avatar'])) {
-                       logger('Empty author: ' . $xml);
+                       Logger::log('Empty author: ' . $xml);
+                       $author['avatar'] = '';
                }
 
                if (DBA::isResult($contact_old) && !$onlyfetch) {
-                       logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
+                       Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
 
                        $poco = ["url" => $contact_old["url"]];
 
@@ -1684,7 +1672,7 @@ class DFRN
                        // If the "hide" element is present then the profile isn't searchable.
                        $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
 
-                       logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
+                       Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
 
                        // If the contact isn't searchable then set the contact to "hidden".
                        // Problem: This can be manually overridden by the user.
@@ -1715,13 +1703,12 @@ class DFRN
                        // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
                        $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
 
-                       if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
+                       if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
                                $bdyear = date("Y");
-                               $value = str_replace("0000", $bdyear, $value);
+                               $value = str_replace(["0000", "0001"], $bdyear, $value);
 
                                if (strtotime($value) < time()) {
                                        $value = str_replace($bdyear, $bdyear + 1, $value);
-                                       $bdyear = $bdyear + 1;
                                }
 
                                $poco["bd"] = $value;
@@ -1730,7 +1717,7 @@ class DFRN
                        $contact = array_merge($contact_old, $poco);
 
                        if ($contact_old["bdyear"] != $contact["bdyear"]) {
-                               self::birthdayEvent($contact, $birthday);
+                               Event::createBirthday($contact, $birthday);
                        }
 
                        // Get all field names
@@ -1756,20 +1743,20 @@ class DFRN
                                $contact[$field] = DateTimeFormat::utc($contact[$field]);
 
                                if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
-                                       logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
+                                       Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
                                        $update = true;
                                }
                        }
 
                        foreach ($fields as $field => $data) {
                                if ($contact[$field] != $contact_old[$field]) {
-                                       logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
+                                       Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
                                        $update = true;
                                }
                        }
 
                        if ($update) {
-                               logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
+                               Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
 
                                q(
                                        "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
@@ -1872,13 +1859,13 @@ class DFRN
         * @param object $mail     mail elements
         * @param array  $importer Record of the importer user mixed with contact of the content
         * @return void
-        * @todo Find good type-hints for all parameter
+        * @throws \Exception
+        * @todo  Find good type-hints for all parameter
         */
        private static function processMail($xpath, $mail, $importer)
        {
-               logger("Processing mails");
+               Logger::log("Processing mails");
 
-               /// @TODO Rewrite this to one statement
                $msg = [];
                $msg["uid"] = $importer["importer_uid"];
                $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
@@ -1890,33 +1877,8 @@ class DFRN
                $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
                $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
                $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
-               $msg["seen"] = 0;
-               $msg["replied"] = 0;
-
-               DBA::insert('mail', $msg);
-
-               $msg["id"] = DBA::lastInsertId();
-
-               // send notifications.
-               /// @TODO Arange this mess
-               $notif_params = [
-                       "type" => NOTIFY_MAIL,
-                       "notify_flags" => $importer["notify-flags"],
-                       "language" => $importer["language"],
-                       "to_name" => $importer["username"],
-                       "to_email" => $importer["email"],
-                       "uid" => $importer["importer_uid"],
-                       "item" => $msg,
-                       "source_name" => $msg["from-name"],
-                       "source_link" => $importer["url"],
-                       "source_photo" => $importer["thumb"],
-                       "verb" => ACTIVITY_POST,
-                       "otype" => "mail"
-               ];
-
-               notification($notif_params);
-
-               logger("Mail is processed, notification was sent.");
+
+               Mail::insert($msg);
        }
 
        /**
@@ -1926,23 +1888,22 @@ class DFRN
         * @param object $suggestion suggestion elements
         * @param array  $importer   Record of the importer user mixed with contact of the content
         * @return boolean
-        * @todo Find good type-hints for all parameter
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  Find good type-hints for all parameter
         */
        private static function processSuggestion($xpath, $suggestion, $importer)
        {
-               $a = get_app();
-
-               logger("Processing suggestions");
+               Logger::log('Processing suggestions');
 
                /// @TODO Rewrite this to one statement
                $suggest = [];
-               $suggest["uid"] = $importer["importer_uid"];
-               $suggest["cid"] = $importer["id"];
-               $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
-               $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
-               $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
-               $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
-               $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
+               $suggest['uid'] = $importer['importer_uid'];
+               $suggest['cid'] = $importer['id'];
+               $suggest['url'] = $xpath->query('dfrn:url/text()', $suggestion)->item(0)->nodeValue;
+               $suggest['name'] = $xpath->query('dfrn:name/text()', $suggestion)->item(0)->nodeValue;
+               $suggest['photo'] = $xpath->query('dfrn:photo/text()', $suggestion)->item(0)->nodeValue;
+               $suggest['request'] = $xpath->query('dfrn:request/text()', $suggestion)->item(0)->nodeValue;
+               $suggest['body'] = $xpath->query('dfrn:note/text()', $suggestion)->item(0)->nodeValue;
 
                // Does our member already have a friend matching this description?
 
@@ -1953,22 +1914,19 @@ class DFRN
                 *
                 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
                 */
-               $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
-                       'uid' => $suggest["uid"]];
+               $condition = ['nurl' => Strings::normaliseLink($suggest['url']), 'uid' => $suggest['uid']];
                if (DBA::exists('contact', $condition)) {
                        return false;
                }
-
                // Do we already have an fcontact record for this person?
 
                $fid = 0;
-               $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
-               $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
+               $fcontact = DBA::selectFirst('fcontact', ['id'], ['url' => $suggest['url']]);
                if (DBA::isResult($fcontact)) {
-                       $fid = $fcontact["id"];
+                       $fid = $fcontact['id'];
 
                        // OK, we do. Do we already have an introduction for this person?
-                       if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
+                       if (DBA::exists('intro', ['uid' => $suggest['uid'], 'fid' => $fid])) {
                                /*
                                 * The valid result means the friend we're about to send a friend
                                 * suggestion already has them in their contact, which means no further
@@ -1979,59 +1937,44 @@ class DFRN
                                return false;
                        }
                }
+
                if (!$fid) {
-                       $r = q(
-                               "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
-                               DBA::escape($suggest["name"]),
-                               DBA::escape($suggest["url"]),
-                               DBA::escape($suggest["photo"]),
-                               DBA::escape($suggest["request"])
-                       );
+                       $fields = ['name' => $suggest['name'], 'url' => $suggest['url'],
+                               'photo' => $suggest['photo'], 'request' => $suggest['request']];
+                       DBA::insert('fcontact', $fields);
+                       $fid = DBA::lastInsertId();
                }
 
-               $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
-               $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
-
                /*
                 * If no record in fcontact is found, below INSERT statement will not
                 * link an introduction to it.
                 */
-               if (!DBA::isResult($fcontact)) {
+               if (empty($fid)) {
                        // Database record did not get created. Quietly give up.
-                       killme();
+                       exit();
                }
 
-               $fid = $r[0]["id"];
+               $hash = Strings::getRandomHex();
 
-               $hash = random_string();
-
-               $r = q(
-                       "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
-                       VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
-                       intval($suggest["uid"]),
-                       intval($fid),
-                       intval($suggest["cid"]),
-                       DBA::escape($suggest["body"]),
-                       DBA::escape($hash),
-                       DBA::escape(DateTimeFormat::utcNow()),
-                       intval(0)
-               );
+               $fields = ['uid' => $suggest['uid'], 'fid' => $fid, 'contact-id' => $suggest['cid'],
+                       'note' => $suggest['body'], 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow(), 'blocked' => false];
+               DBA::insert('intro', $fields);
 
                notification(
                        [
-                               "type"         => NOTIFY_SUGGEST,
-                               "notify_flags" => $importer["notify-flags"],
-                               "language"     => $importer["language"],
-                               "to_name"      => $importer["username"],
-                               "to_email"     => $importer["email"],
-                               "uid"          => $importer["importer_uid"],
-                               "item"         => $suggest,
-                               "link"         => System::baseUrl()."/notifications/intros",
-                               "source_name"  => $importer["name"],
-                               "source_link"  => $importer["url"],
-                               "source_photo" => $importer["photo"],
-                               "verb"         => ACTIVITY_REQ_FRIEND,
-                               "otype"        => "intro"]
+                               'type'         => NOTIFY_SUGGEST,
+                               'notify_flags' => $importer['notify-flags'],
+                               'language'     => $importer['language'],
+                               'to_name'      => $importer['username'],
+                               'to_email'     => $importer['email'],
+                               'uid'          => $importer['importer_uid'],
+                               'item'         => $suggest,
+                               'link'         => System::baseUrl().'/notifications/intros',
+                               'source_name'  => $importer['name'],
+                               'source_link'  => $importer['url'],
+                               'source_photo' => $importer['photo'],
+                               'verb'         => ACTIVITY_REQ_FRIEND,
+                               'otype'        => 'intro']
                );
 
                return true;
@@ -2044,11 +1987,13 @@ class DFRN
         * @param object $relocation relocation elements
         * @param array  $importer   Record of the importer user mixed with contact of the content
         * @return boolean
-        * @todo Find good type-hints for all parameter
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
+        * @todo  Find good type-hints for all parameter
         */
        private static function processRelocation($xpath, $relocation, $importer)
        {
-               logger("Processing relocations");
+               Logger::log("Processing relocations");
 
                /// @TODO Rewrite this to one statement
                $relocate = [];
@@ -2083,7 +2028,7 @@ class DFRN
                );
 
                if (!DBA::isResult($r)) {
-                       logger("Query failed to execute, no result returned in " . __FUNCTION__);
+                       Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
                        return false;
                }
 
@@ -2093,24 +2038,24 @@ class DFRN
                $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
 
                $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
-                       'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
+                       'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
                        'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
                        'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
-               DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
+               DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($old["url"])]);
 
                // Update the contact table. We try to find every entry.
                $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
-                       'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
+                       'url' => $relocate["url"], 'nurl' => Strings::normaliseLink($relocate["url"]),
                        'addr' => $relocate["addr"], 'request' => $relocate["request"],
                        'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
                        'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
-               $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
+               $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
 
                DBA::update('contact', $fields, $condition);
 
                Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
 
-               logger('Contacts are updated.');
+               Logger::log('Contacts are updated.');
 
                /// @TODO
                /// merge with current record, current contents have priority
@@ -2128,7 +2073,8 @@ class DFRN
         * @param array $importer  Record of the importer user mixed with contact of the content
         * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
         * @return mixed
-        * @todo set proper type-hints (array?)
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  set proper type-hints (array?)
         */
        private static function updateContent($current, $item, $importer, $entrytype)
        {
@@ -2159,17 +2105,18 @@ class DFRN
         * @param array $item     the new item record
         *
         * @return int Is it a toplevel entry, a comment or a relayed comment?
-        * @todo set proper type-hints (array?)
+        * @throws \Exception
+        * @todo  set proper type-hints (array?)
         */
        private static function getEntryType($importer, $item)
        {
                if ($item["parent-uri"] != $item["uri"]) {
                        $community = false;
 
-                       if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
+                       if ($importer["page-flags"] == User::PAGE_FLAGS_COMMUNITY || $importer["page-flags"] == User::PAGE_FLAGS_PRVGROUP) {
                                $sql_extra = "";
                                $community = true;
-                               logger("possible community action");
+                               Logger::log("possible community action");
                        } else {
                                $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
                        }
@@ -2206,7 +2153,7 @@ class DFRN
                         */
                        if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
                                $is_a_remote_action = false;
-                               logger("not a community action");
+                               Logger::log("not a community action");
                        }
 
                        if ($is_a_remote_action) {
@@ -2222,13 +2169,13 @@ class DFRN
        /**
         * @brief Send a "poke"
         *
-        * @param array $item      the new item record
+        * @param array $item      The new item record
         * @param array $importer  Record of the importer user mixed with contact of the content
-        * @param int   $posted_id The record number of item record that was just posted
         * @return void
-        * @todo set proper type-hints (array?)
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  set proper type-hints (array?)
         */
-       private static function doPoke($item, $importer, $posted_id)
+       private static function doPoke(array $item, array $importer)
        {
                $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
                if (!$verb) {
@@ -2238,6 +2185,7 @@ class DFRN
 
                if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
                        // somebody was poked/prodded. Was it me?
+                       $Blink = '';
                        foreach ($xo->link as $l) {
                                $atts = $l->attributes();
                                switch ($atts["rel"]) {
@@ -2249,11 +2197,9 @@ class DFRN
                                }
                        }
 
-                       if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
+                       if ($Blink && Strings::compareLink($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
                                $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
 
-                               $item['id'] = $posted_id;
-
                                $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => $importer["importer_uid"]]);
                                $item["parent"] = $parent['id'];
 
@@ -2267,7 +2213,7 @@ class DFRN
                                        "to_email"     => $importer["email"],
                                        "uid"          => $importer["importer_uid"],
                                        "item"         => $item,
-                                       "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
+                                       "link"         => System::baseUrl()."/display/".urlencode($item['guid']),
                                        "source_name"  => $author["name"],
                                        "source_link"  => $author["url"],
                                        "source_photo" => $author["thumb"],
@@ -2289,38 +2235,38 @@ class DFRN
         * @param bool  $is_like   Is the verb a "like"?
         *
         * @return bool Should the processing of the entries be continued?
-        * @todo set proper type-hints (array?)
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  set proper type-hints (array?)
         */
        private static function processVerbs($entrytype, $importer, &$item, &$is_like)
        {
-               logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
+               Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
 
                if (($entrytype == DFRN::TOP_LEVEL)) {
                        // The filling of the the "contact" variable is done for legcy reasons
                        // The functions below are partly used by ostatus.php as well - where we have this variable
                        $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
                        $contact = $r[0];
-                       $nickname = $contact["nick"];
 
                        // Big question: Do we need these functions? They were part of the "consume_feed" function.
                        // This function once was responsible for DFRN and OStatus.
                        if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
-                               logger("New follower");
-                               Contact::addRelationship($importer, $contact, $item, $nickname);
+                               Logger::log("New follower");
+                               Contact::addRelationship($importer, $contact, $item);
                                return false;
                        }
                        if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
-                               logger("Lost follower");
+                               Logger::log("Lost follower");
                                Contact::removeFollower($importer, $contact, $item);
                                return false;
                        }
                        if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
-                               logger("New friend request");
-                               Contact::addRelationship($importer, $contact, $item, $nickname, true);
+                               Logger::log("New friend request");
+                               Contact::addRelationship($importer, $contact, $item, true);
                                return false;
                        }
                        if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
-                               logger("Lost sharer");
+                               Logger::log("Lost sharer");
                                Contact::removeSharer($importer, $contact, $item);
                                return false;
                        }
@@ -2346,6 +2292,12 @@ class DFRN
                                if (Item::exists($condition)) {
                                        return false;
                                }
+
+                               // The owner of an activity must be the author
+                               $item["owner-name"] = $item["author-name"];
+                               $item["owner-link"] = $item["author-link"];
+                               $item["owner-avatar"] = $item["author-avatar"];
+                               $item["owner-id"] = $item["author-id"];
                        } else {
                                $is_like = false;
                        }
@@ -2358,7 +2310,7 @@ class DFRN
                                        $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
 
                                        if (!DBA::isResult($item_tag)) {
-                                               logger("Query failed to execute, no result returned in " . __FUNCTION__);
+                                               Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
                                                return false;
                                        }
 
@@ -2406,8 +2358,6 @@ class DFRN
                                                $item["plink"] = $href;
                                                break;
                                        case "enclosure":
-                                               $enclosure = $href;
-
                                                if (!empty($item["attach"])) {
                                                        $item["attach"] .= ",";
                                                } else {
@@ -2428,13 +2378,15 @@ class DFRN
         * @param object $xpath    XPath object
         * @param object $entry    entry elements
         * @param array  $importer Record of the importer user mixed with contact of the content
-        * @param object $xml      xml
+        * @param string $xml      xml
         * @return void
-        * @todo Add type-hints
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
+        * @todo  Add type-hints
         */
        private static function processEntry($header, $xpath, $entry, $importer, $xml)
        {
-               logger("Processing entries");
+               Logger::log("Processing entries");
 
                $item = $header;
 
@@ -2452,7 +2404,7 @@ class DFRN
                );
                // Is there an existing item?
                if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
-                       logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
+                       Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
                        return;
                }
 
@@ -2481,16 +2433,16 @@ class DFRN
                $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
                $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
                // make sure nobody is trying to sneak some html tags by us
-               $item["body"] = notags(base64url_decode($item["body"]));
+               $item["body"] = Strings::escapeTags(Strings::base64UrlDecode($item["body"]));
 
                $item["body"] = BBCode::limitBodySize($item["body"]);
 
                /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
                if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
-                       $base_url = get_app()->get_baseurl();
-                       $item['body'] = reltoabs($item['body'], $base_url);
+                       $base_url = \get_app()->getBaseURL();
+                       $item['body'] = HTML::relToAbs($item['body'], $base_url);
 
-                       $item['body'] = html2bb_video($item['body']);
+                       $item['body'] = HTML::toBBCodeVideo($item['body']);
 
                        $item['body'] = OEmbed::HTML2BBCode($item['body']);
 
@@ -2535,7 +2487,7 @@ class DFRN
                $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
 
                // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
-               $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
+               $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
                if ($dsprsig != "") {
                        $item["dsprsig"] = $dsprsig;
                }
@@ -2592,8 +2544,6 @@ class DFRN
                        }
                }
 
-               $enclosure = "";
-
                $links = $xpath->query("atom:link", $entry);
                if ($links) {
                        self::parseLinks($links, $item);
@@ -2660,10 +2610,10 @@ class DFRN
 
                        // Is it an event?
                        if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
-                               logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
+                               Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
                                $ev = Event::fromBBCode($item["body"]);
-                               if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
-                                       logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
+                               if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
+                                       Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
                                        $ev["cid"]     = $importer["id"];
                                        $ev["uid"]     = $importer["importer_uid"];
                                        $ev["uri"]     = $item["uri"];
@@ -2679,20 +2629,20 @@ class DFRN
                                        }
 
                                        $event_id = Event::store($ev);
-                                       logger("Event ".$event_id." was stored", LOGGER_DEBUG);
+                                       Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
                                        return;
                                }
                        }
                }
 
                if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
-                       logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
+                       Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
                        return;
                }
 
                // This check is done here to be able to receive connection requests in "processVerbs"
                if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
-                       logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
+                       Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
                        return;
                }
 
@@ -2700,19 +2650,17 @@ class DFRN
                // Update content if 'updated' changes
                if (DBA::isResult($current)) {
                        if (self::updateContent($current, $item, $importer, $entrytype)) {
-                               logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
+                               Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
                        } else {
-                               logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
+                               Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
                        }
                        return;
                }
 
                if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
                        $posted_id = Item::insert($item);
-                       $parent = 0;
-
                        if ($posted_id) {
-                               logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
+                               Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
 
                                if ($item['uid'] == 0) {
                                        Item::distribute($posted_id);
@@ -2722,23 +2670,23 @@ class DFRN
                        }
                } else { // $entrytype == DFRN::TOP_LEVEL
                        if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
-                               logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
+                               Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
                                return;
                        }
-                       if (!link_compare($item["owner-link"], $importer["url"])) {
+                       if (!Strings::compareLink($item["owner-link"], $importer["url"])) {
                                /*
                                 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
                                 * but otherwise there's a possible data mixup on the sender's system.
                                 * the tgroup delivery code called from Item::insert will correct it if it's a forum,
                                 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
                                 */
-                               logger('Correcting item owner.', LOGGER_DEBUG);
+                               Logger::log('Correcting item owner.', Logger::DEBUG);
                                $item["owner-link"] = $importer["url"];
                                $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
                        }
 
                        if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
-                               logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
+                               Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
                                return;
                        }
 
@@ -2752,14 +2700,15 @@ class DFRN
                                $posted_id = $notify;
                        }
 
-                       logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
+                       Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
 
                        if ($item['uid'] == 0) {
                                Item::distribute($posted_id);
                        }
 
                        if (stristr($item["verb"], ACTIVITY_POKE)) {
-                               self::doPoke($item, $importer, $posted_id);
+                               $item['id'] = $posted_id;
+                               self::doPoke($item, $importer);
                        }
                }
        }
@@ -2771,11 +2720,12 @@ class DFRN
         * @param object $deletion deletion elements
         * @param array  $importer Record of the importer user mixed with contact of the content
         * @return void
-        * @todo set proper type-hints
+        * @throws \Exception
+        * @todo  set proper type-hints
         */
        private static function processDeletion($xpath, $deletion, $importer)
        {
-               logger("Processing deletions");
+               Logger::log("Processing deletions");
                $uri = null;
 
                foreach ($deletion->attributes as $attributes) {
@@ -2791,18 +2741,18 @@ class DFRN
                $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
                $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
                if (!DBA::isResult($item)) {
-                       logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
+                       Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
                        return;
                }
 
                if (strstr($item['file'], '[')) {
-                       logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
+                       Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
                        return;
                }
 
                // When it is a starting post it has to belong to the person that wants to delete it
                if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
-                       logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
+                       Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
                        return;
                }
 
@@ -2810,7 +2760,7 @@ class DFRN
                if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
                        $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
                        if (!Item::exists($condition)) {
-                               logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
+                               Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
                                return;
                        }
                }
@@ -2819,7 +2769,7 @@ class DFRN
                        return;
                }
 
-               logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
+               Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
 
                Item::delete(['id' => $item['id']]);
        }
@@ -2831,7 +2781,9 @@ class DFRN
         * @param array  $importer     Record of the importer user mixed with contact of the content
         * @param bool   $sort_by_date Is used when feeds are polled
         * @return integer Import status
-        * @todo set proper type-hints
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
+        * @todo  set proper type-hints
         */
        public static function import($xml, $importer, $sort_by_date = false)
        {
@@ -2873,26 +2825,48 @@ class DFRN
                        self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
                }
 
-               logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
+               Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
 
                // is it a public forum? Private forums aren't exposed with this method
                $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
 
                // The account type is new since 3.5.1
                if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
+                       // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
+
                        $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
 
                        if ($accounttype != $importer["contact-type"]) {
-                               DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
+                               DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer['id']]);
+
+                               // Updating the public contact as well
+                               DBA::update('contact', ['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
                        }
                        // A forum contact can either have set "forum" or "prv" - but not both
-                       if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
-                               $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
+                       if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
+                               // It's a forum, so either set the public or private forum flag
+                               $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
+                               DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
+
+                               // Updating the public contact as well
+                               $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
                                DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
+                       } else {
+                               // It's not a forum, so remove the flags
+                               $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
+                               DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
+
+                               // Updating the public contact as well
+                               $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
+                               DBA::update('contact', ['forum' => false, 'prv' => false], $condition);
                        }
                } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
                        $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
                        DBA::update('contact', ['forum' => $forum], $condition);
+
+                       // Updating the public contact as well
+                       $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
+                       DBA::update('contact', ['forum' => $forum], $condition);
                }
 
 
@@ -2939,18 +2913,19 @@ class DFRN
                                self::processEntry($header, $xpath, $entry, $importer, $xml);
                        }
                }
-               logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
+               Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
                return 200;
        }
 
        /**
         * @param App    $a            App
         * @param string $contact_nick contact nickname
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        public static function autoRedir(App $a, $contact_nick)
        {
                // prevent looping
-               if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
+               if (!empty($_REQUEST['redir'])) {
                        return;
                }
 
@@ -2973,7 +2948,7 @@ class DFRN
                                return;
                        }
                        $baseurl = substr($baseurl, $domain_st + 3);
-                       $nurl = normalise_link($baseurl);
+                       $nurl = Strings::normaliseLink($baseurl);
 
                        /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
                        $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
@@ -3018,15 +2993,15 @@ class DFRN
                                return;
                        }
 
-                       $sec = random_string();
+                       $sec = Strings::getRandomHex();
 
                        DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
 
                        $url = curPageURL();
 
-                       logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
+                       Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
                        $dest = (($url) ? '&destination_url=' . $url : '');
-                       goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
+                       System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
                                . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
                }
 
@@ -3063,23 +3038,23 @@ class DFRN
                        return false;
                }
 
-               $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
-               $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
+               $community_page = ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY);
+               $prvgroup = ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP);
 
-               $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
+               $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
 
                /*
                 * Diaspora uses their own hardwired link URL in @-tags
                 * instead of the one we supply with webfinger
                 */
-               $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
+               $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
 
                $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
                if ($cnt) {
                        foreach ($matches as $mtch) {
-                               if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
+                               if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
                                        $mention = true;
-                                       logger('mention found: ' . $mtch[2]);
+                                       Logger::log('mention found: ' . $mtch[2]);
                                }
                        }
                }
@@ -3099,13 +3074,17 @@ class DFRN
         * item is assumed to be up-to-date.  If the timestamps are equal it
         * assumes the update has been seen before and should be ignored.
         *
+        * @param $existing
+        * @param $update
+        * @return bool
+        * @throws \Exception
         */
        private static function isEditedTimestampNewer($existing, $update)
        {
-               if (!x($existing, 'edited') || !$existing['edited']) {
+               if (empty($existing['edited'])) {
                        return true;
                }
-               if (!x($update, 'edited') || !$update['edited']) {
+               if (empty($update['edited'])) {
                        return false;
                }