3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
7 require_once("include/items.php");
8 require_once("include/bb2diaspora.php");
9 require_once("include/Scrape.php");
10 require_once("include/Contact.php");
11 require_once("include/Photo.php");
12 require_once("include/socgraph.php");
13 require_once("include/group.php");
14 require_once("include/api.php");
17 function from_array($array, &$xml) {
19 if (!is_object($xml)) {
20 foreach($array as $key => $value) {
21 $root = new SimpleXMLElement('<'.$key.'/>');
22 array_to_xml($value, $root);
24 $dom = dom_import_simplexml($root)->ownerDocument;
25 $dom->formatOutput = true;
26 return $dom->saveXML();
30 foreach($array as $key => $value) {
31 if (!is_array($value) AND !is_numeric($key))
32 $xml->addChild($key, $value);
33 elseif (is_array($value))
34 array_to_xml($value, $xml->addChild($key));
38 function copy(&$source, &$target, $elementname) {
39 if (count($source->children()) == 0)
40 $target->addChild($elementname, $source);
42 $child = $target->addChild($elementname);
43 foreach ($source->children() AS $childfield => $childentry)
44 self::copy($childentry, $child, $childfield);
49 * @brief This class contain functions to create and send Diaspora XML files
54 public static function dispatch_public($msg) {
56 $enabled = intval(get_config("system", "diaspora_enabled"));
58 logger("diaspora is disabled");
62 // Use a dummy importer to import the data for the public copy
63 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
64 $item_id = self::dispatch($importer,$msg);
66 // Now distribute it to the followers
67 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
68 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
69 AND NOT `account_expired` AND NOT `account_removed`",
70 dbesc(NETWORK_DIASPORA),
75 logger("delivering to: ".$rr["username"]);
76 self::dispatch($rr,$msg);
79 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
84 public static function dispatch($importer, $msg) {
86 // The sender is the handle of the contact that sent the message.
87 // This will often be different with relayed messages (for example "like" and "comment")
88 $sender = $msg["author"];
90 if (!diaspora::valid_posting($msg, $fields)) {
91 logger("Invalid posting");
95 $type = $fields->getName();
98 case "account_deletion": // Done
100 //return self::import_account_deletion($importer, $fields);
102 case "comment": // Done
104 //return self::import_comment($importer, $sender, $fields);
108 //return self::import_conversation($importer, $fields);
112 //return self::import_like($importer, $sender, $fields);
114 case "message": // Done
116 //return self::import_message($importer, $fields);
118 case "participation": // Not implemented
119 return self::import_participation($importer, $fields);
121 case "photo": // Not needed
122 return self::import_photo($importer, $fields);
124 case "poll_participation": // Not implemented
125 return self::import_poll_participation($importer, $fields);
127 case "profile": // Done
129 //return self::import_profile($importer, $fields);
132 return self::import_request($importer, $fields);
134 case "reshare": // Done
136 //return self::import_reshare($importer, $fields);
139 return self::import_retraction($importer, $fields);
141 case "status_message": // Done
143 //return self::import_status_message($importer, $fields);
146 logger("Unknown message type ".$type);
154 * @brief Checks if a posting is valid and fetches the data fields.
156 * This function does not only check the signature.
157 * It also does the conversion between the old and the new diaspora format.
159 * @param array $msg Array with the XML, the sender handle and the sender signature
160 * @param object $fields SimpleXML object that contains the posting when it is valid
162 * @return bool Is the posting valid?
164 private function valid_posting($msg, &$fields) {
166 $data = parse_xml_string($msg["message"], false);
168 if (!is_object($data))
171 $first_child = $data->getName();
173 // Is this the new or the old version?
174 if ($data->getName() == "XML") {
176 foreach ($data->post->children() as $child)
183 $type = $element->getName();
185 // All retractions are handled identically from now on.
186 // In the new version there will only be "retraction".
187 if (in_array($type, array("signed_retraction", "relayable_retraction")))
188 $type = "retraction";
190 $fields = new SimpleXMLElement("<".$type."/>");
194 foreach ($element->children() AS $fieldname => $entry) {
196 // Translation for the old XML structure
197 if ($fieldname == "diaspora_handle")
198 $fieldname = "author";
200 if ($fieldname == "participant_handles")
201 $fieldname = "participants";
203 if (in_array($type, array("like", "participation"))) {
204 if ($fieldname == "target_type")
205 $fieldname = "parent_type";
208 if ($fieldname == "sender_handle")
209 $fieldname = "author";
211 if ($fieldname == "recipient_handle")
212 $fieldname = "recipient";
214 if ($fieldname == "root_diaspora_id")
215 $fieldname = "root_author";
217 if ($type == "retraction") {
218 if ($fieldname == "post_guid")
219 $fieldname = "target_guid";
221 if ($fieldname == "type")
222 $fieldname = "target_type";
226 if ($fieldname == "author_signature")
227 $author_signature = base64_decode($entry);
228 elseif ($fieldname == "parent_author_signature")
229 $parent_author_signature = base64_decode($entry);
230 elseif ($fieldname != "target_author_signature") {
231 if ($signed_data != "") {
233 $signed_data_parent .= ";";
236 $signed_data .= $entry;
238 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")))
239 xml::copy($entry, $fields, $fieldname);
242 // This is something that shouldn't happen at all.
243 if (in_array($type, array("status_message", "reshare", "profile")))
244 if ($msg["author"] != $fields->author) {
245 logger("Message handle is not the same as envelope sender. Quitting this message.");
249 // Only some message types have signatures. So we quit here for the other types.
250 if (!in_array($type, array("comment", "message", "like")))
253 // No author_signature? This is a must, so we quit.
254 if (!isset($author_signature))
257 if (isset($parent_author_signature)) {
258 $key = self::get_key($msg["author"]);
260 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
264 $key = self::get_key($fields->author);
266 return rsa_verify($signed_data, $author_signature, $key, "sha256");
269 private function get_key($handle) {
270 logger("Fetching diaspora key for: ".$handle);
272 $r = self::get_person_by_handle($handle);
279 private function get_person_by_handle($handle) {
281 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
282 dbesc(NETWORK_DIASPORA),
287 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
289 // update record occasionally so it doesn't get stale
290 $d = strtotime($person["updated"]." +00:00");
291 if ($d < strtotime("now - 14 days"))
295 if (!$person OR $update) {
296 logger("create or refresh", LOGGER_DEBUG);
297 $r = probe_url($handle, PROBE_DIASPORA);
299 // Note that Friendica contacts will return a "Diaspora person"
300 // if Diaspora connectivity is enabled on their server
301 if (count($r) AND ($r["network"] === NETWORK_DIASPORA)) {
302 self::add_fcontact($r, $update);
309 private function add_fcontact($arr, $update = false) {
310 /// @todo Remove this function from include/network.php
313 $r = q("UPDATE `fcontact` SET
326 WHERE `url` = '%s' AND `network` = '%s'",
328 dbesc($arr["photo"]),
329 dbesc($arr["request"]),
332 dbesc($arr["batch"]),
333 dbesc($arr["notify"]),
335 dbesc($arr["confirm"]),
336 dbesc($arr["alias"]),
337 dbesc($arr["pubkey"]),
338 dbesc(datetime_convert()),
340 dbesc($arr["network"])
343 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
344 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
345 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
348 dbesc($arr["photo"]),
349 dbesc($arr["request"]),
352 dbesc($arr["batch"]),
353 dbesc($arr["notify"]),
355 dbesc($arr["confirm"]),
356 dbesc($arr["network"]),
357 dbesc($arr["alias"]),
358 dbesc($arr["pubkey"]),
359 dbesc(datetime_convert())
366 private function get_contact_by_handle($uid, $handle) {
367 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
372 if ($r AND count($r))
375 $handle_parts = explode("@", $handle);
376 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
377 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
388 private function post_allow($importer, $contact, $is_comment = false) {
390 // perhaps we were already sharing with this person. Now they're sharing with us.
391 // That makes us friends.
392 // Normally this should have handled by getting a request - but this could get lost
393 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
394 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
395 intval(CONTACT_IS_FRIEND),
396 intval($contact["id"]),
397 intval($importer["uid"])
399 $contact["rel"] = CONTACT_IS_FRIEND;
400 logger("defining user ".$contact["nick"]." as friend");
403 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
405 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
407 if($contact["rel"] == CONTACT_IS_FOLLOWER)
408 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
411 // Messages for the global users are always accepted
412 if ($importer["uid"] == 0)
418 private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
419 $contact = self::get_contact_by_handle($importer["uid"], $handle);
421 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
425 if (!self::post_allow($importer, $contact, false)) {
426 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
432 private function message_exists($uid, $guid) {
433 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
439 logger("message ".$guid." already exists for user ".$uid);
446 private function fetch_guid($item) {
447 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
448 function ($match) use ($item){
449 return(self::fetch_guid_sub($match, $item));
453 private function fetch_guid_sub($match, $item) {
454 if (!self::store_by_guid($match[1], $item["author-link"]))
455 self::store_by_guid($match[1], $item["owner-link"]);
458 private function store_by_guid($guid, $server, $uid = 0) {
459 $serverparts = parse_url($server);
460 $server = $serverparts["scheme"]."://".$serverparts["host"];
462 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
464 $msg = self::fetch_message($guid, $server);
469 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
471 // Now call the dispatcher
472 return self::dispatch_public($msg);
475 private function fetch_message($guid, $server, $level = 0) {
480 // This will not work if the server is not a Diaspora server
481 $source_url = $server."/p/".$guid.".xml";
482 $x = fetch_url($source_url);
486 /// @todo - should maybe solved by the dispatcher
487 $source_xml = parse_xml_string($x, false);
489 if (!is_object($source_xml))
492 if ($source_xml->post->reshare) {
493 // Reshare of a reshare - old Diaspora version
494 return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
495 } elseif ($source_xml->getName() == "reshare") {
496 // Reshare of a reshare - new Diaspora version
497 return self::fetch_message($source_xml->root_guid, $server, ++$level);
500 // Fetch the author - for the old and the new Diaspora version
501 if ($source_xml->post->status_message->diaspora_handle)
502 $author = (string)$source_xml->post->status_message->diaspora_handle;
503 elseif ($source_xml->author)
504 $author = (string)$source_xml->author;
509 $msg = array("message" => $x, "author" => $author);
511 // We don't really need this, but until the work is unfinished we better will keep this
512 $msg["key"] = self::get_key($msg["author"]);
517 private function fetch_parent_item($uid, $guid, $author, $contact) {
518 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
519 `author-name`, `author-link`, `author-avatar`,
520 `owner-name`, `owner-link`, `owner-avatar`
521 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
522 intval($uid), dbesc($guid));
525 $result = self::store_by_guid($guid, $contact["url"], $uid);
528 $person = self::get_person_by_handle($author);
529 $result = self::store_by_guid($guid, $person["url"], $uid);
533 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
535 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
536 `author-name`, `author-link`, `author-avatar`,
537 `owner-name`, `owner-link`, `owner-avatar`
538 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
539 intval($uid), dbesc($guid));
544 logger("parent item not found: parent: ".$guid." item: ".$guid);
550 private function get_author_contact_by_url($contact, $person, $uid) {
552 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
553 dbesc(normalise_link($person["url"])), intval($uid));
556 $network = $r[0]["network"];
558 $cid = $contact["id"];
559 $network = NETWORK_DIASPORA;
562 return (array("cid" => $cid, "network" => $network));
565 public static function is_redmatrix($url) {
566 return(strstr($url, "/channel/"));
569 private function plink($addr, $guid) {
570 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
574 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
576 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
577 // So we try another way as well.
578 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
580 $r[0]["network"] = $s[0]["network"];
582 if ($r[0]["network"] == NETWORK_DFRN)
583 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
585 if (self::is_redmatrix($r[0]["url"]))
586 return $r[0]["url"]."/?f=&mid=".$guid;
588 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
591 private function import_account_deletion($importer, $data) {
592 $author = notags(unxmlify($data->author));
594 $contact = self::get_contact_by_handle($importer["uid"], $author);
596 logger("cannot find contact for author: ".$author);
600 // We now remove the contact
601 contact_remove($contact["id"]);
605 private function import_comment($importer, $sender, $data) {
606 $guid = notags(unxmlify($data->guid));
607 $parent_guid = notags(unxmlify($data->parent_guid));
608 $text = unxmlify($data->text);
609 $author = notags(unxmlify($data->author));
611 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
615 if (self::message_exists($importer["uid"], $guid))
618 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
622 $person = self::get_person_by_handle($author);
623 if (!is_array($person)) {
624 logger("unable to find author details");
628 // Fetch the contact id - if we know this contact
629 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
633 $datarray["uid"] = $importer["uid"];
634 $datarray["contact-id"] = $author_contact["cid"];
635 $datarray["network"] = $author_contact["network"];
637 $datarray["author-name"] = $person["name"];
638 $datarray["author-link"] = $person["url"];
639 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
641 $datarray["owner-name"] = $contact["name"];
642 $datarray["owner-link"] = $contact["url"];
643 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
645 $datarray["guid"] = $guid;
646 $datarray["uri"] = $author.":".$guid;
648 $datarray["type"] = "remote-comment";
649 $datarray["verb"] = ACTIVITY_POST;
650 $datarray["gravity"] = GRAVITY_COMMENT;
651 $datarray["parent-uri"] = $parent_item["uri"];
653 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
654 $datarray["object"] = json_encode($data);
656 $datarray["body"] = diaspora2bb($text);
658 self::fetch_guid($datarray);
660 $message_id = item_store($datarray);
661 // print_r($datarray);
663 // If we are the origin of the parent we store the original data and notify our followers
664 if($message_id AND $parent_item["origin"]) {
666 // Formerly we stored the signed text, the signature and the author in different fields.
667 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
668 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
670 dbesc(json_encode($data))
674 proc_run("php", "include/notifier.php", "comment-import", $message_id);
680 private function import_conversation($importer, $data) {
684 $guid = notags(unxmlify($xml->guid));
685 $subject = notags(unxmlify($xml->subject));
686 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
687 $participant_handles = notags(unxmlify($xml->participant_handles));
688 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
690 $parent_uri = $diaspora_handle . ':' . $guid;
692 $messages = $xml->message;
694 if(! count($messages)) {
695 logger('empty conversation');
699 $contact = self::get_allowed_contact_by_handle($importer, $sender, true)
703 $conversation = null;
705 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
706 intval($importer["uid"]),
710 $conversation = $c[0];
712 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
713 intval($importer["uid"]),
715 dbesc($diaspora_handle),
716 dbesc(datetime_convert('UTC','UTC',$created_at)),
717 dbesc(datetime_convert()),
719 dbesc($participant_handles)
722 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
723 intval($importer["uid"]),
727 $conversation = $c[0];
729 if(! $conversation) {
730 logger('diaspora_conversation: unable to create conversation.');
734 foreach($messages as $mesg) {
738 $msg_guid = notags(unxmlify($mesg->guid));
739 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
740 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
741 $msg_author_signature = notags(unxmlify($mesg->author_signature));
742 $msg_text = unxmlify($mesg->text);
743 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
744 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
745 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
746 if($msg_conversation_guid != $guid) {
747 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
751 $body = diaspora2bb($msg_text);
752 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
754 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
756 $author_signature = base64_decode($msg_author_signature);
758 if(strcasecmp($msg_diaspora_handle,$msg["author"]) == 0) {
763 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
765 if(is_array($person) && x($person,'pubkey'))
766 $key = $person["pubkey"];
768 logger('diaspora_conversation: unable to find author details');
773 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
774 logger('diaspora_conversation: verification failed.');
778 if($msg_parent_author_signature) {
779 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
781 $parent_author_signature = base64_decode($msg_parent_author_signature);
785 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
786 logger('diaspora_conversation: owner verification failed.');
791 $r = q("select id from mail where `uri` = '%s' limit 1",
795 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
799 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')",
800 intval($importer["uid"]),
802 intval($conversation["id"]),
803 dbesc($person["name"]),
804 dbesc($person["photo"]),
805 dbesc($person["url"]),
806 intval($contact["id"]),
813 dbesc($msg_created_at)
816 q("update conv set updated = '%s' where id = %d",
817 dbesc(datetime_convert()),
818 intval($conversation["id"])
822 'type' => NOTIFY_MAIL,
823 'notify_flags' => $importer["notify-flags"],
824 'language' => $importer["language"],
825 'to_name' => $importer["username"],
826 'to_email' => $importer["email"],
827 'uid' =>$importer["uid"],
828 'item' => array('subject' => $subject, 'body' => $body),
829 'source_name' => $person["name"],
830 'source_link' => $person["url"],
831 'source_photo' => $person["thumb"],
832 'verb' => ACTIVITY_POST,
840 private function construct_like_body($contact, $parent_item, $guid) {
841 $bodyverb = t('%1$s likes %2$s\'s %3$s');
843 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
844 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
845 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
847 return sprintf($bodyverb, $ulink, $alink, $plink);
850 private function construct_like_object($importer, $parent_item) {
851 $objtype = ACTIVITY_OBJ_NOTE;
852 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
853 $parent_body = $parent_item["body"];
858 <type>$objtype</type>
860 <id>{$parent_item["uri"]}</id>
863 <content>$parent_body</content>
870 private function import_like($importer, $sender, $data) {
871 $positive = notags(unxmlify($data->positive));
872 $guid = notags(unxmlify($data->guid));
873 $parent_type = notags(unxmlify($data->parent_type));
874 $parent_guid = notags(unxmlify($data->parent_guid));
875 $author = notags(unxmlify($data->author));
877 // likes on comments aren't supported by Diaspora - only on posts
878 // But maybe this will be supported in the future, so we will accept it.
879 if (!in_array($parent_type, array("Post", "Comment")))
882 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
886 if (self::message_exists($importer["uid"], $guid))
889 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
893 $person = self::get_person_by_handle($author);
894 if (!is_array($person)) {
895 logger("unable to find author details");
899 // Fetch the contact id - if we know this contact
900 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
902 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
903 // We would accept this anyhow.
904 if ($positive === "true")
905 $verb = ACTIVITY_LIKE;
907 $verb = ACTIVITY_DISLIKE;
911 $datarray["uid"] = $importer["uid"];
912 $datarray["contact-id"] = $author_contact["cid"];
913 $datarray["network"] = $author_contact["network"];
915 $datarray["author-name"] = $person["name"];
916 $datarray["author-link"] = $person["url"];
917 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
919 $datarray["owner-name"] = $contact["name"];
920 $datarray["owner-link"] = $contact["url"];
921 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
923 $datarray["guid"] = $guid;
924 $datarray["uri"] = $author.":".$guid;
926 $datarray["type"] = "activity";
927 $datarray["verb"] = $verb;
928 $datarray["gravity"] = GRAVITY_LIKE;
929 $datarray["parent-uri"] = $parent_item["uri"];
931 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
932 $datarray["object"] = self::construct_like_object($importer, $parent_item);
934 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
936 $message_id = item_store($datarray);
937 //print_r($datarray);
939 // If we are the origin of the parent we store the original data and notify our followers
940 if($message_id AND $parent_item["origin"]) {
942 // Formerly we stored the signed text, the signature and the author in different fields.
943 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
944 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
946 dbesc(json_encode($data))
950 proc_run("php", "include/notifier.php", "comment-import", $message_id);
956 private function import_message($importer, $data) {
957 $guid = notags(unxmlify($data->guid));
958 $parent_guid = notags(unxmlify($data->parent_guid));
959 $text = unxmlify($data->text);
960 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
961 $author = notags(unxmlify($data->author));
962 $conversation_guid = notags(unxmlify($data->conversation_guid));
964 $parent_uri = $author.":".$parent_guid;
966 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
970 $conversation = null;
972 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
973 intval($importer["uid"]),
974 dbesc($conversation_guid)
977 $conversation = $c[0];
979 logger("conversation not available.");
985 $body = diaspora2bb($text);
986 $message_id = $author.":".$guid;
988 $person = self::get_person_by_handle($author);
990 logger("unable to find author details");
994 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
996 intval($importer["uid"])
999 logger("duplicate message already delivered.", LOGGER_DEBUG);
1003 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1004 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1005 intval($importer["uid"]),
1007 intval($conversation["id"]),
1008 dbesc($person["name"]),
1009 dbesc($person["photo"]),
1010 dbesc($person["url"]),
1011 intval($contact["id"]),
1012 dbesc($conversation["subject"]),
1021 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1022 dbesc(datetime_convert()),
1023 intval($conversation["id"])
1029 private function import_participation($importer, $data) {
1030 // I'm not sure if we can fully support this message type
1034 private function import_photo($importer, $data) {
1035 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1039 private function import_poll_participation($importer, $data) {
1040 // We don't support polls by now
1044 private function import_profile($importer, $data) {
1045 $author = notags(unxmlify($data->author));
1047 $contact = self::get_contact_by_handle($importer["uid"], $author);
1051 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1052 $image_url = unxmlify($data->image_url);
1053 $birthday = unxmlify($data->birthday);
1054 $location = diaspora2bb(unxmlify($data->location));
1055 $about = diaspora2bb(unxmlify($data->bio));
1056 $gender = unxmlify($data->gender);
1057 $searchable = (unxmlify($data->searchable) == "true");
1058 $nsfw = (unxmlify($data->nsfw) == "true");
1059 $tags = unxmlify($data->tag_string);
1061 $tags = explode("#", $tags);
1063 $keywords = array();
1064 foreach ($tags as $tag) {
1065 $tag = trim(strtolower($tag));
1070 $keywords = implode(", ", $keywords);
1072 $handle_parts = explode("@", $author);
1073 $nick = $handle_parts[0];
1076 $name = $handle_parts[0];
1078 if( preg_match("|^https?://|", $image_url) === 0)
1079 $image_url = "http://".$handle_parts[1].$image_url;
1081 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1083 // Generic birthday. We don't know the timezone. The year is irrelevant.
1085 $birthday = str_replace("1000", "1901", $birthday);
1087 if ($birthday != "")
1088 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1090 // this is to prevent multiple birthday notifications in a single year
1091 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1093 if(substr($birthday,5) === substr($contact["bd"],5))
1094 $birthday = $contact["bd"];
1096 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1097 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1101 dbesc(datetime_convert()),
1107 intval($contact["id"]),
1108 intval($importer["uid"])
1112 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1113 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1116 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1117 "photo" => $image_url, "name" => $name, "location" => $location,
1118 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1119 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1120 "hide" => !$searchable, "nsfw" => $nsfw);
1122 update_gcontact($gcontact);
1127 private function import_request($importer, $data) {
1130 $author = unxmlify($xml->author);
1131 $recipient = unxmlify($xml->recipient);
1133 if (!$author || !$recipient)
1136 $contact = self::get_contact_by_handle($importer["uid"],$author);
1140 // perhaps we were already sharing with this person. Now they're sharing with us.
1141 // That makes us friends.
1143 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1144 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1145 intval(CONTACT_IS_FRIEND),
1146 intval($contact["id"]),
1147 intval($importer["uid"])
1150 // send notification
1152 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1153 intval($importer["uid"])
1156 if((count($r)) && (!$r[0]["hide-friends"]) && (!$contact["hidden"]) && intval(get_pconfig($importer["uid"],'system','post_newfriend'))) {
1158 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1159 intval($importer["uid"])
1162 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1164 if(count($self) && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1167 $arr["uri"] = $arr["parent-uri"] = item_new_uri(App::get_hostname(), $importer["uid"]);
1168 $arr["uid"] = $importer["uid"];
1169 $arr["contact-id"] = $self[0]["id"];
1171 $arr["type"] = 'wall';
1172 $arr["gravity"] = 0;
1174 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1175 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1176 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1177 $arr["verb"] = ACTIVITY_FRIEND;
1178 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1180 $A = '[url=' . $self[0]["url"] . "]' . $self[0]["name"] . '[/url]';
1181 $B = '[url=' . $contact["url"] . "]' . $contact["name"] . '[/url]';
1182 $BPhoto = '[url=' . $contact["url"] . "]' . '[img]' . $contact["thumb"] . '[/img][/url]';
1183 $arr["body"] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
1185 $arr["object"] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact["name"] . '</title>'
1186 . '<id>' . $contact["url"] . '/' . $contact["name"] . '</id>';
1187 $arr["object"] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact["url"] . '" />' . "\n")
1189 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact["thumb"] . '" />' . "\n");
1190 $arr["object"] .= '</link></object>' . "\n";
1191 $arr["last-child"] = 1;
1193 $arr["allow_cid"] = $user[0]["allow_cid"];
1194 $arr["allow_gid"] = $user[0]["allow_gid"];
1195 $arr["deny_cid"] = $user[0]["deny_cid"];
1196 $arr["deny_gid"] = $user[0]["deny_gid"];
1198 $i = item_store($arr);
1200 proc_run('php',"include/notifier.php","activity","$i");
1209 $ret = self::get_person_by_handle($author);
1212 if((! count($ret)) || ($ret["network"] != NETWORK_DIASPORA)) {
1213 logger('diaspora_request: Cannot resolve diaspora handle ' . $author . ' for ' . $recipient);
1217 $batch = (($ret["batch"]) ? $ret["batch"] : implode('/', array_slice(explode('/',$ret["url"]),0,3)) . '/receive/public');
1221 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1222 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
1223 intval($importer["uid"]),
1224 dbesc($ret["network"]),
1225 dbesc($ret["addr"]),
1228 dbesc(normalise_link($ret["url"])),
1230 dbesc($ret["name"]),
1231 dbesc($ret["nick"]),
1232 dbesc($ret["photo"]),
1233 dbesc($ret["pubkey"]),
1234 dbesc($ret["notify"]),
1235 dbesc($ret["poll"]),
1240 // find the contact record we just created
1242 $contact_record = diaspora_get_contact_by_handle($importer["uid"],$author);
1244 if(! $contact_record) {
1245 logger('diaspora_request: unable to locate newly created contact record.');
1249 $g = q("select def_gid from user where uid = %d limit 1",
1250 intval($importer["uid"])
1252 if($g && intval($g[0]["def_gid"])) {
1253 group_add_member($importer["uid"],'',$contact_record["id"],$g[0]["def_gid"]);
1256 if($importer["page-flags"] == PAGE_NORMAL) {
1258 $hash = random_string() . (string) time(); // Generate a confirm_key
1260 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
1261 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
1262 intval($importer["uid"]),
1263 intval($contact_record["id"]),
1266 dbesc( t('Sharing notification from Diaspora network')),
1268 dbesc(datetime_convert())
1273 // automatic friend approval
1275 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1277 // technically they are sharing with us (CONTACT_IS_SHARING),
1278 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1279 // we are going to change the relationship and make them a follower.
1281 if($importer["page-flags"] == PAGE_FREELOVE)
1282 $new_relation = CONTACT_IS_FRIEND;
1284 $new_relation = CONTACT_IS_FOLLOWER;
1286 $r = q("UPDATE `contact` SET `rel` = %d,
1294 intval($new_relation),
1295 dbesc(datetime_convert()),
1296 dbesc(datetime_convert()),
1297 intval($contact_record["id"])
1300 $u = q("select * from user where uid = %d limit 1",intval($importer["uid"]));
1302 $ret = diaspora_share($u[0],$contact_record);
1308 private function get_original_item($guid, $orig_author, $author) {
1310 // Do we already have this item?
1311 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1312 `author-name`, `author-link`, `author-avatar`
1313 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1317 logger("reshared message ".$guid." already exists on system.");
1319 // Maybe it is already a reshared item?
1320 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1321 if (api_share_as_retweet($r[0]))
1328 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1329 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1330 $item_id = self::store_by_guid($guid, $server);
1333 $server = 'https://'.substr($author,strpos($author,'@')+1);
1334 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1335 $item = self::store_by_guid($guid, $server);
1338 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1339 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1340 $item = self::store_by_guid($guid, $server);
1343 $server = 'http://'.substr($author,strpos($author,'@')+1);
1344 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1345 $item = self::store_by_guid($guid, $server);
1349 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1350 `author-name`, `author-link`, `author-avatar`
1351 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1362 private function import_reshare($importer, $data) {
1363 $root_author = notags(unxmlify($data->root_author));
1364 $root_guid = notags(unxmlify($data->root_guid));
1365 $guid = notags(unxmlify($data->guid));
1366 $author = notags(unxmlify($data->author));
1367 $public = notags(unxmlify($data->public));
1368 $created_at = notags(unxmlify($data->created_at));
1370 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1374 // if (self::message_exists($importer["uid"], $guid))
1377 $original_item = self::get_original_item($root_guid, $root_author, $author);
1378 if (!$original_item)
1381 $datarray = array();
1383 $datarray["uid"] = $importer["uid"];
1384 $datarray["contact-id"] = $contact["id"];
1385 $datarray["network"] = NETWORK_DIASPORA;
1387 $datarray["author-name"] = $contact["name"];
1388 $datarray["author-link"] = $contact["url"];
1389 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1391 $datarray["owner-name"] = $datarray["author-name"];
1392 $datarray["owner-link"] = $datarray["author-link"];
1393 $datarray["owner-avatar"] = $datarray["author-avatar"];
1395 $datarray["guid"] = $guid;
1396 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1398 $datarray["verb"] = ACTIVITY_POST;
1399 $datarray["gravity"] = GRAVITY_PARENT;
1401 $datarray["object"] = json_encode($data);
1403 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1404 $original_item["guid"], $original_item["created"], $original_item["uri"]);
1405 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1407 $datarray["tag"] = $original_item["tag"];
1408 $datarray["app"] = $original_item["app"];
1410 $datarray["plink"] = self::plink($author, $guid);
1411 $datarray["private"] = (($public == "false") ? 1 : 0);
1412 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1414 $datarray["object-type"] = $original_item["object-type"];
1416 self::fetch_guid($datarray);
1417 //$message_id = item_store($datarray);
1423 private function item_retraction($importer, $contact, $data) {
1424 $target_guid = notags(unxmlify($data->target_guid));
1426 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1427 dbesc($target_guid),
1428 intval($importer["uid"])
1433 // Only delete it if the author really fits
1434 if (!link_compare($r[0]["author-link"],$contact["url"]))
1437 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
1438 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1439 dbesc(datetime_convert()),
1440 dbesc(datetime_convert()),
1443 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1445 // Now check if the retraction needs to be relayed by us
1447 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
1448 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
1449 // The only item with `parent` and `id` as the parent id is the parent item.
1450 $p = q("SELECT `origin` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
1451 intval($r[0]["parent"]),
1452 intval($r[0]["parent"])
1455 if($p[0]["origin"]) {
1457 // Formerly we stored the signed text, the signature and the author in different fields.
1458 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
1459 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1460 intval($r[0]["id"]),
1461 dbesc(json_encode($data))
1464 // the existence of parent_author_signature would have meant the parent_author or owner
1465 // is already relaying.
1466 logger("relaying retraction");
1468 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1473 private function import_retraction($importer, $data) {
1474 $target_type = notags(unxmlify($data->target_type));
1475 $author = notags(unxmlify($data->author));
1477 $contact = self::get_contact_by_handle($importer["uid"], $author);
1479 logger("cannot find contact for author: ".$author);
1483 switch ($target_type) {
1484 case "Comment": case "Like": case "StatusMessage":
1485 self::item_retraction($importer, $contact, $data);
1489 contact_remove($contact["id"]);
1493 logger("Unknown target type ".$target_type);
1498 private function import_status_message($importer, $data) {
1500 $raw_message = unxmlify($data->raw_message);
1501 $guid = notags(unxmlify($data->guid));
1502 $author = notags(unxmlify($data->author));
1503 $public = notags(unxmlify($data->public));
1504 $created_at = notags(unxmlify($data->created_at));
1505 $provider_display_name = notags(unxmlify($data->provider_display_name));
1507 /// @todo enable support for polls
1508 //if ($data->poll) {
1509 // foreach ($data->poll AS $poll)
1513 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1517 //if (self::message_exists($importer["uid"], $guid))
1521 if ($data->location)
1522 foreach ($data->location->children() AS $fieldname => $data)
1523 $address[$fieldname] = notags(unxmlify($data));
1525 $body = diaspora2bb($raw_message);
1527 $datarray = array();
1530 foreach ($data->photo AS $photo)
1531 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1533 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1535 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1537 // Add OEmbed and other information to the body
1538 if (!self::is_redmatrix($contact["url"]))
1539 $body = add_page_info_to_body($body, false, true);
1544 // This doesn't work. @todo Check if the "tag" field is filled in the "item_store" function.
1545 $cnt = preg_match_all("/@\[url=(.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1547 foreach($matches as $mtch) {
1548 if(strlen($str_tags))
1550 $str_tags .= "@[url=".$mtch[1]."[/url]";
1554 $datarray["uid"] = $importer["uid"];
1555 $datarray["contact-id"] = $contact["id"];
1556 $datarray["network"] = NETWORK_DIASPORA;
1558 $datarray["author-name"] = $contact["name"];
1559 $datarray["author-link"] = $contact["url"];
1560 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1562 $datarray["owner-name"] = $datarray["author-name"];
1563 $datarray["owner-link"] = $datarray["author-link"];
1564 $datarray["owner-avatar"] = $datarray["author-avatar"];
1566 $datarray["guid"] = $guid;
1567 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1569 $datarray["verb"] = ACTIVITY_POST;
1570 $datarray["gravity"] = GRAVITY_PARENT;
1572 $datarray["object"] = json_encode($data);
1574 $datarray["body"] = $body;
1576 $datarray["tag"] = $str_tags;
1577 if ($provider_display_name != "")
1578 $datarray["app"] = $provider_display_name;
1580 $datarray["plink"] = self::plink($author, $guid);
1581 $datarray["private"] = (($public == "false") ? 1 : 0);
1582 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1584 if (isset($address["address"]))
1585 $datarray["location"] = $address["address"];
1587 if (isset($address["lat"]) AND isset($address["lng"]))
1588 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1590 self::fetch_guid($datarray);
1591 //$message_id = item_store($datarray);
1594 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);