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);
135 //return self::import_reshare($importer, $fields);
138 return self::import_retraction($importer, $fields);
140 case "status_message":
142 //return self::import_status_message($importer, $fields, $msg, $data2);
145 logger("Unknown message type ".$type);
153 * @brief Checks if a posting is valid and fetches the data fields.
155 * This function does not only check the signature.
156 * It also does the conversion between the old and the new diaspora format.
158 * @param array $msg Array with the XML, the sender handle and the sender signature
159 * @param object $fields SimpleXML object that contains the posting when it is valid
161 * @return bool Is the posting valid?
163 private function valid_posting($msg, &$fields) {
165 $data = parse_xml_string($msg["message"], false);
167 if (!is_object($data))
170 $first_child = $data->getName();
172 // Is this the new or the old version?
173 if ($data->getName() == "XML") {
175 foreach ($data->post->children() as $child)
182 $type = $element->getName();
184 // All retractions are handled identically from now on.
185 // In the new version there will only be "retraction".
186 if (in_array($type, array("signed_retraction", "relayable_retraction")))
187 $type = "retraction";
189 $fields = new SimpleXMLElement("<".$type."/>");
193 foreach ($element->children() AS $fieldname => $entry) {
195 // Translation for the old XML structure
196 if ($fieldname == "diaspora_handle")
197 $fieldname = "author";
199 if ($fieldname == "participant_handles")
200 $fieldname = "participants";
202 if (in_array($type, array("like", "participation"))) {
203 if ($fieldname == "target_type")
204 $fieldname = "parent_type";
207 if ($fieldname == "sender_handle")
208 $fieldname = "author";
210 if ($fieldname == "recipient_handle")
211 $fieldname = "recipient";
213 if ($fieldname == "root_diaspora_id")
214 $fieldname = "root_author";
216 if ($type == "retraction") {
217 if ($fieldname == "post_guid")
218 $fieldname = "target_guid";
220 if ($fieldname == "type")
221 $fieldname = "target_type";
225 if ($fieldname == "author_signature")
226 $author_signature = base64_decode($entry);
227 elseif ($fieldname == "parent_author_signature")
228 $parent_author_signature = base64_decode($entry);
229 elseif ($fieldname != "target_author_signature") {
230 if ($signed_data != "") {
232 $signed_data_parent .= ";";
235 $signed_data .= $entry;
237 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")))
238 xml::copy($entry, $fields, $fieldname);
241 // This is something that shouldn't happen at all.
242 if (in_array($type, array("status_message", "reshare", "profile")))
243 if ($msg["author"] != $fields->author) {
244 logger("Message handle is not the same as envelope sender. Quitting this message.");
248 // Only some message types have signatures. So we quit here for the other types.
249 if (!in_array($type, array("comment", "conversation", "message", "like")))
252 // No author_signature? This is a must, so we quit.
253 if (!isset($author_signature))
256 if (isset($parent_author_signature)) {
257 $key = self::get_key($msg["author"]);
259 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
263 $key = self::get_key($fields->author);
265 return rsa_verify($signed_data, $author_signature, $key, "sha256");
268 private function get_key($handle) {
269 logger("Fetching diaspora key for: ".$handle);
271 $r = self::get_person_by_handle($handle);
278 private function get_person_by_handle($handle) {
280 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
281 dbesc(NETWORK_DIASPORA),
286 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
288 // update record occasionally so it doesn't get stale
289 $d = strtotime($person["updated"]." +00:00");
290 if ($d < strtotime("now - 14 days"))
294 if (!$person OR $update) {
295 logger("create or refresh", LOGGER_DEBUG);
296 $r = probe_url($handle, PROBE_DIASPORA);
298 // Note that Friendica contacts will return a "Diaspora person"
299 // if Diaspora connectivity is enabled on their server
300 if (count($r) AND ($r["network"] === NETWORK_DIASPORA)) {
301 self::add_fcontact($r, $update);
308 private function add_fcontact($arr, $update = false) {
309 /// @todo Remove this function from include/network.php
312 $r = q("UPDATE `fcontact` SET
325 WHERE `url` = '%s' AND `network` = '%s'",
327 dbesc($arr["photo"]),
328 dbesc($arr["request"]),
331 dbesc($arr["batch"]),
332 dbesc($arr["notify"]),
334 dbesc($arr["confirm"]),
335 dbesc($arr["alias"]),
336 dbesc($arr["pubkey"]),
337 dbesc(datetime_convert()),
339 dbesc($arr["network"])
342 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
343 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
344 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
347 dbesc($arr["photo"]),
348 dbesc($arr["request"]),
351 dbesc($arr["batch"]),
352 dbesc($arr["notify"]),
354 dbesc($arr["confirm"]),
355 dbesc($arr["network"]),
356 dbesc($arr["alias"]),
357 dbesc($arr["pubkey"]),
358 dbesc(datetime_convert())
365 private function get_contact_by_handle($uid, $handle) {
366 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
371 if ($r AND count($r))
374 $handle_parts = explode("@", $handle);
375 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
376 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
387 private function post_allow($importer, $contact, $is_comment = false) {
389 // perhaps we were already sharing with this person. Now they're sharing with us.
390 // That makes us friends.
391 // Normally this should have handled by getting a request - but this could get lost
392 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
393 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
394 intval(CONTACT_IS_FRIEND),
395 intval($contact["id"]),
396 intval($importer["uid"])
398 $contact["rel"] = CONTACT_IS_FRIEND;
399 logger("defining user ".$contact["nick"]." as friend");
402 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
404 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
406 if($contact["rel"] == CONTACT_IS_FOLLOWER)
407 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
410 // Messages for the global users are always accepted
411 if ($importer["uid"] == 0)
417 private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
418 $contact = self::get_contact_by_handle($importer["uid"], $handle);
420 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
424 if (!self::post_allow($importer, $contact, false)) {
425 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
431 private function message_exists($uid, $guid) {
432 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
438 logger("message ".$guid." already exists for user ".$uid);
445 private function fetch_guid($item) {
446 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
447 function ($match) use ($item){
448 return(self::fetch_guid_sub($match, $item));
452 private function fetch_guid_sub($match, $item) {
453 if (!self::store_by_guid($match[1], $item["author-link"]))
454 self::store_by_guid($match[1], $item["owner-link"]);
457 private function store_by_guid($guid, $server, $uid = 0) {
458 $serverparts = parse_url($server);
459 $server = $serverparts["scheme"]."://".$serverparts["host"];
461 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
463 $msg = self::fetch_message($guid, $server);
468 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
470 // Now call the dispatcher
471 return self::dispatch_public($msg);
474 private function fetch_message($guid, $server, $level = 0) {
479 // This will not work if the server is not a Diaspora server
480 $source_url = $server."/p/".$guid.".xml";
481 $x = fetch_url($source_url);
485 /// @todo - should maybe solved by the dispatcher
486 $source_xml = parse_xml_string($x, false);
488 if (!is_object($source_xml))
491 if ($source_xml->post->reshare) {
492 // Reshare of a reshare - old Diaspora version
493 return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
494 } elseif ($source_xml->getName() == "reshare") {
495 // Reshare of a reshare - new Diaspora version
496 return self::fetch_message($source_xml->root_guid, $server, ++$level);
499 // Fetch the author - for the old and the new Diaspora version
500 if ($source_xml->post->status_message->diaspora_handle)
501 $author = (string)$source_xml->post->status_message->diaspora_handle;
502 elseif ($source_xml->author)
503 $author = (string)$source_xml->author;
508 $msg = array("message" => $x, "author" => $author);
510 // We don't really need this, but until the work is unfinished we better will keep this
511 $msg["key"] = self::get_key($msg["author"]);
516 private function fetch_parent_item($uid, $guid, $author, $contact) {
517 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
518 `author-name`, `author-link`, `author-avatar`,
519 `owner-name`, `owner-link`, `owner-avatar`
520 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
521 intval($uid), dbesc($guid));
524 $result = self::store_by_guid($guid, $contact["url"], $uid);
527 $person = self::get_person_by_handle($author);
528 $result = self::store_by_guid($guid, $person["url"], $uid);
532 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
534 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
535 `author-name`, `author-link`, `author-avatar`,
536 `owner-name`, `owner-link`, `owner-avatar`
537 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
538 intval($uid), dbesc($guid));
543 logger("parent item not found: parent: ".$guid." item: ".$guid);
549 private function get_author_contact_by_url($contact, $person, $uid) {
551 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
552 dbesc(normalise_link($person["url"])), intval($uid));
555 $network = $r[0]["network"];
557 $cid = $contact["id"];
558 $network = NETWORK_DIASPORA;
561 return (array("cid" => $cid, "network" => $network));
564 public static function is_redmatrix($url) {
565 return(strstr($url, "/channel/"));
568 private function plink($addr, $guid) {
569 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
573 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
575 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
576 // So we try another way as well.
577 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
579 $r[0]["network"] = $s[0]["network"];
581 if ($r[0]["network"] == NETWORK_DFRN)
582 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
584 if (self::is_redmatrix($r[0]["url"]))
585 return $r[0]["url"]."/?f=&mid=".$guid;
587 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
590 private function import_account_deletion($importer, $data) {
591 $author = notags(unxmlify($data->author));
593 $contact = self::get_contact_by_handle($importer["uid"], $author);
595 logger("cannot find contact for author: ".$author);
599 // We now remove the contact
600 contact_remove($contact["id"]);
604 private function import_comment($importer, $sender, $data) {
605 $guid = notags(unxmlify($data->guid));
606 $parent_guid = notags(unxmlify($data->parent_guid));
607 $text = unxmlify($data->text);
608 $author = notags(unxmlify($data->author));
610 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
614 if (self::message_exists($importer["uid"], $guid))
617 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
621 $person = self::get_person_by_handle($author);
622 if (!is_array($person)) {
623 logger("unable to find author details");
627 // Fetch the contact id - if we know this contact
628 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
632 $datarray["uid"] = $importer["uid"];
633 $datarray["contact-id"] = $author_contact["cid"];
634 $datarray["network"] = $author_contact["network"];
636 $datarray["author-name"] = $person["name"];
637 $datarray["author-link"] = $person["url"];
638 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
640 $datarray["owner-name"] = $contact["name"];
641 $datarray["owner-link"] = $contact["url"];
642 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
644 $datarray["guid"] = $guid;
645 $datarray["uri"] = $author.":".$guid;
647 $datarray["type"] = "remote-comment";
648 $datarray["verb"] = ACTIVITY_POST;
649 $datarray["gravity"] = GRAVITY_COMMENT;
650 $datarray["parent-uri"] = $parent_item["uri"];
652 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
653 $datarray["object"] = json_encode($data);
655 $datarray["body"] = diaspora2bb($text);
657 self::fetch_guid($datarray);
659 $message_id = item_store($datarray);
660 // print_r($datarray);
662 // If we are the origin of the parent we store the original data and notify our followers
663 if($message_id AND $parent_item["origin"]) {
665 // Formerly we stored the signed text, the signature and the author in different fields.
666 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
667 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
669 dbesc(json_encode($data))
673 proc_run("php", "include/notifier.php", "comment-import", $message_id);
679 private function import_conversation($importer, $data) {
683 $guid = notags(unxmlify($xml->guid));
684 $subject = notags(unxmlify($xml->subject));
685 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
686 $participant_handles = notags(unxmlify($xml->participant_handles));
687 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
689 $parent_uri = $diaspora_handle . ':' . $guid;
691 $messages = $xml->message;
693 if(! count($messages)) {
694 logger('diaspora_conversation: empty conversation');
698 $contact = self::get_allowed_contact_by_handle($importer, $sender, true)
702 $conversation = null;
704 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
705 intval($importer['uid']),
709 $conversation = $c[0];
711 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
712 intval($importer['uid']),
714 dbesc($diaspora_handle),
715 dbesc(datetime_convert('UTC','UTC',$created_at)),
716 dbesc(datetime_convert()),
718 dbesc($participant_handles)
721 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
722 intval($importer['uid']),
726 $conversation = $c[0];
728 if(! $conversation) {
729 logger('diaspora_conversation: unable to create conversation.');
733 foreach($messages as $mesg) {
737 $msg_guid = notags(unxmlify($mesg->guid));
738 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
739 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
740 $msg_author_signature = notags(unxmlify($mesg->author_signature));
741 $msg_text = unxmlify($mesg->text);
742 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
743 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
744 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
745 if($msg_conversation_guid != $guid) {
746 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
750 $body = diaspora2bb($msg_text);
751 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
753 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
755 $author_signature = base64_decode($msg_author_signature);
757 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
762 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
764 if(is_array($person) && x($person,'pubkey'))
765 $key = $person['pubkey'];
767 logger('diaspora_conversation: unable to find author details');
772 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
773 logger('diaspora_conversation: verification failed.');
777 if($msg_parent_author_signature) {
778 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
780 $parent_author_signature = base64_decode($msg_parent_author_signature);
784 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
785 logger('diaspora_conversation: owner verification failed.');
790 $r = q("select id from mail where `uri` = '%s' limit 1",
794 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
798 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')",
799 intval($importer['uid']),
801 intval($conversation['id']),
802 dbesc($person['name']),
803 dbesc($person['photo']),
804 dbesc($person['url']),
805 intval($contact['id']),
812 dbesc($msg_created_at)
815 q("update conv set updated = '%s' where id = %d",
816 dbesc(datetime_convert()),
817 intval($conversation['id'])
821 'type' => NOTIFY_MAIL,
822 'notify_flags' => $importer['notify-flags'],
823 'language' => $importer['language'],
824 'to_name' => $importer['username'],
825 'to_email' => $importer['email'],
826 'uid' =>$importer['uid'],
827 'item' => array('subject' => $subject, 'body' => $body),
828 'source_name' => $person['name'],
829 'source_link' => $person['url'],
830 'source_photo' => $person['thumb'],
831 'verb' => ACTIVITY_POST,
839 private function construct_like_body($contact, $parent_item, $guid) {
840 $bodyverb = t('%1$s likes %2$s\'s %3$s');
842 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
843 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
844 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
846 return sprintf($bodyverb, $ulink, $alink, $plink);
849 private function construct_like_object($importer, $parent_item) {
850 $objtype = ACTIVITY_OBJ_NOTE;
851 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
852 $parent_body = $parent_item["body"];
857 <type>$objtype</type>
859 <id>{$parent_item["uri"]}</id>
862 <content>$parent_body</content>
869 private function import_like($importer, $sender, $data) {
870 $positive = notags(unxmlify($data->positive));
871 $guid = notags(unxmlify($data->guid));
872 $parent_type = notags(unxmlify($data->parent_type));
873 $parent_guid = notags(unxmlify($data->parent_guid));
874 $author = notags(unxmlify($data->author));
876 // likes on comments aren't supported by Diaspora - only on posts
877 if ($parent_type !== "Post")
880 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
881 if ($positive === "false") {
885 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
889 if (self::message_exists($importer["uid"], $guid))
892 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
896 $person = self::get_person_by_handle($author);
897 if (!is_array($person)) {
898 logger("unable to find author details");
902 // Fetch the contact id - if we know this contact
903 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
907 $datarray["uid"] = $importer["uid"];
908 $datarray["contact-id"] = $author_contact["cid"];
909 $datarray["network"] = $author_contact["network"];
911 $datarray["author-name"] = $person["name"];
912 $datarray["author-link"] = $person["url"];
913 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
915 $datarray["owner-name"] = $contact["name"];
916 $datarray["owner-link"] = $contact["url"];
917 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
919 $datarray["guid"] = $guid;
920 $datarray["uri"] = $author.":".$guid;
922 $datarray["type"] = "activity";
923 $datarray["verb"] = ACTIVITY_LIKE;
924 $datarray["gravity"] = GRAVITY_LIKE;
925 $datarray["parent-uri"] = $parent_item["uri"];
927 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
928 $datarray["object"] = self::construct_like_object($importer, $parent_item);
930 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
932 $message_id = item_store($datarray);
933 //print_r($datarray);
935 // If we are the origin of the parent we store the original data and notify our followers
936 if($message_id AND $parent_item["origin"]) {
938 // Formerly we stored the signed text, the signature and the author in different fields.
939 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
940 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
942 dbesc(json_encode($data))
946 proc_run("php", "include/notifier.php", "comment-import", $message_id);
952 private function import_message($importer, $data) {
953 $guid = notags(unxmlify($data->guid));
954 $parent_guid = notags(unxmlify($data->parent_guid));
955 $text = unxmlify($data->text);
956 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
957 $author = notags(unxmlify($data->author));
958 $conversation_guid = notags(unxmlify($data->conversation_guid));
960 $parent_uri = $author.":".$parent_guid;
962 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
966 $conversation = null;
968 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
969 intval($importer["uid"]),
970 dbesc($conversation_guid)
973 $conversation = $c[0];
975 logger("conversation not available.");
981 $body = diaspora2bb($text);
982 $message_id = $author.":".$guid;
984 $person = self::get_person_by_handle($author);
986 logger("unable to find author details");
990 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
992 intval($importer["uid"])
995 logger("duplicate message already delivered.", LOGGER_DEBUG);
999 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1000 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1001 intval($importer["uid"]),
1003 intval($conversation["id"]),
1004 dbesc($person["name"]),
1005 dbesc($person["photo"]),
1006 dbesc($person["url"]),
1007 intval($contact["id"]),
1008 dbesc($conversation["subject"]),
1017 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1018 dbesc(datetime_convert()),
1019 intval($conversation["id"])
1025 private function import_participation($importer, $data) {
1026 // I'm not sure if we can fully support this message type
1030 private function import_photo($importer, $data) {
1031 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1035 private function import_poll_participation($importer, $data) {
1036 // We don't support polls by now
1040 private function import_profile($importer, $data) {
1041 $author = notags(unxmlify($data->author));
1043 $contact = self::get_contact_by_handle($importer["uid"], $author);
1047 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1048 $image_url = unxmlify($data->image_url);
1049 $birthday = unxmlify($data->birthday);
1050 $location = diaspora2bb(unxmlify($data->location));
1051 $about = diaspora2bb(unxmlify($data->bio));
1052 $gender = unxmlify($data->gender);
1053 $searchable = (unxmlify($data->searchable) == "true");
1054 $nsfw = (unxmlify($data->nsfw) == "true");
1055 $tags = unxmlify($data->tag_string);
1057 $tags = explode("#", $tags);
1059 $keywords = array();
1060 foreach ($tags as $tag) {
1061 $tag = trim(strtolower($tag));
1066 $keywords = implode(", ", $keywords);
1068 $handle_parts = explode("@", $author);
1069 $nick = $handle_parts[0];
1072 $name = $handle_parts[0];
1074 if( preg_match("|^https?://|", $image_url) === 0)
1075 $image_url = "http://".$handle_parts[1].$image_url;
1077 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1079 // Generic birthday. We don't know the timezone. The year is irrelevant.
1081 $birthday = str_replace("1000", "1901", $birthday);
1083 if ($birthday != "")
1084 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1086 // this is to prevent multiple birthday notifications in a single year
1087 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1089 if(substr($birthday,5) === substr($contact["bd"],5))
1090 $birthday = $contact["bd"];
1092 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1093 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1097 dbesc(datetime_convert()),
1103 intval($contact["id"]),
1104 intval($importer["uid"])
1108 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1109 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1112 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1113 "photo" => $image_url, "name" => $name, "location" => $location,
1114 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1115 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1116 "hide" => !$searchable, "nsfw" => $nsfw);
1118 update_gcontact($gcontact);
1123 private function import_request($importer, $data) {
1126 $author = unxmlify($xml->author);
1127 $recipient = unxmlify($xml->recipient);
1129 if (!$author || !$recipient)
1132 $contact = self::get_contact_by_handle($importer["uid"],$author);
1136 // perhaps we were already sharing with this person. Now they're sharing with us.
1137 // That makes us friends.
1139 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1140 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1141 intval(CONTACT_IS_FRIEND),
1142 intval($contact["id"]),
1143 intval($importer["uid"])
1146 // send notification
1148 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1149 intval($importer["uid"])
1152 if((count($r)) && (!$r[0]["hide-friends"]) && (!$contact["hidden"]) && intval(get_pconfig($importer["uid"],'system','post_newfriend'))) {
1154 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1155 intval($importer["uid"])
1158 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1160 if(count($self) && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1163 $arr["uri"] = $arr["parent-uri"] = item_new_uri(App::get_hostname(), $importer["uid"]);
1164 $arr["uid"] = $importer["uid"];
1165 $arr["contact-id"] = $self[0]["id"];
1167 $arr["type"] = 'wall';
1168 $arr["gravity"] = 0;
1170 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1171 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1172 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1173 $arr["verb"] = ACTIVITY_FRIEND;
1174 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1176 $A = '[url=' . $self[0]["url"] . "]' . $self[0]["name"] . '[/url]';
1177 $B = '[url=' . $contact["url"] . "]' . $contact["name"] . '[/url]';
1178 $BPhoto = '[url=' . $contact["url"] . "]' . '[img]' . $contact["thumb"] . '[/img][/url]';
1179 $arr["body"] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
1181 $arr["object"] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact["name"] . '</title>'
1182 . '<id>' . $contact["url"] . '/' . $contact["name"] . '</id>';
1183 $arr["object"] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact["url"] . '" />' . "\n")
1185 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact["thumb"] . '" />' . "\n");
1186 $arr["object"] .= '</link></object>' . "\n";
1187 $arr["last-child"] = 1;
1189 $arr["allow_cid"] = $user[0]["allow_cid"];
1190 $arr["allow_gid"] = $user[0]["allow_gid"];
1191 $arr["deny_cid"] = $user[0]["deny_cid"];
1192 $arr["deny_gid"] = $user[0]["deny_gid"];
1194 $i = item_store($arr);
1196 proc_run('php',"include/notifier.php","activity","$i");
1205 $ret = self::get_person_by_handle($author);
1208 if((! count($ret)) || ($ret["network"] != NETWORK_DIASPORA)) {
1209 logger('diaspora_request: Cannot resolve diaspora handle ' . $author . ' for ' . $recipient);
1213 $batch = (($ret["batch"]) ? $ret["batch"] : implode('/', array_slice(explode('/',$ret["url"]),0,3)) . '/receive/public');
1217 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1218 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
1219 intval($importer["uid"]),
1220 dbesc($ret["network"]),
1221 dbesc($ret["addr"]),
1224 dbesc(normalise_link($ret["url"])),
1226 dbesc($ret["name"]),
1227 dbesc($ret["nick"]),
1228 dbesc($ret["photo"]),
1229 dbesc($ret["pubkey"]),
1230 dbesc($ret["notify"]),
1231 dbesc($ret["poll"]),
1236 // find the contact record we just created
1238 $contact_record = diaspora_get_contact_by_handle($importer["uid"],$author);
1240 if(! $contact_record) {
1241 logger('diaspora_request: unable to locate newly created contact record.');
1245 $g = q("select def_gid from user where uid = %d limit 1",
1246 intval($importer["uid"])
1248 if($g && intval($g[0]["def_gid"])) {
1249 group_add_member($importer["uid"],'',$contact_record["id"],$g[0]["def_gid"]);
1252 if($importer["page-flags"] == PAGE_NORMAL) {
1254 $hash = random_string() . (string) time(); // Generate a confirm_key
1256 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
1257 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
1258 intval($importer["uid"]),
1259 intval($contact_record["id"]),
1262 dbesc( t('Sharing notification from Diaspora network')),
1264 dbesc(datetime_convert())
1269 // automatic friend approval
1271 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1273 // technically they are sharing with us (CONTACT_IS_SHARING),
1274 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1275 // we are going to change the relationship and make them a follower.
1277 if($importer["page-flags"] == PAGE_FREELOVE)
1278 $new_relation = CONTACT_IS_FRIEND;
1280 $new_relation = CONTACT_IS_FOLLOWER;
1282 $r = q("UPDATE `contact` SET `rel` = %d,
1290 intval($new_relation),
1291 dbesc(datetime_convert()),
1292 dbesc(datetime_convert()),
1293 intval($contact_record["id"])
1296 $u = q("select * from user where uid = %d limit 1",intval($importer["uid"]));
1298 $ret = diaspora_share($u[0],$contact_record);
1304 private function get_original_item($guid, $orig_author, $author) {
1306 // Do we already have this item?
1307 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1308 `author-name`, `author-link`, `author-avatar`
1309 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1313 logger("reshared message ".$guid." already exists on system.");
1315 // Maybe it is already a reshared item?
1316 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1317 if (api_share_as_retweet($r[0]))
1324 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1325 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1326 $item_id = self::store_by_guid($guid, $server);
1329 $server = 'https://'.substr($author,strpos($author,'@')+1);
1330 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1331 $item = self::store_by_guid($guid, $server);
1334 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1335 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1336 $item = self::store_by_guid($guid, $server);
1339 $server = 'http://'.substr($author,strpos($author,'@')+1);
1340 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1341 $item = self::store_by_guid($guid, $server);
1345 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1346 `author-name`, `author-link`, `author-avatar`
1347 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1358 private function import_reshare($importer, $data) {
1359 $root_author = notags(unxmlify($data->root_author));
1360 $root_guid = notags(unxmlify($data->root_guid));
1361 $guid = notags(unxmlify($data->guid));
1362 $author = notags(unxmlify($data->author));
1363 $public = notags(unxmlify($data->public));
1364 $created_at = notags(unxmlify($data->created_at));
1366 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1370 // if (self::message_exists($importer["uid"], $guid))
1373 $original_item = self::get_original_item($root_guid, $root_author, $author);
1374 if (!$original_item)
1377 $datarray = array();
1379 $datarray["uid"] = $importer["uid"];
1380 $datarray["contact-id"] = $contact["id"];
1381 $datarray["network"] = NETWORK_DIASPORA;
1383 $datarray["author-name"] = $contact["name"];
1384 $datarray["author-link"] = $contact["url"];
1385 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1387 $datarray["owner-name"] = $datarray["author-name"];
1388 $datarray["owner-link"] = $datarray["author-link"];
1389 $datarray["owner-avatar"] = $datarray["author-avatar"];
1391 $datarray["guid"] = $guid;
1392 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1394 $datarray["verb"] = ACTIVITY_POST;
1395 $datarray["gravity"] = GRAVITY_PARENT;
1397 $datarray["object"] = json_encode($data);
1399 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1400 $original_item["guid"], $original_item["created"], $original_item["uri"]);
1401 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1403 $datarray["tag"] = $original_item["tag"];
1404 $datarray["app"] = $original_item["app"];
1406 $datarray["plink"] = self::plink($author, $guid);
1407 $datarray["private"] = (($public == "false") ? 1 : 0);
1408 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1410 $datarray["object-type"] = $original_item["object-type"];
1412 self::fetch_guid($datarray);
1413 //$message_id = item_store($datarray);
1419 private function import_retraction($importer, $data) {
1423 private function import_status_message($importer, $data) {
1425 $raw_message = unxmlify($data->raw_message);
1426 $guid = notags(unxmlify($data->guid));
1427 $author = notags(unxmlify($data->author));
1428 $public = notags(unxmlify($data->public));
1429 $created_at = notags(unxmlify($data->created_at));
1430 $provider_display_name = notags(unxmlify($data->provider_display_name));
1432 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1436 if (self::message_exists($importer["uid"], $guid))
1439 /// @todo enable support for polls
1440 // if ($data->poll) {
1441 // print_r($data->poll);
1446 if ($data->location)
1447 foreach ($data->location->children() AS $fieldname => $data)
1448 $address[$fieldname] = notags(unxmlify($data));
1450 $body = diaspora2bb($raw_message);
1453 for ($i = 0; $i < count($data->photo); $i++)
1454 $body = "[img]".$data->photo[$i]->remote_photo_path.$data->photo[$i]->remote_photo_name."[/img]\n".$body;
1456 $datarray = array();
1458 if($data->photo->remote_photo_path AND $data->photo->remote_photo_name)
1459 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1461 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1462 // Add OEmbed and other information to the body
1463 if (!self::is_redmatrix($contact["url"]))
1464 $body = add_page_info_to_body($body, false, true);
1469 $cnt = preg_match_all("/@\[url=(.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1471 foreach($matches as $mtch) {
1472 if(strlen($str_tags))
1474 $str_tags .= "@[url=".$mtch[1]."[/url]";
1478 $datarray["uid"] = $importer["uid"];
1479 $datarray["contact-id"] = $contact["id"];
1480 $datarray["network"] = NETWORK_DIASPORA;
1482 $datarray["author-name"] = $contact["name"];
1483 $datarray["author-link"] = $contact["url"];
1484 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1486 $datarray["owner-name"] = $datarray["author-name"];
1487 $datarray["owner-link"] = $datarray["author-link"];
1488 $datarray["owner-avatar"] = $datarray["author-avatar"];
1490 $datarray["guid"] = $guid;
1491 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1493 $datarray["verb"] = ACTIVITY_POST;
1494 $datarray["gravity"] = GRAVITY_PARENT;
1496 $datarray["object"] = json_encode($data);
1498 $datarray["body"] = $body;
1500 $datarray["tag"] = $str_tags;
1501 if ($provider_display_name != "")
1502 $datarray["app"] = $provider_display_name;
1504 $datarray["plink"] = self::plink($author, $guid);
1505 $datarray["private"] = (($public == "false") ? 1 : 0);
1506 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1508 if (isset($address["address"]))
1509 $datarray["location"] = $address["address"];
1511 if (isset($address["lat"]) AND isset($address["lng"]))
1512 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1514 self::fetch_guid($datarray);
1515 //$message_id = item_store($datarray);
1518 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);