]> git.mxchange.org Git - friendica.git/blobdiff - include/dfrn.php
Fetching new queue tasks in a bulk to increase speed
[friendica.git] / include / dfrn.php
index b7589d7cb7c50f0ca5f2cb6aeef79c60c06b34dd..bc62de6ed9e60333262a48917b4b5a4cb550ac87 100644 (file)
@@ -7,6 +7,8 @@
  * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
  */
 
+use Friendica\App;
+
 require_once("include/Contact.php");
 require_once("include/ostatus.php");
 require_once("include/enotify.php");
@@ -216,13 +218,10 @@ class dfrn {
                        dbesc($sort)
                );
 
-               if (!dbm::is_result($r)) {
-                       logger("Query failed to execute, no result returned in " . __FUNCTION__);
-                       killme();
-               }
-
-               // Will check further below if this actually returned results.
-               // We will provide an empty feed if that is the case.
+               /*
+                * Will check further below if this actually returned results.
+                * We will provide an empty feed if that is the case.
+                */
 
                $items = $r;
 
@@ -243,10 +242,10 @@ class dfrn {
 
                $root = self::add_header($doc, $owner, $author, $alternatelink, true);
 
-               // This hook can't work anymore
+               /// @TODO This hook can't work anymore
                //      call_hooks('atom_feed', $atom);
 
-               if (!count($items) OR $onlyheader) {
+               if (!dbm::is_result($items) || $onlyheader) {
                        $atom = trim($doc->saveXML());
 
                        call_hooks('atom_feed_end', $atom);
@@ -285,6 +284,62 @@ class dfrn {
                return $atom;
        }
 
+       /**
+        * @brief Generate an atom entry for a given item id
+        *
+        * @param int $item_id The item id
+        *
+        * @return string DFRN feed entry
+        */
+       public static function itemFeed($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 `item`.`id` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
+                       AND `item`.`wall` AND NOT `item`.`private`",
+                       intval($item_id)
+               );
+
+               if (!dbm::is_result($r)) {
+                       killme();
+               }
+
+               $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;
+
+               $alternatelink = $owner['url'];
+
+               $root = self::add_header($doc, $owner, 'dfrn:owner', $alternatelink, true);
+
+               $type = 'html';
+
+               $entry = self::entry($doc, $type, $item, $owner, true);
+               $root->appendChild($entry);
+
+               $atom = trim($doc->saveXML());
+               return $atom;
+       }
+
        /**
         * @brief Create XML text for DFRN mails
         *
@@ -373,7 +428,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']] = App::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
                }
 
                unset($rp, $ext);
@@ -434,7 +489,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", App::get_baseurl()."/profile/".$owner["nick"]);
                xml::add_element($doc, $root, "title", $owner["name"]);
 
                $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
@@ -451,13 +506,13 @@ class dfrn {
                        // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
                        ostatus::hublinks($doc, $root);
 
-                       $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
+                       $attributes = array("rel" => "salmon", "href" => App::get_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" => App::get_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" => App::get_baseurl()."/salmon/".$owner["nick"]);
                        xml::add_element($doc, $root, "link", "", $attributes);
                }
 
@@ -509,18 +564,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", App::get_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;
                }
 
@@ -557,8 +612,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"]);
@@ -689,15 +745,15 @@ class dfrn {
                        }
 
                        if ($r->link) {
-                               if (substr($r->link,0,1) == '<') {
-                                       if (strstr($r->link,'&') && (! strstr($r->link,'&amp;'))) {
-                                               $r->link = str_replace('&','&amp;', $r->link);
+                               if (substr($r->link, 0, 1) == '<') {
+                                       if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
+                                               $r->link = str_replace('&', '&amp;', $r->link);
                                        }
 
-                                       $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
+                                       $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
 
                                        // XML does need a single element as root element so we add a dummy element here
-                                       $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
+                                       $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
                                        if (is_object($data)) {
                                                foreach ($data->link AS $link) {
                                                        $attributes = array();
@@ -814,11 +870,33 @@ class dfrn {
                        $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
                        $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
                        $attributes = array("ref" => $parent_item, "type" => "text/html",
-                                               "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
+                                               "href" => App::get_baseurl().'/display/'.$parent[0]['guid'],
                                                "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 = App::get_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"]);
 
@@ -834,7 +912,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" => App::get_baseurl()."/display/".$item["guid"]));
 
                // "comment-allow" is some old fashioned stuff for old Friendica versions.
                // It is included in the rewritten code for completeness
@@ -899,7 +977,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]));
                                }
                        }
@@ -918,12 +996,7 @@ class dfrn {
                                intval($owner["uid"]),
                                dbesc(normalise_link($mention)));
 
-                       if (!dbm::is_result($r)) {
-                               /// @TODO Maybe some logging?
-                               killme();
-                       }
-
-                       if ($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));
@@ -939,6 +1012,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
         *
@@ -963,20 +1060,15 @@ 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'));
                $ssl_policy = '';
 
-               switch($ssl_val){
+               switch ($ssl_val) {
                        case SSL_POLICY_FULL:
                                $ssl_policy = 'full';
                                break;
@@ -1095,14 +1187,14 @@ class dfrn {
                }
 
 
-               if ($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
+               if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
                        logger('rino version: '. $rino_remote_version);
 
-                       switch($rino_remote_version) {
+                       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
@@ -1138,9 +1230,8 @@ class dfrn {
 
                        if ($dfrn_version >= 2.1) {
                                if (($contact['duplex'] && strlen($contact['pubkey']))
-                                       || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
-                                       || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
-
+                                               || ($owner['page-flags'] == 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 +1273,7 @@ class dfrn {
                        return 3;
                }
 
-               if ($contact['term-date'] != '0000-00-00 00:00:00') {
+               if ($contact['term-date'] > NULL_DATE) {
                        logger("dfrn_deliver: $url back from the dead - removing mark for death");
                        require_once('include/Contact.php');
                        unmark_for_death($contact);
@@ -1288,7 +1379,7 @@ class dfrn {
                                        $contact["avatar-date"] = $attributes->textContent;
                                }
                        }
-                       if (($width > 0) AND ($href != "")) {
+                       if (($width > 0) && ($href != "")) {
                                $avatarlist[$width] = $href;
                        }
                }
@@ -1297,20 +1388,20 @@ class dfrn {
                        $author["avatar"] = current($avatarlist);
                }
 
-               if (dbm::is_result($r) AND !$onlyfetch) {
-                       logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
+               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"]);
 
                        // When was the last change to name or uri?
-                       $name_element = $xpath->query($element."/atom:name", $context)->item(0);
+                       $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
                        foreach ($name_element->attributes AS $attributes) {
                                if ($attributes->name == "updated") {
                                        $poco["name-date"] = $attributes->textContent;
                                }
                        }
 
-                       $link_element = $xpath->query($element."/atom:link", $context)->item(0);
+                       $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
                        foreach ($link_element->attributes AS $attributes) {
                                if ($attributes->name == "updated") {
                                        $poco["uri-date"] = $attributes->textContent;
@@ -1318,33 +1409,33 @@ class dfrn {
                        }
 
                        // Update contact data
-                       $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
+                       $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
                        if ($value != "") {
                                $poco["addr"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
+                       $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
                        if ($value != "") {
                                $poco["name"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
+                       $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
                        if ($value != "") {
                                $poco["nick"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
+                       $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
                        if ($value != "") {
                                $poco["about"] = $value;
                        }
 
-                       $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
+                       $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
                        if ($value != "") {
                                $poco["location"] = $value;
                        }
 
                        /// @todo Only search for elements with "poco:type" = "xmpp"
-                       $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
+                       $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
                        if ($value != "") {
                                $poco["xmpp"] = $value;
                        }
@@ -1357,9 +1448,9 @@ class dfrn {
                        /// - poco:country
 
                        // If the "hide" element is present then the profile isn't searchable.
-                       $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
+                       $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
 
-                       logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
+                       logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
 
                        // If the contact isn't searchable then set the contact to "hidden".
                        // Problem: This can be manually overridden by the user.
@@ -1369,7 +1460,7 @@ class dfrn {
 
                        // Save the keywords into the contact table
                        $tags = array();
-                       $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
+                       $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
                        foreach ($tagelements AS $tag) {
                                $tags[$tag->nodeValue] = $tag->nodeValue;
                        }
@@ -1381,7 +1472,7 @@ class dfrn {
                        // "dfrn:birthday" contains the birthday converted to UTC
                        $old_bdyear = $contact["bdyear"];
 
-                       $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
+                       $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
 
                        if (strtotime($birthday) > time()) {
                                $bd_timestamp = strtotime($birthday);
@@ -1390,9 +1481,9 @@ class dfrn {
                        }
 
                        // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
-                       $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
+                       $value = $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);
 
@@ -1427,20 +1518,20 @@ class dfrn {
                        $datefields = array("name-date", "uri-date");
                        foreach ($datefields AS $field) {
                                if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
-                                       logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
+                                       logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
                                        $update = true;
                                }
                        }
 
                        foreach ($fields AS $field => $data) {
                                if ($contact[$field] != $r[0][$field]) {
-                                       logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
+                                       logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
                                        $update = true;
                                }
                        }
 
                        if ($update) {
-                               logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
+                               logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
 
                                q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
                                        `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
@@ -1449,23 +1540,27 @@ 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"]));
                        }
 
                        update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
                                                (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
 
-                       // The generation is a sign for the reliability of the provided data.
-                       // It is used in the socgraph.php to prevent that old contact data
-                       // that was relayed over several servers can overwrite contact
-                       // data that we received directly.
+                       /*
+                        * The generation is a sign for the reliability of the provided data.
+                        * It is used in the socgraph.php to prevent that old contact data
+                        * that was relayed over several servers can overwrite contact
+                        * data that we received directly.
+                        */
 
                        $poco["generation"] = 2;
                        $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);
@@ -1609,8 +1704,14 @@ class dfrn {
                        intval($suggest["uid"])
                );
 
+               /*
+                * The valid result means the friend we're about to send a friend
+                * suggestion already has them in their contact, which means no further
+                * action is required.
+                *
+                * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
+                */
                if (dbm::is_result($r)) {
-                       // Has already friend matching description
                        return false;
                }
 
@@ -1630,30 +1731,42 @@ class dfrn {
                                intval($suggest["uid"]),
                                intval($fid)
                        );
-                       /// @TODO Really abort on valid result??? Maybe missed ! here?
+
+                       /*
+                        * The valid result means the friend we're about to send a friend
+                        * suggestion already has them in their contact, which means no further
+                        * action is required.
+                        *
+                        * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
+                        */
                        if (dbm::is_result($r)) {
                                return false;
                        }
                }
-               if (!$fid)
+               if (!$fid) {
                        $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
-                       dbesc($suggest["name"]),
-                       dbesc($suggest["url"]),
-                       dbesc($suggest["photo"]),
-                       dbesc($suggest["request"])
-               );
+                               dbesc($suggest["name"]),
+                               dbesc($suggest["url"]),
+                               dbesc($suggest["photo"]),
+                               dbesc($suggest["request"])
+                       );
+               }
                $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
                        dbesc($suggest["url"]),
                        dbesc($suggest["name"]),
                        dbesc($suggest["request"])
                );
-               if (dbm::is_result($r)) {
-                       $fid = $r[0]["id"];
-               } else {
+
+               /*
+                * If no record in fcontact is found, below INSERT statement will not
+                * link an introduction to it.
+                */
+               if (!dbm::is_result($r)) {
                        // database record did not get created. Quietly give up.
                        killme();
                }
 
+               $fid = $r[0]["id"];
 
                $hash = random_string();
 
@@ -1717,7 +1830,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"];
                }
 
@@ -1731,8 +1844,8 @@ class dfrn {
                        intval($importer["importer_uid"]));
 
                if (!dbm::is_result($r)) {
-                       /// @todo Don't die quietly
-                       killme();
+                       logger("Query failed to execute, no result returned in " . __FUNCTION__);
+                       return false;
                }
 
                $old = $r[0];
@@ -1800,7 +1913,7 @@ class dfrn {
                        'author-link' => array($old["url"], $relocate["url"]),
                        //'owner-avatar' => array($old["photo"], $relocate["photo"]),
                        //'author-avatar' => array($old["photo"], $relocate["photo"]),
-                       );
+               );
                foreach ($fields as $n=>$f) {
                        $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
                                        $n, dbesc($f[0]),
@@ -1812,9 +1925,9 @@ class dfrn {
                                                $n, dbesc($f[0]),
                                                intval($importer["importer_uid"]));
 
-                               if ($x === false) {
-                                       return false;
-                               }
+                                       if ($x === false) {
+                                               return false;
+                                       }
                        }
                }
 
@@ -1833,6 +1946,7 @@ class dfrn {
         * @param array $item the new item record
         * @param array $importer Record of the importer user mixed with contact of the content
         * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
+        * @todo set proper type-hints (array?)
         */
        private static function update_content($current, $item, $importer, $entrytype) {
                $changed = false;
@@ -1840,8 +1954,9 @@ class dfrn {
                if (edited_timestamp_is_newer($current, $item)) {
 
                        // do not accept (ignore) an earlier edit than one we currently have.
-                       if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
-                               return(false);
+                       if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
+                               return false;
+                       }
 
                        $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                dbesc($item["title"]),
@@ -1863,7 +1978,7 @@ class dfrn {
                }
 
                // update last-child if it changes
-               if ($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
+               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` = %d",
                                dbesc(datetime_convert()),
                                dbesc($item["parent-uri"]),
@@ -1886,6 +2001,7 @@ class dfrn {
         * @param array $item the new item record
         *
         * @return int Is it a toplevel entry, a comment or a relayed comment?
+        * @todo set proper type-hints (array?)
         */
        private static function get_entry_type($importer, $item) {
                if ($item["parent-uri"] != $item["uri"]) {
@@ -1926,16 +2042,17 @@ class dfrn {
                                }
                        }
 
-                       // Does this have the characteristics of a community or private group action?
-                       // If it's an action to a wall post on a community/prvgroup page it's a
-                       // valid community action. Also forum_mode makes it valid for sure.
-                       // If neither, it's not.
+                       /*
+                        * Does this have the characteristics of a community or private group action?
+                        * If it's an action to a wall post on a community/prvgroup page it's a
+                        * valid community action. Also forum_mode makes it valid for sure.
+                        * If neither, it's not.
+                        */
 
-                       if ($is_a_remote_action && $community) {
-                               if ((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
-                                       $is_a_remote_action = false;
-                                       logger("not a community action");
-                               }
+                       /// @TODO Maybe merge these if() blocks into one?
+                       if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
+                               $is_a_remote_action = false;
+                               logger("not a community action");
                        }
 
                        if ($is_a_remote_action) {
@@ -1943,7 +2060,6 @@ class dfrn {
                        } else {
                                return DFRN_REPLY;
                        }
-
                } else {
                        return DFRN_TOP_LEVEL;
                }
@@ -1956,6 +2072,7 @@ class dfrn {
         * @param array $item the new item record
         * @param array $importer Record of the importer user mixed with contact of the content
         * @param int $posted_id The record number of item record that was just posted
+        * @todo set proper type-hints (array?)
         */
        private static function do_poke($item, $importer, $posted_id) {
                $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
@@ -1969,7 +2086,7 @@ class dfrn {
                        // somebody was poked/prodded. Was it me?
                        foreach ($xo->link as $l) {
                                $atts = $l->attributes();
-                               switch($atts["rel"]) {
+                               switch ($atts["rel"]) {
                                        case "alternate":
                                                $Blink = $atts["href"];
                                                break;
@@ -1978,7 +2095,7 @@ class dfrn {
                                }
                        }
 
-                       if ($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
+                       if ($Blink && link_compare($Blink, App::get_baseurl() . "/profile/" . $importer["nickname"])) {
 
                                // send a notification
                                notification(array(
@@ -2012,6 +2129,7 @@ class dfrn {
         * @param bool $is_like Is the verb a "like"?
         *
         * @return bool Should the processing of the entries be continued?
+        * @todo set proper type-hints (array?)
         */
        private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
 
@@ -2026,22 +2144,22 @@ class dfrn {
 
                        // Big question: Do we need these functions? They were part of the "consume_feed" function.
                        // This function once was responsible for DFRN and OStatus.
-                       if (activity_match($item["verb"],ACTIVITY_FOLLOW)) {
+                       if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
                                logger("New follower");
                                new_follower($importer, $contact, $item, $nickname);
                                return false;
                        }
-                       if (activity_match($item["verb"],ACTIVITY_UNFOLLOW))  {
+                       if (activity_match($item["verb"], ACTIVITY_UNFOLLOW))  {
                                logger("Lost follower");
                                lose_follower($importer, $contact, $item);
                                return false;
                        }
-                       if (activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
+                       if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
                                logger("New friend request");
                                new_follower($importer, $contact, $item, $nickname, true);
                                return false;
                        }
-                       if (activity_match($item["verb"],ACTIVITY_UNFRIEND))  {
+                       if (activity_match($item["verb"], ACTIVITY_UNFRIEND))  {
                                logger("Lost sharer");
                                lose_sharer($importer, $contact, $item);
                                return false;
@@ -2092,7 +2210,8 @@ class dfrn {
                                        );
 
                                        if (!dbm::is_result($r)) {
-                                               killme();
+                                               logger("Query failed to execute, no result returned in " . __FUNCTION__);
+                                               return false;
                                        }
 
                                        // extract tag, if not duplicate, add to parent item
@@ -2116,7 +2235,7 @@ class dfrn {
         *
         * @param object $links link elements
         * @param array $item the item record
-        * @todo Add type-hints
+        * @todo set proper type-hints
         */
        private static function parse_links($links, &$item) {
                $rel = "";
@@ -2143,8 +2262,8 @@ class dfrn {
                                        $title = $attributes->textContent;
                                }
                        }
-                       if (($rel != "") AND ($href != ""))
-                               switch($rel) {
+                       if (($rel != "") && ($href != "")) {
+                               switch ($rel) {
                                        case "alternate":
                                                $item["plink"] = $href;
                                                break;
@@ -2154,9 +2273,10 @@ class dfrn {
                                                        $item["attach"] .= ",";
                                                }
 
-                                               $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
+                                               $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
                                                break;
                                }
+                       }
                }
        }
 
@@ -2169,12 +2289,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;
 
@@ -2186,7 +2310,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;
@@ -2260,7 +2384,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);
@@ -2310,9 +2434,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);
 
@@ -2320,7 +2444,7 @@ class dfrn {
                                                        $item["tag"] .= ",";
                                                }
 
-                                               $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
+                                               $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
                                        }
                                }
                        }
@@ -2333,6 +2457,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"];
 
@@ -2358,7 +2496,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"];
                        }
 
@@ -2366,10 +2504,11 @@ 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"];
                        }
 
+                       /// @TODO maybe remove this old-lost code then?
                        // This code was taken from the old DFRN code
                        // When activated, forums don't work.
                        // And: Why should we disallow commenting by followers?
@@ -2394,6 +2533,7 @@ class dfrn {
                                $ev = bbtoevent($item["body"]);
                                if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
                                        logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
+                                       /// @TODO Mixure of "/' ahead ...
                                        $ev["cid"] = $importer["id"];
                                        $ev["uid"] = $importer["uid"];
                                        $ev["uri"] = $item["uri"];
@@ -2423,7 +2563,7 @@ class dfrn {
 
                // Update content if 'updated' changes
                if (dbm::is_result($current)) {
-                       if (self::update_content($r[0], $item, $importer, $entrytype))
+                       if (self::update_content($r[0], $item, $importer, $entrytype)) {
                                logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
                        } else {
                                logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
@@ -2464,7 +2604,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);
                                }
@@ -2473,10 +2613,12 @@ class dfrn {
                        }
                } else { // $entrytype == DFRN_TOP_LEVEL
                        if (!link_compare($item["owner-link"],$importer["url"])) {
-                               // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
-                               // but otherwise there's a possible data mixup on the sender's system.
-                               // the tgroup delivery code called from item_store will correct it if it's a forum,
-                               // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
+                               /*
+                                * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
+                                * but otherwise there's a possible data mixup on the sender's system.
+                                * the tgroup delivery code called from item_store will correct it if it's a forum,
+                                * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
+                                */
                                logger('Correcting item owner.', LOGGER_DEBUG);
                                $item["owner-name"]   = $importer["senderName"];
                                $item["owner-link"]   = $importer["url"];
@@ -2507,6 +2649,7 @@ class dfrn {
         * @param object $xpath XPath object
         * @param object $deletion deletion elements
         * @param array $importer Record of the importer user mixed with contact of the content
+        * @todo set proper type-hints
         */
        private static function process_deletion($xpath, $deletion, $importer) {
 
@@ -2526,7 +2669,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;
                }
 
@@ -2538,7 +2681,7 @@ class dfrn {
                                intval($importer["id"])
                        );
                if (!dbm::is_result($r)) {
-                       logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
+                       logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
                        return;
                } else {
 
@@ -2589,7 +2732,7 @@ class dfrn {
                                                                }
                                                        }
                                                        q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
-                                                               dbesc(implode(',',$newtags)),
+                                                               dbesc(implode(',', $newtags)),
                                                                intval($i[0]["id"])
                                                        );
                                                        create_tags_from_item($i[0]["id"]);
@@ -2644,7 +2787,7 @@ class dfrn {
                                // if this is a relayed delete, propagate it to other recipients
 
                                if ($entrytype == DFRN_REPLY_RC) {
-                                       logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
+                                       logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
                                        proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
                                }
                        }
@@ -2657,11 +2800,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
+        * @todo set proper type-hints
         */
        public static function import($xml,$importer, $sort_by_date = false) {
 
-               if ($xml == "")
+               if ($xml == "") {
                        return;
+               }
 
                if ($importer["readonly"]) {
                        // We aren't receiving stuff from this person. But we will quietly ignore them
@@ -2705,13 +2850,14 @@ class dfrn {
                        self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
                }
 
-               logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
+               logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
 
                // The account type is new since 3.5.1
                if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
                        $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $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"])
@@ -2753,7 +2899,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();
@@ -2767,10 +2913,9 @@ 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);
+               logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
        }
 }
-?>