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":
100 //return self::import_account_deletion($importer, $fields);
104 //return self::import_comment($importer, $sender, $fields);
107 return self::import_conversation($importer, $fields);
111 //return self::import_like($importer, $sender, $fields);
115 //return self::import_message($importer, $fields);
117 case "participation": // Not implemented
118 return self::import_participation($importer, $fields);
121 return self::import_photo($importer, $fields);
123 case "poll_participation": // Not implemented
124 return self::import_poll_participation($importer, $fields);
128 //return self::import_profile($importer, $fields);
131 return self::import_request($importer, $fields);
134 return self::import_reshare($importer, $fields);
137 return self::import_retraction($importer, $fields);
139 case "status_message":
141 //return self::import_status_message($importer, $fields, $msg, $data2);
144 logger("Unknown message type ".$type);
152 * @brief Checks if a posting is valid and fetches the data fields.
154 * This function does not only check the signature.
155 * It also does the conversion between the old and the new diaspora format.
157 * @param array $msg Array with the XML, the sender handle and the sender signature
158 * @param object $fields SimpleXML object that contains the posting when it is valid
160 * @return bool Is the posting valid?
162 private function valid_posting($msg, &$fields) {
164 $data = parse_xml_string($msg["message"], false);
166 if (!is_object($data))
169 $first_child = $data->getName();
171 // Is this the new or the old version?
172 if ($data->getName() == "XML") {
174 foreach ($data->post->children() as $child)
181 $type = $element->getName();
183 // All retractions are handled identically from now on.
184 // In the new version there will only be "retraction".
185 if (in_array($type, array("signed_retraction", "relayable_retraction")))
186 $type = "retraction";
188 $fields = new SimpleXMLElement("<".$type."/>");
192 foreach ($element->children() AS $fieldname => $entry) {
194 // Translation for the old XML structure
195 if ($fieldname == "diaspora_handle")
196 $fieldname = "author";
198 if ($fieldname == "participant_handles")
199 $fieldname = "participants";
201 if (in_array($type, array("like", "participation"))) {
202 if ($fieldname == "target_type")
203 $fieldname = "parent_type";
206 if ($fieldname == "sender_handle")
207 $fieldname = "author";
209 if ($fieldname == "recipient_handle")
210 $fieldname = "recipient";
212 if ($fieldname == "root_diaspora_id")
213 $fieldname = "root_author";
215 if ($type == "retraction") {
216 if ($fieldname == "post_guid")
217 $fieldname = "target_guid";
219 if ($fieldname == "type")
220 $fieldname = "target_type";
224 if ($fieldname == "author_signature")
225 $author_signature = base64_decode($entry);
226 elseif ($fieldname == "parent_author_signature")
227 $parent_author_signature = base64_decode($entry);
228 elseif ($fieldname != "target_author_signature") {
229 if ($signed_data != "") {
231 $signed_data_parent .= ";";
234 $signed_data .= $entry;
236 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")))
237 xml::copy($entry, $fields, $fieldname);
240 // This is something that shouldn't happen at all.
241 if (in_array($type, array("status_message", "reshare", "profile")))
242 if ($msg["author"] != $fields->author) {
243 logger("Message handle is not the same as envelope sender. Quitting this message.");
247 // Only some message types have signatures. So we quit here for the other types.
248 if (!in_array($type, array("comment", "conversation", "message", "like")))
251 // No author_signature? This is a must, so we quit.
252 if (!isset($author_signature))
255 if (isset($parent_author_signature)) {
256 $key = self::get_key($msg["author"]);
258 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
262 $key = self::get_key($fields->author);
264 return rsa_verify($signed_data, $author_signature, $key, "sha256");
267 private function get_key($handle) {
268 logger("Fetching diaspora key for: ".$handle);
270 $r = self::get_person_by_handle($handle);
277 private function get_person_by_handle($handle) {
279 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
280 dbesc(NETWORK_DIASPORA),
285 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
287 // update record occasionally so it doesn't get stale
288 $d = strtotime($person["updated"]." +00:00");
289 if ($d < strtotime("now - 14 days"))
293 if (!$person OR $update) {
294 logger("create or refresh", LOGGER_DEBUG);
295 $r = probe_url($handle, PROBE_DIASPORA);
297 // Note that Friendica contacts will return a "Diaspora person"
298 // if Diaspora connectivity is enabled on their server
299 if (count($r) AND ($r["network"] === NETWORK_DIASPORA)) {
300 self::add_fcontact($r, $update);
307 private function add_fcontact($arr, $update = false) {
308 /// @todo Remove this function from include/network.php
311 $r = q("UPDATE `fcontact` SET
324 WHERE `url` = '%s' AND `network` = '%s'",
326 dbesc($arr["photo"]),
327 dbesc($arr["request"]),
330 dbesc($arr["batch"]),
331 dbesc($arr["notify"]),
333 dbesc($arr["confirm"]),
334 dbesc($arr["alias"]),
335 dbesc($arr["pubkey"]),
336 dbesc(datetime_convert()),
338 dbesc($arr["network"])
341 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
342 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
343 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
346 dbesc($arr["photo"]),
347 dbesc($arr["request"]),
350 dbesc($arr["batch"]),
351 dbesc($arr["notify"]),
353 dbesc($arr["confirm"]),
354 dbesc($arr["network"]),
355 dbesc($arr["alias"]),
356 dbesc($arr["pubkey"]),
357 dbesc(datetime_convert())
364 private function get_contact_by_handle($uid, $handle) {
365 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
370 if ($r AND count($r))
373 $handle_parts = explode("@", $handle);
374 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
375 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
386 private function post_allow($importer, $contact, $is_comment = false) {
388 // perhaps we were already sharing with this person. Now they're sharing with us.
389 // That makes us friends.
390 // Normally this should have handled by getting a request - but this could get lost
391 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
392 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
393 intval(CONTACT_IS_FRIEND),
394 intval($contact["id"]),
395 intval($importer["uid"])
397 $contact["rel"] = CONTACT_IS_FRIEND;
398 logger("defining user ".$contact["nick"]." as friend");
401 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
403 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
405 if($contact["rel"] == CONTACT_IS_FOLLOWER)
406 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
409 // Messages for the global users are always accepted
410 if ($importer["uid"] == 0)
416 private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
417 $contact = self::get_contact_by_handle($importer["uid"], $handle);
419 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
423 if (!self::post_allow($importer, $contact, false)) {
424 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
430 private function message_exists($uid, $guid) {
431 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
437 logger("message ".$guid." already exists for user ".$uid);
444 private function fetch_guid($item) {
445 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
446 function ($match) use ($item){
447 return(self::fetch_guid_sub($match, $item));
451 private function fetch_guid_sub($match, $item) {
452 if (!self::store_by_guid($match[1], $item["author-link"]))
453 self::store_by_guid($match[1], $item["owner-link"]);
456 private function store_by_guid($guid, $server, $uid = 0) {
457 $serverparts = parse_url($server);
458 $server = $serverparts["scheme"]."://".$serverparts["host"];
460 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
462 $msg = self::fetch_message($guid, $server);
467 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
469 // Now call the dispatcher
470 return self::dispatch_public($msg);
473 private function fetch_message($guid, $server, $level = 0) {
478 // This will not work if the server is not a Diaspora server
479 $source_url = $server."/p/".$guid.".xml";
480 $x = fetch_url($source_url);
484 /// @todo - should maybe solved by the dispatcher
485 $source_xml = parse_xml_string($x, false);
487 if (!is_object($source_xml))
490 if ($source_xml->post->reshare) {
491 // Reshare of a reshare - old Diaspora version
492 return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
493 } elseif ($source_xml->getName() == "reshare") {
494 // Reshare of a reshare - new Diaspora version
495 return self::fetch_message($source_xml->root_guid, $server, ++$level);
498 // Fetch the author - for the old and the new Diaspora version
499 if ($source_xml->post->status_message->diaspora_handle)
500 $author = (string)$source_xml->post->status_message->diaspora_handle;
501 elseif ($source_xml->author)
502 $author = (string)$source_xml->author;
507 $msg = array("message" => $x, "author" => $author);
509 // We don't really need this, but until the work is unfinished we better will keep this
510 $msg["key"] = self::get_key($msg["author"]);
515 private function fetch_parent_item($uid, $guid, $author, $contact) {
516 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
517 `author-name`, `author-link`, `author-avatar`,
518 `owner-name`, `owner-link`, `owner-avatar`
519 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
520 intval($uid), dbesc($guid));
523 $result = self::store_by_guid($guid, $contact["url"], $uid);
526 $person = self::get_person_by_handle($author);
527 $result = self::store_by_guid($guid, $person["url"], $uid);
531 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
533 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
534 `author-name`, `author-link`, `author-avatar`,
535 `owner-name`, `owner-link`, `owner-avatar`
536 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
537 intval($uid), dbesc($guid));
542 logger("parent item not found: parent: ".$guid." item: ".$guid);
548 private function get_author_contact_by_url($contact, $person, $uid) {
550 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
551 dbesc(normalise_link($person["url"])), intval($uid));
554 $network = $r[0]["network"];
556 $cid = $contact["id"];
557 $network = NETWORK_DIASPORA;
560 return (array("cid" => $cid, "network" => $network));
563 public static function is_redmatrix($url) {
564 return(strstr($url, "/channel/"));
567 private function plink($addr, $guid) {
568 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
572 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
574 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
575 // So we try another way as well.
576 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
578 $r[0]["network"] = $s[0]["network"];
580 if ($r[0]["network"] == NETWORK_DFRN)
581 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
583 if (self::is_redmatrix($r[0]["url"]))
584 return $r[0]["url"]."/?f=&mid=".$guid;
586 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
589 private function import_account_deletion($importer, $data) {
590 $author = notags(unxmlify($data->author));
592 $contact = self::get_contact_by_handle($importer["uid"], $author);
594 logger("cannot find contact for author: ".$author);
598 // We now remove the contact
599 contact_remove($contact["id"]);
603 private function import_comment($importer, $sender, $data) {
604 $guid = notags(unxmlify($data->guid));
605 $parent_guid = notags(unxmlify($data->parent_guid));
606 $text = unxmlify($data->text);
607 $author = notags(unxmlify($data->author));
609 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
613 if (self::message_exists($importer["uid"], $guid))
616 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
620 $person = self::get_person_by_handle($author);
621 if (!is_array($person)) {
622 logger("unable to find author details");
626 // Fetch the contact id - if we know this contact
627 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
631 $datarray["uid"] = $importer["uid"];
632 $datarray["contact-id"] = $author_contact["cid"];
633 $datarray["network"] = $author_contact["network"];
635 $datarray["author-name"] = $person["name"];
636 $datarray["author-link"] = $person["url"];
637 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
639 $datarray["owner-name"] = $contact["name"];
640 $datarray["owner-link"] = $contact["url"];
641 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
643 $datarray["guid"] = $guid;
644 $datarray["uri"] = $author.":".$guid;
646 $datarray["type"] = "remote-comment";
647 $datarray["verb"] = ACTIVITY_POST;
648 $datarray["gravity"] = GRAVITY_COMMENT;
649 $datarray["parent-uri"] = $parent_item["uri"];
651 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
652 $datarray["object"] = json_encode($data);
654 $datarray["body"] = diaspora2bb($text);
656 self::fetch_guid($datarray);
658 $message_id = item_store($datarray);
659 // print_r($datarray);
661 // If we are the origin of the parent we store the original data and notify our followers
662 if($message_id AND $parent_item["origin"]) {
664 // Formerly we stored the signed text, the signature and the author in different fields.
665 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
666 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
668 dbesc(json_encode($data))
672 proc_run("php", "include/notifier.php", "comment-import", $message_id);
678 private function import_conversation($importer, $data) {
680 $guid = notags(unxmlify($xml->guid));
681 $subject = notags(unxmlify($xml->subject));
682 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
683 $participant_handles = notags(unxmlify($xml->participant_handles));
684 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
686 $parent_uri = $diaspora_handle . ':' . $guid;
688 $messages = $xml->message;
690 if(! count($messages)) {
691 logger('diaspora_conversation: empty conversation');
695 $contact = self::get_allowed_contact_by_handle($importer, $sender, true)
699 $conversation = null;
701 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
702 intval($importer['uid']),
706 $conversation = $c[0];
708 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
709 intval($importer['uid']),
711 dbesc($diaspora_handle),
712 dbesc(datetime_convert('UTC','UTC',$created_at)),
713 dbesc(datetime_convert()),
715 dbesc($participant_handles)
718 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
719 intval($importer['uid']),
723 $conversation = $c[0];
725 if(! $conversation) {
726 logger('diaspora_conversation: unable to create conversation.');
730 foreach($messages as $mesg) {
734 $msg_guid = notags(unxmlify($mesg->guid));
735 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
736 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
737 $msg_author_signature = notags(unxmlify($mesg->author_signature));
738 $msg_text = unxmlify($mesg->text);
739 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
740 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
741 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
742 if($msg_conversation_guid != $guid) {
743 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
747 $body = diaspora2bb($msg_text);
748 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
750 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
752 $author_signature = base64_decode($msg_author_signature);
754 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
759 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
761 if(is_array($person) && x($person,'pubkey'))
762 $key = $person['pubkey'];
764 logger('diaspora_conversation: unable to find author details');
769 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
770 logger('diaspora_conversation: verification failed.');
774 if($msg_parent_author_signature) {
775 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
777 $parent_author_signature = base64_decode($msg_parent_author_signature);
781 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
782 logger('diaspora_conversation: owner verification failed.');
787 $r = q("select id from mail where `uri` = '%s' limit 1",
791 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
795 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')",
796 intval($importer['uid']),
798 intval($conversation['id']),
799 dbesc($person['name']),
800 dbesc($person['photo']),
801 dbesc($person['url']),
802 intval($contact['id']),
809 dbesc($msg_created_at)
812 q("update conv set updated = '%s' where id = %d",
813 dbesc(datetime_convert()),
814 intval($conversation['id'])
818 'type' => NOTIFY_MAIL,
819 'notify_flags' => $importer['notify-flags'],
820 'language' => $importer['language'],
821 'to_name' => $importer['username'],
822 'to_email' => $importer['email'],
823 'uid' =>$importer['uid'],
824 'item' => array('subject' => $subject, 'body' => $body),
825 'source_name' => $person['name'],
826 'source_link' => $person['url'],
827 'source_photo' => $person['thumb'],
828 'verb' => ACTIVITY_POST,
836 private function construct_like_body($contact, $parent_item, $guid) {
837 $bodyverb = t('%1$s likes %2$s\'s %3$s');
839 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
840 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
841 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
843 return sprintf($bodyverb, $ulink, $alink, $plink);
846 private function construct_like_object($importer, $parent_item) {
847 $objtype = ACTIVITY_OBJ_NOTE;
848 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
849 $parent_body = $parent_item["body"];
854 <type>$objtype</type>
856 <id>{$parent_item["uri"]}</id>
859 <content>$parent_body</content>
866 private function import_like($importer, $sender, $data) {
867 $positive = notags(unxmlify($data->positive));
868 $guid = notags(unxmlify($data->guid));
869 $parent_type = notags(unxmlify($data->parent_type));
870 $parent_guid = notags(unxmlify($data->parent_guid));
871 $author = notags(unxmlify($data->author));
873 // likes on comments aren't supported by Diaspora - only on posts
874 if ($parent_type !== "Post")
877 // "positive" = "false" doesn't seem to be supported by Diaspora
878 if ($positive === "false") {
879 logger("Received a like with positive set to 'false' - this shouldn't exist at all");
883 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
887 if (self::message_exists($importer["uid"], $guid))
890 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
894 $person = self::get_person_by_handle($author);
895 if (!is_array($person)) {
896 logger("unable to find author details");
900 // Fetch the contact id - if we know this contact
901 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
905 $datarray["uid"] = $importer["uid"];
906 $datarray["contact-id"] = $author_contact["cid"];
907 $datarray["network"] = $author_contact["network"];
909 $datarray["author-name"] = $person["name"];
910 $datarray["author-link"] = $person["url"];
911 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
913 $datarray["owner-name"] = $contact["name"];
914 $datarray["owner-link"] = $contact["url"];
915 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
917 $datarray["guid"] = $guid;
918 $datarray["uri"] = $author.":".$guid;
920 $datarray["type"] = "activity";
921 $datarray["verb"] = ACTIVITY_LIKE;
922 $datarray["gravity"] = GRAVITY_LIKE;
923 $datarray["parent-uri"] = $parent_item["uri"];
925 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
926 $datarray["object"] = self::construct_like_object($importer, $parent_item);
928 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
930 $message_id = item_store($datarray);
931 //print_r($datarray);
933 // If we are the origin of the parent we store the original data and notify our followers
934 if($message_id AND $parent_item["origin"]) {
936 // Formerly we stored the signed text, the signature and the author in different fields.
937 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
938 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
940 dbesc(json_encode($data))
944 proc_run("php", "include/notifier.php", "comment-import", $message_id);
950 private function import_message($importer, $data) {
951 $guid = notags(unxmlify($data->guid));
952 $parent_guid = notags(unxmlify($data->parent_guid));
953 $text = unxmlify($data->text);
954 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
955 $author = notags(unxmlify($data->author));
956 $conversation_guid = notags(unxmlify($data->conversation_guid));
958 $parent_uri = $author.":".$parent_guid;
960 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
964 $conversation = null;
966 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
967 intval($importer["uid"]),
968 dbesc($conversation_guid)
971 $conversation = $c[0];
973 logger("conversation not available.");
979 $body = diaspora2bb($text);
980 $message_id = $author.":".$guid;
982 $person = self::get_person_by_handle($author);
984 logger("unable to find author details");
988 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
990 intval($importer["uid"])
993 logger("duplicate message already delivered.", LOGGER_DEBUG);
997 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
998 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
999 intval($importer["uid"]),
1001 intval($conversation["id"]),
1002 dbesc($person["name"]),
1003 dbesc($person["photo"]),
1004 dbesc($person["url"]),
1005 intval($contact["id"]),
1006 dbesc($conversation["subject"]),
1015 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1016 dbesc(datetime_convert()),
1017 intval($conversation["id"])
1023 private function import_participation($importer, $data) {
1024 // I'm not sure if we can fully support this message type
1028 private function import_photo($importer, $data) {
1029 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1033 private function import_poll_participation($importer, $data) {
1034 // We don't support polls by now
1038 private function import_profile($importer, $data) {
1039 $author = notags(unxmlify($data->author));
1041 $contact = self::get_contact_by_handle($importer["uid"], $author);
1045 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1046 $image_url = unxmlify($data->image_url);
1047 $birthday = unxmlify($data->birthday);
1048 $location = diaspora2bb(unxmlify($data->location));
1049 $about = diaspora2bb(unxmlify($data->bio));
1050 $gender = unxmlify($data->gender);
1051 $searchable = (unxmlify($data->searchable) == "true");
1052 $nsfw = (unxmlify($data->nsfw) == "true");
1053 $tags = unxmlify($data->tag_string);
1055 $tags = explode("#", $tags);
1057 $keywords = array();
1058 foreach ($tags as $tag) {
1059 $tag = trim(strtolower($tag));
1064 $keywords = implode(", ", $keywords);
1066 $handle_parts = explode("@", $author);
1067 $nick = $handle_parts[0];
1070 $name = $handle_parts[0];
1072 if( preg_match("|^https?://|", $image_url) === 0)
1073 $image_url = "http://".$handle_parts[1].$image_url;
1075 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1077 // Generic birthday. We don't know the timezone. The year is irrelevant.
1079 $birthday = str_replace("1000", "1901", $birthday);
1081 if ($birthday != "")
1082 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1084 // this is to prevent multiple birthday notifications in a single year
1085 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1087 if(substr($birthday,5) === substr($contact["bd"],5))
1088 $birthday = $contact["bd"];
1090 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1091 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1095 dbesc(datetime_convert()),
1101 intval($contact["id"]),
1102 intval($importer["uid"])
1106 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1107 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1110 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1111 "photo" => $image_url, "name" => $name, "location" => $location,
1112 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1113 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1114 "hide" => !$searchable, "nsfw" => $nsfw);
1116 update_gcontact($gcontact);
1121 private function import_request($importer, $data) {
1124 $author = unxmlify($xml->author);
1125 $recipient = unxmlify($xml->recipient);
1127 if (!$author || !$recipient)
1130 $contact = self::get_contact_by_handle($importer["uid"],$author);
1134 // perhaps we were already sharing with this person. Now they're sharing with us.
1135 // That makes us friends.
1137 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1138 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1139 intval(CONTACT_IS_FRIEND),
1140 intval($contact["id"]),
1141 intval($importer["uid"])
1144 // send notification
1146 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1147 intval($importer["uid"])
1150 if((count($r)) && (!$r[0]["hide-friends"]) && (!$contact["hidden"]) && intval(get_pconfig($importer["uid"],'system','post_newfriend'))) {
1152 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1153 intval($importer["uid"])
1156 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1158 if(count($self) && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1161 $arr["uri"] = $arr["parent-uri"] = item_new_uri(App::get_hostname(), $importer["uid"]);
1162 $arr["uid"] = $importer["uid"];
1163 $arr["contact-id"] = $self[0]["id"];
1165 $arr["type"] = 'wall';
1166 $arr["gravity"] = 0;
1168 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1169 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1170 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1171 $arr["verb"] = ACTIVITY_FRIEND;
1172 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1174 $A = '[url=' . $self[0]["url"] . "]' . $self[0]["name"] . '[/url]';
1175 $B = '[url=' . $contact["url"] . "]' . $contact["name"] . '[/url]';
1176 $BPhoto = '[url=' . $contact["url"] . "]' . '[img]' . $contact["thumb"] . '[/img][/url]';
1177 $arr["body"] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
1179 $arr["object"] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact["name"] . '</title>'
1180 . '<id>' . $contact["url"] . '/' . $contact["name"] . '</id>';
1181 $arr["object"] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact["url"] . '" />' . "\n")
1183 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact["thumb"] . '" />' . "\n");
1184 $arr["object"] .= '</link></object>' . "\n";
1185 $arr["last-child"] = 1;
1187 $arr["allow_cid"] = $user[0]["allow_cid"];
1188 $arr["allow_gid"] = $user[0]["allow_gid"];
1189 $arr["deny_cid"] = $user[0]["deny_cid"];
1190 $arr["deny_gid"] = $user[0]["deny_gid"];
1192 $i = item_store($arr);
1194 proc_run('php',"include/notifier.php","activity","$i");
1203 $ret = self::get_person_by_handle($author);
1206 if((! count($ret)) || ($ret["network"] != NETWORK_DIASPORA)) {
1207 logger('diaspora_request: Cannot resolve diaspora handle ' . $author . ' for ' . $recipient);
1211 $batch = (($ret["batch"]) ? $ret["batch"] : implode('/', array_slice(explode('/',$ret["url"]),0,3)) . '/receive/public');
1215 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1216 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
1217 intval($importer["uid"]),
1218 dbesc($ret["network"]),
1219 dbesc($ret["addr"]),
1222 dbesc(normalise_link($ret["url"])),
1224 dbesc($ret["name"]),
1225 dbesc($ret["nick"]),
1226 dbesc($ret["photo"]),
1227 dbesc($ret["pubkey"]),
1228 dbesc($ret["notify"]),
1229 dbesc($ret["poll"]),
1234 // find the contact record we just created
1236 $contact_record = diaspora_get_contact_by_handle($importer["uid"],$author);
1238 if(! $contact_record) {
1239 logger('diaspora_request: unable to locate newly created contact record.');
1243 $g = q("select def_gid from user where uid = %d limit 1",
1244 intval($importer["uid"])
1246 if($g && intval($g[0]["def_gid"])) {
1247 group_add_member($importer["uid"],'',$contact_record["id"],$g[0]["def_gid"]);
1250 if($importer["page-flags"] == PAGE_NORMAL) {
1252 $hash = random_string() . (string) time(); // Generate a confirm_key
1254 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
1255 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
1256 intval($importer["uid"]),
1257 intval($contact_record["id"]),
1260 dbesc( t('Sharing notification from Diaspora network')),
1262 dbesc(datetime_convert())
1267 // automatic friend approval
1269 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1271 // technically they are sharing with us (CONTACT_IS_SHARING),
1272 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1273 // we are going to change the relationship and make them a follower.
1275 if($importer["page-flags"] == PAGE_FREELOVE)
1276 $new_relation = CONTACT_IS_FRIEND;
1278 $new_relation = CONTACT_IS_FOLLOWER;
1280 $r = q("UPDATE `contact` SET `rel` = %d,
1288 intval($new_relation),
1289 dbesc(datetime_convert()),
1290 dbesc(datetime_convert()),
1291 intval($contact_record["id"])
1294 $u = q("select * from user where uid = %d limit 1",intval($importer["uid"]));
1296 $ret = diaspora_share($u[0],$contact_record);
1302 private function get_original_item($guid, $orig_author, $author) {
1304 // Do we already have this item?
1305 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1306 `author-name`, `author-link`, `author-avatar`
1307 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1311 logger("reshared message ".$guid." already exists on system.");
1313 // Maybe it is already a reshared item?
1314 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1315 if (api_share_as_retweet($r[0]))
1322 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1323 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1324 $item_id = self::store_by_guid($guid, $server);
1327 $server = 'https://'.substr($author,strpos($author,'@')+1);
1328 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1329 $item = self::store_by_guid($guid, $server);
1332 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1333 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1334 $item = self::store_by_guid($guid, $server);
1337 $server = 'http://'.substr($author,strpos($author,'@')+1);
1338 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1339 $item = self::store_by_guid($guid, $server);
1343 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1344 `author-name`, `author-link`, `author-avatar`
1345 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1356 private function import_reshare($importer, $data) {
1357 $root_author = notags(unxmlify($data->root_author));
1358 $root_guid = notags(unxmlify($data->root_guid));
1359 $guid = notags(unxmlify($data->guid));
1360 $author = notags(unxmlify($data->author));
1361 $public = notags(unxmlify($data->public));
1362 $created_at = notags(unxmlify($data->created_at));
1364 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1368 // if (self::message_exists($importer["uid"], $guid))
1371 $original_item = self::get_original_item($root_guid, $root_author, $author);
1372 if (!$original_item)
1375 $datarray = array();
1377 $datarray["uid"] = $importer["uid"];
1378 $datarray["contact-id"] = $contact["id"];
1379 $datarray["network"] = NETWORK_DIASPORA;
1381 $datarray["author-name"] = $contact["name"];
1382 $datarray["author-link"] = $contact["url"];
1383 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1385 $datarray["owner-name"] = $datarray["author-name"];
1386 $datarray["owner-link"] = $datarray["author-link"];
1387 $datarray["owner-avatar"] = $datarray["author-avatar"];
1389 $datarray["guid"] = $guid;
1390 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1392 $datarray["verb"] = ACTIVITY_POST;
1393 $datarray["gravity"] = GRAVITY_PARENT;
1395 $datarray["object"] = json_encode($data);
1397 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1398 $original_item["guid"], $original_item["created"], $original_item["uri"]);
1399 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1401 $datarray["tag"] = $original_item["tag"];
1402 $datarray["app"] = $original_item["app"];
1404 $datarray["plink"] = self::plink($author, $guid);
1405 $datarray["private"] = (($public == "false") ? 1 : 0);
1406 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1408 $datarray["object-type"] = $original_item["object-type"];
1410 self::fetch_guid($datarray);
1411 //$message_id = item_store($datarray);
1417 private function import_retraction($importer, $data) {
1421 private function import_status_message($importer, $data) {
1423 $raw_message = unxmlify($data->raw_message);
1424 $guid = notags(unxmlify($data->guid));
1425 $author = notags(unxmlify($data->author));
1426 $public = notags(unxmlify($data->public));
1427 $created_at = notags(unxmlify($data->created_at));
1428 $provider_display_name = notags(unxmlify($data->provider_display_name));
1430 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1434 if (self::message_exists($importer["uid"], $guid))
1437 /// @todo enable support for polls
1438 // if ($data->poll) {
1439 // print_r($data->poll);
1444 if ($data->location)
1445 foreach ($data->location->children() AS $fieldname => $data)
1446 $address[$fieldname] = notags(unxmlify($data));
1448 $body = diaspora2bb($raw_message);
1451 for ($i = 0; $i < count($data->photo); $i++)
1452 $body = "[img]".$data->photo[$i]->remote_photo_path.$data->photo[$i]->remote_photo_name."[/img]\n".$body;
1454 $datarray = array();
1456 if($data->photo->remote_photo_path AND $data->photo->remote_photo_name)
1457 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1459 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1460 // Add OEmbed and other information to the body
1461 if (!self::is_redmatrix($contact["url"]))
1462 $body = add_page_info_to_body($body, false, true);
1467 $cnt = preg_match_all("/@\[url=(.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1469 foreach($matches as $mtch) {
1470 if(strlen($str_tags))
1472 $str_tags .= "@[url=".$mtch[1]."[/url]";
1476 $datarray["uid"] = $importer["uid"];
1477 $datarray["contact-id"] = $contact["id"];
1478 $datarray["network"] = NETWORK_DIASPORA;
1480 $datarray["author-name"] = $contact["name"];
1481 $datarray["author-link"] = $contact["url"];
1482 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1484 $datarray["owner-name"] = $datarray["author-name"];
1485 $datarray["owner-link"] = $datarray["author-link"];
1486 $datarray["owner-avatar"] = $datarray["author-avatar"];
1488 $datarray["guid"] = $guid;
1489 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1491 $datarray["verb"] = ACTIVITY_POST;
1492 $datarray["gravity"] = GRAVITY_PARENT;
1494 $datarray["object"] = json_encode($data);
1496 $datarray["body"] = $body;
1498 $datarray["tag"] = $str_tags;
1499 if ($provider_display_name != "")
1500 $datarray["app"] = $provider_display_name;
1502 $datarray["plink"] = self::plink($author, $guid);
1503 $datarray["private"] = (($public == "false") ? 1 : 0);
1504 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1506 if (isset($address["address"]))
1507 $datarray["location"] = $address["address"];
1509 if (isset($address["lat"]) AND isset($address["lng"]))
1510 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1512 self::fetch_guid($datarray);
1513 //$message_id = item_store($datarray);
1516 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);