]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/DFRN.php
There is no LOGGER_WARNING (triggering E_NOTICE about absent constant). Either (...
[friendica.git] / src / Protocol / DFRN.php
index 592444e3ca513e0be25eff044b2c601aec91e27b..92faba526e24d8f41c4b36c5fe0024434b98c575 100644 (file)
@@ -8,6 +8,8 @@
  */
 namespace Friendica\Protocol;
 
+use DOMDocument;
+use DOMXPath;
 use Friendica\App;
 use Friendica\Content\OEmbed;
 use Friendica\Content\Text\BBCode;
@@ -16,7 +18,7 @@ use Friendica\Core\Addon;
 use Friendica\Core\Config;
 use Friendica\Core\L10n;
 use Friendica\Core\System;
-use Friendica\Core\Worker;
+use Friendica\Database\DBA;
 use Friendica\Database\DBM;
 use Friendica\Model\Contact;
 use Friendica\Model\Event;
@@ -26,15 +28,10 @@ use Friendica\Model\Item;
 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\XML;
-use Friendica\Protocol\Diaspora;
-use dba;
-use DOMDocument;
-use DOMXPath;
 use HTMLPurifier;
 use HTMLPurifier_Config;
 
@@ -50,9 +47,9 @@ require_once "include/text.php";
 class DFRN
 {
 
-       const DFRN_TOP_LEVEL = 0;       // Top level posting
-       const DFRN_REPLY = 1;           // Regular reply that is stored locally
-       const DFRN_REPLY_RC = 2;        // Reply that will be relayed
+       const TOP_LEVEL = 0;    // Top level posting
+       const REPLY = 1;                // Regular reply that is stored locally
+       const REPLY_RC = 2;     // Reply that will be relayed
 
        /**
         * @brief Generates the atom entries for delivery.php
@@ -77,6 +74,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);
                }
@@ -132,7 +134,7 @@ class DFRN
                );
 
                if (! DBM::is_result($r)) {
-                       logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
+                       logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_NORMAL);
                        killme();
                }
 
@@ -168,7 +170,7 @@ class DFRN
                        );
 
                        if (! DBM::is_result($r)) {
-                               logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
+                               logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_NORMAL);
                                killme();
                        }
 
@@ -228,17 +230,10 @@ class DFRN
                $check_date = DateTimeFormat::utc($last_update);
 
                $r = q(
-                       "SELECT `item`.*, `item`.`id` AS `item_id`,
-                       `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
-                       `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
-                       `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-                       `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
+                       "SELECT `item`.`id`
                        FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
                        STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
-                       AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-                       LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
-                       WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
-                       AND `item`.`wall` AND `item`.`changed` > '%s'
+                       WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
                        $sql_extra
                        ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
                        intval($owner_id),
@@ -246,13 +241,23 @@ class DFRN
                        dbesc($sort)
                );
 
+               $ids = [];
+               foreach ($r as $item) {
+                       $ids[] = $item['id'];
+               }
+
+               if (!empty($ids)) {
+                       $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
+                       $items = Item::inArray($ret);
+               } else {
+                       $items = [];
+               }
+
                /*
                 * Will check further below if this actually returned results.
                 * We will provide an empty feed if that is the case.
                 */
 
-               $items = $r;
-
                $doc = new DOMDocument('1.0', 'utf-8');
                $doc->formatOutput = true;
 
@@ -321,33 +326,18 @@ class DFRN
        public static function itemFeed($item_id, $conversation = false)
        {
                if ($conversation) {
-                       $condition = '`item`.`parent`';
+                       $condition = ['parent' => $item_id];
                } else {
-                       $condition = '`item`.`id`';
+                       $condition = ['id' => $item_id];
                }
 
-               $r = q(
-                       "SELECT `item`.*, `item`.`id` AS `item_id`,
-                       `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
-                       `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
-                       `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
-                       `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
-                       FROM `item`
-                       STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
-                               AND (NOT `contact`.`blocked` OR `contact`.`pending`)
-                       LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
-                       WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
-                       AND NOT `item`.`private`",
-                       $condition,
-                       intval($item_id)
-               );
-
-               if (!DBM::is_result($r)) {
+               $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
+               $items = Item::inArray($ret);
+               if (!DBM::is_result($items)) {
                        killme();
                }
 
-               $items = $r;
-               $item = $r[0];
+               $item = $items[0];
 
                if ($item['uid'] != 0) {
                        $owner = User::getOwnerDataById($item['uid']);
@@ -892,7 +882,7 @@ class DFRN
         * @return object XML entry object
         * @todo Find proper type-hints
         */
-       private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
+       private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
        {
                $mentioned = [];
 
@@ -950,10 +940,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);
                }
 
@@ -962,13 +952,13 @@ class DFRN
                $conversation_uri = $conversation_href;
 
                if (isset($parent_item)) {
-                       $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
-                       if (DBM::is_result($r)) {
-                               if ($r['conversation-uri'] != '') {
-                                       $conversation_uri = $r['conversation-uri'];
+                       $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
+                       if (DBM::is_result($conversation)) {
+                               if ($conversation['conversation-uri'] != '') {
+                                       $conversation_uri = $conversation['conversation-uri'];
                                }
-                               if ($r['conversation-href'] != '') {
-                                       $conversation_href = $r['conversation-href'];
+                               if ($conversation['conversation-href'] != '') {
+                                       $conversation_href = $conversation['conversation-href'];
                                }
                        }
                }
@@ -1024,7 +1014,7 @@ class DFRN
                        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");
                }
 
@@ -1199,7 +1189,7 @@ class DFRN
 
                $ret = Network::curl($url);
 
-               if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
+               if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
                        Contact::markForArchival($contact);
                        return -2; // timed out
                }
@@ -1411,7 +1401,7 @@ class DFRN
                        if (empty($contact['addr'])) {
                                logger('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'];
                                }
 
@@ -1546,16 +1536,14 @@ 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;
-
-               $contact_old = dba::fetch_first("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `avatar`, `name-date`, `uri-date`, `addr`,
-                               `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
-                               FROM `contact` WHERE `uid` = ? AND `nurl` = ? AND `network` != ?",
-                       $importer["importer_uid"],
-                       normalise_link($author["link"]),
-                       NETWORK_STATUSNET
-               );
+               $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);
 
                if (DBM::is_result($contact_old)) {
                        $author["contact-id"] = $contact_old["id"];
@@ -1565,6 +1553,7 @@ class DFRN
                                logger("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;
@@ -1620,33 +1609,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;
                        }
@@ -1659,7 +1648,7 @@ 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);
 
@@ -1681,7 +1670,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);
@@ -1690,7 +1679,7 @@ 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"])) {
                                $bdyear = date("Y");
@@ -1866,7 +1855,7 @@ class DFRN
                $msg["seen"] = 0;
                $msg["replied"] = 0;
 
-               dba::insert('mail', $msg);
+               DBA::insert('mail', $msg);
 
                // send notifications.
                /// @TODO Arange this mess
@@ -1986,7 +1975,7 @@ class DFRN
                 * link an introduction to it.
                 */
                if (!DBM::is_result($r)) {
-                       // database record did not get created. Quietly give up.
+                       // Database record did not get created. Quietly give up.
                        killme();
                }
 
@@ -2066,7 +2055,7 @@ 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"])
                );
@@ -2085,7 +2074,7 @@ class DFRN
                        'url' => $relocate["url"], 'nurl' => normalise_link($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' => normalise_link($old["url"])]);
 
                // Update the contact table. We try to find every entry.
                $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
@@ -2095,20 +2084,12 @@ class DFRN
                        'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
                $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($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.');
-
                /// @TODO
                /// merge with current record, current contents have priority
                /// update record, set url-updated
@@ -2145,10 +2126,6 @@ class DFRN
                        Item::update($fields, $condition);
 
                        $changed = true;
-
-                       if ($entrytype == DFRN_REPLY_RC) {
-                               Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
-                       }
                }
                return $changed;
        }
@@ -2180,13 +2157,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 (DBM::is_result($parent)) {
                                $r = q(
                                        "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
                                        INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
@@ -2194,9 +2166,9 @@ 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"]),
+                                       dbesc($parent["parent-uri"]),
+                                       dbesc($parent["parent-uri"]),
+                                       dbesc($parent["parent-uri"]),
                                        intval($importer["importer_uid"])
                                );
                                if (DBM::is_result($r)) {
@@ -2216,12 +2188,12 @@ class DFRN
                        }
 
                        if ($is_a_remote_action) {
-                               return DFRN_REPLY_RC;
+                               return DFRN::REPLY_RC;
                        } else {
-                               return DFRN_REPLY;
+                               return DFRN::REPLY;
                        }
                } else {
-                       return DFRN_TOP_LEVEL;
+                       return DFRN::TOP_LEVEL;
                }
        }
 
@@ -2256,6 +2228,8 @@ class DFRN
                        }
 
                        if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
+                               $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
+
                                // send a notification
                                notification(
                                        [
@@ -2267,10 +2241,9 @@ class DFRN
                                        "uid"          => $importer["importer_uid"],
                                        "item"         => $item,
                                        "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
-                                       "source_name"  => stripslashes($item["author-name"]),
-                                       "source_link"  => $item["author-link"],
-                                       "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
-                                               ? $importer["thumb"] : $item["author-avatar"]),
+                                       "source_name"  => $author["name"],
+                                       "source_link"  => $author["url"],
+                                       "source_photo" => $author["thumb"],
                                        "verb"         => $item["verb"],
                                        "otype"        => "person",
                                        "activity"     => $verb,
@@ -2295,7 +2268,7 @@ class DFRN
        {
                logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
 
-               if (($entrytype == DFRN_TOP_LEVEL)) {
+               if (($entrytype == DFRN::TOP_LEVEL)) {
                        // The filling of the the "contact" variable is done for legcy reasons
                        // The functions below are partly used by ostatus.php as well - where we have this variable
                        $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
@@ -2332,29 +2305,18 @@ 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-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
-                                       intval($item["uid"]),
-                                       dbesc($item["author-link"]),
-                                       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-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
-                                       intval($item["uid"]),
-                                       dbesc($item["author-link"]),
-                                       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;
                                }
                        } else {
@@ -2366,22 +2328,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"])
-                                       );
+                                       $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
 
-                                       if (!DBM::is_result($r)) {
+                                       if (!DBM::is_result($item_tag)) {
                                                logger("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"]]);
                                                }
                                        }
                                }
@@ -2455,12 +2413,11 @@ class 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?
@@ -2472,22 +2429,22 @@ class DFRN
                // Fetch the owner
                $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
 
-               $item["owner-name"] = $owner["name"];
+               $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
+
                $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);
 
-               $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"]));
@@ -2520,19 +2477,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);
@@ -2544,18 +2498,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 = unxmlify(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);
@@ -2592,8 +2546,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]";
@@ -2609,7 +2565,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))) {
@@ -2639,7 +2595,7 @@ class DFRN
                $entrytype = self::getEntryType($importer, $item);
 
                // Now assign the rest of the values that depend on the type of the message
-               if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
+               if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
                        if (!isset($item["object-type"])) {
                                $item["object-type"] = ACTIVITY_OBJ_COMMENT;
                        }
@@ -2661,16 +2617,15 @@ class DFRN
                        }
                }
 
-               if ($entrytype == DFRN_REPLY_RC) {
-                       $item["type"] = "remote-comment";
+               if ($entrytype == DFRN::REPLY_RC) {
                        $item["wall"] = 1;
-               } elseif ($entrytype == DFRN_TOP_LEVEL) {
+               } elseif ($entrytype == DFRN::TOP_LEVEL) {
                        if (!isset($item["object-type"])) {
                                $item["object-type"] = ACTIVITY_OBJ_NOTE;
                        }
 
                        // Is it an event?
-                       if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
+                       if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
                                logger("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")) {
@@ -2703,6 +2658,13 @@ class DFRN
                        return;
                }
 
+               // This check is done here to be able to receive connection requests in "processVerbs"
+               if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
+                       logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
+                       return;
+               }
+
+
                // Update content if 'updated' changes
                if (DBM::is_result($current)) {
                        if (self::updateContent($current, $item, $importer, $entrytype)) {
@@ -2713,7 +2675,7 @@ class DFRN
                        return;
                }
 
-               if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
+               if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
                        $posted_id = Item::insert($item);
                        $parent = 0;
 
@@ -2724,26 +2686,9 @@ class DFRN
                                        Item::distribute($posted_id);
                                }
 
-                               $item["id"] = $posted_id;
-
-                               $r = q(
-                                       "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
-                                       intval($posted_id),
-                                       intval($importer["importer_uid"])
-                               );
-                               if (DBM::is_result($r)) {
-                                       $parent = $r[0]["parent"];
-                                       $parent_uri = $r[0]["parent-uri"];
-                               }
-
-                               if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
-                                       logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
-                                       Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
-                               }
-
                                return true;
                        }
-               } else { // $entrytype == DFRN_TOP_LEVEL
+               } 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);
                                return;
@@ -2756,9 +2701,8 @@ class DFRN
                                 * 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);
-                               $item["owner-name"]   = $importer["senderName"];
-                               $item["owner-link"]   = $importer["url"];
-                               $item["owner-avatar"] = $importer["thumb"];
+                               $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))) {
@@ -2812,13 +2756,18 @@ 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);
+               $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
+               $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
                if (!DBM::is_result($item)) {
                        logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
                        return;
                }
 
+               if (strstr($item['file'], '[')) {
+                       logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
+                       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);
@@ -2828,29 +2777,19 @@ class DFRN
                // 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)) {
+                       if (!Item::exists($condition)) {
                                logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
                                return;
                        }
                }
 
-               $entrytype = self::getEntryType($importer, $item);
-
-               if (!$item["deleted"]) {
-                       logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
-               } else {
+               if ($item["deleted"]) {
                        return;
                }
 
-               Item::deleteById($item["id"]);
+               logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
 
-               if ($entrytype != DFRN_TOP_LEVEL) {
-                       // if this is a relayed delete, propagate it to other recipients
-                       if ($entrytype == DFRN_REPLY_RC) {
-                               logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
-                               Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
-                       }
-               }
+               Item::delete(['id' => $item['id']]);
        }
 
        /**
@@ -2886,7 +2825,6 @@ class DFRN
                $header = [];
                $header["uid"] = $importer["importer_uid"];
                $header["network"] = NETWORK_DFRN;
-               $header["type"] = "remote";
                $header["wall"] = 0;
                $header["origin"] = 0;
                $header["contact-id"] = $importer["id"];
@@ -2906,23 +2844,23 @@ class DFRN
                logger("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"]))) {
                                $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);
                }
 
 
@@ -2958,7 +2896,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;
                        }
 
@@ -3050,7 +2988,7 @@ class DFRN
 
                        $sec = random_string();
 
-                       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();