]> git.mxchange.org Git - friendica.git/blobdiff - include/dfrn.php
Merge pull request #3797 from rabuzarus/20171015_-_duplicate_event
[friendica.git] / include / dfrn.php
index 555fa57f213c1165c8af60202741df40eb3765a6..55c51cb0118a69fd482b2f61c13a9046656647c0 100644 (file)
@@ -7,6 +7,9 @@
  * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
  */
 
+use Friendica\App;
+use Friendica\Core\System;
+
 require_once("include/Contact.php");
 require_once("include/ostatus.php");
 require_once("include/enotify.php");
@@ -243,7 +246,7 @@ class dfrn {
                /// @TODO This hook can't work anymore
                //      call_hooks('atom_feed', $atom);
 
-               if (!dbm::is_result($items) OR $onlyheader) {
+               if (!dbm::is_result($items) || $onlyheader) {
                        $atom = trim($doc->saveXML());
 
                        call_hooks('atom_feed_end', $atom);
@@ -282,6 +285,87 @@ class dfrn {
                return $atom;
        }
 
+       /**
+        * @brief Generate an atom entry for a given item id
+        *
+        * @param int $item_id The item id
+        * @param boolean $conversation Show the conversation. If false show the single post.
+        *
+        * @return string DFRN feed entry
+        */
+       public static function itemFeed($item_id, $conversation = false) {
+               if ($conversation) {
+                       $condition = '`item`.`parent`';
+               } else {
+                       $condition = '`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)) {
+                       killme();
+               }
+
+               $items = $r;
+               $item = $r[0];
+
+               $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
+                       FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
+                       WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
+                       intval($item['uid'])
+               );
+
+               if (!dbm::is_result($r)) {
+                       killme();
+               }
+
+               $owner = $r[0];
+
+               $doc = new DOMDocument('1.0', 'utf-8');
+               $doc->formatOutput = true;
+               $type = 'html';
+
+               if ($conversation) {
+                       $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
+                       $doc->appendChild($root);
+
+                       $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
+                       $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
+                       $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
+                       $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
+                       $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
+                       $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
+                       $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
+                       $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
+                       $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
+
+                       //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
+
+                       foreach ($items as $item) {
+                               $entry = self::entry($doc, $type, $item, $owner, true, 0);
+                               $root->appendChild($entry);
+                       }
+               } else {
+                       $root = self::entry($doc, $type, $item, $owner, true, 0, true);
+               }
+
+               $atom = trim($doc->saveXML());
+               return $atom;
+       }
+
        /**
         * @brief Create XML text for DFRN mails
         *
@@ -370,7 +454,7 @@ class dfrn {
                $ext = Photo::supportedTypes();
 
                foreach ($rp as $p) {
-                       $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
+                       $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
                }
 
                unset($rp, $ext);
@@ -431,7 +515,7 @@ class dfrn {
                $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
                $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
 
-               xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
+               xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
                xml::add_element($doc, $root, "title", $owner["name"]);
 
                $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
@@ -446,15 +530,15 @@ class dfrn {
 
                if ($public) {
                        // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
-                       ostatus::hublinks($doc, $root);
+                       ostatus::hublinks($doc, $root, $owner["nick"]);
 
-                       $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
+                       $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
                        xml::add_element($doc, $root, "link", "", $attributes);
 
-                       $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
+                       $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
                        xml::add_element($doc, $root, "link", "", $attributes);
 
-                       $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
+                       $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
                        xml::add_element($doc, $root, "link", "", $attributes);
                }
 
@@ -506,18 +590,18 @@ class dfrn {
 
                $attributes = array();
 
-               if (!$public OR !$hidewall) {
+               if (!$public || !$hidewall) {
                        $attributes = array("dfrn:updated" => $namdate);
                }
 
                xml::add_element($doc, $author, "name", $owner["name"], $attributes);
-               xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
+               xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
                xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
 
                $attributes = array("rel" => "photo", "type" => "image/jpeg",
                                        "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
 
-               if (!$public OR !$hidewall) {
+               if (!$public || !$hidewall) {
                        $attributes["dfrn:updated"] = $picdate;
                }
 
@@ -554,8 +638,9 @@ class dfrn {
                        xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
                        xml::add_element($doc, $author, "poco:updated", $namdate);
 
-                       if (trim($profile["dob"]) != "0000-00-00")
+                       if (trim($profile["dob"]) > '0001-01-01') {
                                xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
+                       }
 
                        xml::add_element($doc, $author, "poco:note", $profile["about"]);
                        xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
@@ -763,11 +848,12 @@ class dfrn {
         * @param array $owner Owner record
         * @param bool $comment Trigger the sending of the "comment" element
         * @param int $cid Contact ID of the recipient
+        * @param bool $single If set, the entry is created as an XML document with a single "entry" element
         *
         * @return object XML entry object
         * @todo Add type-hints
         */
-       private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
+       private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
 
                $mentioned = array();
 
@@ -780,7 +866,22 @@ class dfrn {
                        return xml::create_element($doc, "at:deleted-entry", "", $attributes);
                }
 
-               $entry = $doc->createElement("entry");
+               if (!$single) {
+                       $entry = $doc->createElement("entry");
+               } else {
+                       $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
+                       $doc->appendChild($entry);
+
+                       $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
+                       $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
+                       $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
+                       $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
+                       $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
+                       $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
+                       $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
+                       $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
+                       $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
+               }
 
                if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
                        $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
@@ -808,14 +909,36 @@ class dfrn {
                $entry->appendChild($dfrnowner);
 
                if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
-                       $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
                        $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']));
                        $attributes = array("ref" => $parent_item, "type" => "text/html",
-                                               "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
+                                               "href" => $parent[0]['plink'],
                                                "dfrn:diaspora_guid" => $parent[0]['guid']);
                        xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
                }
 
+               // Add conversation data. This is used for OStatus
+               $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
+               $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'];
+                               }
+                               if ($r['conversation-href'] != '') {
+                                       $conversation_href = $r['conversation-href'];
+                               }
+                       }
+               }
+
+               $attributes = array(
+                               "href" => $conversation_href,
+                               "ref" => $conversation_uri);
+
+               xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
+
                xml::add_element($doc, $entry, "id", $item["uri"]);
                xml::add_element($doc, $entry, "title", $item["title"]);
 
@@ -831,7 +954,7 @@ class dfrn {
 
                // We save this value in "plink". Maybe we should read it from there as well?
                xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
-                                                               "href" => app::get_baseurl()."/display/".$item["guid"]));
+                                                               "href" => System::baseUrl()."/display/".$item["guid"]));
 
                // "comment-allow" is some old fashioned stuff for old Friendica versions.
                // It is included in the rewritten code for completeness
@@ -867,7 +990,7 @@ class dfrn {
 
                // The signed text contains the content in Markdown, the sender handle and the signatur for the content
                // It is needed for relayed comments to Diaspora.
-               if($item['signed_text']) {
+               if ($item['signed_text']) {
                        $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
                        xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
                }
@@ -896,7 +1019,7 @@ class dfrn {
 
                if (count($tags)) {
                        foreach ($tags as $t) {
-                               if (($type != 'html') OR ($t[0] != "@")) {
+                               if (($type != 'html') || ($t[0] != "@")) {
                                        xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
                                }
                        }
@@ -915,7 +1038,7 @@ class dfrn {
                                intval($owner["uid"]),
                                dbesc(normalise_link($mention)));
 
-                       if (dbm::is_result($r) AND ($r[0]["forum"] OR $r[0]["prv"])) {
+                       if (dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
                                xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
                                                                                        "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
                                                                                        "href" => $mention));
@@ -931,6 +1054,30 @@ class dfrn {
                return $entry;
        }
 
+       /**
+        * @brief encrypts data via AES
+        *
+        * @param string $data The data that is to be encrypted
+        * @param string $key The AES key
+        *
+        * @return string encrypted data
+        */
+       private static function aes_encrypt($data, $key) {
+               return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
+       }
+
+       /**
+        * @brief decrypts data via AES
+        *
+        * @param string $encrypted The encrypted data
+        * @param string $key The AES key
+        *
+        * @return string decrypted data
+        */
+       public static function aes_decrypt($encrypted, $key) {
+               return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
+       }
+
        /**
         * @brief Delivers the atom content to the contacts
         *
@@ -955,14 +1102,9 @@ class dfrn {
                        $idtosend = '1:' . $orig_id;
                }
 
-               $rino = get_config('system','rino_encrypt');
+               $rino = get_config('system', 'rino_encrypt');
                $rino = intval($rino);
 
-               // use RINO1 if mcrypt isn't installed and RINO2 was selected
-               if ($rino == 2 and !function_exists('mcrypt_create_iv')) {
-                       $rino = 1;
-               }
-
                logger("Local rino version: ". $rino, LOGGER_DEBUG);
 
                $ssl_val = intval(get_config('system','ssl_policy'));
@@ -1093,8 +1235,8 @@ class dfrn {
                        switch ($rino_remote_version) {
                                case 1:
                                        // Deprecated rino version!
-                                       $key = substr(random_string(), 0, 16);
-                                       $data = aes_encrypt($postvars['data'],$key);
+                                       $key = openssl_random_pseudo_bytes(16);
+                                       $data = self::aes_encrypt($postvars['data'], $key);
                                        break;
                                case 2:
                                        // RINO 2 based on php-encryption
@@ -1129,10 +1271,9 @@ class dfrn {
 
 
                        if ($dfrn_version >= 2.1) {
-                               if (($contact['duplex'] && strlen($contact['pubkey'])) {
-                                       || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
-                                       || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
-
+                               if (($contact['duplex'] && strlen($contact['pubkey']))
+                                               || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
+                                               || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
                                        openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
                                } else {
                                        openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
@@ -1182,7 +1323,15 @@ class dfrn {
 
                $res = parse_xml_string($xml);
 
-               return $res->status;
+               if (!isset($res->status)) {
+                       return -11;
+               }
+
+               if (!empty($res->message)) {
+                       logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
+               }
+
+               return intval($res->status);
        }
 
        /**
@@ -1269,7 +1418,7 @@ class dfrn {
                        $href = "";
                        $width = 0;
                        foreach ($avatar->attributes AS $attributes) {
-                               /// @TODO Rewrite these similar if() to one switch
+                               /// @TODO Rewrite these similar if () to one switch
                                if ($attributes->name == "href") {
                                        $href = $attributes->textContent;
                                }
@@ -1280,7 +1429,7 @@ class dfrn {
                                        $contact["avatar-date"] = $attributes->textContent;
                                }
                        }
-                       if (($width > 0) AND ($href != "")) {
+                       if (($width > 0) && ($href != "")) {
                                $avatarlist[$width] = $href;
                        }
                }
@@ -1289,7 +1438,7 @@ class dfrn {
                        $author["avatar"] = current($avatarlist);
                }
 
-               if (dbm::is_result($r) AND !$onlyfetch) {
+               if (dbm::is_result($r) && !$onlyfetch) {
                        logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
 
                        $poco = array("url" => $contact["url"]);
@@ -1384,7 +1533,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;
 
-                       if (!in_array($value, array("", "0000-00-00"))) {
+                       if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
                                $bdyear = date("Y");
                                $value = str_replace("0000", $bdyear, $value);
 
@@ -1441,7 +1590,7 @@ class dfrn {
                                        dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
                                        dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
                                        dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
-                                       dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
+                                       dbesc(dbm::date($contact["name-date"])), dbesc(dbm::date($contact["uri-date"])),
                                        intval($contact["id"]), dbesc($contact["network"]));
                        }
 
@@ -1459,7 +1608,9 @@ class dfrn {
                        $poco["photo"] = $author["avatar"];
                        $poco["hide"] = $hide;
                        $poco["contact-type"] = $contact["contact-type"];
-                       update_gcontact($poco);
+                       $gcid = update_gcontact($poco);
+
+                       link_gcontact($gcid, $importer["uid"], $contact["id"]);
                }
 
                return($author);
@@ -1546,9 +1697,7 @@ class dfrn {
                $msg["seen"] = 0;
                $msg["replied"] = 0;
 
-               dbm::esc_array($msg, true);
-
-               $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES (".implode(", ", array_values($msg)).")");
+               dba::insert('mail', $msg);
 
                // send notifications.
                /// @TODO Arange this mess
@@ -1688,7 +1837,7 @@ class dfrn {
                        "to_email"     => $importer["email"],
                        "uid"          => $importer["importer_uid"],
                        "item"         => $suggest,
-                       "link"         => App::get_baseurl()."/notifications/intros",
+                       "link"         => System::baseUrl()."/notifications/intros",
                        "source_name"  => $importer["name"],
                        "source_link"  => $importer["url"],
                        "source_photo" => $importer["photo"],
@@ -1729,7 +1878,7 @@ class dfrn {
                $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
                $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
 
-               if (($relocate["avatar"] == "") AND ($relocate["photo"] != "")) {
+               if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
                        $relocate["avatar"] = $relocate["photo"];
                }
 
@@ -1743,11 +1892,7 @@ class dfrn {
                        intval($importer["importer_uid"]));
 
                if (!dbm::is_result($r)) {
-                       /*
-                        * @TODO maybe one day:
                        logger("Query failed to execute, no result returned in " . __FUNCTION__);
-                       killme();
-                       */
                        return false;
                }
 
@@ -1861,7 +2006,7 @@ class dfrn {
                                return false;
                        }
 
-                       $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
+                       $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
                                dbesc($item["title"]),
                                dbesc($item["body"]),
                                dbesc($item["tag"]),
@@ -1881,13 +2026,13 @@ class dfrn {
                }
 
                // update last-child if it changes
-               if ($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
-                       $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
+               if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
+                       $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
                                dbesc(datetime_convert()),
                                dbesc($item["parent-uri"]),
                                intval($importer["importer_uid"])
                        );
-                       $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
+                       $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
                                intval($item["last-child"]),
                                dbesc(datetime_convert()),
                                dbesc($item["uri"]),
@@ -1998,7 +2143,7 @@ class dfrn {
                                }
                        }
 
-                       if ($Blink && link_compare($Blink, App::get_baseurl() . "/profile/" . $importer["nickname"])) {
+                       if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
 
                                // send a notification
                                notification(array(
@@ -2009,7 +2154,7 @@ class dfrn {
                                        "to_email"     => $importer["email"],
                                        "uid"          => $importer["importer_uid"],
                                        "item"         => $item,
-                                       "link"         => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
+                                       "link"         => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
                                        "source_name"  => stripslashes($item["author-name"]),
                                        "source_link"  => $item["author-link"],
                                        "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
@@ -2113,11 +2258,7 @@ class dfrn {
                                        );
 
                                        if (!dbm::is_result($r)) {
-                                               /*
-                                                * @TODO maybe one day:
                                                logger("Query failed to execute, no result returned in " . __FUNCTION__);
-                                               killme();
-                                               */
                                                return false;
                                        }
 
@@ -2152,7 +2293,7 @@ class dfrn {
                $title = "";
                foreach ($links AS $link) {
                        foreach ($link->attributes AS $attributes) {
-                               /// @TODO Rewrite these repeated (same) if() statements to a switch()
+                               /// @TODO Rewrite these repeated (same) if () statements to a switch()
                                if ($attributes->name == "href") {
                                        $href = $attributes->textContent;
                                }
@@ -2169,7 +2310,7 @@ class dfrn {
                                        $title = $attributes->textContent;
                                }
                        }
-                       if (($rel != "") AND ($href != "")) {
+                       if (($rel != "") && ($href != "")) {
                                switch ($rel) {
                                        case "alternate":
                                                $item["plink"] = $href;
@@ -2196,12 +2337,16 @@ class dfrn {
         * @param array $importer Record of the importer user mixed with contact of the content
         * @todo Add type-hints
         */
-       private static function process_entry($header, $xpath, $entry, $importer) {
+       private static function process_entry($header, $xpath, $entry, $importer, $xml) {
 
                logger("Processing entries");
 
                $item = $header;
 
+               $item["protocol"] = PROTOCOL_DFRN;
+
+               $item["source"] = $xml;
+
                // Get the uri
                $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
 
@@ -2213,7 +2358,7 @@ class dfrn {
                );
 
                // Is there an existing item?
-               if (dbm::is_result($current) AND edited_timestamp_is_newer($current[0], $item) AND
+               if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
                        (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
                        logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
                        return;
@@ -2287,7 +2432,7 @@ class dfrn {
                }
 
                $notice_info = $xpath->query("statusnet:notice_info", $entry);
-               if ($notice_info AND ($notice_info->length > 0)) {
+               if ($notice_info && ($notice_info->length > 0)) {
                        foreach ($notice_info->item(0)->attributes AS $attributes) {
                                if ($attributes->name == "source") {
                                        $item["app"] = strip_tags($attributes->textContent);
@@ -2337,9 +2482,9 @@ class dfrn {
                                        }
                                }
 
-                               if (($term != "") AND ($scheme != "")) {
+                               if (($term != "") && ($scheme != "")) {
                                        $parts = explode(":", $scheme);
-                                       if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
+                                       if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
                                                $termhash = array_shift($parts);
                                                $termurl = implode(":", $parts);
 
@@ -2360,6 +2505,20 @@ class dfrn {
                        self::parse_links($links, $item);
                }
 
+               $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
+
+               $conv = $xpath->query('ostatus:conversation', $entry);
+               if (is_object($conv->item(0))) {
+                       foreach ($conv->item(0)->attributes AS $attributes) {
+                               if ($attributes->name == "ref") {
+                                       $item['conversation-uri'] = $attributes->textContent;
+                               }
+                               if ($attributes->name == "href") {
+                                       $item['conversation-href'] = $attributes->textContent;
+                               }
+                       }
+               }
+
                // Is it a reply or a top level posting?
                $item["parent-uri"] = $item["uri"];
 
@@ -2385,7 +2544,7 @@ class dfrn {
                                $item["contact-id"] = $owner["contact-id"];
                        }
 
-                       if (($item["network"] != $owner["network"]) AND ($owner["network"] != "")) {
+                       if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
                                $item["network"] = $owner["network"];
                        }
 
@@ -2393,7 +2552,7 @@ class dfrn {
                                $item["contact-id"] = $author["contact-id"];
                        }
 
-                       if (($item["network"] != $author["network"]) AND ($author["network"] != "")) {
+                       if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
                                $item["network"] = $author["network"];
                        }
 
@@ -2402,7 +2561,7 @@ class dfrn {
                        // When activated, forums don't work.
                        // And: Why should we disallow commenting by followers?
                        // the behaviour is now similar to the Diaspora part.
-                       //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
+                       //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
                        //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
                        //      return;
                        //}
@@ -2493,7 +2652,7 @@ class dfrn {
                                        );
                                }
 
-                               if ($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
+                               if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
                                        logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
                                        proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
                                }
@@ -2527,7 +2686,7 @@ class dfrn {
 
                        logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
 
-                       if(stristr($item["verb"],ACTIVITY_POKE))
+                       if (stristr($item["verb"],ACTIVITY_POKE))
                                self::do_poke($item, $importer, $posted_id);
                }
        }
@@ -2558,7 +2717,7 @@ class dfrn {
                        $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
                }
 
-               if (!$uri OR !$importer["id"]) {
+               if (!$uri || !$importer["id"]) {
                        return false;
                }
 
@@ -2633,7 +2792,7 @@ class dfrn {
                        if ($entrytype == DFRN_TOP_LEVEL) {
                                $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
                                                `body` = '', `title` = ''
-                                       WHERE `parent-uri` = '%s' AND `uid` = %d",
+                                       WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
                                                dbesc($when),
                                                dbesc(datetime_convert()),
                                                dbesc($uri),
@@ -2645,7 +2804,7 @@ class dfrn {
                        } else {
                                $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
                                                `body` = '', `title` = ''
-                                       WHERE `uri` = '%s' AND `uid` = %d",
+                                       WHERE `uri` = '%s' AND `uid` IN (0, %d)",
                                                dbesc($when),
                                                dbesc(datetime_convert()),
                                                dbesc($uri),
@@ -2654,9 +2813,9 @@ class dfrn {
                                create_tags_from_itemuri($uri, $importer["uid"]);
                                create_files_from_itemuri($uri, $importer["uid"]);
                                update_thread_uri($uri, $importer["importer_uid"]);
-                               if($item["last-child"]) {
+                               if ($item["last-child"]) {
                                        // ensure that last-child is set in case the comment that had it just got wiped.
-                                       q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
+                                       q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
                                                dbesc(datetime_convert()),
                                                dbesc($item["parent-uri"]),
                                                intval($item["uid"])
@@ -2689,19 +2848,13 @@ class dfrn {
         * @param text $xml The DFRN message
         * @param array $importer Record of the importer user mixed with contact of the content
         * @param bool $sort_by_date Is used when feeds are polled
+        * @return integer Import status
         * @todo set proper type-hints
         */
-       public static function import($xml,$importer, $sort_by_date = false) {
+       public static function import($xml, $importer, $sort_by_date = false) {
 
                if ($xml == "") {
-                       return;
-               }
-
-               if ($importer["readonly"]) {
-                       // We aren't receiving stuff from this person. But we will quietly ignore them
-                       // rather than a blatant "go away" message.
-                       logger('ignoring contact '.$importer["id"]);
-                       return;
+                       return 400;
                }
 
                $doc = new DOMDocument();
@@ -2746,11 +2899,7 @@ class dfrn {
                        $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
 
                        if ($accounttype != $importer["contact-type"]) {
-                               /// @TODO this way is the norm or putting ); at the end of the line?
-                               q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
-                                       intval($accounttype),
-                                       intval($importer["id"])
-                               );
+                               dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
                        }
                }
 
@@ -2759,10 +2908,21 @@ class dfrn {
                $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
 
                if ($forum != $importer["forum"]) {
-                       q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
-                               intval($forum), intval($forum),
-                               intval($importer["id"])
-                       );
+                       $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
+                       dba::update('contact', array('forum' => $forum), $condition);
+               }
+
+               // We are processing relocations even if we are ignoring a contact
+               $relocations = $xpath->query("/atom:feed/dfrn:relocate");
+               foreach ($relocations AS $relocation) {
+                       self::process_relocation($xpath, $relocation, $importer);
+               }
+
+               if ($importer["readonly"]) {
+                       // We aren't receiving stuff from this person. But we will quietly ignore them
+                       // rather than a blatant "go away" message.
+                       logger('ignoring contact '.$importer["id"]);
+                       return 403;
                }
 
                $mails = $xpath->query("/atom:feed/dfrn:mail");
@@ -2775,11 +2935,6 @@ class dfrn {
                        self::process_suggestion($xpath, $suggestion, $importer);
                }
 
-               $relocations = $xpath->query("/atom:feed/dfrn:relocate");
-               foreach ($relocations AS $relocation) {
-                       self::process_relocation($xpath, $relocation, $importer);
-               }
-
                $deletions = $xpath->query("/atom:feed/at:deleted-entry");
                foreach ($deletions AS $deletion) {
                        self::process_deletion($xpath, $deletion, $importer);
@@ -2788,7 +2943,7 @@ class dfrn {
                if (!$sort_by_date) {
                        $entries = $xpath->query("/atom:feed/atom:entry");
                        foreach ($entries AS $entry) {
-                               self::process_entry($header, $xpath, $entry, $importer);
+                               self::process_entry($header, $xpath, $entry, $importer, $xml);
                        }
                } else {
                        $newentries = array();
@@ -2802,9 +2957,10 @@ class dfrn {
                        ksort($newentries);
 
                        foreach ($newentries AS $entry) {
-                               self::process_entry($header, $xpath, $entry, $importer);
+                               self::process_entry($header, $xpath, $entry, $importer, $xml);
                        }
                }
                logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
+               return 200;
        }
 }