]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/Diaspora.php
Fix: Events on Diaspora now should look fine
[friendica.git] / src / Protocol / Diaspora.php
index 540f82cc639347e3a8ac5c6254a9a05df2ea1f71..cc4b230831de489328c8d3ff6bc1b93b97726526 100644 (file)
@@ -9,31 +9,33 @@
  */
 namespace Friendica\Protocol;
 
-use Friendica\App;
-use Friendica\Core\System;
+use Friendica\Content\Text\BBCode;
 use Friendica\Core\Cache;
 use Friendica\Core\Config;
 use Friendica\Core\L10n;
 use Friendica\Core\PConfig;
+use Friendica\Core\System;
 use Friendica\Core\Worker;
 use Friendica\Database\DBM;
 use Friendica\Model\Contact;
 use Friendica\Model\GContact;
 use Friendica\Model\Group;
+use Friendica\Model\Item;
 use Friendica\Model\Profile;
 use Friendica\Model\Queue;
 use Friendica\Model\User;
 use Friendica\Network\Probe;
 use Friendica\Util\Crypto;
+use Friendica\Util\DateTimeFormat;
+use Friendica\Util\Network;
 use Friendica\Util\XML;
-
+use Friendica\Util\Map;
 use dba;
 use SimpleXMLElement;
 
 require_once 'include/dba.php';
 require_once 'include/items.php';
 require_once 'include/bb2diaspora.php';
-require_once 'include/datetime.php';
 
 /**
  * @brief This class contain functions to create and send Diaspora XML files
@@ -75,7 +77,7 @@ class Diaspora
                                $r = q(
                                        "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
                                        VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
-                                       datetime_convert(),
+                                       DateTimeFormat::utcNow(),
                                        dbesc($addr),
                                        dbesc($addr),
                                        dbesc($server),
@@ -83,9 +85,9 @@ class Diaspora
                                        dbesc($batch),
                                        dbesc(NETWORK_DIASPORA),
                                        intval(CONTACT_IS_FOLLOWER),
-                                       dbesc(datetime_convert()),
-                                       dbesc(datetime_convert()),
-                                       dbesc(datetime_convert())
+                                       dbesc(DateTimeFormat::utcNow()),
+                                       dbesc(DateTimeFormat::utcNow()),
+                                       dbesc(DateTimeFormat::utcNow())
                                );
 
                                $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
@@ -186,7 +188,7 @@ class Diaspora
         */
        private static function verifyMagicEnvelope($envelope)
        {
-               $basedom = parse_xml_string($envelope);
+               $basedom = XML::parseString($envelope);
 
                if (!is_object($basedom)) {
                        logger("Envelope is no XML file");
@@ -220,11 +222,20 @@ class Diaspora
 
                $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
 
+               if ($handle == '') {
+                       logger('No author could be decoded. Discarding. Message: ' . $envelope);
+                       return false;
+               }
+
                $key = self::key($handle);
+               if ($key == '') {
+                       logger("Couldn't get a key for handle " . $handle . ". Discarding.");
+                       return false;
+               }
 
                $verify = Crypto::rsaVerify($signable_data, $sig, $key);
                if (!$verify) {
-                       logger('Message did not verify. Discarding.');
+                       logger('Message from ' . $handle . ' did not verify. Discarding.');
                        return false;
                }
 
@@ -285,7 +296,7 @@ class Diaspora
 
                        if (!is_object($j_outer_key_bundle)) {
                                logger('Outer Salmon did not verify. Discarding.');
-                               http_status_exit(400);
+                               System::httpExit(400);
                        }
 
                        $outer_iv = base64_decode($j_outer_key_bundle->iv);
@@ -296,11 +307,11 @@ class Diaspora
                        $xml = $raw;
                }
 
-               $basedom = parse_xml_string($xml);
+               $basedom = XML::parseString($xml);
 
                if (!is_object($basedom)) {
                        logger('Received data does not seem to be an XML. Discarding. '.$xml);
-                       http_status_exit(400);
+                       System::httpExit(400);
                }
 
                $base = $basedom->children(NAMESPACE_SALMON_ME);
@@ -320,12 +331,21 @@ class Diaspora
                // Get the senders' public key
                $key_id = $base->sig[0]->attributes()->key_id[0];
                $author_addr = base64_decode($key_id);
+               if ($author_addr == '') {
+                       logger('No author could be decoded. Discarding. Message: ' . $xml);
+                       System::httpExit(400);
+               }
+
                $key = self::key($author_addr);
+               if ($key == '') {
+                       logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
+                       System::httpExit(400);
+               }
 
                $verify = Crypto::rsaVerify($signed_data, $signature, $key);
                if (!$verify) {
                        logger('Message did not verify. Discarding.');
-                       http_status_exit(400);
+                       System::httpExit(400);
                }
 
                return ['message' => (string)base64url_decode($base->data),
@@ -347,7 +367,7 @@ class Diaspora
        public static function decode($importer, $xml)
        {
                $public = false;
-               $basedom = parse_xml_string($xml);
+               $basedom = XML::parseString($xml);
 
                if (!is_object($basedom)) {
                        logger("XML is not parseable.");
@@ -355,6 +375,9 @@ class Diaspora
                }
                $children = $basedom->children('https://joindiaspora.com/protocol');
 
+               $inner_aes_key = null;
+               $inner_iv = null;
+
                if ($children->header) {
                        $public = true;
                        $author_link = str_replace('acct:', '', $children->header->author_id);
@@ -381,7 +404,7 @@ class Diaspora
                        $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
 
                        logger('decrypted: '.$decrypted, LOGGER_DEBUG);
-                       $idom = parse_xml_string($decrypted);
+                       $idom = XML::parseString($decrypted);
 
                        $inner_iv = base64_decode($idom->iv);
                        $inner_aes_key = base64_decode($idom->aes_key);
@@ -393,6 +416,7 @@ class Diaspora
 
                // figure out where in the DOM tree our data is hiding
 
+               $base = null;
                if ($dom->provenance->data) {
                        $base = $dom->provenance;
                } elseif ($dom->env->data) {
@@ -403,7 +427,7 @@ class Diaspora
 
                if (!$base) {
                        logger('unable to locate salmon data in xml');
-                       http_status_exit(400);
+                       System::httpExit(400);
                }
 
 
@@ -441,7 +465,7 @@ class Diaspora
 
                if (!$author_link) {
                        logger('Could not retrieve author URI.');
-                       http_status_exit(400);
+                       System::httpExit(400);
                }
                // Once we have the author URI, go to the web and try to find their public key
                // (first this will look it up locally if it is in the fcontact cache)
@@ -452,14 +476,14 @@ class Diaspora
 
                if (!$key) {
                        logger('Could not retrieve author key.');
-                       http_status_exit(400);
+                       System::httpExit(400);
                }
 
                $verify = Crypto::rsaVerify($signed_data, $signature, $key);
 
                if (!$verify) {
                        logger('Message did not verify. Discarding.');
-                       http_status_exit(400);
+                       System::httpExit(400);
                }
 
                logger('Message verified.');
@@ -631,15 +655,13 @@ class Diaspora
         */
        private static function validPosting($msg)
        {
-               $data = parse_xml_string($msg["message"]);
+               $data = XML::parseString($msg["message"]);
 
                if (!is_object($data)) {
                        logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
                        return false;
                }
 
-               $first_child = $data->getName();
-
                // Is this the new or the old version?
                if ($data->getName() == "XML") {
                        $oldXML = true;
@@ -668,6 +690,8 @@ class Diaspora
                $fields = new SimpleXMLElement("<".$type."/>");
 
                $signed_data = "";
+               $author_signature = null;
+               $parent_author_signature = null;
 
                foreach ($element->children() as $fieldname => $entry) {
                        if ($oldXML) {
@@ -796,14 +820,11 @@ class Diaspora
         */
        public static function personByHandle($handle)
        {
-               $r = q(
-                       "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
-                       dbesc(NETWORK_DIASPORA),
-                       dbesc($handle)
-               );
-               if ($r) {
-                       $person = $r[0];
-                       logger("In cache " . print_r($r, true), LOGGER_DEBUG);
+               $update = false;
+
+               $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
+               if (DBM::is_result($person)) {
+                       logger("In cache " . print_r($person, true), LOGGER_DEBUG);
 
                        // update record occasionally so it doesn't get stale
                        $d = strtotime($person["updated"]." +00:00");
@@ -816,7 +837,7 @@ class Diaspora
                        }
                }
 
-               if (!$person || $update) {
+               if (!DBM::is_result($person) || $update) {
                        logger("create or refresh", LOGGER_DEBUG);
                        $r = Probe::uri($handle, NETWORK_DIASPORA);
 
@@ -824,9 +845,15 @@ class Diaspora
                        // if Diaspora connectivity is enabled on their server
                        if ($r && ($r["network"] === NETWORK_DIASPORA)) {
                                self::addFContact($r, $update);
-                               $person = $r;
+
+                               // Fetch the updated or added contact
+                               $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
+                               if (!DBM::is_result($person)) {
+                                       $person = $r;
+                               }
                        }
                }
+
                return $person;
        }
 
@@ -869,7 +896,7 @@ class Diaspora
                                dbesc($arr["confirm"]),
                                dbesc($arr["alias"]),
                                dbesc($arr["pubkey"]),
-                               dbesc(datetime_convert()),
+                               dbesc(DateTimeFormat::utcNow()),
                                dbesc($arr["url"]),
                                dbesc($arr["network"])
                        );
@@ -892,7 +919,7 @@ class Diaspora
                                dbesc($arr["network"]),
                                dbesc($arr["alias"]),
                                dbesc($arr["pubkey"]),
-                               dbesc(datetime_convert())
+                               dbesc(DateTimeFormat::utcNow())
                        );
                }
 
@@ -900,23 +927,23 @@ class Diaspora
        }
 
        /**
-        * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
+        * @brief get a handle (user@domain.tld) from a given contact id
         *
         * @param int $contact_id  The id in the contact table
-        * @param int $gcontact_id The id in the gcontact table
+        * @param int $pcontact_id The id in the contact table (Used for the public contact)
         *
         * @return string the handle
         */
-       public static function handleFromContact($contact_id, $gcontact_id = 0)
+       private static function handleFromContact($contact_id, $pcontact_id = 0)
        {
                $handle = false;
 
-               logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
+               logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
 
-               if ($gcontact_id != 0) {
+               if ($pcontact_id != 0) {
                        $r = q(
-                               "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
-                               intval($gcontact_id)
+                               "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
+                               intval($pcontact_id)
                        );
 
                        if (DBM::is_result($r)) {
@@ -1057,7 +1084,7 @@ class Diaspora
                //}
 
                // We don't seem to like that person
-               if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
+               if ($contact["blocked"] || $contact["readonly"]) {
                        // Maybe blocked, don't accept.
                        return false;
                        // We are following this person?
@@ -1257,7 +1284,7 @@ class Diaspora
 
                logger("Fetch post from ".$source_url, LOGGER_DEBUG);
 
-               $envelope = fetch_url($source_url);
+               $envelope = Network::fetchUrl($source_url);
                if ($envelope) {
                        logger("Envelope was fetched.", LOGGER_DEBUG);
                        $x = self::verifyMagicEnvelope($envelope);
@@ -1275,13 +1302,13 @@ class Diaspora
                        $source_url = $server."/p/".urlencode($guid).".xml";
                        logger("Fetch post from ".$source_url, LOGGER_DEBUG);
 
-                       $x = fetch_url($source_url);
+                       $x = Network::fetchUrl($source_url);
                        if (!$x) {
                                return false;
                        }
                }
 
-               $source_xml = parse_xml_string($x);
+               $source_xml = XML::parseString($x);
 
                if (!is_object($source_xml)) {
                        return false;
@@ -1374,26 +1401,23 @@ class Diaspora
        /**
         * @brief returns contact details
         *
-        * @param array $contact The default contact if the person isn't found
-        * @param array $person  The record of the person
-        * @param int   $uid     The user id
+        * @param array $def_contact The default contact if the person isn't found
+        * @param array $person      The record of the person
+        * @param int   $uid         The user id
         *
         * @return array
         *      'cid' => contact id
         *      'network' => network type
         */
-       private static function authorContactByUrl($contact, $person, $uid)
+       private static function authorContactByUrl($def_contact, $person, $uid)
        {
-               $r = q(
-                       "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
-                       dbesc(normalise_link($person["url"])),
-                       intval($uid)
-               );
-               if ($r) {
-                       $cid = $r[0]["id"];
-                       $network = $r[0]["network"];
-               } else {
+               $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
+               $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
+               if (DBM::is_result($contact)) {
                        $cid = $contact["id"];
+                       $network = $contact["network"];
+               } else {
+                       $cid = $def_contact["id"];
                        $network = NETWORK_DIASPORA;
                }
 
@@ -1652,9 +1676,9 @@ class Diaspora
                $text = unxmlify($data->text);
 
                if (isset($data->created_at)) {
-                       $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+                       $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
                } else {
-                       $created_at = datetime_convert();
+                       $created_at = DateTimeFormat::utcNow();
                }
 
                if (isset($data->thread_parent_guid)) {
@@ -1730,7 +1754,7 @@ class Diaspora
 
                self::fetchGuid($datarray);
 
-               $message_id = item_store($datarray);
+               $message_id = Item::insert($datarray);
 
                if ($message_id <= 0) {
                        return false;
@@ -1784,7 +1808,7 @@ class Diaspora
                $msg_guid = notags(unxmlify($mesg->guid));
                $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
                $msg_text = unxmlify($mesg->text);
-               $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
+               $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
 
                if ($msg_conversation_guid != $guid) {
                        logger("message conversation guid does not belong to the current conversation.");
@@ -1829,7 +1853,7 @@ class Diaspora
 
                dba::unlock();
 
-               dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
+               dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
 
                notification(
                        [
@@ -1863,7 +1887,7 @@ class Diaspora
                $author = notags(unxmlify($data->author));
                $guid = notags(unxmlify($data->guid));
                $subject = notags(unxmlify($data->subject));
-               $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+               $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
                $participants = notags(unxmlify($data->participants));
 
                $messages = $data->message;
@@ -1895,7 +1919,7 @@ class Diaspora
                                dbesc($guid),
                                dbesc($author),
                                dbesc($created_at),
-                               dbesc(datetime_convert()),
+                               dbesc(DateTimeFormat::utcNow()),
                                dbesc($subject),
                                dbesc($participants)
                        );
@@ -2051,7 +2075,7 @@ class Diaspora
 
                $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
 
-               $message_id = item_store($datarray);
+               $message_id = Item::insert($datarray);
 
                if ($message_id <= 0) {
                        return false;
@@ -2096,7 +2120,7 @@ class Diaspora
                $guid = notags(unxmlify($data->guid));
                $conversation_guid = notags(unxmlify($data->conversation_guid));
                $text = unxmlify($data->text);
-               $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+               $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
 
                $contact = self::allowedContactByHandle($importer, $author, true);
                if (!$contact) {
@@ -2162,7 +2186,7 @@ class Diaspora
 
                dba::unlock();
 
-               dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
+               dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
                return true;
        }
 
@@ -2206,7 +2230,10 @@ class Diaspora
                }
 
                logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
-               dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
+
+               if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
+                       dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
+               }
 
                // Send all existing comments and likes to the requesting server
                $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
@@ -2313,7 +2340,7 @@ class Diaspora
                $birthday = str_replace("1000", "1901", $birthday);
 
                if ($birthday != "") {
-                       $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
+                       $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
                }
 
                // this is to prevent multiple birthday notifications in a single year
@@ -2329,7 +2356,7 @@ class Diaspora
                        dbesc($name),
                        dbesc($nick),
                        dbesc($author),
-                       dbesc(datetime_convert()),
+                       dbesc(DateTimeFormat::utcNow()),
                        dbesc($birthday),
                        dbesc($location),
                        dbesc($about),
@@ -2417,7 +2444,7 @@ class Diaspora
                                $arr["deny_cid"]  = $user["deny_cid"];
                                $arr["deny_gid"]  = $user["deny_gid"];
 
-                               $i = item_store($arr);
+                               $i = Item::insert($arr);
                                if ($i) {
                                        Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
                                }
@@ -2501,7 +2528,7 @@ class Diaspora
                                return true;
                        } else {
                                logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
-                               lose_follower($importer, $contact);
+                               Contact::removeFollower($importer, $contact);
                                return true;
                        }
                }
@@ -2535,7 +2562,7 @@ class Diaspora
                        intval($importer["uid"]),
                        dbesc($ret["network"]),
                        dbesc($ret["addr"]),
-                       datetime_convert(),
+                       DateTimeFormat::utcNow(),
                        dbesc($ret["url"]),
                        dbesc(normalise_link($ret["url"])),
                        dbesc($batch),
@@ -2578,7 +2605,7 @@ class Diaspora
                                0,
                                dbesc(L10n::t("Sharing notification from Diaspora network")),
                                dbesc($hash),
-                               dbesc(datetime_convert())
+                               dbesc(DateTimeFormat::utcNow())
                        );
                } else {
                        // automatic friend approval
@@ -2609,8 +2636,8 @@ class Diaspora
                                WHERE `id` = %d
                                ",
                                intval($new_relation),
-                               dbesc(datetime_convert()),
-                               dbesc(datetime_convert()),
+                               dbesc(DateTimeFormat::utcNow()),
+                               dbesc(DateTimeFormat::utcNow()),
                                intval($contact_record["id"])
                        );
 
@@ -2714,7 +2741,7 @@ class Diaspora
        {
                $author = notags(unxmlify($data->author));
                $guid = notags(unxmlify($data->guid));
-               $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+               $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
                $root_author = notags(unxmlify($data->root_author));
                $root_guid = notags(unxmlify($data->root_guid));
                /// @todo handle unprocessed property "provider_display_name"
@@ -2780,7 +2807,7 @@ class Diaspora
                $datarray["object-type"] = $original_item["object-type"];
 
                self::fetchGuid($datarray);
-               $message_id = item_store($datarray);
+               $message_id = Item::insert($datarray);
 
                self::sendParticipation($contact, $datarray);
 
@@ -2842,23 +2869,7 @@ class Diaspora
                                continue;
                        }
 
-                       // Currently we don't have a central deletion function that we could use in this case.
-                       // The function "item_drop" doesn't work for that case
-                       dba::update(
-                               'item',
-                               [
-                                       'deleted' => true,
-                                       'title' => '',
-                                       'body' => '',
-                                       'edited' => datetime_convert(),
-                                       'changed' => datetime_convert()],
-                               ['id' => $item["id"]]
-                       );
-
-                       // Delete the thread - if it is a starting post and not a comment
-                       if ($target_type != 'Comment') {
-                               delete_thread($item["id"], $item["parent-uri"]);
-                       }
+                       Item::deleteById($item["id"]);
 
                        logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
 
@@ -2928,7 +2939,7 @@ class Diaspora
        {
                $author = notags(unxmlify($data->author));
                $guid = notags(unxmlify($data->guid));
-               $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
+               $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
                $public = notags(unxmlify($data->public));
                $text = unxmlify($data->text);
                $provider_display_name = notags(unxmlify($data->provider_display_name));
@@ -3020,7 +3031,7 @@ class Diaspora
                }
 
                self::fetchGuid($datarray);
-               $message_id = item_store($datarray);
+               $message_id = Item::insert($datarray);
 
                self::sendParticipation($contact, $datarray);
 
@@ -3197,7 +3208,7 @@ class Diaspora
         *
         * @return int Result of the transmission
         */
-       public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
+       public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
        {
                $a = get_app();
 
@@ -3207,13 +3218,14 @@ class Diaspora
                }
 
                $logid = random_string(4);
-               $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
 
-               // Fetch the fcontact entry when there is missing data
-               // Will possibly happen when data is transmitted to a DFRN contact
-               if (empty($dest_url) && !empty($contact['addr'])) {
+               // We always try to use the data from the fcontact table.
+               // This is important for transmitting data to Friendica servers.
+               if (!empty($contact['addr'])) {
                        $fcontact = self::personByHandle($contact['addr']);
                        $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
+               } else {
+                       $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
                }
 
                if (!$dest_url) {
@@ -3229,7 +3241,7 @@ class Diaspora
                        if (!intval(Config::get("system", "diaspora_test"))) {
                                $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
 
-                               post_url($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
+                               Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
                                $return_code = $a->get_curl_code();
                        } else {
                                logger("test_mode");
@@ -3240,30 +3252,20 @@ class Diaspora
                logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
 
                if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
-                       logger("queue message");
-
-                       $r = q(
-                               "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
-                               intval($contact["id"]),
-                               dbesc(NETWORK_DIASPORA),
-                               dbesc($envelope),
-                               intval($public_batch)
-                       );
-                       if ($r) {
-                               logger("add_to_queue ignored - identical item already in queue");
-                       } else {
+                       if (!$no_queue) {
+                               logger("queue message");
                                // queue message for redelivery
-                               Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
-
-                               // The message could not be delivered. We mark the contact as "dead"
-                               Contact::markForArchival($contact);
+                               Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
                        }
+
+                       // The message could not be delivered. We mark the contact as "dead"
+                       Contact::markForArchival($contact);
                } elseif (($return_code >= 200) && ($return_code <= 299)) {
                        // We successfully delivered a message, the contact is alive
                        Contact::unmarkForArchival($contact);
                }
 
-               return(($return_code) ? $return_code : (-1));
+               return $return_code ? $return_code : -1;
        }
 
 
@@ -3310,7 +3312,7 @@ class Diaspora
                $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
 
                if ($spool) {
-                       Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
+                       Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
                        return true;
                } else {
                        $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
@@ -3591,7 +3593,7 @@ class Diaspora
                        $eventdata['guid'] = $event['guid'];
                }
 
-               $mask = 'Y-m-d\TH:i:s\Z';
+               $mask = DateTimeFormat::ATOM;
 
                /// @todo - establish "all day" events in Friendica
                $eventdata["all_day"] = "false";
@@ -3605,10 +3607,10 @@ class Diaspora
                }
 
                if ($event['start']) {
-                       $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
+                       $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
                }
                if ($event['finish'] && !$event['nofinish']) {
-                       $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
+                       $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
                }
                if ($event['summary']) {
                        $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
@@ -3617,10 +3619,18 @@ class Diaspora
                        $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
                }
                if ($event['location']) {
+                       $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
+                       $coord = Map::getCoordinates($event['location']);
+
                        $location = [];
                        $location["address"] = html_entity_decode(bb2diaspora($event['location']));
-                       $location["lat"] = 0;
-                       $location["lng"] = 0;
+                       if (!empty($coord['lat']) && !empty($coord['lon'])) {
+                               $location["lat"] = $coord['lat'];
+                               $location["lng"] = $coord['lon'];
+                       } else {
+                               $location["lat"] = 0;
+                               $location["lng"] = 0;
+                       }
                        $eventdata['location'] = $location;
                }
 
@@ -3650,7 +3660,7 @@ class Diaspora
 
                $public = (($item["private"]) ? "false" : "true");
 
-               $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
+               $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
 
                // Detect a share element and do a reshare
                if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
@@ -3714,7 +3724,13 @@ class Diaspora
                                if (count($event)) {
                                        $message['event'] = $event;
 
-                                       /// @todo Once Diaspora supports it, we will remove the body
+                                       if (!empty($event['location']['address']) &&
+                                               !empty($event['location']['lat']) &&
+                                               !empty($event['location']['lng'])) {
+                                               $message['location'] = $event['location'];
+                                       }
+
+                                       /// @todo Once Diaspora supports it, we will remove the body and the location hack above
                                        // $message['text'] = '';
                                }
                        }
@@ -3767,6 +3783,7 @@ class Diaspora
                $parent = $p[0];
 
                $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
+               $positive = null;
                if ($item['verb'] === ACTIVITY_LIKE) {
                        $positive = "true";
                } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
@@ -3853,7 +3870,7 @@ class Diaspora
                $parent = $p[0];
 
                $text = html_entity_decode(bb2diaspora($item["body"]));
-               $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
+               $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
 
                $comment = ["author" => self::myHandle($owner),
                                "guid" => $item["guid"],
@@ -4034,7 +4051,7 @@ class Diaspora
         */
        public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
        {
-               $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
+               $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
 
                $msg_type = "retraction";
 
@@ -4084,12 +4101,12 @@ class Diaspora
                        "author" => $cnv["creator"],
                        "guid" => $cnv["guid"],
                        "subject" => $cnv["subject"],
-                       "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
+                       "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
                        "participants" => $cnv["recips"]
                ];
 
                $body = bb2diaspora($item["body"]);
-               $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
+               $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
 
                $msg = [
                        "author" => $myaddr,
@@ -4107,7 +4124,7 @@ class Diaspora
                                        "author" => $cnv["creator"],
                                        "guid" => $cnv["guid"],
                                        "subject" => $cnv["subject"],
-                                       "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
+                                       "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
                                        "participants" => $cnv["recips"],
                                        "message" => $msg];
 
@@ -4207,6 +4224,10 @@ class Diaspora
                $small = System::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
                $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
 
+               $dob = null;
+               $about = null;
+               $location = null;
+               $tags = null;
                if ($searchable === 'true') {
                        $dob = '';
 
@@ -4215,11 +4236,11 @@ class Diaspora
                                if ($year < 1004) {
                                        $year = 1004;
                                }
-                               $dob = datetime_convert('UTC', 'UTC', $year . '-' . $month . '-'. $day, 'Y-m-d');
+                               $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
                        }
 
                        $about = $profile['about'];
-                       $about = strip_tags(bbcode($about));
+                       $about = strip_tags(BBCode::convert($about));
 
                        $location = Profile::formatLocation($profile);
                        $tags = '';