]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/DFRN.php
Merge pull request #6224 from annando/dba-delete-contact
[friendica.git] / src / Protocol / DFRN.php
index a9e836499feaae3050118caac54a15131d77a162..7c807b921e22cad9ff923fed1def135bd8b9918a 100644 (file)
@@ -8,33 +8,32 @@
  */
 namespace Friendica\Protocol;
 
+use DOMDocument;
+use DOMXPath;
 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\Logger;
+use Friendica\Core\Protocol;
 use Friendica\Core\System;
-use Friendica\Core\Worker;
-use Friendica\Database\DBM;
+use Friendica\Database\DBA;
 use Friendica\Model\Contact;
+use Friendica\Model\Conversation;
 use Friendica\Model\Event;
 use Friendica\Model\GContact;
-use Friendica\Model\Group;
 use Friendica\Model\Item;
+use Friendica\Model\PermissionSet;
 use Friendica\Model\Profile;
 use Friendica\Model\User;
 use Friendica\Object\Image;
-use Friendica\Protocol\OStatus;
 use Friendica\Util\Crypto;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
+use Friendica\Util\Strings;
 use Friendica\Util\XML;
-use Friendica\Protocol\Diaspora;
-use dba;
-use DOMDocument;
-use DOMXPath;
 use HTMLPurifier;
 use HTMLPurifier_Config;
 
@@ -54,6 +53,46 @@ class DFRN
        const REPLY = 1;                // Regular reply that is stored locally
        const REPLY_RC = 2;     // Reply that will be relayed
 
+       /**
+        * @brief Generates an array of contact and user for DFRN imports
+        *
+        * This array contains not only the receiver but also the sender of the message.
+        *
+        * @param integer $cid Contact id
+        * @param integer $uid User id
+        *
+        * @return array importer
+        */
+       public static function getImporter($cid, $uid = 0)
+       {
+               $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
+               $contact = DBA::selectFirst('contact', [], $condition);
+               if (!DBA::isResult($contact)) {
+                       return [];
+               }
+
+               $contact['cpubkey'] = $contact['pubkey'];
+               $contact['cprvkey'] = $contact['prvkey'];
+               $contact['senderName'] = $contact['name'];
+
+               if ($uid != 0) {
+                       $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
+                       $user = DBA::selectFirst('user', [], $condition);
+                       if (!DBA::isResult($user)) {
+                               return [];
+                       }
+
+                       $user['importer_uid'] = $user['uid'];
+                       $user['uprvkey'] = $user['prvkey'];
+               } else {
+                       $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
+                               'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
+                               'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
+               }
+
+               return array_merge($contact, $user);
+       }
+
        /**
         * @brief Generates the atom entries for delivery.php
         *
@@ -77,6 +116,11 @@ class DFRN
                }
 
                foreach ($items as $item) {
+                       // These values aren't sent when sending from the queue.
+                       /// @todo Check if we can set these values from the queue or if they are needed at all.
+                       $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
+                       $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);
                }
@@ -122,17 +166,17 @@ class DFRN
 
                // default permissions - anonymous user
 
-               $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' ";
+               $sql_extra = " AND NOT `item`.`private` ";
 
                $r = q(
                        "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
                        FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
                        WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
-                       dbesc($owner_nick)
+                       DBA::escape($owner_nick)
                );
 
-               if (! DBM::is_result($r)) {
-                       logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
+               if (! DBA::isResult($r)) {
+                       Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
                        killme();
                }
 
@@ -146,15 +190,15 @@ class DFRN
                        $sql_extra = '';
                        switch ($direction) {
                                case (-1):
-                                       $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
+                                       $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 ", dbesc($dfrn_id));
+                                       $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 ", dbesc($dfrn_id));
+                                       $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
                                        $my_id = '0:' . $dfrn_id;
                                        break;
                                default:
@@ -167,37 +211,20 @@ class DFRN
                                intval($owner_id)
                        );
 
-                       if (! DBM::is_result($r)) {
-                               logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
+                       if (! DBA::isResult($r)) {
+                               Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
                                killme();
                        }
 
                        $contact = $r[0];
-                       include_once 'include/security.php';
-                       $groups = Group::getIdsByContactId($contact['id']);
 
-                       if (count($groups)) {
-                               for ($x = 0; $x < count($groups); $x ++) {
-                                       $groups[$x] = '<' . intval($groups[$x]) . '>' ;
-                               }
+                       $set = PermissionSet::get($owner_id, $contact['id']);
 
-                               $gs = implode('|', $groups);
+                       if (!empty($set)) {
+                               $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")";
                        } else {
-                               $gs = '<<>>' ; // Impossible to match
-                       }
-
-                       $sql_extra = sprintf(
-                               "
-                               AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
-                               AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' )
-                               AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
-                               AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s')
-                       ",
-                               intval($contact['id']),
-                               intval($contact['id']),
-                               dbesc($gs),
-                               dbesc($gs)
-                       );
+                               $sql_extra = " AND NOT `item`.`private`";
+                       }
                }
 
                if ($public_feed) {
@@ -213,12 +240,12 @@ 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` ",
-                               dbesc(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');
+                       //$sql_extra .= FileTag::fileQuery('item',$category,'category');
                }
 
                if ($public_feed && ! $converse) {
@@ -235,8 +262,8 @@ class DFRN
                        $sql_extra
                        ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
                        intval($owner_id),
-                       dbesc($check_date),
-                       dbesc($sort)
+                       DBA::escape($check_date),
+                       DBA::escape($sort)
                );
 
                $ids = [];
@@ -246,7 +273,7 @@ class DFRN
 
                if (!empty($ids)) {
                        $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
-                       $items = dba::inArray($ret);
+                       $items = Item::inArray($ret);
                } else {
                        $items = [];
                }
@@ -276,7 +303,7 @@ class DFRN
                /// @TODO This hook can't work anymore
                //      Addon::callHooks('atom_feed', $atom);
 
-               if (!DBM::is_result($items) || $onlyheader) {
+               if (!DBA::isResult($items) || $onlyheader) {
                        $atom = trim($doc->saveXML());
 
                        Addon::callHooks('atom_feed_end', $atom);
@@ -286,7 +313,7 @@ class DFRN
 
                foreach ($items as $item) {
                        // prevent private email from leaking.
-                       if ($item['network'] == NETWORK_MAIL) {
+                       if ($item['network'] == Protocol::MAIL) {
                                continue;
                        }
 
@@ -330,8 +357,8 @@ class DFRN
                }
 
                $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
-               $items = dba::inArray($ret);
-               if (!DBM::is_result($items)) {
+               $items = Item::inArray($ret);
+               if (!DBA::isResult($items)) {
                        killme();
                }
 
@@ -561,14 +588,14 @@ class DFRN
                }
 
                // For backward compatibility we keep this element
-               if ($owner['page-flags'] == PAGE_COMMUNITY) {
+               if ($owner['page-flags'] == Contact::PAGE_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 "PAGE_PRVGROUP"
+               /// @todo We need a way to transmit the different page flags like "Contact::PAGE_PRVGROUP"
 
                XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
 
@@ -597,7 +624,7 @@ class DFRN
                                WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
                        intval($owner['uid'])
                );
-               if (DBM::is_result($r)) {
+               if (DBA::isResult($r)) {
                        $hidewall = true;
                } else {
                        $hidewall = false;
@@ -620,7 +647,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;
@@ -656,13 +683,13 @@ class DFRN
                                WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
                        intval($owner['uid'])
                );
-               if (DBM::is_result($r)) {
+               if (DBA::isResult($r)) {
                        $profile = $r[0];
 
                        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"])));
                        }
 
@@ -910,7 +937,7 @@ class DFRN
                        $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
                }
 
-               if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
+               if ($item['private']) {
                        $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
                } else {
                        $body = $item['body'];
@@ -938,10 +965,10 @@ class DFRN
 
                if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
                        $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
-                       $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
+                       $parent = Item::selectFirst(['guid', 'plink'], ['uri' => $parent_item, 'uid' => $item['uid']]);
                        $attributes = ["ref" => $parent_item, "type" => "text/html",
-                                               "href" => $parent[0]['plink'],
-                                               "dfrn:diaspora_guid" => $parent[0]['guid']];
+                                               "href" => $parent['plink'],
+                                               "dfrn:diaspora_guid" => $parent['guid']];
                        XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
                }
 
@@ -950,12 +977,12 @@ class DFRN
                $conversation_uri = $conversation_href;
 
                if (isset($parent_item)) {
-                       $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
-                       if (DBM::is_result($conversation)) {
-                               if ($r['conversation-uri'] != '') {
+                       $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
+                       if (DBA::isResult($conversation)) {
+                               if ($conversation['conversation-uri'] != '') {
                                        $conversation_uri = $conversation['conversation-uri'];
                                }
-                               if ($r['conversation-href'] != '') {
+                               if ($conversation['conversation-href'] != '') {
                                        $conversation_href = $conversation['conversation-href'];
                                }
                        }
@@ -974,7 +1001,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"
@@ -1004,15 +1031,15 @@ class DFRN
                        XML::addElement($doc, $entry, "georss:point", $item['coord']);
                }
 
-               if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
-                       XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
+               if ($item['private']) {
+                       XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1));
                }
 
                if ($item['extid']) {
                        XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
                }
 
-               if ($item['bookmark']) {
+               if ($item['post-type'] == Item::PT_PAGE) {
                        XML::addElement($doc, $entry, "dfrn:bookmark", "true");
                }
 
@@ -1069,13 +1096,10 @@ class DFRN
                }
 
                foreach ($mentioned as $mention) {
-                       $r = q(
-                               "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
-                               intval($owner["uid"]),
-                               dbesc(normalise_link($mention))
-                       );
+                       $condition = ['uid' => $owner["uid"], 'nurl' => Strings::normaliseLink($mention)];
+                       $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
 
-                       if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
+                       if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
                                XML::addElement(
                                        $doc,
                                        $entry,
@@ -1140,15 +1164,17 @@ class DFRN
         * @return int Deliver status. Negative values mean an error.
         * @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']);
@@ -1163,7 +1189,7 @@ 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 = '';
@@ -1183,24 +1209,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 ($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);
@@ -1208,17 +1234,24 @@ 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;
                }
 
                $res = XML::parseString($xml);
 
-               if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
+               if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
                        Contact::markForArchival($contact);
-                       return ($res->status ? $res->status : 3);
+
+                       if (empty($res->status)) {
+                               $status = 3;
+                       } else {
+                               $status = $res->status;
+                       }
+
+                       return $status;
                }
 
                $postvars     = [];
@@ -1227,32 +1260,29 @@ 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'] == PAGE_COMMUNITY) ? 1 : 0);
+               $page         = (($owner['page-flags'] == Contact::PAGE_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'] == PAGE_PRVGROUP) {
+               if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
                        $page = 2;
                }
 
                $final_dfrn_id = '';
 
                if ($perm) {
-                       if ((($perm == 'rw') && (! intval($contact['writable'])))
-                               || (($perm == 'r') && (intval($contact['writable'])))
+                       if ((($perm == 'rw') && !intval($contact['writable']))
+                               || (($perm == 'r') && intval($contact['writable']))
                        ) {
-                               q(
-                                       "update contact set writable = %d where id = %d",
-                                       intval(($perm == 'rw') ? 1 : 0),
-                                       intval($contact['id'])
-                               );
+                               DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
+
                                $contact['writable'] = (string) 1 - intval($contact['writable']);
                        }
                }
 
                if (($contact['duplex'] && strlen($contact['pubkey']))
-                       || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
-                       || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
+                       || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
+                       || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
                ) {
                        openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
                        openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
@@ -1268,7 +1298,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;
@@ -1280,7 +1310,7 @@ class DFRN
                        $postvars['dissolve'] = '1';
                }
 
-               if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
+               if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
                        $postvars['data'] = $atom;
                        $postvars['perm'] = 'rw';
                } else {
@@ -1296,15 +1326,16 @@ 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:
                                        $key = openssl_random_pseudo_bytes(16);
                                        $data = self::aesEncrypt($postvars['data'], $key);
                                        break;
+
                                default:
-                                       logger("rino: invalid requested version '$rino_remote_version'");
+                                       Logger::log("rino: invalid requested version '$rino_remote_version'");
                                        Contact::markForArchival($contact);
                                        return -8;
                        }
@@ -1314,47 +1345,49 @@ class DFRN
 
                        if ($dfrn_version >= 2.1) {
                                if (($contact['duplex'] && strlen($contact['pubkey']))
-                                       || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
-                                       || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
+                                       || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
+                                       || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
                                ) {
                                        openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
                                } else {
                                        openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
                                }
                        } else {
-                               if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
+                               if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_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);
 
-               $xml = Network::post($contact['notify'], $postvars);
+               $postResult = Network::post($contact['notify'], $postvars);
 
-               logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
+               $xml = $postResult->getBody();
 
-               $curl_stat = $a->get_curl_code();
+               Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
+
+               $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;
                }
@@ -1372,7 +1405,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)) {
@@ -1397,14 +1430,14 @@ class DFRN
 
                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']]);
+                                       $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;
                                }
@@ -1412,7 +1445,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;
                        }
@@ -1436,23 +1469,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;
                }
@@ -1465,7 +1499,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)) {
@@ -1475,49 +1509,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
-               $r = q(
-                       "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
-                       intval($contact['uid']),
-                       intval($contact['id']),
-                       dbesc(DateTimeFormat::utc($birthday)),
-                       dbesc('birthday')
-               );
-
-               if (DBM::is_result($r)) {
-                       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']),
-                       dbesc(DateTimeFormat::utcNow()),
-                       dbesc(DateTimeFormat::utcNow()),
-                       dbesc(DateTimeFormat::utc($birthday)),
-                       dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
-                       dbesc($bdtext),
-                       dbesc($bdtext2),
-                       dbesc('birthday')
-               );
-       }
-
        /**
         * @brief Fetch the author data from head or entry items
         *
@@ -1534,23 +1525,24 @@ class DFRN
        private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
        {
                $author = [];
-               $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
-               $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
+               $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
+               $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
 
                $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"]), NETWORK_STATUSNET];
-               $contact_old = dba::selectFirst('contact', $fields, $condition);
+                       $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
+               $contact_old = DBA::selectFirst('contact', $fields, $condition);
 
-               if (DBM::is_result($contact_old)) {
+               if (DBA::isResult($contact_old)) {
                        $author["contact-id"] = $contact_old["id"];
                        $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::log("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, Logger::DEBUG);
                        }
 
+                       $author["contact-unknown"] = true;
                        $author["contact-id"] = $importer["id"];
                        $author["network"] = $importer["network"];
                        $onlyfetch = true;
@@ -1585,8 +1577,22 @@ class DFRN
                        $author["avatar"] = current($avatarlist);
                }
 
-               if (DBM::is_result($contact_old) && !$onlyfetch) {
-                       logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
+               if (empty($author['avatar']) && !empty($author['link'])) {
+                       $cid = Contact::getIdForURL($author['link'], 0);
+                       if (!empty($cid)) {
+                               $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
+                               if (DBA::isResult($contact)) {
+                                       $author['avatar'] = $contact['avatar'];
+                               }
+                       }
+               }
+
+               if (empty($author['avatar'])) {
+                       Logger::log('Empty author: ' . $xml);
+               }
+
+               if (DBA::isResult($contact_old) && !$onlyfetch) {
+                       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"]];
 
@@ -1606,33 +1612,33 @@ class DFRN
                        }
 
                        // Update contact data
-                       $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
+                       $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
                        if ($value != "") {
                                $poco["addr"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
+                       $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
                        if ($value != "") {
                                $poco["name"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
+                       $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
                        if ($value != "") {
                                $poco["nick"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
+                       $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
                        if ($value != "") {
                                $poco["about"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
+                       $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
                        if ($value != "") {
                                $poco["location"] = $value;
                        }
 
                        /// @todo Only search for elements with "poco:type" = "xmpp"
-                       $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
+                       $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
                        if ($value != "") {
                                $poco["xmpp"] = $value;
                        }
@@ -1645,9 +1651,9 @@ class DFRN
                        /// - poco:country
 
                        // If the "hide" element is present then the profile isn't searchable.
-                       $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
+                       $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.
@@ -1667,7 +1673,7 @@ class DFRN
                        }
 
                        // "dfrn:birthday" contains the birthday converted to UTC
-                       $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
+                       $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
 
                        if (strtotime($birthday) > time()) {
                                $bd_timestamp = strtotime($birthday);
@@ -1676,11 +1682,11 @@ class DFRN
                        }
 
                        // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
-                       $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
+                       $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);
@@ -1693,7 +1699,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
@@ -1714,32 +1720,36 @@ class DFRN
                        // Update check for this field has to be done differently
                        $datefields = ["name-date", "uri-date"];
                        foreach ($datefields as $field) {
+                               // The date fields arrives as '2018-07-17T10:44:45Z' - the database return '2018-07-17 10:44:45'
+                               // The fields have to be in the same format to be comparable, since strtotime does add timezones.
+                               $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',
                                        `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
                                        `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
                                        WHERE `id` = %d AND `network` = '%s'",
-                                       dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]),     dbesc($contact["location"]),
-                                       dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
-                                       dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
-                                       dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
-                                       intval($contact["id"]), dbesc($contact["network"])
+                                       DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]),   DBA::escape($contact["location"]),
+                                       DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
+                                       DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
+                                       DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
+                                       intval($contact["id"]), DBA::escape($contact["network"])
                                );
                        }
 
@@ -1835,7 +1845,7 @@ class DFRN
         */
        private static function processMail($xpath, $mail, $importer)
        {
-               logger("Processing mails");
+               Logger::log("Processing mails");
 
                /// @TODO Rewrite this to one statement
                $msg = [];
@@ -1852,7 +1862,9 @@ class DFRN
                $msg["seen"] = 0;
                $msg["replied"] = 0;
 
-               dba::insert('mail', $msg);
+               DBA::insert('mail', $msg);
+
+               $msg["id"] = DBA::lastInsertId();
 
                // send notifications.
                /// @TODO Arange this mess
@@ -1873,7 +1885,7 @@ class DFRN
 
                notification($notif_params);
 
-               logger("Mail is processed, notification was sent.");
+               Logger::log("Mail is processed, notification was sent.");
        }
 
        /**
@@ -1889,7 +1901,7 @@ class DFRN
        {
                $a = get_app();
 
-               logger("Processing suggestions");
+               Logger::log("Processing suggestions");
 
                /// @TODO Rewrite this to one statement
                $suggest = [];
@@ -1903,13 +1915,6 @@ class DFRN
 
                // Does our member already have a friend matching this description?
 
-               $r = q(
-                       "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
-                       dbesc($suggest["name"]),
-                       dbesc(normalise_link($suggest["url"])),
-                       intval($suggest["uid"])
-               );
-
                /*
                 * The valid result means the friend we're about to send a friend
                 * suggestion already has them in their contact, which means no further
@@ -1917,68 +1922,57 @@ class DFRN
                 *
                 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
                 */
-               if (DBM::is_result($r)) {
+               $condition = ['name' => $suggest["name"], '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;
-               $r = q(
-                       "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
-                       dbesc($suggest["url"]),
-                       dbesc($suggest["name"]),
-                       dbesc($suggest["request"])
-               );
-               if (DBM::is_result($r)) {
-                       $fid = $r[0]["id"];
-
-                       // OK, we do. Do we already have an introduction for this person ?
-                       $r = q(
-                               "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
-                               intval($suggest["uid"]),
-                               intval($fid)
-                       );
+               $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
+               $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
+               if (DBA::isResult($fcontact)) {
+                       $fid = $fcontact["id"];
 
-                       /*
-                        * The valid result means the friend we're about to send a friend
-                        * suggestion already has them in their contact, which means no further
-                        * action is required.
-                        *
-                        * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
-                        */
-                       if (DBM::is_result($r)) {
+                       // OK, we do. Do we already have an introduction for this person?
+                       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
+                                * action is required.
+                                *
+                                * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
+                                */
                                return false;
                        }
                }
                if (!$fid) {
                        $r = q(
                                "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
-                               dbesc($suggest["name"]),
-                               dbesc($suggest["url"]),
-                               dbesc($suggest["photo"]),
-                               dbesc($suggest["request"])
+                               DBA::escape($suggest["name"]),
+                               DBA::escape($suggest["url"]),
+                               DBA::escape($suggest["photo"]),
+                               DBA::escape($suggest["request"])
                        );
                }
-               $r = q(
-                       "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
-                       dbesc($suggest["url"]),
-                       dbesc($suggest["name"]),
-                       dbesc($suggest["request"])
-               );
+
+               $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 (!DBM::is_result($r)) {
-                       // database record did not get created. Quietly give up.
+               if (!DBA::isResult($fcontact)) {
+                       // Database record did not get created. Quietly give up.
                        killme();
                }
 
                $fid = $r[0]["id"];
 
-               $hash = random_string();
+               $hash = Strings::getRandomHex();
 
                $r = q(
                        "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
@@ -1986,9 +1980,9 @@ class DFRN
                        intval($suggest["uid"]),
                        intval($fid),
                        intval($suggest["cid"]),
-                       dbesc($suggest["body"]),
-                       dbesc($hash),
-                       dbesc(DateTimeFormat::utcNow()),
+                       DBA::escape($suggest["body"]),
+                       DBA::escape($hash),
+                       DBA::escape(DateTimeFormat::utcNow()),
                        intval(0)
                );
 
@@ -2023,7 +2017,7 @@ class DFRN
         */
        private static function processRelocation($xpath, $relocation, $importer)
        {
-               logger("Processing relocations");
+               Logger::log("Processing relocations");
 
                /// @TODO Rewrite this to one statement
                $relocate = [];
@@ -2052,13 +2046,13 @@ class DFRN
 
                // update contact
                $r = q(
-                       "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
+                       "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
                        intval($importer["id"]),
                        intval($importer["importer_uid"])
                );
 
-               if (!DBM::is_result($r)) {
-                       logger("Query failed to execute, no result returned in " . __FUNCTION__);
+               if (!DBA::isResult($r)) {
+                       Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
                        return false;
                }
 
@@ -2068,33 +2062,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"])];
-               dba::update('contact', $fields, $condition);
+               $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], Strings::normaliseLink($old["url"])];
 
-               // @TODO No dba:update here?
-               dba::update('contact', $fields, $condition);
+               DBA::update('contact', $fields, $condition);
 
                Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
 
-               logger('Contacts are updated.');
-
-               // update items
-               // This is an extreme performance killer
-               Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
-               Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
-
-               logger('Items are updated.');
+               Logger::log('Contacts are updated.');
 
                /// @TODO
                /// merge with current record, current contents have priority
@@ -2150,10 +2135,10 @@ class DFRN
                if ($item["parent-uri"] != $item["uri"]) {
                        $community = false;
 
-                       if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
+                       if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
                                $sql_extra = "";
                                $community = true;
-                               logger("possible community action");
+                               Logger::log("possible community action");
                        } else {
                                $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
                        }
@@ -2163,13 +2148,8 @@ class DFRN
 
                        $is_a_remote_action = false;
 
-                       $r = q(
-                               "SELECT `item`.`parent-uri` FROM `item`
-                               WHERE `item`.`uri` = '%s'
-                               LIMIT 1",
-                               dbesc($item["parent-uri"])
-                       );
-                       if (DBM::is_result($r)) {
+                       $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
+                       if (DBA::isResult($parent)) {
                                $r = q(
                                        "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
                                        INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
@@ -2177,12 +2157,12 @@ class DFRN
                                        AND `item`.`uid` = %d
                                        $sql_extra
                                        LIMIT 1",
-                                       dbesc($r[0]["parent-uri"]),
-                                       dbesc($r[0]["parent-uri"]),
-                                       dbesc($r[0]["parent-uri"]),
+                                       DBA::escape($parent["parent-uri"]),
+                                       DBA::escape($parent["parent-uri"]),
+                                       DBA::escape($parent["parent-uri"]),
                                        intval($importer["importer_uid"])
                                );
-                               if (DBM::is_result($r)) {
+                               if (DBA::isResult($r)) {
                                        $is_a_remote_action = true;
                                }
                        }
@@ -2195,7 +2175,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) {
@@ -2238,8 +2218,13 @@ class DFRN
                                }
                        }
 
-                       if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
-                               $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
+                       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'];
 
                                // send a notification
                                notification(
@@ -2277,7 +2262,7 @@ class DFRN
         */
        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
@@ -2289,22 +2274,22 @@ class DFRN
                        // 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");
+                               Logger::log("New follower");
                                Contact::addRelationship($importer, $contact, $item, $nickname);
                                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");
+                               Logger::log("New friend request");
                                Contact::addRelationship($importer, $contact, $item, $nickname, true);
                                return false;
                        }
                        if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
-                               logger("Lost sharer");
+                               Logger::log("Lost sharer");
                                Contact::removeSharer($importer, $contact, $item);
                                return false;
                        }
@@ -2316,31 +2301,26 @@ class DFRN
                                || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
                        ) {
                                $is_like = true;
-                               $item["type"] = "activity";
-                               $item["gravity"] = GRAVITY_LIKE;
+                               $item["gravity"] = GRAVITY_ACTIVITY;
                                // only one like or dislike per person
                                // splitted into two queries for performance issues
-                               $r = q(
-                                       "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
-                                       intval($item["uid"]),
-                                       intval($item["author-id"]),
-                                       dbesc($item["verb"]),
-                                       dbesc($item["parent-uri"])
-                               );
-                               if (DBM::is_result($r)) {
+                               $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
+                                       'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
+                               if (Item::exists($condition)) {
                                        return false;
                                }
 
-                               $r = q(
-                                       "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
-                                       intval($item["uid"]),
-                                       intval($item["author-id"]),
-                                       dbesc($item["verb"]),
-                                       dbesc($item["parent-uri"])
-                               );
-                               if (DBM::is_result($r)) {
+                               $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
+                                       'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
+                               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;
                        }
@@ -2350,22 +2330,18 @@ class DFRN
                                $xt = XML::parseString($item["target"], false);
 
                                if ($xt->type == ACTIVITY_OBJ_NOTE) {
-                                       $r = q(
-                                               "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
-                                               dbesc($xt->id),
-                                               intval($importer["importer_uid"])
-                                       );
-
-                                       if (!DBM::is_result($r)) {
-                                               logger("Query failed to execute, no result returned in " . __FUNCTION__);
+                                       $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
+
+                                       if (!DBA::isResult($item_tag)) {
+                                               Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
                                                return false;
                                        }
 
                                        // extract tag, if not duplicate, add to parent item
                                        if ($xo->content) {
-                                               if (!stristr($r[0]["tag"], trim($xo->content))) {
-                                                       $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
-                                                       Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
+                                               if (!stristr($item_tag["tag"], trim($xo->content))) {
+                                                       $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
+                                                       Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
                                                }
                                        }
                                }
@@ -2406,8 +2382,11 @@ class DFRN
                                                break;
                                        case "enclosure":
                                                $enclosure = $href;
-                                               if (strlen($item["attach"])) {
+
+                                               if (!empty($item["attach"])) {
                                                        $item["attach"] .= ",";
+                                               } else {
+                                                       $item["attach"] = "";
                                                }
 
                                                $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
@@ -2430,58 +2409,63 @@ class DFRN
         */
        private static function processEntry($header, $xpath, $entry, $importer, $xml)
        {
-               logger("Processing entries");
+               Logger::log("Processing entries");
 
                $item = $header;
 
-               $item["protocol"] = PROTOCOL_DFRN;
+               $item["protocol"] = Conversation::PARCEL_DFRN;
 
                $item["source"] = $xml;
 
                // Get the uri
-               $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
+               $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
 
-               $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
+               $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
 
-               $current = dba::selectFirst('item',
-                       ['id', 'uid', 'edited', 'body'],
+               $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
                        ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
                );
                // Is there an existing item?
-               if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
-                       logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
+               if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
+                       Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
                        return;
                }
 
                // Fetch the owner
-               $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
+               $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true, $xml);
+
+               $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
 
+               $item["owner-name"] = $owner["name"];
                $item["owner-link"] = $owner["link"];
+               $item["owner-avatar"] = $owner["avatar"];
                $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
 
                // fetch the author
-               $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
+               $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true, $xml);
 
+               $item["author-name"] = $author["name"];
                $item["author-link"] = $author["link"];
+               $item["author-avatar"] = $author["avatar"];
                $item["author-id"] = Contact::getIdForURL($author["link"], 0);
 
-               $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
+               $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
 
-               $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
+               $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
 
-               $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
+               $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']);
 
@@ -2502,19 +2486,16 @@ class DFRN
                // We don't need the content element since "dfrn:env" is always present
                //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
 
-               $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
+               $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
 
-               $georsspoint = $xpath->query("georss:point", $entry);
-               if ($georsspoint) {
-                       $item["coord"] = $georsspoint->item(0)->nodeValue;
-               }
+               $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
 
-               $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
+               $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
 
-               $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
+               $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
 
-               if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
-                       $item["bookmark"] = true;
+               if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
+                       $item["post-type"] = Item::PT_PAGE;
                }
 
                $notice_info = $xpath->query("statusnet:notice_info", $entry);
@@ -2526,18 +2507,18 @@ class DFRN
                        }
                }
 
-               $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
+               $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($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
+               $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
                if ($dsprsig != "") {
                        $item["dsprsig"] = $dsprsig;
                }
 
-               $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
+               $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
 
-               if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
-                       $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
+               if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
+                       $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
                }
 
                $object = $xpath->query("activity:object", $entry)->item(0);
@@ -2574,8 +2555,10 @@ class DFRN
                                                $termhash = array_shift($parts);
                                                $termurl = implode(":", $parts);
 
-                                               if (strlen($item["tag"])) {
+                                               if (!empty($item["tag"])) {
                                                        $item["tag"] .= ",";
+                                               } else {
+                                                       $item["tag"] = "";
                                                }
 
                                                $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
@@ -2591,7 +2574,7 @@ class DFRN
                        self::parseLinks($links, $item);
                }
 
-               $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
+               $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
 
                $conv = $xpath->query('ostatus:conversation', $entry);
                if (is_object($conv->item(0))) {
@@ -2644,7 +2627,6 @@ class DFRN
                }
 
                if ($entrytype == DFRN::REPLY_RC) {
-                       $item["type"] = "remote-comment";
                        $item["wall"] = 1;
                } elseif ($entrytype == DFRN::TOP_LEVEL) {
                        if (!isset($item["object-type"])) {
@@ -2652,45 +2634,50 @@ class DFRN
                        }
 
                        // Is it an event?
-                       if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
-                               logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
+                       if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
+                               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"];
                                        $ev["edited"]  = $item["edited"];
                                        $ev["private"] = $item["private"];
                                        $ev["guid"]    = $item["guid"];
+                                       $ev["plink"]   = $item["plink"];
 
-                                       $r = q(
-                                               "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
-                                               dbesc($item["uri"]),
-                                               intval($importer["importer_uid"])
-                                       );
-                                       if (DBM::is_result($r)) {
-                                               $ev["id"] = $r[0]["id"];
+                                       $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
+                                       $event = DBA::selectFirst('event', ['id'], $condition);
+                                       if (DBA::isResult($event)) {
+                                               $ev["id"] = $event["id"];
                                        }
 
                                        $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::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
                        return;
                }
 
+
                // Update content if 'updated' changes
-               if (DBM::is_result($current)) {
+               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;
                }
@@ -2700,7 +2687,7 @@ class DFRN
                        $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);
@@ -2710,23 +2697,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_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
-                               logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
+                       if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
+                               Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
                                return;
                        }
 
@@ -2740,7 +2727,7 @@ 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);
@@ -2763,7 +2750,7 @@ class DFRN
         */
        private static function processDeletion($xpath, $deletion, $importer)
        {
-               logger("Processing deletions");
+               Logger::log("Processing deletions");
                $uri = null;
 
                foreach ($deletion->attributes as $attributes) {
@@ -2776,24 +2763,29 @@ class DFRN
                        return false;
                }
 
-               $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
-               $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
-               if (!DBM::is_result($item)) {
-                       logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
+               $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
+               $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
+               if (!DBA::isResult($item)) {
+                       Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
+                       return;
+               }
+
+               if (strstr($item['file'], '[')) {
+                       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;
                }
 
                // Comments can be deleted by the thread owner or comment owner
                if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
                        $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
-                       if (!dba::exists('item', $condition)) {
-                               logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
+                       if (!Item::exists($condition)) {
+                               Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
                                return;
                        }
                }
@@ -2802,7 +2794,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']]);
        }
@@ -2839,8 +2831,7 @@ class DFRN
 
                $header = [];
                $header["uid"] = $importer["importer_uid"];
-               $header["network"] = NETWORK_DFRN;
-               $header["type"] = "remote";
+               $header["network"] = Protocol::DFRN;
                $header["wall"] = 0;
                $header["origin"] = 0;
                $header["contact-id"] = $importer["id"];
@@ -2857,26 +2848,26 @@ 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($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
+               $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) {
-                       $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
+                       $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"]]);
                        }
                        // A forum contact can either have set "forum" or "prv" - but not both
-                       if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
+                       if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
                                $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
-                               dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
+                               DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
                        }
                } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
                        $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
-                       dba::update('contact', ['forum' => $forum], $condition);
+                       DBA::update('contact', ['forum' => $forum], $condition);
                }
 
 
@@ -2912,7 +2903,7 @@ class DFRN
                        $newentries = [];
                        $entries = $xpath->query("/atom:feed/atom:entry");
                        foreach ($entries as $entry) {
-                               $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
+                               $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
                                $newentries[strtotime($created)] = $entry;
                        }
 
@@ -2923,7 +2914,7 @@ 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;
        }
 
@@ -2934,7 +2925,7 @@ class DFRN
        public static function autoRedir(App $a, $contact_nick)
        {
                // prevent looping
-               if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
+               if (!empty($_REQUEST['redir'])) {
                        return;
                }
 
@@ -2957,28 +2948,28 @@ 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)
                                        AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
-                               dbesc($contact_nick),
-                               dbesc($a->user['nickname']),
-                               dbesc($baseurl),
-                               dbesc($nurl)
+                               DBA::escape($contact_nick),
+                               DBA::escape($a->user['nickname']),
+                               DBA::escape($baseurl),
+                               DBA::escape($nurl)
                        );
-                       if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
+                       if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
                                return;
                        }
 
                        $r = q("SELECT * FROM contact WHERE nick = '%s'
                                        AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
-                               dbesc($contact_nick),
-                               dbesc(NETWORK_DFRN),
+                               DBA::escape($contact_nick),
+                               DBA::escape(Protocol::DFRN),
                                intval(local_user()),
-                               dbesc($baseurl)
+                               DBA::escape($baseurl)
                        );
-                       if (! DBM::is_result($r)) {
+                       if (! DBA::isResult($r)) {
                                return;
                        }
 
@@ -3002,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]);
+                       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);
                }
 
@@ -3042,30 +3033,28 @@ class DFRN
                        return false;
                }
 
-               $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
-                       intval($uid)
-               );
-               if (!DBM::is_result($u)) {
+               $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
+               if (!DBA::isResult($user)) {
                        return false;
                }
 
-               $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
-               $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
+               $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
+               $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
 
-               $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['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/' . $u[0]['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]);
                                }
                        }
                }
@@ -3088,10 +3077,10 @@ class DFRN
         */
        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;
                }