3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
7 require_once("include/bb2diaspora.php");
8 require_once("include/Scrape.php");
9 require_once("include/Contact.php");
10 require_once("include/Photo.php");
11 require_once("include/socgraph.php");
14 function from_array($array, &$xml) {
16 if (!is_object($xml)) {
17 foreach($array as $key => $value) {
18 $root = new SimpleXMLElement('<'.$key.'/>');
19 array_to_xml($value, $root);
21 $dom = dom_import_simplexml($root)->ownerDocument;
22 $dom->formatOutput = true;
23 return $dom->saveXML();
27 foreach($array as $key => $value) {
28 if (!is_array($value) AND !is_numeric($key))
29 $xml->addChild($key, $value);
30 elseif (is_array($value))
31 array_to_xml($value, $xml->addChild($key));
35 function copy(&$source, &$target, $elementname) {
36 if (count($source->children()) == 0)
37 $target->addChild($elementname, $source);
39 $child = $target->addChild($elementname);
40 foreach ($source->children() AS $childfield => $childentry)
41 self::copy($childentry, $child, $childfield);
46 * @brief This class contain functions to create and send Diaspora XML files
51 public static function dispatch_public($msg) {
53 $enabled = intval(get_config("system", "diaspora_enabled"));
55 logger("diaspora is disabled");
59 // Use a dummy importer to import the data for the public copy
60 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
61 $item_id = self::dispatch($importer,$msg);
63 // Now distribute it to the followers
64 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
65 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
66 AND NOT `account_expired` AND NOT `account_removed`",
67 dbesc(NETWORK_DIASPORA),
72 logger("delivering to: ".$rr["username"]);
73 self::dispatch($rr,$msg);
76 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
81 public static function dispatch($importer, $msg) {
83 // The sender is the handle of the contact that sent the message.
84 // This will often be different with relayed messages (for example "like" and "comment")
85 $sender = $msg["author"];
87 if (!diaspora::valid_posting($msg, $fields)) {
88 logger("Invalid posting");
92 $type = $fields->getName();
95 case "account_deletion":
97 //return self::import_account_deletion($importer, $fields);
101 //return self::import_comment($importer, $sender, $fields);
104 return self::import_conversation($importer, $fields);
108 //return self::import_like($importer, $sender, $fields);
112 //return self::import_message($importer, $fields);
114 case "participation": // Not implemented
115 return self::import_participation($importer, $fields);
118 return self::import_photo($importer, $fields);
120 case "poll_participation": // Not implemented
121 return self::import_poll_participation($importer, $fields);
125 //return self::import_profile($importer, $fields);
128 return self::import_request($importer, $fields);
131 return self::import_reshare($importer, $fields);
134 return self::import_retraction($importer, $fields);
136 case "status_message":
138 //return self::import_status_message($importer, $fields, $msg, $data2);
141 logger("Unknown message type ".$type);
149 * @brief Checks if a posting is valid and fetches the data fields.
151 * This function does not only check the signature.
152 * It also does the conversion between the old and the new diaspora format.
154 * @param array $msg Array with the XML, the sender handle and the sender signature
155 * @param object $fields SimpleXML object that contains the posting when it is valid
157 * @return bool Is the posting valid?
159 private function valid_posting($msg, &$fields) {
161 $data = parse_xml_string($msg["message"], false);
163 if (!is_object($data))
166 $first_child = $data->getName();
168 // Is this the new or the old version?
169 if ($data->getName() == "XML") {
171 foreach ($data->post->children() as $child)
178 $type = $element->getName();
180 // All retractions are handled identically from now on.
181 // In the new version there will only be "retraction".
182 if (in_array($type, array("signed_retraction", "relayable_retraction")))
183 $type = "retraction";
185 $fields = new SimpleXMLElement("<".$type."/>");
189 foreach ($element->children() AS $fieldname => $entry) {
191 // Translation for the old XML structure
192 if ($fieldname == "diaspora_handle")
193 $fieldname = "author";
195 if ($fieldname == "participant_handles")
196 $fieldname = "participants";
198 if (in_array($type, array("like", "participation"))) {
199 if ($fieldname == "target_type")
200 $fieldname = "parent_type";
203 if ($fieldname == "sender_handle")
204 $fieldname = "author";
206 if ($fieldname == "recipient_handle")
207 $fieldname = "recipient";
209 if ($fieldname == "root_diaspora_id")
210 $fieldname = "root_author";
212 if ($type == "retraction") {
213 if ($fieldname == "post_guid")
214 $fieldname = "target_guid";
216 if ($fieldname == "type")
217 $fieldname = "target_type";
221 if ($fieldname == "author_signature")
222 $author_signature = base64_decode($entry);
223 elseif ($fieldname == "parent_author_signature")
224 $parent_author_signature = base64_decode($entry);
225 elseif ($fieldname != "target_author_signature") {
226 if ($signed_data != "") {
228 $signed_data_parent .= ";";
231 $signed_data .= $entry;
233 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")))
234 xml::copy($entry, $fields, $fieldname);
237 // This is something that shouldn't happen at all.
238 if (in_array($type, array("status_message", "reshare", "profile")))
239 if ($msg["author"] != $fields->author) {
240 logger("Message handle is not the same as envelope sender. Quitting this message.");
244 // Only some message types have signatures. So we quit here for the other types.
245 if (!in_array($type, array("comment", "conversation", "message", "like")))
248 // No author_signature? This is a must, so we quit.
249 if (!isset($author_signature))
252 if (isset($parent_author_signature)) {
253 $key = self::get_key($msg["author"]);
255 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
259 $key = self::get_key($fields->author);
261 return rsa_verify($signed_data, $author_signature, $key, "sha256");
264 private function get_key($handle) {
265 logger("Fetching diaspora key for: ".$handle);
267 $r = self::get_person_by_handle($handle);
274 private function get_person_by_handle($handle) {
276 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
277 dbesc(NETWORK_DIASPORA),
282 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
284 // update record occasionally so it doesn't get stale
285 $d = strtotime($person["updated"]." +00:00");
286 if ($d < strtotime("now - 14 days"))
290 if (!$person OR $update) {
291 logger("create or refresh", LOGGER_DEBUG);
292 $r = probe_url($handle, PROBE_DIASPORA);
294 // Note that Friendica contacts will return a "Diaspora person"
295 // if Diaspora connectivity is enabled on their server
296 if (count($r) AND ($r["network"] === NETWORK_DIASPORA)) {
297 self::add_fcontact($r, $update);
304 private function add_fcontact($arr, $update = false) {
305 /// @todo Remove this function from include/network.php
308 $r = q("UPDATE `fcontact` SET
321 WHERE `url` = '%s' AND `network` = '%s'",
323 dbesc($arr["photo"]),
324 dbesc($arr["request"]),
327 dbesc($arr["batch"]),
328 dbesc($arr["notify"]),
330 dbesc($arr["confirm"]),
331 dbesc($arr["alias"]),
332 dbesc($arr["pubkey"]),
333 dbesc(datetime_convert()),
335 dbesc($arr["network"])
338 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
339 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
340 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
343 dbesc($arr["photo"]),
344 dbesc($arr["request"]),
347 dbesc($arr["batch"]),
348 dbesc($arr["notify"]),
350 dbesc($arr["confirm"]),
351 dbesc($arr["network"]),
352 dbesc($arr["alias"]),
353 dbesc($arr["pubkey"]),
354 dbesc(datetime_convert())
361 private function get_contact_by_handle($uid, $handle) {
362 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
367 if ($r AND count($r))
370 $handle_parts = explode("@", $handle);
371 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
372 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
383 private function fetch_guid($item) {
384 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
385 function ($match) use ($item){
386 return(self::fetch_guid_sub($match, $item));
390 private function fetch_guid_sub($match, $item) {
393 if (!self::store_by_guid($match[1], $item["author-link"]))
394 self::store_by_guid($match[1], $item["owner-link"]);
397 private function store_by_guid($guid, $server, $uid = 0) {
398 $serverparts = parse_url($server);
399 $server = $serverparts["scheme"]."://".$serverparts["host"];
401 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
403 $msg = self::fetch_message($guid, $server);
408 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
410 // Now call the dispatcher
411 return self::dispatch_public($msg);
414 private function fetch_message($guid, $server, $level = 0) {
419 // This will not work if the server is not a Diaspora server
420 $source_url = $server."/p/".$guid.".xml";
421 $x = fetch_url($source_url);
425 /// @todo - should maybe solved by the dispatcher
426 $source_xml = parse_xml_string($x, false);
428 if (!is_object($source_xml))
431 if ($source_xml->post->reshare) {
432 // Reshare of a reshare - old Diaspora version
433 return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
434 } elseif ($source_xml->getName() == "reshare") {
435 // Reshare of a reshare - new Diaspora version
436 return self::fetch_message($source_xml->root_guid, $server, ++$level);
439 // Fetch the author - for the old and the new Diaspora version
440 if ($source_xml->post->status_message->diaspora_handle)
441 $author = (string)$source_xml->post->status_message->diaspora_handle;
442 elseif ($source_xml->author)
443 $author = (string)$source_xml->author;
448 $msg = array("message" => $x, "author" => $author);
450 // We don't really need this, but until the work is unfinished we better will keep this
451 $msg["key"] = self::get_key($msg["author"]);
456 private function post_allow($importer, $contact, $is_comment = false) {
458 // perhaps we were already sharing with this person. Now they're sharing with us.
459 // That makes us friends.
460 // Normally this should have handled by getting a request - but this could get lost
461 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
462 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
463 intval(CONTACT_IS_FRIEND),
464 intval($contact["id"]),
465 intval($importer["uid"])
467 $contact["rel"] = CONTACT_IS_FRIEND;
468 logger("defining user ".$contact["nick"]." as friend");
471 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
473 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
475 if($contact["rel"] == CONTACT_IS_FOLLOWER)
476 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
479 // Messages for the global users are always accepted
480 if ($importer["uid"] == 0)
486 private function fetch_parent_item($uid, $guid, $author, $contact) {
487 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
488 `author-name`, `author-link`, `author-avatar`,
489 `owner-name`, `owner-link`, `owner-avatar`
490 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
491 intval($uid), dbesc($guid));
494 $result = self::store_by_guid($guid, $contact["url"], $uid);
497 $person = self::get_person_by_handle($author);
498 $result = self::store_by_guid($guid, $person["url"], $uid);
502 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
504 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
505 `author-name`, `author-link`, `author-avatar`,
506 `owner-name`, `owner-link`, `owner-avatar`
507 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
508 intval($uid), dbesc($guid));
513 logger("parent item not found: parent: ".$guid." item: ".$guid);
519 private function get_author_contact_by_url($contact, $person, $uid) {
521 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
522 dbesc(normalise_link($person["url"])), intval($uid));
525 $network = $r[0]["network"];
527 $cid = $contact["id"];
528 $network = NETWORK_DIASPORA;
531 return (array("cid" => $cid, "network" => $network));
534 public static function is_redmatrix($url) {
535 return(strstr($url, "/channel/"));
538 private function plink($addr, $guid) {
539 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
543 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
545 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
546 // So we try another way as well.
547 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
549 $r[0]["network"] = $s[0]["network"];
551 if ($r[0]["network"] == NETWORK_DFRN)
552 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
554 if (self::is_redmatrix($r[0]["url"]))
555 return $r[0]["url"]."/?f=&mid=".$guid;
557 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
560 private function import_account_deletion($importer, $data) {
561 $author = notags(unxmlify($data->author));
563 $contact = self::get_contact_by_handle($importer["uid"], $author);
565 logger("cannot find contact for sender: ".$sender);
569 // We now remove the contact
570 contact_remove($contact["id"]);
574 private function import_comment($importer, $sender, $data) {
575 $guid = notags(unxmlify($data->guid));
576 $parent_guid = notags(unxmlify($data->parent_guid));
577 $text = unxmlify($data->text);
578 $author = notags(unxmlify($data->author));
580 $contact = self::get_contact_by_handle($importer["uid"], $sender);
582 logger("cannot find contact for sender: ".$sender);
586 if (!self::post_allow($importer,$contact, true)) {
587 logger("Ignoring the author ".$sender);
591 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
592 intval($importer["uid"]),
596 logger("The comment already exists: ".$guid);
600 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
604 $person = self::get_person_by_handle($author);
605 if (!is_array($person)) {
606 logger("unable to find author details");
610 // Fetch the contact id - if we know this contact
611 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
615 $datarray["uid"] = $importer["uid"];
616 $datarray["contact-id"] = $author_contact["cid"];
617 $datarray["network"] = $author_contact["network"];
619 $datarray["author-name"] = $person["name"];
620 $datarray["author-link"] = $person["url"];
621 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
623 $datarray["owner-name"] = $contact["name"];
624 $datarray["owner-link"] = $contact["url"];
625 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
627 $datarray["guid"] = $guid;
628 $datarray["uri"] = $author.":".$guid;
630 $datarray["type"] = "remote-comment";
631 $datarray["verb"] = ACTIVITY_POST;
632 $datarray["gravity"] = GRAVITY_COMMENT;
633 $datarray["parent-uri"] = $parent_item["uri"];
635 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
636 $datarray["object"] = json_encode($data);
638 $datarray["body"] = diaspora2bb($text);
640 self::fetch_guid($datarray);
642 $message_id = item_store($datarray);
643 // print_r($datarray);
645 // If we are the origin of the parent we store the original data and notify our followers
646 if($message_id AND $parent_item["origin"]) {
648 // Formerly we stored the signed text, the signature and the author in different fields.
649 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
650 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
652 dbesc(json_encode($data))
656 proc_run("php", "include/notifier.php", "comment-import", $message_id);
662 private function import_conversation($importer, $data) {
664 $guid = notags(unxmlify($xml->guid));
665 $subject = notags(unxmlify($xml->subject));
666 $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
667 $participant_handles = notags(unxmlify($xml->participant_handles));
668 $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
670 $parent_uri = $diaspora_handle . ':' . $guid;
672 $messages = $xml->message;
674 if(! count($messages)) {
675 logger('diaspora_conversation: empty conversation');
679 $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
681 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
685 if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) {
686 logger('diaspora_conversation: Ignoring this author.');
690 $conversation = null;
692 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
693 intval($importer['uid']),
697 $conversation = $c[0];
699 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
700 intval($importer['uid']),
702 dbesc($diaspora_handle),
703 dbesc(datetime_convert('UTC','UTC',$created_at)),
704 dbesc(datetime_convert()),
706 dbesc($participant_handles)
709 $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
710 intval($importer['uid']),
714 $conversation = $c[0];
716 if(! $conversation) {
717 logger('diaspora_conversation: unable to create conversation.');
721 foreach($messages as $mesg) {
725 $msg_guid = notags(unxmlify($mesg->guid));
726 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
727 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
728 $msg_author_signature = notags(unxmlify($mesg->author_signature));
729 $msg_text = unxmlify($mesg->text);
730 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
731 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
732 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
733 if($msg_conversation_guid != $guid) {
734 logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
738 $body = diaspora2bb($msg_text);
739 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
741 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
743 $author_signature = base64_decode($msg_author_signature);
745 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
750 $person = find_diaspora_person_by_handle($msg_diaspora_handle);
752 if(is_array($person) && x($person,'pubkey'))
753 $key = $person['pubkey'];
755 logger('diaspora_conversation: unable to find author details');
760 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
761 logger('diaspora_conversation: verification failed.');
765 if($msg_parent_author_signature) {
766 $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
768 $parent_author_signature = base64_decode($msg_parent_author_signature);
772 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
773 logger('diaspora_conversation: owner verification failed.');
778 $r = q("select id from mail where `uri` = '%s' limit 1",
782 logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
786 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')",
787 intval($importer['uid']),
789 intval($conversation['id']),
790 dbesc($person['name']),
791 dbesc($person['photo']),
792 dbesc($person['url']),
793 intval($contact['id']),
800 dbesc($msg_created_at)
803 q("update conv set updated = '%s' where id = %d",
804 dbesc(datetime_convert()),
805 intval($conversation['id'])
809 'type' => NOTIFY_MAIL,
810 'notify_flags' => $importer['notify-flags'],
811 'language' => $importer['language'],
812 'to_name' => $importer['username'],
813 'to_email' => $importer['email'],
814 'uid' =>$importer['uid'],
815 'item' => array('subject' => $subject, 'body' => $body),
816 'source_name' => $person['name'],
817 'source_link' => $person['url'],
818 'source_photo' => $person['thumb'],
819 'verb' => ACTIVITY_POST,
827 private function construct_like_body($contact, $parent_item, $guid) {
828 $bodyverb = t('%1$s likes %2$s\'s %3$s');
830 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
831 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
832 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
834 return sprintf($bodyverb, $ulink, $alink, $plink);
837 private function construct_like_object($importer, $parent_item) {
838 $objtype = ACTIVITY_OBJ_NOTE;
839 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
840 $parent_body = $parent_item["body"];
845 <type>$objtype</type>
847 <id>{$parent_item["uri"]}</id>
850 <content>$parent_body</content>
857 private function import_like($importer, $sender, $data) {
858 $positive = notags(unxmlify($data->positive));
859 $guid = notags(unxmlify($data->guid));
860 $parent_type = notags(unxmlify($data->parent_type));
861 $parent_guid = notags(unxmlify($data->parent_guid));
862 $author = notags(unxmlify($data->author));
864 // likes on comments aren't supported by Diaspora - only on posts
865 if ($parent_type !== "Post")
868 // "positive" = "false" doesn't seem to be supported by Diaspora
869 if ($positive === "false") {
870 logger("Received a like with positive set to 'false' - this shouldn't exist at all");
874 $contact = self::get_contact_by_handle($importer["uid"], $sender);
876 logger("cannot find contact for sender: ".$sender);
880 if (!self::post_allow($importer,$contact, true)) {
881 logger("Ignoring the author ".$sender);
885 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
886 intval($importer["uid"]),
890 logger("The like already exists: ".$guid);
894 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
898 $person = self::get_person_by_handle($author);
899 if (!is_array($person)) {
900 logger("unable to find author details");
904 // Fetch the contact id - if we know this contact
905 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
909 $datarray["uid"] = $importer["uid"];
910 $datarray["contact-id"] = $author_contact["cid"];
911 $datarray["network"] = $author_contact["network"];
913 $datarray["author-name"] = $person["name"];
914 $datarray["author-link"] = $person["url"];
915 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
917 $datarray["owner-name"] = $contact["name"];
918 $datarray["owner-link"] = $contact["url"];
919 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
921 $datarray["guid"] = $guid;
922 $datarray["uri"] = $author.":".$guid;
924 $datarray["type"] = "activity";
925 $datarray["verb"] = ACTIVITY_LIKE;
926 $datarray["gravity"] = GRAVITY_LIKE;
927 $datarray["parent-uri"] = $parent_item["uri"];
929 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
930 $datarray["object"] = self::construct_like_object($importer, $parent_item);
932 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
934 $message_id = item_store($datarray);
935 //print_r($datarray);
937 // If we are the origin of the parent we store the original data and notify our followers
938 if($message_id AND $parent_item["origin"]) {
940 // Formerly we stored the signed text, the signature and the author in different fields.
941 // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
942 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
944 dbesc(json_encode($data))
948 proc_run("php", "include/notifier.php", "comment-import", $message_id);
954 private function import_message($importer, $data) {
955 $guid = notags(unxmlify($data->guid));
956 $parent_guid = notags(unxmlify($data->parent_guid));
957 $text = unxmlify($data->text);
958 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
959 $author = notags(unxmlify($data->author));
960 $conversation_guid = notags(unxmlify($data->conversation_guid));
962 $parent_uri = $author.":".$parent_guid;
964 $contact = self::get_contact_by_handle($importer["uid"], $author);
966 logger("cannot find contact: ".$author);
970 if(($contact["rel"] == CONTACT_IS_FOLLOWER) || ($contact["blocked"]) || ($contact["readonly"])) {
971 logger("Ignoring this author.");
975 $conversation = null;
977 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
978 intval($importer["uid"]),
979 dbesc($conversation_guid)
982 $conversation = $c[0];
984 logger("conversation not available.");
990 $body = diaspora2bb($text);
991 $message_id = $author.":".$guid;
993 $person = self::get_person_by_handle($author);
995 logger("unable to find author details");
999 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1001 intval($importer["uid"])
1004 logger("duplicate message already delivered.", LOGGER_DEBUG);
1008 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1009 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1010 intval($importer["uid"]),
1012 intval($conversation["id"]),
1013 dbesc($person["name"]),
1014 dbesc($person["photo"]),
1015 dbesc($person["url"]),
1016 intval($contact["id"]),
1017 dbesc($conversation["subject"]),
1026 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1027 dbesc(datetime_convert()),
1028 intval($conversation["id"])
1034 private function import_participation($importer, $data) {
1035 // I'm not sure if we can fully support this message type
1039 private function import_photo($importer, $data) {
1040 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1044 private function import_poll_participation($importer, $data) {
1045 // We don't support polls by now
1049 private function import_profile($importer, $data) {
1050 $author = notags(unxmlify($data->author));
1052 $contact = self::get_contact_by_handle($importer["uid"], $author);
1056 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1057 $image_url = unxmlify($data->image_url);
1058 $birthday = unxmlify($data->birthday);
1059 $location = diaspora2bb(unxmlify($data->location));
1060 $about = diaspora2bb(unxmlify($data->bio));
1061 $gender = unxmlify($data->gender);
1062 $searchable = (unxmlify($data->searchable) == "true");
1063 $nsfw = (unxmlify($data->nsfw) == "true");
1064 $tags = unxmlify($data->tag_string);
1066 $tags = explode("#", $tags);
1068 $keywords = array();
1069 foreach ($tags as $tag) {
1070 $tag = trim(strtolower($tag));
1075 $keywords = implode(", ", $keywords);
1077 $handle_parts = explode("@", $author);
1078 $nick = $handle_parts[0];
1081 $name = $handle_parts[0];
1083 if( preg_match("|^https?://|", $image_url) === 0)
1084 $image_url = "http://".$handle_parts[1].$image_url;
1086 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1088 // Generic birthday. We don't know the timezone. The year is irrelevant.
1090 $birthday = str_replace("1000", "1901", $birthday);
1092 if ($birthday != "")
1093 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1095 // this is to prevent multiple birthday notifications in a single year
1096 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1098 if(substr($birthday,5) === substr($contact["bd"],5))
1099 $birthday = $contact["bd"];
1101 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1102 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1106 dbesc(datetime_convert()),
1112 intval($contact["id"]),
1113 intval($importer["uid"])
1117 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1118 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1121 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1122 "photo" => $image_url, "name" => $name, "location" => $location,
1123 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1124 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1125 "hide" => !$searchable, "nsfw" => $nsfw);
1127 update_gcontact($gcontact);
1132 private function import_request($importer, $data) {
1135 $author = unxmlify($xml->author);
1136 $recipient = unxmlify($xml->recipient);
1138 if (!$author || !$recipient)
1141 $contact = self::get_contact_by_handle($importer["uid"],$author);
1145 // perhaps we were already sharing with this person. Now they're sharing with us.
1146 // That makes us friends.
1148 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1149 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1150 intval(CONTACT_IS_FRIEND),
1151 intval($contact["id"]),
1152 intval($importer["uid"])
1155 // send notification
1157 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1158 intval($importer["uid"])
1161 if((count($r)) && (!$r[0]["hide-friends"]) && (!$contact["hidden"]) && intval(get_pconfig($importer["uid"],'system','post_newfriend'))) {
1162 require_once('include/items.php');
1164 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1165 intval($importer["uid"])
1168 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1170 if(count($self) && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1173 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1174 $arr["uid"] = $importer["uid"];
1175 $arr["contact-id"] = $self[0]["id"];
1177 $arr["type"] = 'wall';
1178 $arr["gravity"] = 0;
1180 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1181 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1182 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1183 $arr["verb"] = ACTIVITY_FRIEND;
1184 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1186 $A = '[url=' . $self[0]["url"] . "]' . $self[0]["name"] . '[/url]';
1187 $B = '[url=' . $contact["url"] . "]' . $contact["name"] . '[/url]';
1188 $BPhoto = '[url=' . $contact["url"] . "]' . '[img]' . $contact["thumb"] . '[/img][/url]';
1189 $arr["body"] = sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
1191 $arr["object"] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact["name"] . '</title>'
1192 . '<id>' . $contact["url"] . '/' . $contact["name"] . '</id>';
1193 $arr["object"] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact["url"] . '" />' . "\n")
1195 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact["thumb"] . '" />' . "\n");
1196 $arr["object"] .= '</link></object>' . "\n";
1197 $arr["last-child"] = 1;
1199 $arr["allow_cid"] = $user[0]["allow_cid"];
1200 $arr["allow_gid"] = $user[0]["allow_gid"];
1201 $arr["deny_cid"] = $user[0]["deny_cid"];
1202 $arr["deny_gid"] = $user[0]["deny_gid"];
1204 $i = item_store($arr);
1206 proc_run('php',"include/notifier.php","activity","$i");
1215 $ret = self::get_person_by_handle($author);
1218 if((! count($ret)) || ($ret["network"] != NETWORK_DIASPORA)) {
1219 logger('diaspora_request: Cannot resolve diaspora handle ' . $author . ' for ' . $recipient);
1223 $batch = (($ret["batch"]) ? $ret["batch"] : implode('/', array_slice(explode('/',$ret["url"]),0,3)) . '/receive/public');
1227 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1228 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
1229 intval($importer["uid"]),
1230 dbesc($ret["network"]),
1231 dbesc($ret["addr"]),
1234 dbesc(normalise_link($ret["url"])),
1236 dbesc($ret["name"]),
1237 dbesc($ret["nick"]),
1238 dbesc($ret["photo"]),
1239 dbesc($ret["pubkey"]),
1240 dbesc($ret["notify"]),
1241 dbesc($ret["poll"]),
1246 // find the contact record we just created
1248 $contact_record = diaspora_get_contact_by_handle($importer["uid"],$author);
1250 if(! $contact_record) {
1251 logger('diaspora_request: unable to locate newly created contact record.');
1255 $g = q("select def_gid from user where uid = %d limit 1",
1256 intval($importer["uid"])
1258 if($g && intval($g[0]["def_gid"])) {
1259 require_once('include/group.php');
1260 group_add_member($importer["uid"],'',$contact_record["id"],$g[0]["def_gid"]);
1263 if($importer["page-flags"] == PAGE_NORMAL) {
1265 $hash = random_string() . (string) time(); // Generate a confirm_key
1267 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
1268 VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
1269 intval($importer["uid"]),
1270 intval($contact_record["id"]),
1273 dbesc( t('Sharing notification from Diaspora network')),
1275 dbesc(datetime_convert())
1280 // automatic friend approval
1282 require_once('include/Photo.php');
1284 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1286 // technically they are sharing with us (CONTACT_IS_SHARING),
1287 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1288 // we are going to change the relationship and make them a follower.
1290 if($importer["page-flags"] == PAGE_FREELOVE)
1291 $new_relation = CONTACT_IS_FRIEND;
1293 $new_relation = CONTACT_IS_FOLLOWER;
1295 $r = q("UPDATE `contact` SET `rel` = %d,
1303 intval($new_relation),
1304 dbesc(datetime_convert()),
1305 dbesc(datetime_convert()),
1306 intval($contact_record["id"])
1309 $u = q("select * from user where uid = %d limit 1",intval($importer["uid"]));
1311 $ret = diaspora_share($u[0],$contact_record);
1317 private function import_reshare($importer, $data) {
1318 $root_author = notags(unxmlify($data->root_author));
1319 $root_guid = notags(unxmlify($data->root_guid));
1320 $guid = notags(unxmlify($data->guid));
1321 $author = notags(unxmlify($data->author));
1322 $public = notags(unxmlify($data->public));
1323 $created_at = notags(unxmlify($data->created_at));
1325 $contact = self::get_contact_by_handle($importer["uid"], $author);
1329 if (!self::post_allow($importer, $contact, false)) {
1330 logger("Ignoring this author: ".$author." ".print_r($data,true));
1334 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1335 intval($importer["uid"]),
1339 logger("message exists: ".$guid);
1343 $orig_author = $root_author;
1344 $orig_guid = $root_guid;
1345 $orig_url = App::get_baseurl()."/display/".$guid;
1347 $create_original_post = false;
1349 // Do we already have this item?
1350 $r = q("SELECT `body`, `tag`, `app`, `created`, `plink`, `object`, `object-type`, `uri` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1352 dbesc(NETWORK_DIASPORA)
1355 logger("reshared message ".$orig_guid." reshared by ".$guid." already exists on system.");
1357 // Maybe it is already a reshared item?
1358 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1359 require_once('include/api.php');
1360 if (api_share_as_retweet($r[0]))
1363 $body = $r[0]["body"];
1364 $str_tags = $r[0]["tag"];
1365 $app = $r[0]["app"];
1366 $orig_created = $r[0]["created"];
1367 $orig_plink = $r[0]["plink"];
1368 $orig_uri = $r[0]["uri"];
1369 $object = $r[0]["object"];
1370 $objecttype = $r[0]["object-type"];
1380 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1381 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1382 $item = self::fetch_message($orig_guid, $server);
1385 $server = 'https://'.substr($author,strpos($author,'@')+1);
1386 logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1387 $item = diaspora_fetch_message($orig_guid, $server);
1390 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1391 logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1392 $item = diaspora_fetch_message($orig_guid, $server);
1395 $server = 'http://'.substr($author,strpos($author,'@')+1);
1396 logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1397 $item = diaspora_fetch_message($orig_guid, $server);
1401 $body = $item["body"];
1402 $str_tags = $item["tag"];
1403 $app = $item["app"];
1404 $orig_created = $item["created"];
1405 $orig_author = $item["author"];
1406 $orig_guid = $item["guid"];
1407 $orig_plink = diaspora_plink($orig_author, $orig_guid);
1408 $orig_uri = $orig_author.":".$orig_guid;
1409 $create_original_post = ($body != "");
1410 $object = $item["object"];
1411 $objecttype = $item["object-type"];
1415 $plink = self::plink($author, $guid);
1417 $person = self::get_person_by_handle($orig_author);
1419 $private = (($public == "false") ? 1 : 0);
1421 $datarray = array();
1423 $datarray["uid"] = $importer["uid"];
1424 $datarray["contact-id"] = $contact["id"];
1425 $datarray["network"] = NETWORK_DIASPORA;
1427 $datarray["author-name"] = $contact["name"];
1428 $datarray["author-link"] = $contact["url"];
1429 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1431 $datarray["owner-name"] = $datarray["author-name"];
1432 $datarray["owner-link"] = $datarray["author-link"];
1433 $datarray["owner-avatar"] = $datarray["author-avatar"];
1435 $datarray["guid"] = $guid;
1436 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1438 $datarray["verb"] = ACTIVITY_POST;
1439 $datarray["gravity"] = GRAVITY_PARENT;
1441 $datarray["object"] = json_encode($data);
1443 $prefix = share_header($person["name"], $person["url"], ((x($person,'thumb')) ? $person["thumb"] : $person["photo"]),
1444 $orig_guid, $orig_created, $orig_url);
1445 $datarray["body"] = $prefix.$body."[/share]";
1447 $datarray["tag"] = $str_tags;
1448 $datarray["app"] = $app;
1450 $datarray["plink"] = $plink;
1451 $datarray["private"] = $private;
1452 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1454 $datarray["object-type"] = $objecttype;
1456 self::fetch_guid($datarray);
1457 //$message_id = item_store($datarray);
1463 private function import_retraction($importer, $data) {
1467 private function import_status_message($importer, $data) {
1469 $raw_message = unxmlify($data->raw_message);
1470 $guid = notags(unxmlify($data->guid));
1471 $author = notags(unxmlify($data->author));
1472 $public = notags(unxmlify($data->public));
1473 $created_at = notags(unxmlify($data->created_at));
1474 $provider_display_name = notags(unxmlify($data->provider_display_name));
1476 $contact = self::get_contact_by_handle($importer["uid"], $author);
1478 logger("A Contact for handle ".$author." and user ".$importer["uid"]." was not found");
1482 if (!self::post_allow($importer, $contact, false)) {
1483 logger("Ignoring this author.");
1487 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1488 intval($importer["uid"]),
1492 logger("message exists: ".$guid);
1496 /// @todo enable support for polls
1497 // if ($data->poll) {
1498 // print_r($data->poll);
1503 if ($data->location)
1504 foreach ($data->location->children() AS $fieldname => $data)
1505 $address[$fieldname] = notags(unxmlify($data));
1507 $private = (($public == "false") ? 1 : 0);
1509 $body = diaspora2bb($raw_message);
1512 for ($i = 0; $i < count($data->photo); $i++)
1513 $body = "[img]".$data->photo[$i]->remote_photo_path.$data->photo[$i]->remote_photo_name."[/img]\n".$body;
1515 $datarray = array();
1517 if($data->photo->remote_photo_path AND $data->photo->remote_photo_name)
1518 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1520 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1521 // Add OEmbed and other information to the body
1522 if (!self::is_redmatrix($contact["url"]))
1523 $body = add_page_info_to_body($body, false, true);
1528 $cnt = preg_match_all("/@\[url=(.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1530 foreach($matches as $mtch) {
1531 if(strlen($str_tags))
1533 $str_tags .= "@[url=".$mtch[1]."[/url]";
1536 $plink = self::plink($author, $guid);
1538 $datarray["uid"] = $importer["uid"];
1539 $datarray["contact-id"] = $contact["id"];
1540 $datarray["network"] = NETWORK_DIASPORA;
1542 $datarray["author-name"] = $contact["name"];
1543 $datarray["author-link"] = $contact["url"];
1544 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1546 $datarray["owner-name"] = $datarray["author-name"];
1547 $datarray["owner-link"] = $datarray["author-link"];
1548 $datarray["owner-avatar"] = $datarray["author-avatar"];
1550 $datarray["guid"] = $guid;
1551 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1553 $datarray["verb"] = ACTIVITY_POST;
1554 $datarray["gravity"] = GRAVITY_PARENT;
1556 $datarray["object"] = json_encode($data);
1558 $datarray["body"] = $body;
1560 $datarray["tag"] = $str_tags;
1561 if ($provider_display_name != "")
1562 $datarray["app"] = $provider_display_name;
1564 $datarray["plink"] = $plink;
1565 $datarray["private"] = $private;
1566 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1568 if (isset($address["address"]))
1569 $datarray["location"] = $address["address"];
1571 if (isset($address["lat"]) AND isset($address["lng"]))
1572 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1574 self::fetch_guid($datarray);
1575 //$message_id = item_store($datarray);
1578 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);