]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/Diaspora.php
empty is better than isset
[friendica.git] / src / Protocol / Diaspora.php
index 0b5c9c9496783c898c5a380ec8a04e3093ff7d12..77ad0170442359a5cac8a6bf3dc27898f194d7e7 100644 (file)
@@ -10,6 +10,7 @@
 
 namespace Friendica\Protocol;
 
+use Friendica\Content\Feature;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\Markdown;
 use Friendica\Core\Cache;
@@ -34,12 +35,10 @@ use Friendica\Util\Crypto;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Map;
 use Friendica\Util\Network;
+use Friendica\Util\Strings;
 use Friendica\Util\XML;
 use SimpleXMLElement;
 
-require_once 'include/dba.php';
-require_once 'include/items.php';
-
 /**
  * @brief This class contain functions to create and send Diaspora XML files
  *
@@ -55,6 +54,7 @@ class Diaspora
         * @param array   $contacts The previously fetched contacts
         *
         * @return array of relay servers
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        public static function relayList($item_id, array $contacts = [])
        {
@@ -112,7 +112,7 @@ class Diaspora
                // Now we are collecting all relay contacts
                foreach ($serverlist as $server_url) {
                        // We don't send messages to ourselves
-                       if (link_compare($server_url, System::baseUrl())) {
+                       if (Strings::compareLink($server_url, System::baseUrl())) {
                                continue;
                        }
                        $contact = self::getRelayContact($server_url);
@@ -140,14 +140,15 @@ class Diaspora
         *
         * @param string $server_url The url of the server
         * @return array with the contact
+        * @throws \Exception
         */
        private static function getRelayContact($server_url)
        {
                $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
 
                // Fetch the relay contact
-               $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
-                       'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
+               $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
+                       'contact-type' => Contact::TYPE_RELAY];
                $contact = DBA::selectFirst('contact', $fields, $condition);
 
                if (DBA::isResult($contact)) {
@@ -171,8 +172,9 @@ class Diaspora
        /**
         * @brief Update or insert a relay contact
         *
-        * @param string $server_url The url of the server
-        * @param array $network_fields Optional network specific fields
+        * @param string $server_url     The url of the server
+        * @param array  $network_fields Optional network specific fields
+        * @throws \Exception
         */
        public static function setRelayContact($server_url, array $network_fields = [])
        {
@@ -185,8 +187,8 @@ class Diaspora
 
                $fields = array_merge($fields, $network_fields);
 
-               $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
-                       'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
+               $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
+                       'contact-type' => Contact::TYPE_RELAY];
 
                if (DBA::exists('contact', $condition)) {
                        unset($fields['created']);
@@ -206,6 +208,7 @@ class Diaspora
         * @param array   $contacts The previously fetched contacts
         *
         * @return array of relay servers
+        * @throws \Exception
         */
        public static function participantsForThread($thread, array $contacts)
        {
@@ -252,6 +255,7 @@ class Diaspora
         * @param integer $level     This value is only set inside this function to avoid endless loops
         *
         * @return string the repaired signature
+        * @throws \Exception
         */
        private static function repairSignature($signature, $handle = "", $level = 1)
        {
@@ -278,6 +282,8 @@ class Diaspora
         * @param string $envelope The magic envelope
         *
         * @return string verified data
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function verifyMagicEnvelope($envelope)
        {
@@ -297,23 +303,23 @@ class Diaspora
 
                $handle = "";
 
-               $data = base64url_decode($children->data);
+               $data = Strings::base64UrlDecode($children->data);
                $type = $children->data->attributes()->type[0];
 
                $encoding = $children->encoding;
 
                $alg = $children->alg;
 
-               $sig = base64url_decode($children->sig);
+               $sig = Strings::base64UrlDecode($children->sig);
                $key_id = $children->sig->attributes()->key_id[0];
                if ($key_id != "") {
-                       $handle = base64url_decode($key_id);
+                       $handle = Strings::base64UrlDecode($key_id);
                }
 
-               $b64url_data = base64url_encode($data);
+               $b64url_data = Strings::base64UrlEncode($data);
                $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
 
-               $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
+               $signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
 
                if ($handle == '') {
                        Logger::log('No author could be decoded. Discarding. Message: ' . $envelope);
@@ -374,6 +380,8 @@ class Diaspora
         * 'message' -> decoded Diaspora XML message
         * 'author' -> author diaspora handle
         * 'key' -> author public key (converted to pkcs#8)
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function decodeRaw(array $importer, $raw, $no_exit = false)
        {
@@ -425,10 +433,10 @@ class Diaspora
                $type = $base->data[0]->attributes()->type[0];
                $encoding = $base->encoding;
                $alg = $base->alg;
-               $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
+               $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
 
                // This is the signature
-               $signature = base64url_decode($base->sig);
+               $signature = Strings::base64UrlDecode($base->sig);
 
                // Get the senders' public key
                $key_id = $base->sig[0]->attributes()->key_id[0];
@@ -462,7 +470,7 @@ class Diaspora
                        }
                }
 
-               return ['message' => (string)base64url_decode($base->data),
+               return ['message' => (string)Strings::base64UrlDecode($base->data),
                                'author' => XML::unescape($author_addr),
                                'key' => (string)$key];
        }
@@ -477,6 +485,8 @@ class Diaspora
         * 'message' -> decoded Diaspora XML message
         * 'author' -> author diaspora handle
         * 'key' -> author public key (converted to pkcs#8)
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function decode(array $importer, $xml)
        {
@@ -546,7 +556,7 @@ class Diaspora
 
 
                // Stash the signature away for now. We have to find their key or it won't be good for anything.
-               $signature = base64url_decode($base->sig);
+               $signature = Strings::base64UrlDecode($base->sig);
 
                // unpack the  data
 
@@ -562,11 +572,11 @@ class Diaspora
                $alg = $base->alg;
 
 
-               $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
+               $signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg);
 
 
                // decode the data
-               $data = base64url_decode($data);
+               $data = Strings::base64UrlDecode($data);
 
 
                if ($public) {
@@ -614,6 +624,8 @@ class Diaspora
         * @param array $msg The post that will be dispatched
         *
         * @return int The message id of the generated message, "true" or "false" if there was an error
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function dispatchPublic($msg)
        {
@@ -628,7 +640,7 @@ class Diaspora
                        return false;
                }
 
-               $importer = ["uid" => 0, "page-flags" => Contact::PAGE_FREELOVE];
+               $importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE];
                $success = self::dispatch($importer, $msg, $fields);
 
                return $success;
@@ -637,13 +649,15 @@ class Diaspora
        /**
         * @brief Dispatches the different message types to the different functions
         *
-        * @param array  $importer Array of the importer user
-        * @param array  $msg      The post that will be dispatched
-        * @param object $fields   SimpleXML object that contains the message
+        * @param array            $importer Array of the importer user
+        * @param array            $msg      The post that will be dispatched
+        * @param SimpleXMLElement $fields   SimpleXML object that contains the message
         *
         * @return int The message id of the generated message, "true" or "false" if there was an error
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
-       public static function dispatch(array $importer, $msg, $fields = null)
+       public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null)
        {
                // The sender is the handle of the contact that sent the message.
                // This will often be different with relayed messages (for example "like" and "comment")
@@ -735,8 +749,6 @@ class Diaspora
                                Logger::log("Unknown message type ".$type);
                                return false;
                }
-
-               return true;
        }
 
        /**
@@ -747,7 +759,9 @@ class Diaspora
         *
         * @param array $msg Array with the XML, the sender handle and the sender signature
         *
-        * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
+        * @return bool|SimpleXMLElement If the posting is valid then an array with an SimpleXML object is returned
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function validPosting($msg)
        {
@@ -896,6 +910,8 @@ class Diaspora
         * @param string $handle The handle
         *
         * @return string The public key
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function key($handle)
        {
@@ -917,6 +933,8 @@ class Diaspora
         * @param string $handle The handle
         *
         * @return array the queried data
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function personByHandle($handle)
        {
@@ -962,6 +980,7 @@ class Diaspora
         * @brief Updates the fcontact table
         *
         * @param array $arr The fcontact data
+        * @throws \Exception
         */
        private static function updateFContact($arr)
        {
@@ -985,6 +1004,7 @@ class Diaspora
         * @param int $pcontact_id The id in the contact table (Used for the public contact)
         *
         * @return string the handle
+        * @throws \Exception
         */
        private static function handleFromContact($contact_id, $pcontact_id = 0)
        {
@@ -1031,6 +1051,7 @@ class Diaspora
         * @param mixed $fcontact_guid Hexadecimal string guid
         *
         * @return string the contact url or null
+        * @throws \Exception
         */
        public static function urlFromContactGuid($fcontact_guid)
        {
@@ -1052,12 +1073,14 @@ class Diaspora
        /**
         * @brief Get a contact id for a given handle
         *
-        * @todo Move to Friendica\Model\Contact
+        * @todo  Move to Friendica\Model\Contact
         *
         * @param int    $uid    The user id
         * @param string $handle The handle in the format user@domain.tld
         *
-        * @return int Contact id
+        * @return array Contact data
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function contactByHandle($uid, $handle)
        {
@@ -1101,7 +1124,7 @@ class Diaspora
                 */
                // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
                // It is not removed by now. Possibly the code is needed?
-               //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(Contact::PAGE_FREELOVE))) {
+               //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(User::PAGE_FLAGS_FREELOVE))) {
                //      DBA::update(
                //              'contact',
                //              array('rel' => Contact::FRIEND, 'writable' => true),
@@ -1121,7 +1144,7 @@ class Diaspora
                        // Yes, then it is fine.
                        return true;
                        // Is it a post to a community?
-               } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
+               } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
                        // That's good
                        return true;
                        // Is the message a global user or a comment?
@@ -1141,6 +1164,7 @@ class Diaspora
         * @param bool   $is_comment Is the check for a comment?
         *
         * @return array The contact data
+        * @throws \Exception
         */
        private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
        {
@@ -1171,6 +1195,7 @@ class Diaspora
         * @param string $guid The guid of the message
         *
         * @return int|bool message id if the message already was stored into the system - or false.
+        * @throws \Exception
         */
        private static function messageExists($uid, $guid)
        {
@@ -1251,6 +1276,8 @@ class Diaspora
         * @param array $match array containing a link that has to be checked for a message link
         * @param array $item  The item array
         * @return void
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function fetchGuidSub($match, $item)
        {
@@ -1267,6 +1294,8 @@ class Diaspora
         * @param int    $uid    The user id of the user
         *
         * @return int the message id of the stored message or false
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function storeByGuid($guid, $server, $uid = 0)
        {
@@ -1303,6 +1332,7 @@ class Diaspora
         *      'message' => The message XML
         *      'author' => The author handle
         *      'key' => The public key of the author
+        * @throws \Exception
         */
        private static function message($guid, $server, $level = 0)
        {
@@ -1328,15 +1358,8 @@ class Diaspora
                        $x = false;
                }
 
-               // This will work for older Diaspora and Friendica servers
                if (!$x) {
-                       $source_url = $server."/p/".urlencode($guid).".xml";
-                       Logger::log("Fetch post from ".$source_url, Logger::DEBUG);
-
-                       $x = Network::fetchUrl($source_url);
-                       if (!$x) {
-                               return false;
-                       }
+                       return false;
                }
 
                $source_xml = XML::parseString($x);
@@ -1386,6 +1409,7 @@ class Diaspora
         * @param array  $contact The contact of the item owner
         *
         * @return array the item record
+        * @throws \Exception
         */
        private static function parentItem($uid, $guid, $author, array $contact)
        {
@@ -1430,10 +1454,11 @@ class Diaspora
         * @return array
         *      'cid' => contact id
         *      'network' => network type
+        * @throws \Exception
         */
        private static function authorContactByUrl($def_contact, $person, $uid)
        {
-               $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
+               $condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid];
                $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
                if (DBA::isResult($contact)) {
                        $cid = $contact["id"];
@@ -1466,6 +1491,8 @@ class Diaspora
         * @param string $parent_guid optional parent guid
         *
         * @return string the post link
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function plink($addr, $guid, $parent_guid = '')
        {
@@ -1502,12 +1529,14 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool Success
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function receiveAccountMigration(array $importer, $data)
        {
-               $old_handle = notags(XML::unescape($data->author));
-               $new_handle = notags(XML::unescape($data->profile->author));
-               $signature = notags(XML::unescape($data->signature));
+               $old_handle = Strings::escapeTags(XML::unescape($data->author));
+               $new_handle = Strings::escapeTags(XML::unescape($data->profile->author));
+               $signature = Strings::escapeTags(XML::unescape($data->signature));
 
                $contact = self::contactByHandle($importer["uid"], $old_handle);
                if (!$contact) {
@@ -1535,7 +1564,7 @@ class Diaspora
                        return false;
                }
 
-               $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
+               $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
                                'name' => $data['name'], 'nick' => $data['nick'],
                                'addr' => $data['addr'], 'batch' => $data['batch'],
                                'notify' => $data['notify'], 'poll' => $data['poll'],
@@ -1543,7 +1572,7 @@ class Diaspora
 
                DBA::update('contact', $fields, ['addr' => $old_handle]);
 
-               $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
+               $fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']),
                                'name' => $data['name'], 'nick' => $data['nick'],
                                'addr' => $data['addr'], 'connect' => $data['addr'],
                                'notify' => $data['notify'], 'photo' => $data['photo'],
@@ -1559,13 +1588,14 @@ class Diaspora
        /**
         * @brief Processes an account deletion
         *
-        * @param object $data     The message object
+        * @param object $data The message object
         *
         * @return bool Success
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function receiveAccountDeletion($data)
        {
-               $author = notags(XML::unescape($data->author));
+               $author = Strings::escapeTags(XML::unescape($data->author));
 
                $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
                while ($contact = DBA::fetch($contacts)) {
@@ -1587,6 +1617,8 @@ class Diaspora
         * @param boolean $onlyfound Only return uri when found in the database
         *
         * @return string The constructed uri or the one from our database
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function getUriFromGuid($author, $guid, $onlyfound = false)
        {
@@ -1613,6 +1645,7 @@ class Diaspora
         * @param string $uid Author handle
         *
         * @return string The post guid
+        * @throws \Exception
         */
        private static function getGuidFromUri($uri, $uid)
        {
@@ -1630,6 +1663,7 @@ class Diaspora
         * @param string $guid The guid of the item
         *
         * @return array|boolean the origin owner of that post - or false
+        * @throws \Exception
         */
        private static function importerForGuid($guid)
        {
@@ -1653,22 +1687,24 @@ class Diaspora
         * @param string $xml      The original XML of the message
         *
         * @return int The message id of the generated comment or "false" if there was an error
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function receiveComment(array $importer, $sender, $data, $xml)
        {
-               $author = notags(XML::unescape($data->author));
-               $guid = notags(XML::unescape($data->guid));
-               $parent_guid = notags(XML::unescape($data->parent_guid));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $guid = Strings::escapeTags(XML::unescape($data->guid));
+               $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
                $text = XML::unescape($data->text);
 
                if (isset($data->created_at)) {
-                       $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
+                       $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
                } else {
                        $created_at = DateTimeFormat::utcNow();
                }
 
                if (isset($data->thread_parent_guid)) {
-                       $thread_parent_guid = notags(XML::unescape($data->thread_parent_guid));
+                       $thread_parent_guid = Strings::escapeTags(XML::unescape($data->thread_parent_guid));
                        $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
                } else {
                        $thr_uri = "";
@@ -1770,27 +1806,28 @@ class Diaspora
         * @param array  $conversation The conversation record to which this message belongs
         *
         * @return bool "true" if it was successful
+        * @throws \Exception
         */
        private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
        {
-               $author = notags(XML::unescape($data->author));
-               $guid = notags(XML::unescape($data->guid));
-               $subject = notags(XML::unescape($data->subject));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $guid = Strings::escapeTags(XML::unescape($data->guid));
+               $subject = Strings::escapeTags(XML::unescape($data->subject));
 
                // "diaspora_handle" is the element name from the old version
                // "author" is the element name from the new version
                if ($mesg->author) {
-                       $msg_author = notags(XML::unescape($mesg->author));
+                       $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
                } elseif ($mesg->diaspora_handle) {
-                       $msg_author = notags(XML::unescape($mesg->diaspora_handle));
+                       $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
                } else {
                        return false;
                }
 
-               $msg_guid = notags(XML::unescape($mesg->guid));
-               $msg_conversation_guid = notags(XML::unescape($mesg->conversation_guid));
+               $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
+               $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
                $msg_text = XML::unescape($mesg->text);
-               $msg_created_at = DateTimeFormat::utc(notags(XML::unescape($mesg->created_at)));
+               $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
 
                if ($msg_conversation_guid != $guid) {
                        Logger::log("message conversation guid does not belong to the current conversation.");
@@ -1809,44 +1846,45 @@ class Diaspora
                        return false;
                }
 
-               q(
-                       "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
-                       VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
-                       intval($importer["uid"]),
-                       DBA::escape($msg_guid),
-                       intval($conversation["id"]),
-                       DBA::escape($person["name"]),
-                       DBA::escape($person["photo"]),
-                       DBA::escape($person["url"]),
-                       intval($contact["id"]),
-                       DBA::escape($subject),
-                       DBA::escape($body),
-                       0,
-                       0,
-                       DBA::escape($message_uri),
-                       DBA::escape($author.":".$guid),
-                       DBA::escape($msg_created_at)
-               );
+               DBA::insert('mail', [
+                       'uid'        => $importer['uid'],
+                       'guid'       => $msg_guid,
+                       'convid'     => $conversation['id'],
+                       'from-name'  => $person['name'],
+                       'from-photo' => $person['photo'],
+                       'from-url'   => $person['url'],
+                       'contact-id' => $contact['id'],
+                       'title'      => $subject,
+                       'body'       => $body,
+                       'seen'       => 0,
+                       'reply'      => 0,
+                       'uri'        => $message_uri,
+                       'parent-uri' => $author . ':' . $guid,
+                       'created'    => $msg_created_at
+               ]);
+
+               $message_id = DBA::lastInsertId();
 
                DBA::unlock();
 
                DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
 
-               notification(
-                       [
+               notification([
                        "type" => NOTIFY_MAIL,
                        "notify_flags" => $importer["notify-flags"],
                        "language" => $importer["language"],
                        "to_name" => $importer["username"],
                        "to_email" => $importer["email"],
-                       "uid" =>$importer["uid"],
-                       "item" => ["id" => $conversation["id"], "title" => $subject, "subject" => $subject, "body" => $body],
+                       "uid" => $importer["uid"],
+                       "item" => ["id" => $message_id, "title" => $subject, "subject" => $subject, "body" => $body],
+                       "parent" => $conversation["id"],
                        "source_name" => $person["name"],
                        "source_link" => $person["url"],
                        "source_photo" => $person["photo"],
                        "verb" => ACTIVITY_POST,
-                       "otype" => "mail"]
-               );
+                       "otype" => "mail"
+               ]);
+
                return true;
        }
 
@@ -1858,14 +1896,15 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool Success
+        * @throws \Exception
         */
        private static function receiveConversation(array $importer, $msg, $data)
        {
-               $author = notags(XML::unescape($data->author));
-               $guid = notags(XML::unescape($data->guid));
-               $subject = notags(XML::unescape($data->subject));
-               $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
-               $participants = notags(XML::unescape($data->participants));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $guid = Strings::escapeTags(XML::unescape($data->guid));
+               $subject = Strings::escapeTags(XML::unescape($data->subject));
+               $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
+               $participants = Strings::escapeTags(XML::unescape($data->participants));
 
                $messages = $data->message;
 
@@ -1916,14 +1955,16 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return int The message id of the generated like or "false" if there was an error
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function receiveLike(array $importer, $sender, $data)
        {
-               $author = notags(XML::unescape($data->author));
-               $guid = notags(XML::unescape($data->guid));
-               $parent_guid = notags(XML::unescape($data->parent_guid));
-               $parent_type = notags(XML::unescape($data->parent_type));
-               $positive = notags(XML::unescape($data->positive));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $guid = Strings::escapeTags(XML::unescape($data->guid));
+               $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
+               $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
+               $positive = Strings::escapeTags(XML::unescape($data->positive));
 
                // likes on comments aren't supported by Diaspora - only on posts
                // But maybe this will be supported in the future, so we will accept it.
@@ -2025,14 +2066,15 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool Success?
+        * @throws \Exception
         */
        private static function receiveMessage(array $importer, $data)
        {
-               $author = notags(XML::unescape($data->author));
-               $guid = notags(XML::unescape($data->guid));
-               $conversation_guid = notags(XML::unescape($data->conversation_guid));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $guid = Strings::escapeTags(XML::unescape($data->guid));
+               $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
                $text = XML::unescape($data->text);
-               $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
+               $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
 
                $contact = self::allowedContactByHandle($importer, $author, true);
                if (!$contact) {
@@ -2068,28 +2110,45 @@ class Diaspora
                        return false;
                }
 
-               q(
-                       "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
-                               VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
-                       intval($importer["uid"]),
-                       DBA::escape($guid),
-                       intval($conversation["id"]),
-                       DBA::escape($person["name"]),
-                       DBA::escape($person["photo"]),
-                       DBA::escape($person["url"]),
-                       intval($contact["id"]),
-                       DBA::escape($conversation["subject"]),
-                       DBA::escape($body),
-                       0,
-                       1,
-                       DBA::escape($message_uri),
-                       DBA::escape($author.":".$conversation["guid"]),
-                       DBA::escape($created_at)
-               );
+               DBA::insert('mail', [
+                       'uid'        => $importer['uid'],
+                       'guid'       => $guid,
+                       'convid'     => $conversation['id'],
+                       'from-name'  => $person['name'],
+                       'from-photo' => $person['photo'],
+                       'from-url'   => $person['url'],
+                       'contact-id' => $contact['id'],
+                       'title'      => $conversation['subject'],
+                       'body'       => $body,
+                       'seen'       => 0,
+                       'reply'      => 1,
+                       'uri'        => $message_uri,
+                       'parent-uri' => $author.":".$conversation['guid'],
+                       'created'    => $created_at
+               ]);
+
+               $message_id = DBA::lastInsertId();
 
                DBA::unlock();
 
                DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
+
+               notification([
+                       "type" => NOTIFY_MAIL,
+                       "notify_flags" => $importer["notify-flags"],
+                       "language" => $importer["language"],
+                       "to_name" => $importer["username"],
+                       "to_email" => $importer["email"],
+                       "uid" => $importer["uid"],
+                       "item" => ["id" => $message_id, "title" => $conversation["subject"], "subject" => $conversation["subject"], "body" => $body],
+                       "parent" => $conversation["id"],
+                       "source_name" => $person["name"],
+                       "source_link" => $person["url"],
+                       "source_photo" => $person["photo"],
+                       "verb" => ACTIVITY_POST,
+                       "otype" => "mail"
+               ]);
+
                return true;
        }
 
@@ -2100,11 +2159,13 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool always true
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function receiveParticipation(array $importer, $data)
        {
-               $author = strtolower(notags(XML::unescape($data->author)));
-               $parent_guid = notags(XML::unescape($data->parent_guid));
+               $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
+               $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
 
                $contact_id = Contact::getIdForURL($author);
                if (!$contact_id) {
@@ -2193,10 +2254,12 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool Success
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function receiveProfile(array $importer, $data)
        {
-               $author = strtolower(notags(XML::unescape($data->author)));
+               $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
 
                $contact = self::contactByHandle($importer["uid"], $author);
                if (!$contact) {
@@ -2286,11 +2349,10 @@ class Diaspora
         * @param array $importer Array of the importer user
         * @param array $contact  The contact that send the request
         * @return void
+        * @throws \Exception
         */
        private static function receiveRequestMakeFriend(array $importer, array $contact)
        {
-               $a = get_app();
-
                if ($contact["rel"] == Contact::SHARING) {
                        DBA::update(
                                'contact',
@@ -2307,6 +2369,7 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool Success
+        * @throws \Exception
         */
        private static function receiveContactRequest(array $importer, $data)
        {
@@ -2349,7 +2412,7 @@ class Diaspora
                                        $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
                                        if (DBA::isResult($user)) {
                                                Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
-                                               $ret = self::sendShare($user, $contact);
+                                               self::sendShare($user, $contact);
                                        }
                                }
                                return true;
@@ -2360,7 +2423,7 @@ class Diaspora
                        }
                }
 
-               if (!$following && $sharing && in_array($importer["page-flags"], [Contact::PAGE_SOAPBOX, Contact::PAGE_NORMAL])) {
+               if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
                        Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
                        return false;
                } elseif (!$following && !$sharing) {
@@ -2383,7 +2446,7 @@ class Diaspora
 
                $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
 
-               $r = q(
+               q(
                        "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
                        VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
                        intval($importer["uid"]),
@@ -2391,7 +2454,7 @@ class Diaspora
                        DBA::escape($ret["addr"]),
                        DateTimeFormat::utcNow(),
                        DBA::escape($ret["url"]),
-                       DBA::escape(normalise_link($ret["url"])),
+                       DBA::escape(Strings::normaliseLink($ret["url"])),
                        DBA::escape($batch),
                        DBA::escape($ret["name"]),
                        DBA::escape($ret["nick"]),
@@ -2418,12 +2481,12 @@ class Diaspora
 
                Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
 
-               if (in_array($importer["page-flags"], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP])) {
+               if (in_array($importer["page-flags"], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])) {
                        Logger::log("Sending intra message for author ".$author.".", Logger::DEBUG);
 
-                       $hash = random_string().(string)time();   // Generate a confirm_key
+                       $hash = Strings::getRandomHex().(string)time();   // Generate a confirm_key
 
-                       $ret = q(
+                       q(
                                "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
                                VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
                                intval($importer["uid"]),
@@ -2446,15 +2509,15 @@ class Diaspora
                         * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
                         * we are going to change the relationship and make them a follower.
                         */
-                       if (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing && $following) {
+                       if (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing && $following) {
                                $new_relation = Contact::FRIEND;
-                       } elseif (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing) {
+                       } elseif (($importer["page-flags"] == User::PAGE_FLAGS_FREELOVE) && $sharing) {
                                $new_relation = Contact::SHARING;
                        } else {
                                $new_relation = Contact::FOLLOWER;
                        }
 
-                       $r = q(
+                       q(
                                "UPDATE `contact` SET `rel` = %d,
                                `name-date` = '%s',
                                `uri-date` = '%s',
@@ -2472,7 +2535,7 @@ class Diaspora
                        $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
                        if (DBA::isResult($user)) {
                                Logger::log("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], Logger::DEBUG);
-                               $ret = self::sendShare($user, $contact_record);
+                               self::sendShare($user, $contact_record);
 
                                // Send the profile data, maybe it weren't transmitted before
                                self::sendProfile($importer["uid"], [$contact_record]);
@@ -2487,9 +2550,9 @@ class Diaspora
         *
         * @param string $guid        message guid
         * @param string $orig_author handle of the original post
-        * @param string $author      handle of the sharer
-        *
         * @return array The fetched item
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function originalItem($guid, $orig_author)
        {
@@ -2570,16 +2633,18 @@ class Diaspora
         * @param string $xml      The original XML of the message
         *
         * @return int the message id
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function receiveReshare(array $importer, $data, $xml)
        {
-               $author = notags(XML::unescape($data->author));
-               $guid = notags(XML::unescape($data->guid));
-               $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
-               $root_author = notags(XML::unescape($data->root_author));
-               $root_guid = notags(XML::unescape($data->root_guid));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $guid = Strings::escapeTags(XML::unescape($data->guid));
+               $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
+               $root_author = Strings::escapeTags(XML::unescape($data->root_author));
+               $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
                /// @todo handle unprocessed property "provider_display_name"
-               $public = notags(XML::unescape($data->public));
+               $public = Strings::escapeTags(XML::unescape($data->public));
 
                $contact = self::allowedContactByHandle($importer, $author, false);
                if (!$contact) {
@@ -2662,12 +2727,13 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool success
+        * @throws \Exception
         */
        private static function itemRetraction(array $importer, array $contact, $data)
        {
-               $author = notags(XML::unescape($data->author));
-               $target_guid = notags(XML::unescape($data->target_guid));
-               $target_type = notags(XML::unescape($data->target_type));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
+               $target_type = Strings::escapeTags(XML::unescape($data->target_type));
 
                $person = self::personByHandle($author);
                if (!is_array($person)) {
@@ -2705,7 +2771,7 @@ class Diaspora
                        $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
 
                        // Only delete it if the parent author really fits
-                       if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
+                       if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
                                Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
                                continue;
                        }
@@ -2726,10 +2792,11 @@ class Diaspora
         * @param object $data     The message object
         *
         * @return bool Success
+        * @throws \Exception
         */
        private static function receiveRetraction(array $importer, $sender, $data)
        {
-               $target_type = notags(XML::unescape($data->target_type));
+               $target_type = Strings::escapeTags(XML::unescape($data->target_type));
 
                $contact = self::contactByHandle($importer["uid"], $sender);
                if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
@@ -2766,20 +2833,22 @@ class Diaspora
        /**
         * @brief Receives status messages
         *
-        * @param array  $importer Array of the importer user
-        * @param object $data     The message object
-        * @param string $xml      The original XML of the message
+        * @param array            $importer Array of the importer user
+        * @param SimpleXMLElement $data     The message object
+        * @param string           $xml      The original XML of the message
         *
         * @return int The message id of the newly created item
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
        {
-               $author = notags(XML::unescape($data->author));
-               $guid = notags(XML::unescape($data->guid));
-               $created_at = DateTimeFormat::utc(notags(XML::unescape($data->created_at)));
-               $public = notags(XML::unescape($data->public));
+               $author = Strings::escapeTags(XML::unescape($data->author));
+               $guid = Strings::escapeTags(XML::unescape($data->guid));
+               $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
+               $public = Strings::escapeTags(XML::unescape($data->public));
                $text = XML::unescape($data->text);
-               $provider_display_name = notags(XML::unescape($data->provider_display_name));
+               $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
 
                $contact = self::allowedContactByHandle($importer, $author, false);
                if (!$contact) {
@@ -2794,7 +2863,7 @@ class Diaspora
                $address = [];
                if ($data->location) {
                        foreach ($data->location->children() as $fieldname => $data) {
-                               $address[$fieldname] = notags(XML::unescape($data));
+                               $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
                        }
                }
 
@@ -2891,6 +2960,7 @@ class Diaspora
         * @param array $contact contact array
         *
         * @return string the handle in the format user@domain.tld
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function myHandle(array $contact)
        {
@@ -2920,6 +2990,7 @@ class Diaspora
         * @param string $pubkey  The public key of the receiver
         *
         * @return string The encrypted data
+        * @throws \Exception
         */
        public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
        {
@@ -2958,17 +3029,18 @@ class Diaspora
         * @param array  $user The record of the sender
         *
         * @return string The envelope
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        public static function buildMagicEnvelope($msg, array $user)
        {
-               $b64url_data = base64url_encode($msg);
+               $b64url_data = Strings::base64UrlEncode($msg);
                $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
 
-               $key_id = base64url_encode(self::myHandle($user));
+               $key_id = Strings::base64UrlEncode(self::myHandle($user));
                $type = "application/xml";
                $encoding = "base64url";
                $alg = "RSA-SHA256";
-               $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
+               $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
 
                // Fallback if the private key wasn't transmitted in the expected field
                if ($user['uprvkey'] == "") {
@@ -2976,7 +3048,7 @@ class Diaspora
                }
 
                $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
-               $sig = base64url_encode($signature);
+               $sig = Strings::base64UrlEncode($signature);
 
                $xmldata = ["me:env" => ["me:data" => $data,
                                                        "@attributes" => ["type" => $type],
@@ -3001,6 +3073,7 @@ class Diaspora
         * @param bool   $public  Is the message public?
         *
         * @return string The message that will be transmitted to other servers
+        * @throws \Exception
         */
        public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
        {
@@ -3044,18 +3117,19 @@ class Diaspora
         * @param bool   $queue_run    Is the transmission called from the queue?
         * @param string $guid         message guid
         *
+        * @param bool   $no_queue
         * @return int Result of the transmission
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
        {
-               $a = get_app();
-
                $enabled = intval(Config::get("system", "diaspora_enabled"));
                if (!$enabled) {
                        return 200;
                }
 
-               $logid = random_string(4);
+               $logid = Strings::getRandomHex(4);
 
                $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
 
@@ -3092,7 +3166,7 @@ class Diaspora
                Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
 
                if (!$return_code || (($return_code == 503) && (stristr($postResult->getHeader(), "retry-after")))) {
-                       if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::ACCOUNT_TYPE_RELAY)) {
+                       if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::TYPE_RELAY)) {
                                Logger::log("queue message");
                                // queue message for redelivery
                                Queue::add($contact["id"], Protocol::DIASPORA, $envelope, $public_batch, $guid);
@@ -3136,6 +3210,8 @@ class Diaspora
         * @param bool   $spool        Should the transmission be spooled or transmitted?
         *
         * @return int Result of the transmission
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
        {
@@ -3167,9 +3243,10 @@ class Diaspora
         * @brief sends a participation (Used to get all further updates)
         *
         * @param array $contact Target of the communication
-        * @param array $item    Item array
+        * @param array $item    Item array
         *
         * @return int The result of the transmission
+        * @throws \Exception
         */
        private static function sendParticipation(array $contact, array $item)
        {
@@ -3216,9 +3293,11 @@ class Diaspora
         *
         * @param array $owner   the array of the item owner
         * @param array $contact Target of the communication
-        * @param int   $uid     User ID
+        * @param int   $uid     User ID
         *
         * @return int The result of the transmission
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function sendAccountMigration(array $owner, array $contact, $uid)
        {
@@ -3244,6 +3323,7 @@ class Diaspora
         * @param array $contact Target of the communication
         *
         * @return int The result of the transmission
+        * @throws \Exception
         */
        public static function sendShare(array $owner, array $contact)
        {
@@ -3287,6 +3367,7 @@ class Diaspora
         * @param array $contact Target of the communication
         *
         * @return int The result of the transmission
+        * @throws \Exception
         */
        public static function sendUnshare(array $owner, array $contact)
        {
@@ -3307,6 +3388,8 @@ class Diaspora
         * @param bool   $complete Should it be a complete check or a simple check?
         *
         * @return array|bool Reshare details or "false" if no reshare
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function isReshare($body, $complete = true)
        {
@@ -3394,6 +3477,7 @@ class Diaspora
         * @param integer $event_id The id of the event
         *
         * @return array with event data
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function buildEvent($event_id)
        {
@@ -3476,6 +3560,8 @@ class Diaspora
         * @return array
         * 'type' -> Message type ("status_message" or "reshare")
         * 'message' -> Array of XML elements of the status
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function buildStatus(array $item, array $owner)
        {
@@ -3581,6 +3667,20 @@ class Diaspora
                return $msg;
        }
 
+       private static function prependParentAuthorMention($body, $profile_url)
+       {
+               $profile = Contact::getDetailsByURL($profile_url);
+               if (!empty($profile['addr'])
+                       && $profile['contact-type'] != Contact::TYPE_COMMUNITY
+                       && !strstr($body, $profile['addr'])
+                       && !strstr($body, $profile_url)
+               ) {
+                       $body = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url] ' . $body;
+               }
+
+               return $body;
+       }
+
        /**
         * @brief Sends a post
         *
@@ -3590,6 +3690,8 @@ class Diaspora
         * @param bool  $public_batch Is it a public post?
         *
         * @return int The result of the transmission
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
        {
@@ -3605,6 +3707,7 @@ class Diaspora
         * @param array $owner the array of the item owner
         *
         * @return array The data for a "like"
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function constructLike(array $item, array $owner)
        {
@@ -3636,6 +3739,7 @@ class Diaspora
         * @param array $owner the array of the item owner
         *
         * @return array The data for an "EventParticipation"
+        * @throws \Exception
         */
        private static function constructAttend(array $item, array $owner)
        {
@@ -3673,6 +3777,7 @@ class Diaspora
         * @param array $owner the array of the item owner
         *
         * @return array The data for a comment
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function constructComment(array $item, array $owner)
        {
@@ -3683,12 +3788,18 @@ class Diaspora
                        return $result;
                }
 
-               $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
+               $parent = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
                if (!DBA::isResult($parent)) {
                        return false;
                }
 
-               $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
+               $body = $item["body"];
+
+               if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
+                       $body = self::prependParentAuthorMention($body, $parent['author-link']);
+               }
+
+               $text = html_entity_decode(BBCode::toMarkdown($body));
                $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
 
                $comment = ["author" => self::myHandle($owner),
@@ -3717,6 +3828,8 @@ class Diaspora
         * @param bool  $public_batch Is it a public post?
         *
         * @return int The result of the transmission
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
        {
@@ -3726,12 +3839,12 @@ class Diaspora
                } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
                        $message = self::constructLike($item, $owner);
                        $type = "like";
-               } else {
+               } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW])) {
                        $message = self::constructComment($item, $owner);
                        $type = "comment";
                }
 
-               if (!$message) {
+               if (empty($message)) {
                        return false;
                }
 
@@ -3743,10 +3856,8 @@ class Diaspora
        /**
         * @brief Creates a message from a signature record entry
         *
-        * @param array $item      The item that will be exported
-        * @param array $signature The entry of the "sign" record
-        *
-        * @return string The message
+        * @param array $item The item that will be exported
+        * @return array The message
         */
        private static function messageFromSignature(array $item)
        {
@@ -3775,15 +3886,14 @@ class Diaspora
                        // Remove the handle
                        $handle = array_pop($signed_parts);
 
-                       // Glue the parts together
-                       $text = implode(";", $signed_parts);
-
-                       $message = ["author" => $handle,
-                                       "guid" => $guid,
-                                       "parent_guid" => $parent_guid,
-                                       "text" => implode(";", $signed_parts),
-                                       "author_signature" => $item['signature'],
-                                       "parent_author_signature" => ""];
+                       $message = [
+                               "author" => $handle,
+                               "guid" => $guid,
+                               "parent_guid" => $parent_guid,
+                               "text" => implode(";", $signed_parts),
+                               "author_signature" => $item['signature'],
+                               "parent_author_signature" => ""
+                       ];
                }
                return $message;
        }
@@ -3797,6 +3907,7 @@ class Diaspora
         * @param bool  $public_batch Is it a public post?
         *
         * @return int The result of the transmission
+        * @throws \Exception
         */
        public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
        {
@@ -3853,6 +3964,7 @@ class Diaspora
         * @param bool  $relay        Is the retraction transmitted from a relay?
         *
         * @return int The result of the transmission
+        * @throws \Exception
         */
        public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
        {
@@ -3885,6 +3997,8 @@ class Diaspora
         * @param array $contact Target of the communication
         *
         * @return int The result of the transmission
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \ImagickException
         */
        public static function sendMail(array $item, array $owner, array $contact)
        {
@@ -3896,14 +4010,6 @@ class Diaspora
                        return;
                }
 
-               $conv = [
-                       "author" => $cnv["creator"],
-                       "guid" => $cnv["guid"],
-                       "subject" => $cnv["subject"],
-                       "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
-                       "participants" => $cnv["recips"]
-               ];
-
                $body = BBCode::toMarkdown($item["body"]);
                $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
 
@@ -3920,12 +4026,13 @@ class Diaspora
                        $type = "message";
                } else {
                        $message = [
-                                       "author" => $cnv["creator"],
-                                       "guid" => $cnv["guid"],
-                                       "subject" => $cnv["subject"],
-                                       "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
-                                       "participants" => $cnv["recips"],
-                                       "message" => $msg];
+                               "author" => $cnv["creator"],
+                               "guid" => $cnv["guid"],
+                               "subject" => $cnv["subject"],
+                               "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
+                               "participants" => $cnv["recips"],
+                               "message" => $msg
+                       ];
 
                        $type = "conversation";
                }
@@ -3995,6 +4102,7 @@ class Diaspora
         * @param int $uid The user id
         *
         * @return array The profile data
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function createProfileData($uid)
        {
@@ -4046,7 +4154,7 @@ class Diaspora
                        if ($profile['pub_keywords']) {
                                $kw = str_replace(',', ' ', $profile['pub_keywords']);
                                $kw = str_replace('  ', ' ', $kw);
-                               $arr = explode(' ', $profile['pub_keywords']);
+                               $arr = explode(' ', $kw);
                                if (count($arr)) {
                                        for ($x = 0; $x < 5; $x ++) {
                                                if (!empty($arr[$x])) {
@@ -4079,6 +4187,7 @@ class Diaspora
         * @param int  $uid    The user id
         * @param bool $recips optional, default false
         * @return void
+        * @throws \Exception
         */
        public static function sendProfile($uid, $recips = false)
        {
@@ -4120,6 +4229,7 @@ class Diaspora
         * @param array   $item Item array
         *
         * @return array Signed content
+        * @throws \Exception
         */
        public static function createLikeSignature($uid, array $item)
        {
@@ -4150,6 +4260,7 @@ class Diaspora
         * @param array   $item Item array
         *
         * @return array Signed content
+        * @throws \Exception
         */
        public static function createCommentSignature($uid, array $item)
        {