]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/Diaspora.php
Merge pull request #6939 from annando/ap-delivery-failure
[friendica.git] / src / Protocol / Diaspora.php
index 0087ced4b1644317dad3b4a4a1bcd8e2661beb23..12f4115384e938bb9c01ff8cd9f770136db15074 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;
@@ -147,7 +148,7 @@ class Diaspora
 
                // Fetch the relay contact
                $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
-                       'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
+                       'contact-type' => Contact::TYPE_RELAY];
                $contact = DBA::selectFirst('contact', $fields, $condition);
 
                if (DBA::isResult($contact)) {
@@ -187,7 +188,7 @@ class Diaspora
                $fields = array_merge($fields, $network_fields);
 
                $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($server_url),
-                       'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
+                       'contact-type' => Contact::TYPE_RELAY];
 
                if (DBA::exists('contact', $condition)) {
                        unset($fields['created']);
@@ -639,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;
@@ -648,15 +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")
@@ -748,8 +749,6 @@ class Diaspora
                                Logger::log("Unknown message type ".$type);
                                return false;
                }
-
-               return true;
        }
 
        /**
@@ -760,7 +759,7 @@ 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
         */
@@ -943,7 +942,7 @@ class Diaspora
 
                $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
                if (DBA::isResult($person)) {
-                       Logger::log("In cache " . print_r($person, true), Logger::DEBUG);
+                       Logger::debug("In cache " . print_r($person, true));
 
                        // update record occasionally so it doesn't get stale
                        $d = strtotime($person["updated"]." +00:00");
@@ -1079,7 +1078,7 @@ class Diaspora
         * @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
         */
@@ -1125,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),
@@ -1136,8 +1135,11 @@ class Diaspora
                //      Logger::log("defining user ".$contact["nick"]." as friend");
                //}
 
-               // We don't seem to like that person
-               if ($contact["blocked"]) {
+               // Contact server is blocked
+               if (Network::isUrlBlocked($contact['url'])) {
+                       return false;
+                       // We don't seem to like that person
+               } elseif ($contact["blocked"]) {
                        // Maybe blocked, don't accept.
                        return false;
                        // We are following this person?
@@ -1145,7 +1147,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?
@@ -2354,8 +2356,6 @@ class Diaspora
         */
        private static function receiveRequestMakeFriend(array $importer, array $contact)
        {
-               $a = \get_app();
-
                if ($contact["rel"] == Contact::SHARING) {
                        DBA::update(
                                'contact',
@@ -2415,7 +2415,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;
@@ -2426,7 +2426,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) {
@@ -2449,7 +2449,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"]),
@@ -2484,12 +2484,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 = 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"]),
@@ -2512,15 +2512,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',
@@ -2538,7 +2538,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]);
@@ -3127,8 +3127,6 @@ class Diaspora
         */
        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;
@@ -3171,7 +3169,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);
@@ -3672,6 +3670,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['name'] . '[/url] ' . $body;
+               }
+
+               return $body;
+       }
+
        /**
         * @brief Sends a post
         *
@@ -3767,7 +3779,7 @@ class Diaspora
         * @param array $item  The item that will be exported
         * @param array $owner the array of the item owner
         *
-        * @return array The data for a comment
+        * @return array|false The data for a comment
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
        private static function constructComment(array $item, array $owner)
@@ -3779,24 +3791,40 @@ class Diaspora
                        return $result;
                }
 
-               $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
-               if (!DBA::isResult($parent)) {
+               $toplevel_item = Item::selectFirst(['guid', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
+               if (!DBA::isResult($toplevel_item)) {
+                       Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
                        return false;
                }
 
-               $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
+               $thread_parent_item = $toplevel_item;
+               if ($item['thr-parent'] != $item['parent-uri']) {
+                       $thread_parent_item = Item::selectFirst(['guid', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
+               }
+
+               $body = $item["body"];
+
+               if ((empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
+                       && !Config::get('system', 'disable_implicit_mentions')
+               ) {
+                       $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
+               }
+
+               $text = html_entity_decode(BBCode::toMarkdown($body));
                $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
 
-               $comment = ["author" => self::myHandle($owner),
-                               "guid" => $item["guid"],
-                               "created_at" => $created,
-                               "parent_guid" => $parent["guid"],
-                               "text" => $text,
-                               "author_signature" => ""];
+               $comment = [
+                       "author"      => self::myHandle($owner),
+                       "guid"        => $item["guid"],
+                       "created_at"  => $created,
+                       "parent_guid" => $toplevel_item["guid"],
+                       "text"        => $text,
+                       "author_signature" => ""
+               ];
 
                // Send the thread parent guid only if it is a threaded comment
                if ($item['thr-parent'] != $item['parent-uri']) {
-                       $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
+                       $comment['thread_parent_guid'] = $thread_parent_item['guid'];
                }
 
                Cache::set($cachekey, $comment, Cache::QUARTER_HOUR);
@@ -3871,15 +3899,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;
        }
@@ -3996,14 +4023,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);
 
@@ -4020,12 +4039,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";
                }
@@ -4147,7 +4167,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])) {