]> git.mxchange.org Git - friendica.git/blobdiff - include/diaspora2.php
Likes would now work with unlikes and with likes on comments.
[friendica.git] / include / diaspora2.php
index 578a496c0a9d0bc4f957ff961f221b42b8240de9..97d22b4b97b7f2daf0874fc981877ef303777ccb 100644 (file)
@@ -4,11 +4,14 @@
  * @brief The implementation of the diaspora protocol
  */
 
+require_once("include/items.php");
 require_once("include/bb2diaspora.php");
 require_once("include/Scrape.php");
 require_once("include/Contact.php");
 require_once("include/Photo.php");
 require_once("include/socgraph.php");
+require_once("include/group.php");
+require_once("include/api.php");
 
 class xml {
        function from_array($array, &$xml) {
@@ -58,7 +61,7 @@ class diaspora {
 
                // Use a dummy importer to import the data for the public copy
                $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
-               self::dispatch($importer,$msg);
+               $item_id = self::dispatch($importer,$msg);
 
                // Now distribute it to the followers
                $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
@@ -74,6 +77,8 @@ class diaspora {
                        }
                } else
                        logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
+
+               return $item_id;
        }
 
        public static function dispatch($importer, $msg) {
@@ -82,7 +87,7 @@ class diaspora {
                // This will often be different with relayed messages (for example "like" and "comment")
                $sender = $msg["author"];
 
-               if (!diaspora::valid_posting($msg, $fields, $data2)) {
+               if (!diaspora::valid_posting($msg, $fields)) {
                        logger("Invalid posting");
                        return false;
                }
@@ -90,15 +95,17 @@ class diaspora {
                $type = $fields->getName();
 
                switch ($type) {
-                       case "account_deletion": // Not implemented
-                               return self::import_account_deletion($importer, $fields);
+                       case "account_deletion":
+                               return true;
+                               //return self::import_account_deletion($importer, $fields);
 
                        case "comment":
                                return true;
                                //return self::import_comment($importer, $sender, $fields);
 
                        case "conversation":
-                               return self::import_conversation($importer, $fields);
+                               return true;
+                               //return self::import_conversation($importer, $fields);
 
                        case "like":
                                return true;
@@ -125,13 +132,15 @@ class diaspora {
                                return self::import_request($importer, $fields);
 
                        case "reshare":
-                               return self::import_reshare($importer, $fields);
+                               return true;
+                               //return self::import_reshare($importer, $fields);
 
                        case "retraction":
                                return self::import_retraction($importer, $fields);
 
                        case "status_message":
-                               return self::import_status_message($importer, $fields, $msg, $data2);
+                               //return true;
+                               return self::import_status_message($importer, $fields);
 
                        default:
                                logger("Unknown message type ".$type);
@@ -152,7 +161,7 @@ class diaspora {
         *
         * @return bool Is the posting valid?
         */
-       private function valid_posting($msg, &$fields, &$element) {
+       private function valid_posting($msg, &$fields) {
 
                $data = parse_xml_string($msg["message"], false);
 
@@ -238,7 +247,7 @@ class diaspora {
                        }
 
                // Only some message types have signatures. So we quit here for the other types.
-               if (!in_array($type, array("comment", "conversation", "message", "like")))
+               if (!in_array($type, array("comment", "message", "like")))
                        return true;
 
                // No author_signature? This is a must, so we quit.
@@ -376,6 +385,64 @@ class diaspora {
                return false;
        }
 
+       private function post_allow($importer, $contact, $is_comment = false) {
+
+               // perhaps we were already sharing with this person. Now they're sharing with us.
+               // That makes us friends.
+               // Normally this should have handled by getting a request - but this could get lost
+               if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
+                       q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
+                               intval(CONTACT_IS_FRIEND),
+                               intval($contact["id"]),
+                               intval($importer["uid"])
+                       );
+                       $contact["rel"] = CONTACT_IS_FRIEND;
+                       logger("defining user ".$contact["nick"]." as friend");
+               }
+
+               if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
+                       return false;
+               if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
+                       return true;
+               if($contact["rel"] == CONTACT_IS_FOLLOWER)
+                       if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
+                               return true;
+
+               // Messages for the global users are always accepted
+               if ($importer["uid"] == 0)
+                       return true;
+
+               return false;
+       }
+
+       private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
+               $contact = self::get_contact_by_handle($importer["uid"], $handle);
+               if (!$contact) {
+                       logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
+                       return false;
+               }
+
+               if (!self::post_allow($importer, $contact, false)) {
+                       logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
+                       return false;
+               }
+               return $contact;
+       }
+
+       private function message_exists($uid, $guid) {
+               $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
+                       intval($uid),
+                       dbesc($guid)
+               );
+
+               if(count($r)) {
+                       logger("message ".$guid." already exists for user ".$uid);
+                       return false;
+               }
+
+               return true;
+       }
+
        private function fetch_guid($item) {
                preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
                        function ($match) use ($item){
@@ -384,8 +451,6 @@ class diaspora {
        }
 
        private function fetch_guid_sub($match, $item) {
-               $a = get_app();
-
                if (!self::store_by_guid($match[1], $item["author-link"]))
                        self::store_by_guid($match[1], $item["owner-link"]);
        }
@@ -449,36 +514,6 @@ class diaspora {
                return $msg;
        }
 
-       private function post_allow($importer, $contact, $is_comment = false) {
-
-               // perhaps we were already sharing with this person. Now they're sharing with us.
-               // That makes us friends.
-               // Normally this should have handled by getting a request - but this could get lost
-               if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
-                       q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
-                               intval(CONTACT_IS_FRIEND),
-                               intval($contact["id"]),
-                               intval($importer["uid"])
-                       );
-                       $contact["rel"] = CONTACT_IS_FRIEND;
-                       logger("defining user ".$contact["nick"]." as friend");
-               }
-
-               if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
-                       return false;
-               if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
-                       return true;
-               if($contact["rel"] == CONTACT_IS_FOLLOWER)
-                       if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
-                               return true;
-
-               // Messages for the global users are always accepted
-               if ($importer["uid"] == 0)
-                       return true;
-
-               return false;
-       }
-
        private function fetch_parent_item($uid, $guid, $author, $contact) {
                $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
                                `author-name`, `author-link`, `author-avatar`,
@@ -554,7 +589,16 @@ class diaspora {
        }
 
        private function import_account_deletion($importer, $data) {
-               // Not supported by now. We are waiting for sample data
+               $author = notags(unxmlify($data->author));
+
+               $contact = self::get_contact_by_handle($importer["uid"], $author);
+               if (!$contact) {
+                       logger("cannot find contact for author: ".$author);
+                       return false;
+               }
+
+               // We now remove the contact
+               contact_remove($contact["id"]);
                return true;
        }
 
@@ -564,25 +608,12 @@ class diaspora {
                $text = unxmlify($data->text);
                $author = notags(unxmlify($data->author));
 
-               $contact = self::get_contact_by_handle($importer["uid"], $sender);
-               if (!$contact) {
-                       logger("cannot find contact for sender: ".$sender);
-                       return false;
-               }
-
-               if (!self::post_allow($importer,$contact, true)) {
-                       logger("Ignoring the author ".$sender);
+               $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
+               if (!$contact)
                        return false;
-               }
 
-               $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
-                       intval($importer["uid"]),
-                       dbesc($guid)
-               );
-               if(count($r)) {
-                       logger("The comment already exists: ".$guid);
+               if (self::message_exists($importer["uid"], $guid))
                        return false;
-               }
 
                $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
                if (!$parent_item)
@@ -647,6 +678,162 @@ class diaspora {
        }
 
        private function import_conversation($importer, $data) {
+               print_r($data);
+               die();
+/*
+        $guid = notags(unxmlify($xml->guid));
+        $subject = notags(unxmlify($xml->subject));
+        $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
+        $participant_handles = notags(unxmlify($xml->participant_handles));
+        $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
+
+        $parent_uri = $diaspora_handle . ':' . $guid;
+
+        $messages = $xml->message;
+
+        if(! count($messages)) {
+                logger('empty conversation');
+                return;
+        }
+
+               $contact = self::get_allowed_contact_by_handle($importer, $sender, true)
+               if (!$contact)
+                       return false;
+
+        $conversation = null;
+
+        $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
+                intval($importer['uid']),
+                dbesc($guid)
+        );
+        if(count($c))
+                $conversation = $c[0];
+        else {
+                $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
+                        intval($importer['uid']),
+                        dbesc($guid),
+                        dbesc($diaspora_handle),
+                        dbesc(datetime_convert('UTC','UTC',$created_at)),
+                        dbesc(datetime_convert()),
+                        dbesc($subject),
+                        dbesc($participant_handles)
+                );
+                if($r)
+                        $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
+                intval($importer['uid']),
+            dbesc($guid)
+        );
+            if(count($c))
+            $conversation = $c[0];
+        }
+        if(! $conversation) {
+                logger('diaspora_conversation: unable to create conversation.');
+                return;
+        }
+
+        foreach($messages as $mesg) {
+
+                $reply = 0;
+
+                $msg_guid = notags(unxmlify($mesg->guid));
+                $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
+                $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
+                $msg_author_signature = notags(unxmlify($mesg->author_signature));
+                $msg_text = unxmlify($mesg->text);
+                $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
+                $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
+                $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
+                if($msg_conversation_guid != $guid) {
+                        logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
+                        continue;
+                }
+
+                $body = diaspora2bb($msg_text);
+                $message_id = $msg_diaspora_handle . ':' . $msg_guid;
+
+                $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
+
+                $author_signature = base64_decode($msg_author_signature);
+
+                if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
+                        $person = $contact;
+                        $key = $msg['key'];
+                }
+                else {
+                        $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
+
+                        if(is_array($person) && x($person,'pubkey'))
+                                $key = $person['pubkey'];
+                        else {
+                                logger('diaspora_conversation: unable to find author details');
+                                continue;
+                        }
+                }
+
+                if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
+                        logger('diaspora_conversation: verification failed.');
+                        continue;
+                }
+
+                if($msg_parent_author_signature) {
+                        $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
+
+                        $parent_author_signature = base64_decode($msg_parent_author_signature);
+
+                        $key = $msg['key'];
+
+                        if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
+                                logger('diaspora_conversation: owner verification failed.');
+                                continue;
+                        }
+                }
+
+                $r = q("select id from mail where `uri` = '%s' limit 1",
+                        dbesc($message_id)
+                );
+                if(count($r)) {
+                        logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
+                        continue;
+                }
+
+                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']),
+                        dbesc($msg_guid),
+                        intval($conversation['id']),
+                        dbesc($person['name']),
+                        dbesc($person['photo']),
+                        dbesc($person['url']),
+                        intval($contact['id']),
+                        dbesc($subject),
+                        dbesc($body),
+                        0,
+                        0,
+                        dbesc($message_id),
+                        dbesc($parent_uri),
+                        dbesc($msg_created_at)
+                );
+
+                q("update conv set updated = '%s' where id = %d",
+                        dbesc(datetime_convert()),
+                        intval($conversation['id'])
+                );
+
+                notification(array(
+                        'type' => NOTIFY_MAIL,
+                        'notify_flags' => $importer['notify-flags'],
+                        'language' => $importer['language'],
+                        'to_name' => $importer['username'],
+                        'to_email' => $importer['email'],
+                        'uid' =>$importer['uid'],
+                        'item' => array('subject' => $subject, 'body' => $body),
+                        'source_name' => $person['name'],
+                        'source_link' => $person['url'],
+                        'source_photo' => $person['thumb'],
+                        'verb' => ACTIVITY_POST,
+                        'otype' => 'mail'
+                ));
+        }
+*/
                return true;
        }
 
@@ -688,34 +875,16 @@ EOT;
                $author = notags(unxmlify($data->author));
 
                // likes on comments aren't supported by Diaspora - only on posts
-               if ($parent_type !== "Post")
-                       return false;
-
-               // "positive" = "false" doesn't seem to be supported by Diaspora
-               if ($positive === "false") {
-                       logger("Received a like with positive set to 'false' - this shouldn't exist at all");
+               // But maybe this will be supported in the future, so we will accept it.
+               if (!in_array($parent_type, array("Post", "Comment")))
                        return false;
-               }
 
-               $contact = self::get_contact_by_handle($importer["uid"], $sender);
-               if (!$contact) {
-                       logger("cannot find contact for sender: ".$sender);
+               $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
+               if (!$contact)
                        return false;
-               }
 
-               if (!self::post_allow($importer,$contact, true)) {
-                       logger("Ignoring the author ".$sender);
+               if (self::message_exists($importer["uid"], $guid))
                        return false;
-               }
-
-               $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
-                       intval($importer["uid"]),
-                       dbesc($guid)
-               );
-               if(count($r)) {
-                       logger("The like already exists: ".$guid);
-                       return false;
-               }
 
                $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
                if (!$parent_item)
@@ -730,6 +899,13 @@ EOT;
                // Fetch the contact id - if we know this contact
                $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
 
+               // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
+               // We would accept this anyhow.
+               if ($positive === "true")
+                       $verb = ACTIVITY_LIKE;
+               else
+                       $verb = ACTIVITY_DISLIKE;
+
                $datarray = array();
 
                $datarray["uid"] = $importer["uid"];
@@ -748,7 +924,7 @@ EOT;
                $datarray["uri"] = $author.":".$guid;
 
                $datarray["type"] = "activity";
-               $datarray["verb"] = ACTIVITY_LIKE;
+               $datarray["verb"] = $verb;
                $datarray["gravity"] = GRAVITY_LIKE;
                $datarray["parent-uri"] = $parent_item["uri"];
 
@@ -787,16 +963,9 @@ EOT;
 
                $parent_uri = $author.":".$parent_guid;
 
-               $contact = self::get_contact_by_handle($importer["uid"], $author);
-               if (!$contact) {
-                       logger("cannot find contact: ".$author);
-                       return false;
-               }
-
-               if(($contact["rel"] == CONTACT_IS_FOLLOWER) || ($contact["blocked"]) || ($contact["readonly"])) {
-                       logger("Ignoring this author.");
+               $contact = self::get_allowed_contact_by_handle($importer, $author, true);
+               if (!$contact)
                        return false;
-               }
 
                $conversation = null;
 
@@ -858,14 +1027,17 @@ EOT;
        }
 
        private function import_participation($importer, $data) {
+               // I'm not sure if we can fully support this message type
                return true;
        }
 
        private function import_photo($importer, $data) {
+               // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
                return true;
        }
 
        private function import_poll_participation($importer, $data) {
+               // We don't support polls by now
                return true;
        }
 
@@ -982,7 +1154,6 @@ print_r($data);
                );
 
                if((count($r)) && (!$r[0]["hide-friends"]) && (!$contact["hidden"]) && intval(get_pconfig($importer["uid"],'system','post_newfriend'))) {
-                       require_once('include/items.php');
 
                        $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
                                intval($importer["uid"])
@@ -993,7 +1164,7 @@ print_r($data);
                        if(count($self) && $contact["rel"] == CONTACT_IS_FOLLOWER) {
 
                                $arr = array();
-                               $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
+                               $arr["uri"] = $arr["parent-uri"] = item_new_uri(App::get_hostname(), $importer["uid"]);
                                $arr["uid"] = $importer["uid"];
                                $arr["contact-id"] = $self[0]["id"];
                                $arr["wall"] = 1;
@@ -1079,7 +1250,6 @@ print_r($data);
                intval($importer["uid"])
        );
        if($g && intval($g[0]["def_gid"])) {
-               require_once('include/group.php');
                group_add_member($importer["uid"],'',$contact_record["id"],$g[0]["def_gid"]);
        }
 
@@ -1102,8 +1272,6 @@ print_r($data);
 
                // automatic friend approval
 
-               require_once('include/Photo.php');
-
                update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
 
                // technically they are sharing with us (CONTACT_IS_SHARING),
@@ -1137,186 +1305,126 @@ print_r($data);
                return true;
        }
 
-       private function import_reshare($importer, $data) {
-/*
-       $guid = notags(unxmlify($xml->guid));
-       $author = notags(unxmlify($xml->author));
+       private function get_original_item($guid, $orig_author, $author) {
 
+               // Do we already have this item?
+               $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
+                               `author-name`, `author-link`, `author-avatar`
+                               FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
+                       dbesc($guid));
 
-       if($author != $msg["author"]) {
-               logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
-               return 202;
-       }
-
-       $contact = diaspora_get_contact_by_handle($importer["uid"],$author);
-       if(! $contact)
-               return;
-
-       if(! diaspora_post_allow($importer,$contact, false)) {
-               logger('diaspora_reshare: Ignoring this author: ' . $author . ' ' . print_r($xml,true));
-               return 202;
-       }
-
-       $message_id = $author . ':' . $guid;
-       $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
-               intval($importer["uid"]),
-               dbesc($guid)
-       );
-       if(count($r)) {
-               logger('diaspora_reshare: message exists: ' . $guid);
-               return;
-       }
-
-       $orig_author = notags(unxmlify($xml->root_diaspora_id));
-       $orig_guid = notags(unxmlify($xml->root_guid));
-       $orig_url = $a->get_baseurl()."/display/".$orig_guid;
-
-       $create_original_post = false;
-
-       // Do we already have this item?
-       $r = q("SELECT `body`, `tag`, `app`, `created`, `plink`, `object`, `object-type`, `uri` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT 
-`deleted` AND `body` != '' LIMIT 1",
-               dbesc($orig_guid),
-               dbesc(NETWORK_DIASPORA)
-       );
-       if(count($r)) {
-               logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
-
-               // Maybe it is already a reshared item?
-               // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
-               require_once('include/api.php');
-               if (api_share_as_retweet($r[0]))
-                       $r = array();
-               else {
-                       $body = $r[0]["body"];
-                       $str_tags = $r[0]["tag"];
-                       $app = $r[0]["app"];
-                       $orig_created = $r[0]["created"];
-                       $orig_plink = $r[0]["plink"];
-                       $orig_uri = $r[0]["uri"];
-                       $object = $r[0]["object"];
-                       $objecttype = $r[0]["object-type"];
+               if(count($r)) {
+                       logger("reshared message ".$guid." already exists on system.");
+
+                       // Maybe it is already a reshared item?
+                       // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
+                       if (api_share_as_retweet($r[0]))
+                               $r = array();
+                       else
+                               return $r[0];
                }
-       }
 
-       if (!count($r)) {
-               $body = "";
-               $str_tags = "";
-               $app = "";
+               if (!count($r)) {
+                       $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
+                       logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
+                       $item_id = self::store_by_guid($guid, $server);
+
+                       if (!$item_id) {
+                               $server = 'https://'.substr($author,strpos($author,'@')+1);
+                               logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
+                               $item = self::store_by_guid($guid, $server);
+                       }
+                       if (!$item_id) {
+                               $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
+                               logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
+                               $item = self::store_by_guid($guid, $server);
+                       }
+                       if (!$item_id) {
+                               $server = 'http://'.substr($author,strpos($author,'@')+1);
+                               logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
+                               $item = self::store_by_guid($guid, $server);
+                       }
 
-               $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
-               logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
-               $item = diaspora_fetch_message($orig_guid, $server);
+                       if ($item_id) {
+                               $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
+                                               `author-name`, `author-link`, `author-avatar`
+                                       FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
+                                       intval($item_id));
 
-               if (!$item) {
-                       $server = 'https://'.substr($author,strpos($author,'@')+1);
-                       logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
-                       $item = diaspora_fetch_message($orig_guid, $server);
-               }
-               if (!$item) {
-                       $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
-                       logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
-                       $item = diaspora_fetch_message($orig_guid, $server);
-               }
-               if (!$item) {
-                       $server = 'http://'.substr($author,strpos($author,'@')+1);
-                       logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
-                       $item = diaspora_fetch_message($orig_guid, $server);
-               }
+                               if ($r)
+                                       return $r[0];
 
-               if ($item) {
-                       $body = $item["body"];
-                       $str_tags = $item["tag"];
-                       $app = $item["app"];
-                       $orig_created = $item["created"];
-                       $orig_author = $item["author"];
-                       $orig_guid = $item["guid"];
-                       $orig_plink = diaspora_plink($orig_author, $orig_guid);
-                       $orig_uri = $orig_author.':'.$orig_guid;
-                       $create_original_post = ($body != "");
-                       $object = $item["object"];
-                       $objecttype = $item["object-type"];
+                       }
                }
+               return false;
        }
 
-       $plink = diaspora_plink($author, $guid);
+       private function import_reshare($importer, $data) {
+               $root_author = notags(unxmlify($data->root_author));
+               $root_guid = notags(unxmlify($data->root_guid));
+               $guid = notags(unxmlify($data->guid));
+               $author = notags(unxmlify($data->author));
+               $public = notags(unxmlify($data->public));
+               $created_at = notags(unxmlify($data->created_at));
 
-       $person = find_diaspora_person_by_handle($orig_author);
+               $contact = self::get_allowed_contact_by_handle($importer, $author, false);
+               if (!$contact)
+                       return false;
+
+//             if (self::message_exists($importer["uid"], $guid))
+//                     return false;
 
-       $created = unxmlify($xml->created_at);
-       $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
+               $original_item = self::get_original_item($root_guid, $root_author, $author);
+               if (!$original_item)
+                       return false;
 
-       $datarray = array();
+               $datarray = array();
 
-       $datarray["uid"] = $importer["uid"];
-       $datarray["contact-id"] = $contact["id"];
-       $datarray["wall"] = 0;
-       $datarray["network"]  = NETWORK_DIASPORA;
-       $datarray["guid"] = $guid;
-       $datarray["uri"] = $datarray["parent-uri"] = $message_id;
-       $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert('UTC','UTC',$created);
-       $datarray["private"] = $private;
-       $datarray["parent"] = 0;
-       $datarray["plink"] = $plink;
-       $datarray["owner-name"] = $contact["name"];
-       $datarray["owner-link"] = $contact["url"];
-       $datarray["owner-avatar"] = ((x($contact,'thumb')) ? $contact["thumb"] : $contact["photo"]);
-             $prefix = share_header($person["name"], $person["url"], ((x($person,'thumb')) ? $person["thumb"] : $person["photo"]), $orig_guid, $orig_created, $orig_url);
+               $datarray["uid"] = $importer["uid"];
+               $datarray["contact-id"] = $contact["id"];
+               $datarray["network"]  = NETWORK_DIASPORA;
 
                $datarray["author-name"] = $contact["name"];
                $datarray["author-link"] = $contact["url"];
-               $datarray["author-avatar"] = $contact["thumb"];
-               $datarray["body"] = $prefix.$body."[/share]";
+               $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
 
-       $datarray["object"] = json_encode($xml);
-       $datarray["object-type"] = $objecttype;
+               $datarray["owner-name"] = $datarray["author-name"];
+               $datarray["owner-link"] = $datarray["author-link"];
+               $datarray["owner-avatar"] = $datarray["author-avatar"];
 
-       $datarray["tag"] = $str_tags;
-       $datarray["app"]  = $app;
+               $datarray["guid"] = $guid;
+               $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
 
-       // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
-       $datarray["visible"] = ((strlen($body)) ? 1 : 0);
+               $datarray["verb"] = ACTIVITY_POST;
+               $datarray["gravity"] = GRAVITY_PARENT;
 
-       // Store the original item of a reshare
-       if ($create_original_post) {
-               require_once("include/Contact.php");
+               $datarray["object"] = json_encode($data);
 
-               $datarray2 = $datarray;
+               $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
+                                       $original_item["guid"], $original_item["created"], $original_item["uri"]);
+               $datarray["body"] = $prefix.$original_item["body"]."[/share]";
 
-               $datarray2["uid"] = 0;
-               $datarray2["contact-id"] = get_contact($person["url"], 0);
-               $datarray2["guid"] = $orig_guid;
-               $datarray2["uri"] = $datarray2["parent-uri"] = $orig_uri;
-               $datarray2["changed"] = $datarray2["created"] = $datarray2["edited"] = $datarray2["commented"] = $datarray2["received"] = datetime_convert('UTC','UTC',$orig_created);
-               $datarray2["parent"] = 0;
-               $datarray2["plink"] = $orig_plink;
+               $datarray["tag"] = $original_item["tag"];
+               $datarray["app"]  = $original_item["app"];
 
-               $datarray2["author-name"] = $person["name"];
-               $datarray2["author-link"] = $person["url"];
-               $datarray2["author-avatar"] = ((x($person,'thumb')) ? $person["thumb"] : $person["photo"]);
-               $datarray2["owner-name"] = $datarray2["author-name"];
-               $datarray2["owner-link"] = $datarray2["author-link"];
-               $datarray2["owner-avatar"] = $datarray2["author-avatar"];
-               $datarray2["body"] = $body;
-               $datarray2["object"] = $object;
+               $datarray["plink"] = self::plink($author, $guid);
+               $datarray["private"] = (($public == "false") ? 1 : 0);
+               $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
 
-               DiasporaFetchGuid($datarray2);
-               $message_id = item_store($datarray2);
+               $datarray["object-type"] = $original_item["object-type"];
 
-               logger("Store original item ".$orig_guid." under message id ".$message_id);
-       }
+               self::fetch_guid($datarray);
+               //$message_id = item_store($datarray);
+               print_r($datarray);
 
-       DiasporaFetchGuid($datarray);
-       $message_id = item_store($datarray);
-*/
-               return true;
+               return $message_id;
        }
 
        private function import_retraction($importer, $data) {
                return true;
        }
 
-       private function import_status_message($importer, $data, $msg, $data2) {
+       private function import_status_message($importer, $data) {
 
                $raw_message = unxmlify($data->raw_message);
                $guid = notags(unxmlify($data->guid));
@@ -1325,58 +1433,30 @@ print_r($data);
                $created_at = notags(unxmlify($data->created_at));
                $provider_display_name = notags(unxmlify($data->provider_display_name));
 
-               foreach ($data->children() AS $name => $entry)
-                       if (count($entry->children()))
-                               if (!in_array($name, array("location", "photo", "poll")))
-                                       die("Kinder: ".$name."\n");
-/*
-               if ($data->location) {
-                       print_r($location);
-                       foreach ($data->location->children() AS $fieldname => $data)
-                               echo $fieldname." - ".$data."\n";
-                       die("Location!\n");
-               }
-*/
-/*
-               if ($data->photo) {
-                       print_r($data->photo);
-                       foreach ($data->photo->children() AS $fieldname => $data)
-                               echo $fieldname." - ".$data."\n";
-                       die("Photo!\n");
-               }
-*/
-
+               /// @todo enable support for polls
                if ($data->poll) {
-                       print_r($data2);
-                       print_r($data);
+                       foreach ($data->poll AS $poll)
+                               print_r($poll);
                        die("poll!\n");
                }
-
-
-               $contact = self::get_contact_by_handle($importer["uid"], $author);
-               if (!$contact) {
-                       logger("A Contact for handle ".$author." and user ".$importer["uid"]." was not found");
+               $contact = self::get_allowed_contact_by_handle($importer, $author, false);
+               if (!$contact)
                        return false;
-               }
 
-               if (!self::post_allow($importer, $contact, false)) {
-                       logger("Ignoring this author.");
-                       return false;
-               }
-/*
-               $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
-                       intval($importer["uid"]),
-                       dbesc($guid)
-               );
-               if(count($r)) {
-                       logger("message exists: ".$guid);
-                       return false;
-               }
-*/
-               $private = (($public == "false") ? 1 : 0);
+               //if (self::message_exists($importer["uid"], $guid))
+               //      return false;
+
+               $address = array();
+               if ($data->location)
+                       foreach ($data->location->children() AS $fieldname => $data)
+                               $address[$fieldname] = notags(unxmlify($data));
 
                $body = diaspora2bb($raw_message);
 
+               if ($data->photo)
+                       foreach ($data->photo AS $photo)
+                               $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
+
                $datarray = array();
 
                if($data->photo->remote_photo_path AND $data->photo->remote_photo_name)
@@ -1398,7 +1478,6 @@ print_r($data);
                                $str_tags .= "@[url=".$mtch[1]."[/url]";
                        }
                }
-               $plink = self::plink($author, $guid);
 
                $datarray["uid"] = $importer["uid"];
                $datarray["contact-id"] = $contact["id"];
@@ -1426,13 +1505,15 @@ print_r($data);
                if ($provider_display_name != "")
                        $datarray["app"] = $provider_display_name;
 
-               $datarray["plink"] = $plink;
-               $datarray["private"] = $private;
+               $datarray["plink"] = self::plink($author, $guid);
+               $datarray["private"] = (($public == "false") ? 1 : 0);
                $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
 
-               // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
+               if (isset($address["address"]))
+                       $datarray["location"] = $address["address"];
 
-               $datarray["visible"] = ((strlen($body)) ? 1 : 0);
+               if (isset($address["lat"]) AND isset($address["lng"]))
+                       $datarray["coord"] = $address["lat"]." ".$address["lng"];
 
                self::fetch_guid($datarray);
                //$message_id = item_store($datarray);