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/xml.php");
15 require_once("include/datetime.php");
18 * @brief This class contain functions to create and send Diaspora XML files
23 public static function fetch_relay() {
25 $serverdata = get_config("system", "relay_server");
26 if ($serverdata == "")
31 $servers = explode(",", $serverdata);
33 foreach($servers AS $server) {
34 $server = trim($server);
35 $batch = $server."/receive/public";
37 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
40 $addr = "relay@".str_replace("http://", "", normalise_link($server));
42 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
43 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
48 dbesc(normalise_link($server)),
50 dbesc(NETWORK_DIASPORA),
51 intval(CONTACT_IS_FOLLOWER),
52 dbesc(datetime_convert()),
53 dbesc(datetime_convert()),
54 dbesc(datetime_convert())
57 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
59 $relay[] = $relais[0];
61 $relay[] = $relais[0];
68 * @brief Dispatches public messages and find the fitting receivers
70 * @param array $msg The post that will be dispatched
72 * @return bool Was the message accepted?
74 public static function dispatch_public($msg) {
76 $enabled = intval(get_config("system", "diaspora_enabled"));
78 logger("diaspora is disabled");
82 // Use a dummy importer to import the data for the public copy
83 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
84 $item_id = self::dispatch($importer,$msg);
86 // Now distribute it to the followers
87 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
88 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
89 AND NOT `account_expired` AND NOT `account_removed`",
90 dbesc(NETWORK_DIASPORA),
95 logger("delivering to: ".$rr["username"]);
96 self::dispatch($rr,$msg);
99 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
105 * @brief Dispatches the different message types to the different functions
107 * @param array $importer Array of the importer user
108 * @param array $msg The post that will be dispatched
110 * @return bool Was the message accepted?
112 public static function dispatch($importer, $msg) {
114 // The sender is the handle of the contact that sent the message.
115 // This will often be different with relayed messages (for example "like" and "comment")
116 $sender = $msg["author"];
118 if (!diaspora::valid_posting($msg, $fields)) {
119 logger("Invalid posting");
123 $type = $fields->getName();
126 case "account_deletion": // Done
128 return self::receive_account_deletion($importer, $fields);
130 case "comment": // Done
132 return self::receive_comment($importer, $sender, $fields);
134 case "conversation": // Done
136 return self::receive_conversation($importer, $msg, $fields);
140 return self::receive_like($importer, $sender, $fields);
142 case "message": // Done
144 return self::receive_message($importer, $fields);
146 case "participation": // Not implemented
147 return self::receive_participation($importer, $fields);
149 case "photo": // Not needed
150 return self::receive_photo($importer, $fields);
152 case "poll_participation": // Not implemented
153 return self::receive_poll_participation($importer, $fields);
155 case "profile": // Done
157 return self::receive_profile($importer, $fields);
161 return self::receive_request($importer, $fields);
163 case "reshare": // Done
165 return self::receive_reshare($importer, $fields);
167 case "retraction": // Done
169 return self::receive_retraction($importer, $sender, $fields);
171 case "status_message": // Done
173 return self::receive_status_message($importer, $fields);
176 logger("Unknown message type ".$type);
184 * @brief Checks if a posting is valid and fetches the data fields.
186 * This function does not only check the signature.
187 * It also does the conversion between the old and the new diaspora format.
189 * @param array $msg Array with the XML, the sender handle and the sender signature
190 * @param object $fields SimpleXML object that contains the posting when it is valid
192 * @return bool Is the posting valid?
194 private function valid_posting($msg, &$fields) {
196 $data = parse_xml_string($msg["message"], false);
198 if (!is_object($data))
201 $first_child = $data->getName();
203 // Is this the new or the old version?
204 if ($data->getName() == "XML") {
206 foreach ($data->post->children() as $child)
213 $type = $element->getName();
216 // All retractions are handled identically from now on.
217 // In the new version there will only be "retraction".
218 if (in_array($type, array("signed_retraction", "relayable_retraction")))
219 $type = "retraction";
221 $fields = new SimpleXMLElement("<".$type."/>");
225 foreach ($element->children() AS $fieldname => $entry) {
227 // Translation for the old XML structure
228 if ($fieldname == "diaspora_handle")
229 $fieldname = "author";
231 if ($fieldname == "participant_handles")
232 $fieldname = "participants";
234 if (in_array($type, array("like", "participation"))) {
235 if ($fieldname == "target_type")
236 $fieldname = "parent_type";
239 if ($fieldname == "sender_handle")
240 $fieldname = "author";
242 if ($fieldname == "recipient_handle")
243 $fieldname = "recipient";
245 if ($fieldname == "root_diaspora_id")
246 $fieldname = "root_author";
248 if ($type == "retraction") {
249 if ($fieldname == "post_guid")
250 $fieldname = "target_guid";
252 if ($fieldname == "type")
253 $fieldname = "target_type";
257 if ($fieldname == "author_signature")
258 $author_signature = base64_decode($entry);
259 elseif ($fieldname == "parent_author_signature")
260 $parent_author_signature = base64_decode($entry);
261 elseif ($fieldname != "target_author_signature") {
262 if ($signed_data != "") {
264 $signed_data_parent .= ";";
267 $signed_data .= $entry;
269 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
270 ($orig_type == "relayable_retraction"))
271 xml::copy($entry, $fields, $fieldname);
274 // This is something that shouldn't happen at all.
275 if (in_array($type, array("status_message", "reshare", "profile")))
276 if ($msg["author"] != $fields->author) {
277 logger("Message handle is not the same as envelope sender. Quitting this message.");
281 // Only some message types have signatures. So we quit here for the other types.
282 if (!in_array($type, array("comment", "message", "like")))
285 // No author_signature? This is a must, so we quit.
286 if (!isset($author_signature))
289 if (isset($parent_author_signature)) {
290 $key = self::get_key($msg["author"]);
292 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
296 $key = self::get_key($fields->author);
298 return rsa_verify($signed_data, $author_signature, $key, "sha256");
302 * @brief Fetches the public key for a given handle
304 * @param string $handle The handle
306 * @return string The public key
308 private function get_key($handle) {
309 logger("Fetching diaspora key for: ".$handle);
311 $r = self::get_person_by_handle($handle);
319 * @brief Fetches data for a given handle
321 * @param string $handle The handle
323 * @return array the queried data
325 private function get_person_by_handle($handle) {
327 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
328 dbesc(NETWORK_DIASPORA),
333 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
335 // update record occasionally so it doesn't get stale
336 $d = strtotime($person["updated"]." +00:00");
337 if ($d < strtotime("now - 14 days"))
341 if (!$person OR $update) {
342 logger("create or refresh", LOGGER_DEBUG);
343 $r = probe_url($handle, PROBE_DIASPORA);
345 // Note that Friendica contacts will return a "Diaspora person"
346 // if Diaspora connectivity is enabled on their server
347 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
348 self::add_fcontact($r, $update);
356 * @brief Updates the fcontact table
358 * @param array $arr The fcontact data
359 * @param bool $update Update or insert?
361 * @return string The id of the fcontact entry
363 private function add_fcontact($arr, $update = false) {
364 /// @todo Remove this function from include/network.php
367 $r = q("UPDATE `fcontact` SET
380 WHERE `url` = '%s' AND `network` = '%s'",
382 dbesc($arr["photo"]),
383 dbesc($arr["request"]),
386 dbesc($arr["batch"]),
387 dbesc($arr["notify"]),
389 dbesc($arr["confirm"]),
390 dbesc($arr["alias"]),
391 dbesc($arr["pubkey"]),
392 dbesc(datetime_convert()),
394 dbesc($arr["network"])
397 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
398 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
399 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
402 dbesc($arr["photo"]),
403 dbesc($arr["request"]),
406 dbesc($arr["batch"]),
407 dbesc($arr["notify"]),
409 dbesc($arr["confirm"]),
410 dbesc($arr["network"]),
411 dbesc($arr["alias"]),
412 dbesc($arr["pubkey"]),
413 dbesc(datetime_convert())
420 private function get_contact_by_handle($uid, $handle) {
421 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
429 $handle_parts = explode("@", $handle);
430 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
431 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
442 private function post_allow($importer, $contact, $is_comment = false) {
444 // perhaps we were already sharing with this person. Now they're sharing with us.
445 // That makes us friends.
446 // Normally this should have handled by getting a request - but this could get lost
447 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
448 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
449 intval(CONTACT_IS_FRIEND),
450 intval($contact["id"]),
451 intval($importer["uid"])
453 $contact["rel"] = CONTACT_IS_FRIEND;
454 logger("defining user ".$contact["nick"]." as friend");
457 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
459 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
461 if($contact["rel"] == CONTACT_IS_FOLLOWER)
462 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
465 // Messages for the global users are always accepted
466 if ($importer["uid"] == 0)
472 private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
473 $contact = self::get_contact_by_handle($importer["uid"], $handle);
475 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
479 if (!self::post_allow($importer, $contact, false)) {
480 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
486 private function message_exists($uid, $guid) {
487 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
493 logger("message ".$guid." already exists for user ".$uid);
500 private function fetch_guid($item) {
501 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
502 function ($match) use ($item){
503 return(self::fetch_guid_sub($match, $item));
507 private function fetch_guid_sub($match, $item) {
508 if (!self::store_by_guid($match[1], $item["author-link"]))
509 self::store_by_guid($match[1], $item["owner-link"]);
512 private function store_by_guid($guid, $server, $uid = 0) {
513 $serverparts = parse_url($server);
514 $server = $serverparts["scheme"]."://".$serverparts["host"];
516 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
518 $msg = self::fetch_message($guid, $server);
523 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
525 // Now call the dispatcher
526 return self::dispatch_public($msg);
529 private function fetch_message($guid, $server, $level = 0) {
534 // This will work for Diaspora and newer Friendica servers
535 $source_url = $server."/p/".$guid.".xml";
536 $x = fetch_url($source_url);
540 $source_xml = parse_xml_string($x, false);
542 if (!is_object($source_xml))
545 if ($source_xml->post->reshare) {
546 // Reshare of a reshare - old Diaspora version
547 return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
548 } elseif ($source_xml->getName() == "reshare") {
549 // Reshare of a reshare - new Diaspora version
550 return self::fetch_message($source_xml->root_guid, $server, ++$level);
553 // Fetch the author - for the old and the new Diaspora version
554 if ($source_xml->post->status_message->diaspora_handle)
555 $author = (string)$source_xml->post->status_message->diaspora_handle;
556 elseif ($source_xml->author)
557 $author = (string)$source_xml->author;
562 $msg = array("message" => $x, "author" => $author);
564 $msg["key"] = self::get_key($msg["author"]);
569 private function fetch_parent_item($uid, $guid, $author, $contact) {
570 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
571 `author-name`, `author-link`, `author-avatar`,
572 `owner-name`, `owner-link`, `owner-avatar`
573 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
574 intval($uid), dbesc($guid));
577 $result = self::store_by_guid($guid, $contact["url"], $uid);
580 $person = self::get_person_by_handle($author);
581 $result = self::store_by_guid($guid, $person["url"], $uid);
585 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
587 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
588 `author-name`, `author-link`, `author-avatar`,
589 `owner-name`, `owner-link`, `owner-avatar`
590 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
591 intval($uid), dbesc($guid));
596 logger("parent item not found: parent: ".$guid." item: ".$guid);
602 private function get_author_contact_by_url($contact, $person, $uid) {
604 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
605 dbesc(normalise_link($person["url"])), intval($uid));
608 $network = $r[0]["network"];
610 $cid = $contact["id"];
611 $network = NETWORK_DIASPORA;
614 return (array("cid" => $cid, "network" => $network));
617 public static function is_redmatrix($url) {
618 return(strstr($url, "/channel/"));
621 private function plink($addr, $guid) {
622 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
626 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
628 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
629 // So we try another way as well.
630 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
632 $r[0]["network"] = $s[0]["network"];
634 if ($r[0]["network"] == NETWORK_DFRN)
635 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
637 if (self::is_redmatrix($r[0]["url"]))
638 return $r[0]["url"]."/?f=&mid=".$guid;
640 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
643 private function receive_account_deletion($importer, $data) {
644 $author = notags(unxmlify($data->author));
646 $contact = self::get_contact_by_handle($importer["uid"], $author);
648 logger("cannot find contact for author: ".$author);
652 // We now remove the contact
653 contact_remove($contact["id"]);
657 private function receive_comment($importer, $sender, $data) {
658 $guid = notags(unxmlify($data->guid));
659 $parent_guid = notags(unxmlify($data->parent_guid));
660 $text = unxmlify($data->text);
661 $author = notags(unxmlify($data->author));
663 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
667 if (self::message_exists($importer["uid"], $guid))
670 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
674 $person = self::get_person_by_handle($author);
675 if (!is_array($person)) {
676 logger("unable to find author details");
680 // Fetch the contact id - if we know this contact
681 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
685 $datarray["uid"] = $importer["uid"];
686 $datarray["contact-id"] = $author_contact["cid"];
687 $datarray["network"] = $author_contact["network"];
689 $datarray["author-name"] = $person["name"];
690 $datarray["author-link"] = $person["url"];
691 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
693 $datarray["owner-name"] = $contact["name"];
694 $datarray["owner-link"] = $contact["url"];
695 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
697 $datarray["guid"] = $guid;
698 $datarray["uri"] = $author.":".$guid;
700 $datarray["type"] = "remote-comment";
701 $datarray["verb"] = ACTIVITY_POST;
702 $datarray["gravity"] = GRAVITY_COMMENT;
703 $datarray["parent-uri"] = $parent_item["uri"];
705 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
706 $datarray["object"] = json_encode($data);
708 $datarray["body"] = diaspora2bb($text);
710 self::fetch_guid($datarray);
712 $message_id = item_store($datarray);
713 // print_r($datarray);
715 // If we are the origin of the parent we store the original data and notify our followers
716 if($message_id AND $parent_item["origin"]) {
718 // Formerly we stored the signed text, the signature and the author in different fields.
719 // We now store the raw data so that we are more flexible.
720 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
722 dbesc(json_encode($data))
726 proc_run("php", "include/notifier.php", "comment-import", $message_id);
732 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
733 $guid = notags(unxmlify($data->guid));
734 $subject = notags(unxmlify($data->subject));
735 $author = notags(unxmlify($data->author));
739 $msg_guid = notags(unxmlify($mesg->guid));
740 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
741 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
742 $msg_author_signature = notags(unxmlify($mesg->author_signature));
743 $msg_text = unxmlify($mesg->text);
744 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
746 // "diaspora_handle" is the element name from the old version
747 // "author" is the element name from the new version
749 $msg_author = notags(unxmlify($mesg->author));
750 elseif ($mesg->diaspora_handle)
751 $msg_author = notags(unxmlify($mesg->diaspora_handle));
755 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
757 if($msg_conversation_guid != $guid) {
758 logger("message conversation guid does not belong to the current conversation.");
762 $body = diaspora2bb($msg_text);
763 $message_uri = $msg_author.":".$msg_guid;
765 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
767 $author_signature = base64_decode($msg_author_signature);
769 if(strcasecmp($msg_author,$msg["author"]) == 0) {
773 $person = self::get_person_by_handle($msg_author);
775 if (is_array($person) && x($person, "pubkey"))
776 $key = $person["pubkey"];
778 logger("unable to find author details");
783 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
784 logger("verification failed.");
788 if($msg_parent_author_signature) {
789 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
791 $parent_author_signature = base64_decode($msg_parent_author_signature);
795 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
796 logger("owner verification failed.");
801 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
805 logger("duplicate message already delivered.", LOGGER_DEBUG);
809 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
810 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
811 intval($importer["uid"]),
813 intval($conversation["id"]),
814 dbesc($person["name"]),
815 dbesc($person["photo"]),
816 dbesc($person["url"]),
817 intval($contact["id"]),
823 dbesc($author.":".$guid),
824 dbesc($msg_created_at)
827 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
828 dbesc(datetime_convert()),
829 intval($conversation["id"])
833 "type" => NOTIFY_MAIL,
834 "notify_flags" => $importer["notify-flags"],
835 "language" => $importer["language"],
836 "to_name" => $importer["username"],
837 "to_email" => $importer["email"],
838 "uid" =>$importer["uid"],
839 "item" => array("subject" => $subject, "body" => $body),
840 "source_name" => $person["name"],
841 "source_link" => $person["url"],
842 "source_photo" => $person["thumb"],
843 "verb" => ACTIVITY_POST,
848 private function receive_conversation($importer, $msg, $data) {
849 $guid = notags(unxmlify($data->guid));
850 $subject = notags(unxmlify($data->subject));
851 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
852 $author = notags(unxmlify($data->author));
853 $participants = notags(unxmlify($data->participants));
855 $messages = $data->message;
857 if (!count($messages)) {
858 logger("empty conversation");
862 $contact = self::get_allowed_contact_by_handle($importer, $msg["author"], true);
866 $conversation = null;
868 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
869 intval($importer["uid"]),
873 $conversation = $c[0];
875 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
876 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
877 intval($importer["uid"]),
880 dbesc(datetime_convert("UTC", "UTC", $created_at)),
881 dbesc(datetime_convert()),
886 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
887 intval($importer["uid"]),
892 $conversation = $c[0];
894 if (!$conversation) {
895 logger("unable to create conversation.");
899 foreach($messages as $mesg)
900 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
905 private function construct_like_body($contact, $parent_item, $guid) {
906 $bodyverb = t('%1$s likes %2$s\'s %3$s');
908 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
909 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
910 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
912 return sprintf($bodyverb, $ulink, $alink, $plink);
915 private function construct_like_object($importer, $parent_item) {
916 $objtype = ACTIVITY_OBJ_NOTE;
917 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
918 $parent_body = $parent_item["body"];
923 <type>$objtype</type>
925 <id>{$parent_item["uri"]}</id>
928 <content>$parent_body</content>
935 private function receive_like($importer, $sender, $data) {
936 $positive = notags(unxmlify($data->positive));
937 $guid = notags(unxmlify($data->guid));
938 $parent_type = notags(unxmlify($data->parent_type));
939 $parent_guid = notags(unxmlify($data->parent_guid));
940 $author = notags(unxmlify($data->author));
942 // likes on comments aren't supported by Diaspora - only on posts
943 // But maybe this will be supported in the future, so we will accept it.
944 if (!in_array($parent_type, array("Post", "Comment")))
947 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
951 if (self::message_exists($importer["uid"], $guid))
954 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
958 $person = self::get_person_by_handle($author);
959 if (!is_array($person)) {
960 logger("unable to find author details");
964 // Fetch the contact id - if we know this contact
965 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
967 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
968 // We would accept this anyhow.
969 if ($positive === "true")
970 $verb = ACTIVITY_LIKE;
972 $verb = ACTIVITY_DISLIKE;
976 $datarray["uid"] = $importer["uid"];
977 $datarray["contact-id"] = $author_contact["cid"];
978 $datarray["network"] = $author_contact["network"];
980 $datarray["author-name"] = $person["name"];
981 $datarray["author-link"] = $person["url"];
982 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
984 $datarray["owner-name"] = $contact["name"];
985 $datarray["owner-link"] = $contact["url"];
986 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
988 $datarray["guid"] = $guid;
989 $datarray["uri"] = $author.":".$guid;
991 $datarray["type"] = "activity";
992 $datarray["verb"] = $verb;
993 $datarray["gravity"] = GRAVITY_LIKE;
994 $datarray["parent-uri"] = $parent_item["uri"];
996 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
997 $datarray["object"] = self::construct_like_object($importer, $parent_item);
999 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1001 $message_id = item_store($datarray);
1002 // print_r($datarray);
1004 // If we are the origin of the parent we store the original data and notify our followers
1005 if($message_id AND $parent_item["origin"]) {
1007 // Formerly we stored the signed text, the signature and the author in different fields.
1008 // We now store the raw data so that we are more flexible.
1009 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1010 intval($message_id),
1011 dbesc(json_encode($data))
1015 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1021 private function receive_message($importer, $data) {
1022 $guid = notags(unxmlify($data->guid));
1023 $parent_guid = notags(unxmlify($data->parent_guid));
1024 $text = unxmlify($data->text);
1025 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1026 $author = notags(unxmlify($data->author));
1027 $conversation_guid = notags(unxmlify($data->conversation_guid));
1029 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
1033 $conversation = null;
1035 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1036 intval($importer["uid"]),
1037 dbesc($conversation_guid)
1040 $conversation = $c[0];
1042 logger("conversation not available.");
1048 $body = diaspora2bb($text);
1049 $message_uri = $author.":".$guid;
1051 $person = self::get_person_by_handle($author);
1053 logger("unable to find author details");
1057 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1058 dbesc($message_uri),
1059 intval($importer["uid"])
1062 logger("duplicate message already delivered.", LOGGER_DEBUG);
1066 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1067 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1068 intval($importer["uid"]),
1070 intval($conversation["id"]),
1071 dbesc($person["name"]),
1072 dbesc($person["photo"]),
1073 dbesc($person["url"]),
1074 intval($contact["id"]),
1075 dbesc($conversation["subject"]),
1079 dbesc($message_uri),
1080 dbesc($author.":".$parent_guid),
1084 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1085 dbesc(datetime_convert()),
1086 intval($conversation["id"])
1092 private function receive_participation($importer, $data) {
1093 // I'm not sure if we can fully support this message type
1097 private function receive_photo($importer, $data) {
1098 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1102 private function receive_poll_participation($importer, $data) {
1103 // We don't support polls by now
1107 private function receive_profile($importer, $data) {
1108 $author = notags(unxmlify($data->author));
1110 $contact = self::get_contact_by_handle($importer["uid"], $author);
1114 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1115 $image_url = unxmlify($data->image_url);
1116 $birthday = unxmlify($data->birthday);
1117 $location = diaspora2bb(unxmlify($data->location));
1118 $about = diaspora2bb(unxmlify($data->bio));
1119 $gender = unxmlify($data->gender);
1120 $searchable = (unxmlify($data->searchable) == "true");
1121 $nsfw = (unxmlify($data->nsfw) == "true");
1122 $tags = unxmlify($data->tag_string);
1124 $tags = explode("#", $tags);
1126 $keywords = array();
1127 foreach ($tags as $tag) {
1128 $tag = trim(strtolower($tag));
1133 $keywords = implode(", ", $keywords);
1135 $handle_parts = explode("@", $author);
1136 $nick = $handle_parts[0];
1139 $name = $handle_parts[0];
1141 if( preg_match("|^https?://|", $image_url) === 0)
1142 $image_url = "http://".$handle_parts[1].$image_url;
1144 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1146 // Generic birthday. We don't know the timezone. The year is irrelevant.
1148 $birthday = str_replace("1000", "1901", $birthday);
1150 if ($birthday != "")
1151 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1153 // this is to prevent multiple birthday notifications in a single year
1154 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1156 if(substr($birthday,5) === substr($contact["bd"],5))
1157 $birthday = $contact["bd"];
1159 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1160 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1164 dbesc(datetime_convert()),
1170 intval($contact["id"]),
1171 intval($importer["uid"])
1175 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1176 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1179 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1180 "photo" => $image_url, "name" => $name, "location" => $location,
1181 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1182 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1183 "hide" => !$searchable, "nsfw" => $nsfw);
1185 update_gcontact($gcontact);
1190 private function receive_request_make_friend($importer, $contact) {
1194 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1195 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1196 intval(CONTACT_IS_FRIEND),
1197 intval($contact["id"]),
1198 intval($importer["uid"])
1201 // send notification
1203 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1204 intval($importer["uid"])
1207 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1209 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1210 intval($importer["uid"])
1213 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1215 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1218 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1219 $arr["uid"] = $importer["uid"];
1220 $arr["contact-id"] = $self[0]["id"];
1222 $arr["type"] = 'wall';
1223 $arr["gravity"] = 0;
1225 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1226 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1227 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1228 $arr["verb"] = ACTIVITY_FRIEND;
1229 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1231 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1232 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1233 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1234 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1236 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1237 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1238 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1239 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1240 $arr["object"] .= "</link></object>\n";
1241 $arr["last-child"] = 1;
1243 $arr["allow_cid"] = $user[0]["allow_cid"];
1244 $arr["allow_gid"] = $user[0]["allow_gid"];
1245 $arr["deny_cid"] = $user[0]["deny_cid"];
1246 $arr["deny_gid"] = $user[0]["deny_gid"];
1248 $i = item_store($arr);
1250 proc_run("php", "include/notifier.php", "activity", $i);
1257 private function receive_request($importer, $data) {
1258 $author = unxmlify($data->author);
1259 $recipient = unxmlify($data->recipient);
1261 if (!$author || !$recipient)
1264 $contact = self::get_contact_by_handle($importer["uid"],$author);
1268 // perhaps we were already sharing with this person. Now they're sharing with us.
1269 // That makes us friends.
1271 self::receive_request_make_friend($importer, $contact);
1275 $ret = self::get_person_by_handle($author);
1277 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1278 logger("Cannot resolve diaspora handle ".$author ." for ".$recipient);
1282 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1284 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1285 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1286 intval($importer["uid"]),
1287 dbesc($ret["network"]),
1288 dbesc($ret["addr"]),
1291 dbesc(normalise_link($ret["url"])),
1293 dbesc($ret["name"]),
1294 dbesc($ret["nick"]),
1295 dbesc($ret["photo"]),
1296 dbesc($ret["pubkey"]),
1297 dbesc($ret["notify"]),
1298 dbesc($ret["poll"]),
1303 // find the contact record we just created
1305 $contact_record = self::get_contact_by_handle($importer["uid"],$author);
1307 if (!$contact_record) {
1308 logger("unable to locate newly created contact record.");
1312 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1313 intval($importer["uid"])
1316 if($g && intval($g[0]["def_gid"]))
1317 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1319 if($importer["page-flags"] == PAGE_NORMAL) {
1321 $hash = random_string().(string)time(); // Generate a confirm_key
1323 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1324 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1325 intval($importer["uid"]),
1326 intval($contact_record["id"]),
1329 dbesc(t("Sharing notification from Diaspora network")),
1331 dbesc(datetime_convert())
1335 // automatic friend approval
1337 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1339 // technically they are sharing with us (CONTACT_IS_SHARING),
1340 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1341 // we are going to change the relationship and make them a follower.
1343 if($importer["page-flags"] == PAGE_FREELOVE)
1344 $new_relation = CONTACT_IS_FRIEND;
1346 $new_relation = CONTACT_IS_FOLLOWER;
1348 $r = q("UPDATE `contact` SET `rel` = %d,
1356 intval($new_relation),
1357 dbesc(datetime_convert()),
1358 dbesc(datetime_convert()),
1359 intval($contact_record["id"])
1362 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1364 $ret = diaspora_share($u[0], $contact_record);
1370 private function get_original_item($guid, $orig_author, $author) {
1372 // Do we already have this item?
1373 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1374 `author-name`, `author-link`, `author-avatar`
1375 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1379 logger("reshared message ".$guid." already exists on system.");
1381 // Maybe it is already a reshared item?
1382 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1383 if (self::is_reshare($r[0]["body"]))
1390 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1391 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1392 $item_id = self::store_by_guid($guid, $server);
1395 $server = "https://".substr($author, strpos($author, "@") + 1);
1396 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1397 $item = self::store_by_guid($guid, $server);
1400 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1401 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1402 $item = self::store_by_guid($guid, $server);
1405 $server = "http://".substr($author, strpos($author, "@") + 1);
1406 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1407 $item = self::store_by_guid($guid, $server);
1411 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1412 `author-name`, `author-link`, `author-avatar`
1413 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1424 private function receive_reshare($importer, $data) {
1425 $root_author = notags(unxmlify($data->root_author));
1426 $root_guid = notags(unxmlify($data->root_guid));
1427 $guid = notags(unxmlify($data->guid));
1428 $author = notags(unxmlify($data->author));
1429 $public = notags(unxmlify($data->public));
1430 $created_at = notags(unxmlify($data->created_at));
1432 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1436 if (self::message_exists($importer["uid"], $guid))
1439 $original_item = self::get_original_item($root_guid, $root_author, $author);
1440 if (!$original_item)
1443 $datarray = array();
1445 $datarray["uid"] = $importer["uid"];
1446 $datarray["contact-id"] = $contact["id"];
1447 $datarray["network"] = NETWORK_DIASPORA;
1449 $datarray["author-name"] = $contact["name"];
1450 $datarray["author-link"] = $contact["url"];
1451 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1453 $datarray["owner-name"] = $datarray["author-name"];
1454 $datarray["owner-link"] = $datarray["author-link"];
1455 $datarray["owner-avatar"] = $datarray["author-avatar"];
1457 $datarray["guid"] = $guid;
1458 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1460 $datarray["verb"] = ACTIVITY_POST;
1461 $datarray["gravity"] = GRAVITY_PARENT;
1463 $datarray["object"] = json_encode($data);
1465 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1466 $original_item["guid"], $original_item["created"], $original_item["uri"]);
1467 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1469 $datarray["tag"] = $original_item["tag"];
1470 $datarray["app"] = $original_item["app"];
1472 $datarray["plink"] = self::plink($author, $guid);
1473 $datarray["private"] = (($public == "false") ? 1 : 0);
1474 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1476 $datarray["object-type"] = $original_item["object-type"];
1478 self::fetch_guid($datarray);
1479 $message_id = item_store($datarray);
1480 // print_r($datarray);
1485 private function item_retraction($importer, $contact, $data) {
1486 $target_type = notags(unxmlify($data->target_type));
1487 $target_guid = notags(unxmlify($data->target_guid));
1488 $author = notags(unxmlify($data->author));
1490 $person = self::get_person_by_handle($author);
1491 if (!is_array($person)) {
1492 logger("unable to find author detail for ".$author);
1496 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1497 dbesc($target_guid),
1498 intval($importer["uid"])
1503 // Only delete it if the author really fits
1504 if (!link_compare($r[0]["author-link"],$person["url"]))
1507 // Check if the sender is the thread owner
1508 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1509 intval($r[0]["parent"]));
1511 // Only delete it if the parent author really fits
1512 if (!link_compare($p[0]["author-link"], $contact["url"]))
1515 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
1516 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1517 dbesc(datetime_convert()),
1518 dbesc(datetime_convert()),
1521 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1523 // Now check if the retraction needs to be relayed by us
1524 if($p[0]["origin"]) {
1526 // Formerly we stored the signed text, the signature and the author in different fields.
1527 // We now store the raw data so that we are more flexible.
1528 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1529 intval($r[0]["id"]),
1530 dbesc(json_encode($data))
1534 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1538 private function receive_retraction($importer, $sender, $data) {
1539 $target_type = notags(unxmlify($data->target_type));
1541 $contact = self::get_contact_by_handle($importer["uid"], $sender);
1543 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1547 switch ($target_type) {
1550 case "Post": // "Post" will be supported in a future version
1552 case "StatusMessage":
1553 return self::item_retraction($importer, $contact, $data);;
1556 contact_remove($contact["id"]);
1560 logger("Unknown target type ".$target_type);
1566 private function receive_status_message($importer, $data) {
1568 $raw_message = unxmlify($data->raw_message);
1569 $guid = notags(unxmlify($data->guid));
1570 $author = notags(unxmlify($data->author));
1571 $public = notags(unxmlify($data->public));
1572 $created_at = notags(unxmlify($data->created_at));
1573 $provider_display_name = notags(unxmlify($data->provider_display_name));
1575 /// @todo enable support for polls
1576 //if ($data->poll) {
1577 // foreach ($data->poll AS $poll)
1581 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1585 if (self::message_exists($importer["uid"], $guid))
1589 if ($data->location)
1590 foreach ($data->location->children() AS $fieldname => $data)
1591 $address[$fieldname] = notags(unxmlify($data));
1593 $body = diaspora2bb($raw_message);
1595 $datarray = array();
1598 foreach ($data->photo AS $photo)
1599 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1601 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1603 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1605 // Add OEmbed and other information to the body
1606 if (!self::is_redmatrix($contact["url"]))
1607 $body = add_page_info_to_body($body, false, true);
1610 $datarray["uid"] = $importer["uid"];
1611 $datarray["contact-id"] = $contact["id"];
1612 $datarray["network"] = NETWORK_DIASPORA;
1614 $datarray["author-name"] = $contact["name"];
1615 $datarray["author-link"] = $contact["url"];
1616 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1618 $datarray["owner-name"] = $datarray["author-name"];
1619 $datarray["owner-link"] = $datarray["author-link"];
1620 $datarray["owner-avatar"] = $datarray["author-avatar"];
1622 $datarray["guid"] = $guid;
1623 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1625 $datarray["verb"] = ACTIVITY_POST;
1626 $datarray["gravity"] = GRAVITY_PARENT;
1628 $datarray["object"] = json_encode($data);
1630 $datarray["body"] = $body;
1632 if ($provider_display_name != "")
1633 $datarray["app"] = $provider_display_name;
1635 $datarray["plink"] = self::plink($author, $guid);
1636 $datarray["private"] = (($public == "false") ? 1 : 0);
1637 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1639 if (isset($address["address"]))
1640 $datarray["location"] = $address["address"];
1642 if (isset($address["lat"]) AND isset($address["lng"]))
1643 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1645 self::fetch_guid($datarray);
1646 $message_id = item_store($datarray);
1647 // print_r($datarray);
1649 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1654 /*******************************************************************************************
1655 * Here come all the functions that are needed to transmit data with the Diaspora protocol *
1656 *******************************************************************************************/
1658 private function get_my_handle($me) {
1659 if ($contact["addr"] != "")
1660 return $contact["addr"];
1662 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1663 // So - just in case - we build the the address here.
1664 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1667 function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1669 logger("Message: ".$msg, LOGGER_DATA);
1671 $handle = self::get_my_handle($user);
1673 $b64url_data = base64url_encode($msg);
1675 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1677 $type = "application/xml";
1678 $encoding = "base64url";
1679 $alg = "RSA-SHA256";
1681 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1683 $signature = rsa_sign($signable_data,$prvkey);
1684 $sig = base64url_encode($signature);
1686 $magic_env = <<< EOT
1687 <?xml version='1.0' encoding='UTF-8'?>
1688 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1690 <author_id>$handle</author_id>
1693 <me:encoding>base64url</me:encoding>
1694 <me:alg>RSA-SHA256</me:alg>
1695 <me:data type="application/xml">$data</me:data>
1696 <me:sig>$sig</me:sig>
1701 logger("magic_env: ".$magic_env, LOGGER_DATA);
1705 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1707 logger("Message: ".$msg, LOGGER_DATA);
1709 // without a public key nothing will work
1712 logger("pubkey missing: contact id: ".$contact["id"]);
1716 $inner_aes_key = random_string(32);
1717 $b_inner_aes_key = base64_encode($inner_aes_key);
1718 $inner_iv = random_string(16);
1719 $b_inner_iv = base64_encode($inner_iv);
1721 $outer_aes_key = random_string(32);
1722 $b_outer_aes_key = base64_encode($outer_aes_key);
1723 $outer_iv = random_string(16);
1724 $b_outer_iv = base64_encode($outer_iv);
1726 $handle = self::get_my_handle($user);
1728 $padded_data = pkcs5_pad($msg,16);
1729 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1731 $b64_data = base64_encode($inner_encrypted);
1734 $b64url_data = base64url_encode($b64_data);
1735 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1737 $type = "application/xml";
1738 $encoding = "base64url";
1739 $alg = "RSA-SHA256";
1741 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1743 $signature = rsa_sign($signable_data,$prvkey);
1744 $sig = base64url_encode($signature);
1746 $decrypted_header = <<< EOT
1748 <iv>$b_inner_iv</iv>
1749 <aes_key>$b_inner_aes_key</aes_key>
1750 <author_id>$handle</author_id>
1754 $decrypted_header = pkcs5_pad($decrypted_header,16);
1756 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1758 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1760 $encrypted_outer_key_bundle = "";
1761 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1763 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1765 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1767 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1768 "ciphertext" => base64_encode($ciphertext)));
1769 $cipher_json = base64_encode($encrypted_header_json_object);
1771 $encrypted_header = "<encrypted_header>".$cipher_json."</encrypted_header>";
1773 $magic_env = <<< EOT
1774 <?xml version='1.0' encoding='UTF-8'?>
1775 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1778 <me:encoding>base64url</me:encoding>
1779 <me:alg>RSA-SHA256</me:alg>
1780 <me:data type="application/xml">$data</me:data>
1781 <me:sig>$sig</me:sig>
1786 logger("magic_env: ".$magic_env, LOGGER_DATA);
1790 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1793 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1795 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1797 // The data that will be transmitted is double encoded via "urlencode", strange ...
1798 $slap = "xml=".urlencode(urlencode($magic_env));
1802 private function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
1806 $enabled = intval(get_config("system", "diaspora_enabled"));
1810 $logid = random_string(4);
1811 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
1813 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
1817 logger("transmit: ".$logid."-".$guid." ".$dest_url);
1819 if (!$queue_run && was_recently_delayed($contact["id"])) {
1822 if (!intval(get_config("system", "diaspora_test"))) {
1823 post_url($dest_url."/", $slap);
1824 $return_code = $a->get_curl_code();
1826 logger("test_mode");
1831 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
1833 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
1834 logger("queue message");
1836 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
1837 intval($contact["id"]),
1838 dbesc(NETWORK_DIASPORA),
1840 intval($public_batch)
1843 logger("add_to_queue ignored - identical item already in queue");
1845 // queue message for redelivery
1846 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
1851 return(($return_code) ? $return_code : (-1));
1854 public static function send_share($me,$contact) {
1855 $myaddr = self::get_my_handle($me);
1856 $theiraddr = $contact["addr"];
1858 $data = array("XML" => array("post" => array("request" => array(
1859 "sender_handle" => $myaddr,
1860 "recipient_handle" => $theiraddr
1863 $msg = xml::from_array($data, $xml);
1865 $slap = self::build_message($msg, $me, $contact, $me["prvkey"], $contact["pubkey"]);
1867 return(self::transmit($owner,$contact,$slap, false));
1871 public static function send_unshare($me,$contact) {
1872 $myaddr = self::get_my_handle($me);
1874 $data = array("XML" => array("post" => array("retraction" => array(
1875 "post_guid" => $me["guid"],
1876 "diaspora_handle" => $myaddr,
1880 $msg = xml::from_array($data, $xml);
1882 $slap = self::build_message($msg, $me, $contact, $me["prvkey"], $contact["pubkey"]);
1884 return(self::transmit($owner,$contact,$slap, false));
1887 function is_reshare($body) {
1888 $body = trim($body);
1890 // Skip if it isn't a pure repeated messages
1891 // Does it start with a share?
1892 if (strpos($body, "[share") > 0)
1895 // Does it end with a share?
1896 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1899 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1900 // Skip if there is no shared message in there
1901 if ($body == $attributes)
1905 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1906 if ($matches[1] != "")
1907 $guid = $matches[1];
1909 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1910 if ($matches[1] != "")
1911 $guid = $matches[1];
1914 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
1915 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
1918 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
1919 $ret["root_guid"] = $guid;
1925 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
1926 if ($matches[1] != "")
1927 $profile = $matches[1];
1929 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
1930 if ($matches[1] != "")
1931 $profile = $matches[1];
1935 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
1936 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
1940 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1941 if ($matches[1] != "")
1942 $link = $matches[1];
1944 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1945 if ($matches[1] != "")
1946 $link = $matches[1];
1948 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
1949 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
1954 function send_status($item, $owner, $contact, $public_batch = false) {
1956 $myaddr = self::get_my_handle($owner);
1957 $theiraddr = $contact["addr"];
1959 $title = $item["title"];
1960 $body = $item["body"];
1962 // convert to markdown
1963 $body = html_entity_decode(bb2diaspora($body));
1967 $body = "## ".html_entity_decode($title)."\n\n".$body;
1969 if ($item["attach"]) {
1970 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
1972 $body .= "\n".t("Attachments:")."\n";
1973 foreach($matches as $mtch)
1974 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
1979 $public = (($item["private"]) ? "false" : "true");
1981 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
1983 // Detect a share element and do a reshare
1984 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
1985 $message = array("root_diaspora_id" => $ret["root_handle"],
1986 "root_guid" => $ret["root_guid"],
1987 "guid" => $item["guid"],
1988 "diaspora_handle" => $myaddr,
1989 "public" => $public,
1990 "created_at" => $created,
1991 "provider_display_name" => $item["app"]);
1993 $data = array("XML" => array("post" => array("reshare" => $message)));
1995 $location = array();
1997 if ($item["location"] != "")
1998 $location["address"] = $item["location"];
2000 if ($item["coord"] != "") {
2001 $coord = explode(" ", $item["coord"]);
2002 $location["lat"] = $coord[0];
2003 $location["lng"] = $coord[1];
2006 $message = array("raw_message" => $body,
2007 "location" => $location,
2008 "guid" => $item["guid"],
2009 "diaspora_handle" => $myaddr,
2010 "public" => $public,
2011 "created_at" => $created,
2012 "provider_display_name" => $item["app"]);
2014 if (count($location) == 0)
2015 unset($message["location"]);
2017 $data = array("XML" => array("post" => array("status_message" => $message)));
2020 $msg = xml::from_array($data, $xml);
2022 logger("status: ".$owner["username"]." -> ".$contact["name"]." base message: ".$msg, LOGGER_DATA);
2023 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2025 $slap = self::build_message($msg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], $public_batch);
2027 $return_code = self::transmit($owner,$contact,$slap, false);
2029 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2031 return $return_code;
2034 function send_mail($item,$owner,$contact) {
2036 $myaddr = self::get_my_handle($owner);
2038 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2039 intval($item["convid"]),
2040 intval($item["uid"])
2044 logger("conversation not found.");
2050 "guid" => $cnv["guid"],
2051 "subject" => $cnv["subject"],
2052 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2053 "diaspora_handle" => $cnv["creator"],
2054 "participant_handles" => $cnv["recips"]
2057 $body = bb2diaspora($item["body"]);
2058 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2060 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2062 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2065 "guid" => $item["guid"],
2066 "parent_guid" => $cnv["guid"],
2067 "parent_author_signature" => $sig,
2068 "author_signature" => $sig,
2070 "created_at" => $created,
2071 "diaspora_handle" => $myaddr,
2072 "conversation_guid" => $cnv["guid"]
2076 $data = array("XML" => array("post" => array("message" => $msg)));
2078 $message = array("guid" => $cnv["guid"],
2079 "subject" => $cnv["subject"],
2080 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2082 "diaspora_handle" => $cnv["creator"],
2083 "participant_handles" => $cnv["recips"]);
2085 $data = array("XML" => array("post" => array("conversation" => $message)));
2088 $xmsg = xml::from_array($data, $xml);
2090 logger("conversation: ".print_r($xmsg,true), LOGGER_DATA);
2091 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2093 $slap = self::build_message($xmsg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], false);
2095 $return_code = self::transmit($owner, $contact, $slap, false, false, $item["guid"]);
2097 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2099 return $return_code;