]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/Diaspora.php
Add missing default config keys
[friendica.git] / src / Protocol / Diaspora.php
index 70728a71baab94f0ec608091a3adf9b8c32222ac..282320ff6d3099d616578a524970c33e2571c99e 100644 (file)
@@ -68,6 +68,12 @@ class Diaspora
                }
 
                if (Config::get("system", "relay_directly", false)) {
+                       // We distribute our stuff based on the parent to ensure that the thread will be complete
+                       $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
+                       if (!DBM::is_result($parent)) {
+                               return;
+                       }
+
                        // Servers that want to get all content
                        $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
                        while ($server = dba::fetch($servers)) {
@@ -75,7 +81,7 @@ class Diaspora
                        }
 
                        // All tags of the current post
-                       $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $item_id];
+                       $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
                        $tags = dba::select('term', ['term'], $condition);
                        $taglist = [];
                        while ($tag = dba::fetch($tags)) {
@@ -134,55 +140,58 @@ class Diaspora
         */
        private static function getRelayContact($server_url)
        {
-               $batch = $server_url . '/receive/public';
-
                $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
 
                // Fetch the relay contact
-               $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
+               $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
                        'contact-type' => ACCOUNT_TYPE_RELAY];
                $contact = dba::selectFirst('contact', $fields, $condition);
 
-               // If there is nothing found, we check if there is some unmarked relay
-               // This code segment can be removed before the release 2018-05
-               if (!DBM::is_result($contact)) {
-                       $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
-                               'name' => 'relay', 'nick' => 'relay', 'url' => $server_url];
-                       $contact = dba::selectFirst('contact', $fields, $condition);
-
-                       if (DBM::is_result($contact)) {
-                               // Mark the relay account as a relay account
-                               $fields = ['contact-type' => ACCOUNT_TYPE_RELAY];
-                               dba::update('contact', $fields, ['id' => $contact['id']]);
-                       }
-               }
                if (DBM::is_result($contact)) {
                        if ($contact['archive'] || $contact['blocked']) {
                                return false;
                        }
                        return $contact;
                } else {
-                       $fields = ['uid' => 0, 'created' => DateTimeFormat::utcNow(),
-                               'name' => 'relay', 'nick' => 'relay',
-                               'url' => $server_url, 'nurl' => normalise_link($server_url),
-                               'batch' => $batch, 'network' => NETWORK_DIASPORA,
-                               'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
-                               'contact-type' => ACCOUNT_TYPE_RELAY,
-                               'pending' => false, 'writable' => true];
-                       dba::insert('contact', $fields);
-
-                       $fields = ['batch', 'id', 'name', 'network'];
+                       self::setRelayContact($server_url);
+
                        $contact = dba::selectFirst('contact', $fields, $condition);
                        if (DBM::is_result($contact)) {
                                return $contact;
                        }
-
                }
 
                // It should never happen that we arrive here
                return [];
        }
 
+       /**
+        * @brief Update or insert a relay contact
+        *
+        * @param string $server_url The url of the server
+        * @param array $network_fields Optional network specific fields
+        */
+       public static function setRelayContact($server_url, $network_fields = [])
+       {
+               $fields = ['created' => DateTimeFormat::utcNow(),
+                       'name' => 'relay', 'nick' => 'relay',
+                       'url' => $server_url, 'network' => NETWORK_DIASPORA,
+                       'batch' => $server_url . '/receive/public',
+                       'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
+                       'pending' => false, 'writable' => true];
+
+               $fields = array_merge($fields, $network_fields);
+
+               $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
+                       'contact-type' => ACCOUNT_TYPE_RELAY];
+
+               if (dba::exists('contact', $condition)) {
+                       unset($fields['created']);
+               }
+
+               dba::update('contact', $fields, $condition, true);
+       }
+
        /**
         * @brief Return a list of participating contacts for a thread
         *
@@ -596,9 +605,9 @@ class Diaspora
                }
 
                $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
-               $message_id = self::dispatch($importer, $msg, $fields);
+               $success = self::dispatch($importer, $msg, $fields);
 
-               return $message_id;
+               return $success;
        }
 
        /**
@@ -911,7 +920,7 @@ class Diaspora
                        // Note that Friendica contacts will return a "Diaspora person"
                        // if Diaspora connectivity is enabled on their server
                        if ($r && ($r["network"] === NETWORK_DIASPORA)) {
-                               self::addFContact($r, $update);
+                               self::updateFContact($r);
 
                                // Fetch the updated or added contact
                                $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
@@ -927,70 +936,21 @@ class Diaspora
        /**
         * @brief Updates the fcontact table
         *
-        * @param array $arr    The fcontact data
-        * @param bool  $update Update or insert?
-        *
-        * @return string The id of the fcontact entry
+        * @param array $arr The fcontact data
         */
-       private static function addFContact($arr, $update = false)
+       private static function updateFContact($arr)
        {
-               if ($update) {
-                       $r = q(
-                               "UPDATE `fcontact` SET
-                                       `name` = '%s',
-                                       `photo` = '%s',
-                                       `request` = '%s',
-                                       `nick` = '%s',
-                                       `addr` = '%s',
-                                       `guid` = '%s',
-                                       `batch` = '%s',
-                                       `notify` = '%s',
-                                       `poll` = '%s',
-                                       `confirm` = '%s',
-                                       `alias` = '%s',
-                                       `pubkey` = '%s',
-                                       `updated` = '%s'
-                               WHERE `url` = '%s' AND `network` = '%s'",
-                               dbesc($arr["name"]),
-                               dbesc($arr["photo"]),
-                               dbesc($arr["request"]),
-                               dbesc($arr["nick"]),
-                               dbesc(strtolower($arr["addr"])),
-                               dbesc($arr["guid"]),
-                               dbesc($arr["batch"]),
-                               dbesc($arr["notify"]),
-                               dbesc($arr["poll"]),
-                               dbesc($arr["confirm"]),
-                               dbesc($arr["alias"]),
-                               dbesc($arr["pubkey"]),
-                               dbesc(DateTimeFormat::utcNow()),
-                               dbesc($arr["url"]),
-                               dbesc($arr["network"])
-                       );
-               } else {
-                       $r = q(
-                               "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
-                                       `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
-                               VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
-                               dbesc($arr["url"]),
-                               dbesc($arr["name"]),
-                               dbesc($arr["photo"]),
-                               dbesc($arr["request"]),
-                               dbesc($arr["nick"]),
-                               dbesc($arr["addr"]),
-                               dbesc($arr["guid"]),
-                               dbesc($arr["batch"]),
-                               dbesc($arr["notify"]),
-                               dbesc($arr["poll"]),
-                               dbesc($arr["confirm"]),
-                               dbesc($arr["network"]),
-                               dbesc($arr["alias"]),
-                               dbesc($arr["pubkey"]),
-                               dbesc(DateTimeFormat::utcNow())
-                       );
-               }
+               $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
+                       'request' => $arr["request"], 'nick' => $arr["nick"],
+                       'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
+                       'batch' => $arr["batch"], 'notify' => $arr["notify"],
+                       'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
+                       'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
+                       'updated' => DateTimeFormat::utcNow()];
+
+               $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
 
-               return $r;
+               dba::update('fcontact', $fields, $condition, true);
        }
 
        /**
@@ -1151,7 +1111,7 @@ class Diaspora
                //}
 
                // We don't seem to like that person
-               if ($contact["blocked"] || $contact["readonly"]) {
+               if ($contact["blocked"]) {
                        // Maybe blocked, don't accept.
                        return false;
                        // We are following this person?
@@ -1210,15 +1170,10 @@ class Diaspora
         */
        private static function messageExists($uid, $guid)
        {
-               $r = q(
-                       "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
-                       intval($uid),
-                       dbesc($guid)
-               );
-
-               if (DBM::is_result($r)) {
+               $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
+               if (DBM::is_result($item)) {
                        logger("message ".$guid." already exists for user ".$uid);
-                       return $r[0]["id"];
+                       return $item["id"];
                }
 
                return false;
@@ -1394,7 +1349,7 @@ class Diaspora
                $author = "";
 
                // Fetch the author - for the old and the new Diaspora version
-               if ($source_xml->post->status_message->diaspora_handle) {
+               if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
                        $author = (string)$source_xml->post->status_message->diaspora_handle;
                } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
                        $author = (string)$source_xml->author;
@@ -1425,16 +1380,13 @@ class Diaspora
         */
        private static function parentItem($uid, $guid, $author, $contact)
        {
-               $r = q(
-                       "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
-                               `author-name`, `author-link`, `author-avatar`,
-                               `owner-name`, `owner-link`, `owner-avatar`
-                       FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
-                       intval($uid),
-                       dbesc($guid)
-               );
+               $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
+                       'author-name', 'author-link', 'author-avatar',
+                       'owner-name', 'owner-link', 'owner-avatar'];
+               $condition = ['uid' => $uid, 'guid' => $guid];
+               $item = Item::selectFirst($fields, $condition);
 
-               if (!$r) {
+               if (!DBM::is_result($item)) {
                        $result = self::storeByGuid($guid, $contact["url"], $uid);
 
                        if (!$result) {
@@ -1445,23 +1397,16 @@ class Diaspora
                        if ($result) {
                                logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
 
-                               $r = q(
-                                       "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
-                                               `author-name`, `author-link`, `author-avatar`,
-                                               `owner-name`, `owner-link`, `owner-avatar`
-                                       FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
-                                       intval($uid),
-                                       dbesc($guid)
-                               );
+                               $item = Item::selectFirst($fields, $condition);
                        }
                }
 
-               if (!$r) {
+               if (!DBM::is_result($item)) {
                        logger("parent item not found: parent: ".$guid." - user: ".$uid);
                        return false;
                } else {
                        logger("parent item found: parent: ".$guid." - user: ".$uid);
-                       return $r[0];
+                       return $item;
                }
        }
 
@@ -1598,38 +1543,6 @@ class Diaspora
 
                logger('Contacts are updated.');
 
-               // update items
-               /// @todo This is an extreme performance killer
-               $fields = [
-                       'owner-link' => [$contact["url"], $data["url"]],
-                       'author-link' => [$contact["url"], $data["url"]],
-               ];
-               foreach ($fields as $n => $f) {
-                       $r = q(
-                               "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
-                               $n,
-                               dbesc($f[0]),
-                               intval($importer["uid"])
-                       );
-
-                       if (DBM::is_result($r)) {
-                               $x = q(
-                                       "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
-                                       $n,
-                                       dbesc($f[1]),
-                                       $n,
-                                       dbesc($f[0]),
-                                       intval($importer["uid"])
-                               );
-
-                               if ($x === false) {
-                                       return false;
-                               }
-                       }
-               }
-
-               logger('Items are updated.');
-
                return true;
        }
 
@@ -1667,11 +1580,21 @@ class Diaspora
         */
        private static function getUriFromGuid($author, $guid, $onlyfound = false)
        {
-               $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
-               if (DBM::is_result($r)) {
-                       return $r[0]["uri"];
+               $item = Item::selectFirst(['uri'], ['guid' => $guid]);
+               if (DBM::is_result($item)) {
+                       return $item["uri"];
                } elseif (!$onlyfound) {
-                       return $author.":".$guid;
+                       $contact = Contact::getDetailsByAddr($author, 0);
+                       if (!empty($contact['network'])) {
+                               $prefix = 'urn:X-' . $contact['network'] . ':';
+                       } else {
+                               // This fallback should happen most unlikely
+                               $prefix = 'urn:X-dspr:';
+                       }
+
+                       $author_parts = explode('@', $author);
+
+                       return $prefix . $author_parts[1] . ':' . $author_parts[0] . ':'. $guid;
                }
 
                return "";
@@ -1687,9 +1610,9 @@ class Diaspora
         */
        private static function getGuidFromUri($uri, $uid)
        {
-               $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
-               if (DBM::is_result($r)) {
-                       return $r[0]["guid"];
+               $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
+               if (DBM::is_result($item)) {
+                       return $item["guid"];
                } else {
                        return false;
                }
@@ -1704,11 +1627,10 @@ class Diaspora
         */
        private static function importerForGuid($guid)
        {
-               $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
-
+               $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
                if (DBM::is_result($item)) {
                        logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
-                       $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
+                       $contact = dba::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
                        if (DBM::is_result($contact)) {
                                return $contact;
                        }
@@ -1776,13 +1698,11 @@ class Diaspora
                $datarray["contact-id"] = $author_contact["cid"];
                $datarray["network"]  = $author_contact["network"];
 
-               $datarray["author-name"] = $person["name"];
                $datarray["author-link"] = $person["url"];
-               $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
+               $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
 
-               $datarray["owner-name"] = $contact["name"];
                $datarray["owner-link"] = $contact["url"];
-               $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
+               $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
 
                $datarray["guid"] = $guid;
                $datarray["uri"] = self::getUriFromGuid($author, $guid);
@@ -1812,6 +1732,12 @@ class Diaspora
 
                self::fetchGuid($datarray);
 
+               // If we are the origin of the parent we store the original data.
+               // We notify our followers during the item storage.
+               if ($parent_item["origin"]) {
+                       $datarray['diaspora_signed_text'] = json_encode($data);
+               }
+
                $message_id = Item::insert($datarray);
 
                if ($message_id <= 0) {
@@ -1821,20 +1747,10 @@ class Diaspora
                if ($message_id) {
                        logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
                        if ($datarray['uid'] == 0) {
-                               Item::distribute($message_id);
+                               Item::distribute($message_id, json_encode($data));
                        }
                }
 
-               // If we are the origin of the parent we store the original data and notify our followers
-               if ($message_id && $parent_item["origin"]) {
-                       // Formerly we stored the signed text, the signature and the author in different fields.
-                       // We now store the raw data so that we are more flexible.
-                       dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
-
-                       // notify others
-                       Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
-               }
-
                return true;
        }
 
@@ -2008,50 +1924,6 @@ class Diaspora
                return true;
        }
 
-       /**
-        * @brief Creates the body for a "like" message
-        *
-        * @param array  $contact     The contact that send us the "like"
-        * @param array  $parent_item The item array of the parent item
-        * @param string $guid        message guid
-        *
-        * @return string the body
-        */
-       private static function constructLikeBody($contact, $parent_item, $guid)
-       {
-               $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
-
-               $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
-               $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
-               $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
-
-               return sprintf($bodyverb, $ulink, $alink, $plink);
-       }
-
-       /**
-        * @brief Creates a XML object for a "like"
-        *
-        * @param array $importer    Array of the importer user
-        * @param array $parent_item The item array of the parent item
-        *
-        * @return string The XML
-        */
-       private static function constructLikeObject($importer, $parent_item)
-       {
-               $objtype = ACTIVITY_OBJ_NOTE;
-               $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
-               $parent_body = $parent_item["body"];
-
-               $xmldata = ["object" => ["type" => $objtype,
-                                               "local" => "1",
-                                               "id" => $parent_item["uri"],
-                                               "link" => $link,
-                                               "title" => "",
-                                               "content" => $parent_body]];
-
-               return XML::fromArray($xmldata, $xml, true);
-       }
-
        /**
         * @brief Processes "like" messages
         *
@@ -2115,26 +1987,40 @@ class Diaspora
                $datarray["contact-id"] = $author_contact["cid"];
                $datarray["network"]  = $author_contact["network"];
 
-               $datarray["author-name"] = $person["name"];
                $datarray["author-link"] = $person["url"];
-               $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
+               $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
 
-               $datarray["owner-name"] = $contact["name"];
                $datarray["owner-link"] = $contact["url"];
-               $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
+               $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
 
                $datarray["guid"] = $guid;
                $datarray["uri"] = self::getUriFromGuid($author, $guid);
 
                $datarray["type"] = "activity";
                $datarray["verb"] = $verb;
-               $datarray["gravity"] = GRAVITY_LIKE;
+               $datarray["gravity"] = GRAVITY_ACTIVITY;
                $datarray["parent-uri"] = $parent_item["uri"];
 
                $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
-               $datarray["object"] = self::constructLikeObject($importer, $parent_item);
 
-               $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
+               $datarray["body"] = $verb;
+
+               // Diaspora doesn't provide a date for likes
+               $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
+
+               // like on comments have the comment as parent. So we need to fetch the toplevel parent
+               if ($parent_item["id"] != $parent_item["parent"]) {
+                       $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
+                       $origin = $toplevel["origin"];
+               } else {
+                       $origin = $parent_item["origin"];
+               }
+
+               // If we are the origin of the parent we store the original data.
+               // We notify our followers during the item storage.
+               if ($origin) {
+                       $datarray['diaspora_signed_text'] = json_encode($data);
+               }
 
                $message_id = Item::insert($datarray);
 
@@ -2145,28 +2031,10 @@ class Diaspora
                if ($message_id) {
                        logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
                        if ($datarray['uid'] == 0) {
-                               Item::distribute($message_id);
+                               Item::distribute($message_id, json_encode($data));
                        }
                }
 
-               // like on comments have the comment as parent. So we need to fetch the toplevel parent
-               if ($parent_item["id"] != $parent_item["parent"]) {
-                       $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
-                       $origin = $toplevel["origin"];
-               } else {
-                       $origin = $parent_item["origin"];
-               }
-
-               // If we are the origin of the parent we store the original data and notify our followers
-               if ($message_id && $origin) {
-                       // Formerly we stored the signed text, the signature and the author in different fields.
-                       // We now store the raw data so that we are more flexible.
-                       dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
-
-                       // notify others
-                       Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
-               }
-
                return true;
        }
 
@@ -2279,7 +2147,7 @@ class Diaspora
                        return false;
                }
 
-               $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
+               $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
                if (!DBM::is_result($item)) {
                        logger('Item not found, no origin or private: '.$parent_guid);
                        return false;
@@ -2300,11 +2168,11 @@ class Diaspora
                }
 
                // Send all existing comments and likes to the requesting server
-               $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
-                               FROM `item`
-                               INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
-                               WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
-               while ($comment = dba::fetch($comments)) {
+               $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
+               while ($comment = Item::fetch($comments)) {
+                       if ($comment['id'] == $comment['parent']) {
+                               continue;
+                       }
                        if ($comment['verb'] == ACTIVITY_POST) {
                                $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
                        } else {
@@ -2414,21 +2282,17 @@ class Diaspora
                        $birthday = $contact["bd"];
                }
 
-               $r = q(
-                       "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
-                               `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
-                       dbesc($name),
-                       dbesc($nick),
-                       dbesc($author),
-                       dbesc(DateTimeFormat::utcNow()),
-                       dbesc($birthday),
-                       dbesc($location),
-                       dbesc($about),
-                       dbesc($keywords),
-                       dbesc($gender),
-                       intval($contact["id"]),
-                       intval($importer["uid"])
-               );
+               $fields = ['name' => $name, 'location' => $location,
+                       'name-date' => DateTimeFormat::utcNow(),
+                       'about' => $about, 'gender' => $gender,
+                       'addr' => $author, 'nick' => $nick,
+                       'keywords' => $keywords];
+
+               if (!empty($birthday)) {
+                       $fields['bd'] = $birthday;
+               }
+
+               dba::update('contact', $fields, ['id' => $contact['id']]);
 
                $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
                                        "photo" => $image_url, "name" => $name, "location" => $location,
@@ -2463,78 +2327,6 @@ class Diaspora
                                ['id' => $contact["id"], 'uid' => $importer["uid"]]
                        );
                }
-               // send notification
-
-               $r = q(
-                       "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
-                       intval($importer["uid"])
-               );
-
-               if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
-                       $self = q(
-                               "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
-                               intval($importer["uid"])
-                       );
-
-                       // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
-
-                       if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
-                               $arr = [];
-                               $arr["protocol"] = PROTOCOL_DIASPORA;
-                               $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
-                               $arr["uid"] = $importer["uid"];
-                               $arr["contact-id"] = $self[0]["id"];
-                               $arr["wall"] = 1;
-                               $arr["type"] = 'wall';
-                               $arr["gravity"] = 0;
-                               $arr["origin"] = 1;
-                               $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
-                               $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
-                               $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
-                               $arr["verb"] = ACTIVITY_FRIEND;
-                               $arr["object-type"] = ACTIVITY_OBJ_PERSON;
-
-                               $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
-                               $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
-                               $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
-                               $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
-
-                               $arr["object"] = self::constructNewFriendObject($contact);
-
-                               $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
-
-                               $arr["allow_cid"] = $user["allow_cid"];
-                               $arr["allow_gid"] = $user["allow_gid"];
-                               $arr["deny_cid"]  = $user["deny_cid"];
-                               $arr["deny_gid"]  = $user["deny_gid"];
-
-                               $i = Item::insert($arr);
-                               if ($i) {
-                                       Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
-                               }
-                       }
-               }
-       }
-
-       /**
-        * @brief Creates a XML object for a "new friend" message
-        *
-        * @param array $contact Array of the contact
-        *
-        * @return string The XML
-        */
-       private static function constructNewFriendObject($contact)
-       {
-               $objtype = ACTIVITY_OBJ_PERSON;
-               $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
-                       '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
-
-               $xmldata = ["object" => ["type" => $objtype,
-                                               "title" => $contact["name"],
-                                               "id" => $contact["url"]."/".$contact["name"],
-                                               "link" => $link]];
-
-               return XML::fromArray($xmldata, $xml, true);
        }
 
        /**
@@ -2729,11 +2521,16 @@ class Diaspora
         */
        public static function originalItem($guid, $orig_author)
        {
+               if (empty($guid)) {
+                       logger('Empty guid. Quitting.');
+                       return false;
+               }
+
                // Do we already have this item?
                $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
                        'author-name', 'author-link', 'author-avatar'];
-               $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false];
-               $item = dba::selectfirst('item', $fields, $condition);
+               $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
+               $item = Item::selectFirst($fields, $condition);
 
                if (DBM::is_result($item)) {
                        logger("reshared message ".$guid." already exists on system.");
@@ -2742,7 +2539,7 @@ class Diaspora
                        // Then refetch the content, if it is a reshare from a reshare.
                        // If it is a reshared post from another network then reformat to avoid display problems with two share elements
                        if (self::isReshare($item["body"], true)) {
-                               $r = [];
+                               $item = [];
                        } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
                                $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
 
@@ -2757,22 +2554,27 @@ class Diaspora
                        }
                }
 
-               if (!DBM::is_result($r)) {
+               if (!DBM::is_result($item)) {
+                       if (empty($orig_author)) {
+                               logger('Empty author for guid ' . $guid . '. Quitting.');
+                               return false;
+                       }
+
                        $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
                        logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
-                       $item_id = self::storeByGuid($guid, $server);
+                       $stored = self::storeByGuid($guid, $server);
 
-                       if (!$item_id) {
+                       if (!$stored) {
                                $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
-                               logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
-                               $item_id = self::storeByGuid($guid, $server);
+                               logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
+                               $stored = self::storeByGuid($guid, $server);
                        }
 
-                       if ($item_id) {
+                       if ($stored) {
                                $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
                                        'author-name', 'author-link', 'author-avatar'];
-                               $condition = ['id' => $item_id, 'visible' => true, 'deleted' => false];
-                               $item = dba::selectfirst('item', $fields, $condition);
+                               $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
+                               $item = Item::selectFirst($fields, $condition);
 
                                if (DBM::is_result($item)) {
                                        // If it is a reshared post from another network then reformat to avoid display problems with two share elements
@@ -2830,13 +2632,11 @@ class Diaspora
                $datarray["contact-id"] = $contact["id"];
                $datarray["network"]  = NETWORK_DIASPORA;
 
-               $datarray["author-name"] = $contact["name"];
                $datarray["author-link"] = $contact["url"];
-               $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
+               $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
 
-               $datarray["owner-name"] = $datarray["author-name"];
                $datarray["owner-link"] = $datarray["author-link"];
-               $datarray["owner-avatar"] = $datarray["author-avatar"];
+               $datarray["owner-id"] = $datarray["author-id"];
 
                $datarray["guid"] = $guid;
                $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
@@ -2908,23 +2708,29 @@ class Diaspora
                }
 
                // Fetch items that are about to be deleted
-               $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
+               $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
 
                // When we receive a public retraction, we delete every item that we find.
                if ($importer['uid'] == 0) {
-                       $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
+                       $condition = ['guid' => $target_guid, 'deleted' => false];
                } else {
-                       $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
+                       $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
                }
-               $r = dba::select('item', $fields, $condition);
+
+               $r = Item::select($fields, $condition);
                if (!DBM::is_result($r)) {
                        logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
                        return false;
                }
 
-               while ($item = dba::fetch($r)) {
+               while ($item = Item::fetch($r)) {
+                       if (strstr($item['file'], '[')) {
+                               logger("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
+                               continue;
+                       }
+
                        // Fetch the parent item
-                       $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
+                       $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
 
                        // Only delete it if the parent author really fits
                        if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
@@ -2932,15 +2738,9 @@ class Diaspora
                                continue;
                        }
 
-                       Item::deleteById($item["id"]);
+                       Item::delete(['id' => $item['id']]);
 
                        logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
-
-                       // Now check if the retraction needs to be relayed by us
-                       if ($parent["origin"]) {
-                               // notify others
-                               Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
-                       }
                }
 
                return true;
@@ -2975,12 +2775,10 @@ class Diaspora
                        case "StatusMessage":
                                return self::itemRetraction($importer, $contact, $data);
 
-                       case "Contact":
-                       case "Person":
-                               /// @todo What should we do with an "unshare"?
-                               // Removing the contact isn't correct since we still can read the public items
-                               Contact::remove($contact["id"]);
-                               return true;
+                       case "PollParticipation":
+                       case "Photo":
+                               // Currently unsupported
+                               break;
 
                        default:
                                logger("Unknown target type ".$target_type);
@@ -3058,13 +2856,11 @@ class Diaspora
                $datarray["contact-id"] = $contact["id"];
                $datarray["network"] = NETWORK_DIASPORA;
 
-               $datarray["author-name"] = $contact["name"];
                $datarray["author-link"] = $contact["url"];
-               $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
+               $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
 
-               $datarray["owner-name"] = $datarray["author-name"];
                $datarray["owner-link"] = $datarray["author-link"];
-               $datarray["owner-avatar"] = $datarray["author-avatar"];
+               $datarray["owner-id"] = $datarray["author-id"];
 
                $datarray["guid"] = $guid;
                $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
@@ -3427,7 +3223,7 @@ class Diaspora
                $author = self::myHandle($owner);
 
                $message = ["author" => $author,
-                               "guid" => get_guid(32),
+                               "guid" => System::createGUID(32),
                                "parent_type" => "Post",
                                "parent_guid" => $item["guid"]];
 
@@ -3559,34 +3355,42 @@ class Diaspora
 
                $guid = "";
                preg_match("/guid='(.*?)'/ism", $attributes, $matches);
-               if ($matches[1] != "") {
+               if (!empty($matches[1])) {
                        $guid = $matches[1];
                }
 
                preg_match('/guid="(.*?)"/ism', $attributes, $matches);
-               if ($matches[1] != "") {
+               if (!empty($matches[1])) {
                        $guid = $matches[1];
                }
 
                if (($guid != "") && $complete) {
                        $condition = ['guid' => $guid, 'network' => [NETWORK_DFRN, NETWORK_DIASPORA]];
-                       $item = dba::selectFirst('item', ['contact-id'], $condition);
+                       $item = Item::selectFirst(['contact-id'], $condition);
                        if (DBM::is_result($item)) {
                                $ret= [];
                                $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
                                $ret["root_guid"] = $guid;
                                return $ret;
+                       } elseif ($complete) {
+                               // We are resharing something that isn't a DFRN or Diaspora post.
+                               // So we have to return "false" on "$complete" to not trigger a reshare.
+                               return false;
                        }
+               } elseif (($guid == "") && $complete) {
+                       return false;
                }
 
+               $ret["root_guid"] = $guid;
+
                $profile = "";
                preg_match("/profile='(.*?)'/ism", $attributes, $matches);
-               if ($matches[1] != "") {
+               if (!empty($matches[1])) {
                        $profile = $matches[1];
                }
 
                preg_match('/profile="(.*?)"/ism', $attributes, $matches);
-               if ($matches[1] != "") {
+               if (!empty($matches[1])) {
                        $profile = $matches[1];
                }
 
@@ -3599,10 +3403,6 @@ class Diaspora
                        }
                }
 
-               if (!empty($guid)) {
-                       $ret["root_guid"] = $guid;
-               }
-
                if (empty($ret) && !$complete) {
                        return true;
                }
@@ -3833,16 +3633,11 @@ class Diaspora
         */
        private static function constructLike($item, $owner)
        {
-               $p = q(
-                       "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
-                       dbesc($item["thr-parent"])
-               );
-               if (!DBM::is_result($p)) {
+               $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
+               if (!DBM::is_result($parent)) {
                        return false;
                }
 
-               $parent = $p[0];
-
                $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
                $positive = null;
                if ($item['verb'] === ACTIVITY_LIKE) {
@@ -3869,16 +3664,11 @@ class Diaspora
         */
        private static function constructAttend($item, $owner)
        {
-               $p = q(
-                       "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
-                       dbesc($item["thr-parent"])
-               );
-               if (!DBM::is_result($p)) {
+               $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
+               if (!DBM::is_result($parent)) {
                        return false;
                }
 
-               $parent = $p[0];
-
                switch ($item['verb']) {
                        case ACTIVITY_ATTEND:
                                $attend_answer = 'accepted';
@@ -3918,18 +3708,11 @@ class Diaspora
                        return $result;
                }
 
-               $p = q(
-                       "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
-                       intval($item["parent"]),
-                       intval($item["parent"])
-               );
-
-               if (!DBM::is_result($p)) {
+               $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
+               if (!DBM::is_result($parent)) {
                        return false;
                }
 
-               $parent = $p[0];
-
                $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
                $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
 
@@ -4398,16 +4181,16 @@ class Diaspora
 
                $contact["uprvkey"] = $r[0]['prvkey'];
 
-               $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
-               if (!DBM::is_result($r)) {
+               $item = Item::selectFirst([], ['id' => $post_id]);
+               if (!DBM::is_result($item)) {
                        return false;
                }
 
-               if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
+               if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
                        return false;
                }
 
-               $message = self::constructLike($r[0], $contact);
+               $message = self::constructLike($item, $contact);
                if ($message === false) {
                        return false;
                }