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);
555 // Fetch the author - for the old and the new Diaspora version
556 if ($source_xml->post->status_message->diaspora_handle)
557 $author = (string)$source_xml->post->status_message->diaspora_handle;
558 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
559 $author = (string)$source_xml->author;
561 // If this isn't a "status_message" then quit
565 $msg = array("message" => $x, "author" => $author);
567 $msg["key"] = self::get_key($msg["author"]);
572 private function fetch_parent_item($uid, $guid, $author, $contact) {
573 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
574 `author-name`, `author-link`, `author-avatar`,
575 `owner-name`, `owner-link`, `owner-avatar`
576 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
577 intval($uid), dbesc($guid));
580 $result = self::store_by_guid($guid, $contact["url"], $uid);
583 $person = self::get_person_by_handle($author);
584 $result = self::store_by_guid($guid, $person["url"], $uid);
588 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
590 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
591 `author-name`, `author-link`, `author-avatar`,
592 `owner-name`, `owner-link`, `owner-avatar`
593 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
594 intval($uid), dbesc($guid));
599 logger("parent item not found: parent: ".$guid." item: ".$guid);
605 private function get_author_contact_by_url($contact, $person, $uid) {
607 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
608 dbesc(normalise_link($person["url"])), intval($uid));
611 $network = $r[0]["network"];
613 $cid = $contact["id"];
614 $network = NETWORK_DIASPORA;
617 return (array("cid" => $cid, "network" => $network));
620 public static function is_redmatrix($url) {
621 return(strstr($url, "/channel/"));
624 private function plink($addr, $guid) {
625 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
629 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
631 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
632 // So we try another way as well.
633 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
635 $r[0]["network"] = $s[0]["network"];
637 if ($r[0]["network"] == NETWORK_DFRN)
638 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
640 if (self::is_redmatrix($r[0]["url"]))
641 return $r[0]["url"]."/?f=&mid=".$guid;
643 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
646 private function receive_account_deletion($importer, $data) {
647 $author = notags(unxmlify($data->author));
649 $contact = self::get_contact_by_handle($importer["uid"], $author);
651 logger("cannot find contact for author: ".$author);
655 // We now remove the contact
656 contact_remove($contact["id"]);
660 private function receive_comment($importer, $sender, $data) {
661 $guid = notags(unxmlify($data->guid));
662 $parent_guid = notags(unxmlify($data->parent_guid));
663 $text = unxmlify($data->text);
664 $author = notags(unxmlify($data->author));
666 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
670 if (self::message_exists($importer["uid"], $guid))
673 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
677 $person = self::get_person_by_handle($author);
678 if (!is_array($person)) {
679 logger("unable to find author details");
683 // Fetch the contact id - if we know this contact
684 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
688 $datarray["uid"] = $importer["uid"];
689 $datarray["contact-id"] = $author_contact["cid"];
690 $datarray["network"] = $author_contact["network"];
692 $datarray["author-name"] = $person["name"];
693 $datarray["author-link"] = $person["url"];
694 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
696 $datarray["owner-name"] = $contact["name"];
697 $datarray["owner-link"] = $contact["url"];
698 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
700 $datarray["guid"] = $guid;
701 $datarray["uri"] = $author.":".$guid;
703 $datarray["type"] = "remote-comment";
704 $datarray["verb"] = ACTIVITY_POST;
705 $datarray["gravity"] = GRAVITY_COMMENT;
706 $datarray["parent-uri"] = $parent_item["uri"];
708 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
709 $datarray["object"] = json_encode($data);
711 $datarray["body"] = diaspora2bb($text);
713 self::fetch_guid($datarray);
715 $message_id = item_store($datarray);
716 // print_r($datarray);
718 // If we are the origin of the parent we store the original data and notify our followers
719 if($message_id AND $parent_item["origin"]) {
721 // Formerly we stored the signed text, the signature and the author in different fields.
722 // We now store the raw data so that we are more flexible.
723 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
725 dbesc(json_encode($data))
729 proc_run("php", "include/notifier.php", "comment-import", $message_id);
735 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
736 $guid = notags(unxmlify($data->guid));
737 $subject = notags(unxmlify($data->subject));
738 $author = notags(unxmlify($data->author));
742 $msg_guid = notags(unxmlify($mesg->guid));
743 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
744 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
745 $msg_author_signature = notags(unxmlify($mesg->author_signature));
746 $msg_text = unxmlify($mesg->text);
747 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
749 // "diaspora_handle" is the element name from the old version
750 // "author" is the element name from the new version
752 $msg_author = notags(unxmlify($mesg->author));
753 elseif ($mesg->diaspora_handle)
754 $msg_author = notags(unxmlify($mesg->diaspora_handle));
758 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
760 if($msg_conversation_guid != $guid) {
761 logger("message conversation guid does not belong to the current conversation.");
765 $body = diaspora2bb($msg_text);
766 $message_uri = $msg_author.":".$msg_guid;
768 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
770 $author_signature = base64_decode($msg_author_signature);
772 if(strcasecmp($msg_author,$msg["author"]) == 0) {
776 $person = self::get_person_by_handle($msg_author);
778 if (is_array($person) && x($person, "pubkey"))
779 $key = $person["pubkey"];
781 logger("unable to find author details");
786 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
787 logger("verification failed.");
791 if($msg_parent_author_signature) {
792 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
794 $parent_author_signature = base64_decode($msg_parent_author_signature);
798 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
799 logger("owner verification failed.");
804 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
808 logger("duplicate message already delivered.", LOGGER_DEBUG);
812 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
813 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
814 intval($importer["uid"]),
816 intval($conversation["id"]),
817 dbesc($person["name"]),
818 dbesc($person["photo"]),
819 dbesc($person["url"]),
820 intval($contact["id"]),
826 dbesc($author.":".$guid),
827 dbesc($msg_created_at)
830 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
831 dbesc(datetime_convert()),
832 intval($conversation["id"])
836 "type" => NOTIFY_MAIL,
837 "notify_flags" => $importer["notify-flags"],
838 "language" => $importer["language"],
839 "to_name" => $importer["username"],
840 "to_email" => $importer["email"],
841 "uid" =>$importer["uid"],
842 "item" => array("subject" => $subject, "body" => $body),
843 "source_name" => $person["name"],
844 "source_link" => $person["url"],
845 "source_photo" => $person["thumb"],
846 "verb" => ACTIVITY_POST,
851 private function receive_conversation($importer, $msg, $data) {
852 $guid = notags(unxmlify($data->guid));
853 $subject = notags(unxmlify($data->subject));
854 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
855 $author = notags(unxmlify($data->author));
856 $participants = notags(unxmlify($data->participants));
858 $messages = $data->message;
860 if (!count($messages)) {
861 logger("empty conversation");
865 $contact = self::get_allowed_contact_by_handle($importer, $msg["author"], true);
869 $conversation = null;
871 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
872 intval($importer["uid"]),
876 $conversation = $c[0];
878 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
879 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
880 intval($importer["uid"]),
883 dbesc(datetime_convert("UTC", "UTC", $created_at)),
884 dbesc(datetime_convert()),
889 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
890 intval($importer["uid"]),
895 $conversation = $c[0];
897 if (!$conversation) {
898 logger("unable to create conversation.");
902 foreach($messages as $mesg)
903 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
908 private function construct_like_body($contact, $parent_item, $guid) {
909 $bodyverb = t('%1$s likes %2$s\'s %3$s');
911 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
912 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
913 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
915 return sprintf($bodyverb, $ulink, $alink, $plink);
918 private function construct_like_object($importer, $parent_item) {
919 $objtype = ACTIVITY_OBJ_NOTE;
920 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
921 $parent_body = $parent_item["body"];
926 <type>$objtype</type>
928 <id>{$parent_item["uri"]}</id>
931 <content>$parent_body</content>
938 private function receive_like($importer, $sender, $data) {
939 $positive = notags(unxmlify($data->positive));
940 $guid = notags(unxmlify($data->guid));
941 $parent_type = notags(unxmlify($data->parent_type));
942 $parent_guid = notags(unxmlify($data->parent_guid));
943 $author = notags(unxmlify($data->author));
945 // likes on comments aren't supported by Diaspora - only on posts
946 // But maybe this will be supported in the future, so we will accept it.
947 if (!in_array($parent_type, array("Post", "Comment")))
950 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
954 if (self::message_exists($importer["uid"], $guid))
957 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
961 $person = self::get_person_by_handle($author);
962 if (!is_array($person)) {
963 logger("unable to find author details");
967 // Fetch the contact id - if we know this contact
968 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
970 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
971 // We would accept this anyhow.
972 if ($positive === "true")
973 $verb = ACTIVITY_LIKE;
975 $verb = ACTIVITY_DISLIKE;
979 $datarray["uid"] = $importer["uid"];
980 $datarray["contact-id"] = $author_contact["cid"];
981 $datarray["network"] = $author_contact["network"];
983 $datarray["author-name"] = $person["name"];
984 $datarray["author-link"] = $person["url"];
985 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
987 $datarray["owner-name"] = $contact["name"];
988 $datarray["owner-link"] = $contact["url"];
989 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
991 $datarray["guid"] = $guid;
992 $datarray["uri"] = $author.":".$guid;
994 $datarray["type"] = "activity";
995 $datarray["verb"] = $verb;
996 $datarray["gravity"] = GRAVITY_LIKE;
997 $datarray["parent-uri"] = $parent_item["uri"];
999 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1000 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1002 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1004 $message_id = item_store($datarray);
1005 // print_r($datarray);
1007 // If we are the origin of the parent we store the original data and notify our followers
1008 if($message_id AND $parent_item["origin"]) {
1010 // Formerly we stored the signed text, the signature and the author in different fields.
1011 // We now store the raw data so that we are more flexible.
1012 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1013 intval($message_id),
1014 dbesc(json_encode($data))
1018 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1024 private function receive_message($importer, $data) {
1025 $guid = notags(unxmlify($data->guid));
1026 $parent_guid = notags(unxmlify($data->parent_guid));
1027 $text = unxmlify($data->text);
1028 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1029 $author = notags(unxmlify($data->author));
1030 $conversation_guid = notags(unxmlify($data->conversation_guid));
1032 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
1036 $conversation = null;
1038 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1039 intval($importer["uid"]),
1040 dbesc($conversation_guid)
1043 $conversation = $c[0];
1045 logger("conversation not available.");
1051 $body = diaspora2bb($text);
1052 $message_uri = $author.":".$guid;
1054 $person = self::get_person_by_handle($author);
1056 logger("unable to find author details");
1060 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1061 dbesc($message_uri),
1062 intval($importer["uid"])
1065 logger("duplicate message already delivered.", LOGGER_DEBUG);
1069 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1070 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1071 intval($importer["uid"]),
1073 intval($conversation["id"]),
1074 dbesc($person["name"]),
1075 dbesc($person["photo"]),
1076 dbesc($person["url"]),
1077 intval($contact["id"]),
1078 dbesc($conversation["subject"]),
1082 dbesc($message_uri),
1083 dbesc($author.":".$parent_guid),
1087 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1088 dbesc(datetime_convert()),
1089 intval($conversation["id"])
1095 private function receive_participation($importer, $data) {
1096 // I'm not sure if we can fully support this message type
1100 private function receive_photo($importer, $data) {
1101 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1105 private function receive_poll_participation($importer, $data) {
1106 // We don't support polls by now
1110 private function receive_profile($importer, $data) {
1111 $author = notags(unxmlify($data->author));
1113 $contact = self::get_contact_by_handle($importer["uid"], $author);
1117 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1118 $image_url = unxmlify($data->image_url);
1119 $birthday = unxmlify($data->birthday);
1120 $location = diaspora2bb(unxmlify($data->location));
1121 $about = diaspora2bb(unxmlify($data->bio));
1122 $gender = unxmlify($data->gender);
1123 $searchable = (unxmlify($data->searchable) == "true");
1124 $nsfw = (unxmlify($data->nsfw) == "true");
1125 $tags = unxmlify($data->tag_string);
1127 $tags = explode("#", $tags);
1129 $keywords = array();
1130 foreach ($tags as $tag) {
1131 $tag = trim(strtolower($tag));
1136 $keywords = implode(", ", $keywords);
1138 $handle_parts = explode("@", $author);
1139 $nick = $handle_parts[0];
1142 $name = $handle_parts[0];
1144 if( preg_match("|^https?://|", $image_url) === 0)
1145 $image_url = "http://".$handle_parts[1].$image_url;
1147 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1149 // Generic birthday. We don't know the timezone. The year is irrelevant.
1151 $birthday = str_replace("1000", "1901", $birthday);
1153 if ($birthday != "")
1154 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1156 // this is to prevent multiple birthday notifications in a single year
1157 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1159 if(substr($birthday,5) === substr($contact["bd"],5))
1160 $birthday = $contact["bd"];
1162 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1163 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1167 dbesc(datetime_convert()),
1173 intval($contact["id"]),
1174 intval($importer["uid"])
1178 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1179 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1182 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1183 "photo" => $image_url, "name" => $name, "location" => $location,
1184 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1185 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1186 "hide" => !$searchable, "nsfw" => $nsfw);
1188 update_gcontact($gcontact);
1193 private function receive_request_make_friend($importer, $contact) {
1197 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1198 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1199 intval(CONTACT_IS_FRIEND),
1200 intval($contact["id"]),
1201 intval($importer["uid"])
1204 // send notification
1206 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1207 intval($importer["uid"])
1210 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1212 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1213 intval($importer["uid"])
1216 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1218 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1221 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1222 $arr["uid"] = $importer["uid"];
1223 $arr["contact-id"] = $self[0]["id"];
1225 $arr["type"] = 'wall';
1226 $arr["gravity"] = 0;
1228 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1229 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1230 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1231 $arr["verb"] = ACTIVITY_FRIEND;
1232 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1234 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1235 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1236 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1237 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1239 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1240 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1241 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1242 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1243 $arr["object"] .= "</link></object>\n";
1244 $arr["last-child"] = 1;
1246 $arr["allow_cid"] = $user[0]["allow_cid"];
1247 $arr["allow_gid"] = $user[0]["allow_gid"];
1248 $arr["deny_cid"] = $user[0]["deny_cid"];
1249 $arr["deny_gid"] = $user[0]["deny_gid"];
1251 $i = item_store($arr);
1253 proc_run("php", "include/notifier.php", "activity", $i);
1260 private function receive_request($importer, $data) {
1261 $author = unxmlify($data->author);
1262 $recipient = unxmlify($data->recipient);
1264 if (!$author || !$recipient)
1267 $contact = self::get_contact_by_handle($importer["uid"],$author);
1271 // perhaps we were already sharing with this person. Now they're sharing with us.
1272 // That makes us friends.
1274 self::receive_request_make_friend($importer, $contact);
1278 $ret = self::get_person_by_handle($author);
1280 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1281 logger("Cannot resolve diaspora handle ".$author ." for ".$recipient);
1285 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1287 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1288 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1289 intval($importer["uid"]),
1290 dbesc($ret["network"]),
1291 dbesc($ret["addr"]),
1294 dbesc(normalise_link($ret["url"])),
1296 dbesc($ret["name"]),
1297 dbesc($ret["nick"]),
1298 dbesc($ret["photo"]),
1299 dbesc($ret["pubkey"]),
1300 dbesc($ret["notify"]),
1301 dbesc($ret["poll"]),
1306 // find the contact record we just created
1308 $contact_record = self::get_contact_by_handle($importer["uid"],$author);
1310 if (!$contact_record) {
1311 logger("unable to locate newly created contact record.");
1315 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1316 intval($importer["uid"])
1319 if($g && intval($g[0]["def_gid"]))
1320 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1322 if($importer["page-flags"] == PAGE_NORMAL) {
1324 $hash = random_string().(string)time(); // Generate a confirm_key
1326 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1327 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1328 intval($importer["uid"]),
1329 intval($contact_record["id"]),
1332 dbesc(t("Sharing notification from Diaspora network")),
1334 dbesc(datetime_convert())
1338 // automatic friend approval
1340 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1342 // technically they are sharing with us (CONTACT_IS_SHARING),
1343 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1344 // we are going to change the relationship and make them a follower.
1346 if($importer["page-flags"] == PAGE_FREELOVE)
1347 $new_relation = CONTACT_IS_FRIEND;
1349 $new_relation = CONTACT_IS_FOLLOWER;
1351 $r = q("UPDATE `contact` SET `rel` = %d,
1359 intval($new_relation),
1360 dbesc(datetime_convert()),
1361 dbesc(datetime_convert()),
1362 intval($contact_record["id"])
1365 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1367 $ret = diaspora_share($u[0], $contact_record);
1373 private function get_original_item($guid, $orig_author, $author) {
1375 // Do we already have this item?
1376 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1377 `author-name`, `author-link`, `author-avatar`
1378 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1382 logger("reshared message ".$guid." already exists on system.");
1384 // Maybe it is already a reshared item?
1385 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1386 if (self::is_reshare($r[0]["body"]))
1393 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1394 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1395 $item_id = self::store_by_guid($guid, $server);
1398 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1399 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1400 $item_id = self::store_by_guid($guid, $server);
1403 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1405 $server = "https://".substr($author, strpos($author, "@") + 1);
1406 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1407 $item_id = self::store_by_guid($guid, $server);
1410 $server = "http://".substr($author, strpos($author, "@") + 1);
1411 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1412 $item_id = self::store_by_guid($guid, $server);
1416 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1417 `author-name`, `author-link`, `author-avatar`
1418 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1429 private function receive_reshare($importer, $data) {
1430 $root_author = notags(unxmlify($data->root_author));
1431 $root_guid = notags(unxmlify($data->root_guid));
1432 $guid = notags(unxmlify($data->guid));
1433 $author = notags(unxmlify($data->author));
1434 $public = notags(unxmlify($data->public));
1435 $created_at = notags(unxmlify($data->created_at));
1437 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1441 if (self::message_exists($importer["uid"], $guid))
1444 $original_item = self::get_original_item($root_guid, $root_author, $author);
1445 if (!$original_item)
1448 $datarray = array();
1450 $datarray["uid"] = $importer["uid"];
1451 $datarray["contact-id"] = $contact["id"];
1452 $datarray["network"] = NETWORK_DIASPORA;
1454 $datarray["author-name"] = $contact["name"];
1455 $datarray["author-link"] = $contact["url"];
1456 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1458 $datarray["owner-name"] = $datarray["author-name"];
1459 $datarray["owner-link"] = $datarray["author-link"];
1460 $datarray["owner-avatar"] = $datarray["author-avatar"];
1462 $datarray["guid"] = $guid;
1463 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1465 $datarray["verb"] = ACTIVITY_POST;
1466 $datarray["gravity"] = GRAVITY_PARENT;
1468 $datarray["object"] = json_encode($data);
1470 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1471 $original_item["guid"], $original_item["created"], $original_item["uri"]);
1472 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1474 $datarray["tag"] = $original_item["tag"];
1475 $datarray["app"] = $original_item["app"];
1477 $datarray["plink"] = self::plink($author, $guid);
1478 $datarray["private"] = (($public == "false") ? 1 : 0);
1479 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1481 $datarray["object-type"] = $original_item["object-type"];
1483 self::fetch_guid($datarray);
1484 $message_id = item_store($datarray);
1485 // print_r($datarray);
1490 private function item_retraction($importer, $contact, $data) {
1491 $target_type = notags(unxmlify($data->target_type));
1492 $target_guid = notags(unxmlify($data->target_guid));
1493 $author = notags(unxmlify($data->author));
1495 $person = self::get_person_by_handle($author);
1496 if (!is_array($person)) {
1497 logger("unable to find author detail for ".$author);
1501 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1502 dbesc($target_guid),
1503 intval($importer["uid"])
1508 // Only delete it if the author really fits
1509 if (!link_compare($r[0]["author-link"],$person["url"]))
1512 // Check if the sender is the thread owner
1513 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1514 intval($r[0]["parent"]));
1516 // Only delete it if the parent author really fits
1517 if (!link_compare($p[0]["author-link"], $contact["url"]))
1520 // 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
1521 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1522 dbesc(datetime_convert()),
1523 dbesc(datetime_convert()),
1526 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1528 // Now check if the retraction needs to be relayed by us
1529 if($p[0]["origin"]) {
1531 // Formerly we stored the signed text, the signature and the author in different fields.
1532 // We now store the raw data so that we are more flexible.
1533 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1534 intval($r[0]["id"]),
1535 dbesc(json_encode($data))
1539 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1543 private function receive_retraction($importer, $sender, $data) {
1544 $target_type = notags(unxmlify($data->target_type));
1546 $contact = self::get_contact_by_handle($importer["uid"], $sender);
1548 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1552 switch ($target_type) {
1555 case "Post": // "Post" will be supported in a future version
1557 case "StatusMessage":
1558 return self::item_retraction($importer, $contact, $data);;
1560 case "Person": /// @todo an "unshare" shouldn't remove the contact
1561 contact_remove($contact["id"]);
1565 logger("Unknown target type ".$target_type);
1571 private function receive_status_message($importer, $data) {
1573 $raw_message = unxmlify($data->raw_message);
1574 $guid = notags(unxmlify($data->guid));
1575 $author = notags(unxmlify($data->author));
1576 $public = notags(unxmlify($data->public));
1577 $created_at = notags(unxmlify($data->created_at));
1578 $provider_display_name = notags(unxmlify($data->provider_display_name));
1580 /// @todo enable support for polls
1581 //if ($data->poll) {
1582 // foreach ($data->poll AS $poll)
1586 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1590 if (self::message_exists($importer["uid"], $guid))
1594 if ($data->location)
1595 foreach ($data->location->children() AS $fieldname => $data)
1596 $address[$fieldname] = notags(unxmlify($data));
1598 $body = diaspora2bb($raw_message);
1600 $datarray = array();
1603 foreach ($data->photo AS $photo)
1604 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1606 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1608 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1610 // Add OEmbed and other information to the body
1611 if (!self::is_redmatrix($contact["url"]))
1612 $body = add_page_info_to_body($body, false, true);
1615 $datarray["uid"] = $importer["uid"];
1616 $datarray["contact-id"] = $contact["id"];
1617 $datarray["network"] = NETWORK_DIASPORA;
1619 $datarray["author-name"] = $contact["name"];
1620 $datarray["author-link"] = $contact["url"];
1621 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1623 $datarray["owner-name"] = $datarray["author-name"];
1624 $datarray["owner-link"] = $datarray["author-link"];
1625 $datarray["owner-avatar"] = $datarray["author-avatar"];
1627 $datarray["guid"] = $guid;
1628 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1630 $datarray["verb"] = ACTIVITY_POST;
1631 $datarray["gravity"] = GRAVITY_PARENT;
1633 $datarray["object"] = json_encode($data);
1635 $datarray["body"] = $body;
1637 if ($provider_display_name != "")
1638 $datarray["app"] = $provider_display_name;
1640 $datarray["plink"] = self::plink($author, $guid);
1641 $datarray["private"] = (($public == "false") ? 1 : 0);
1642 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1644 if (isset($address["address"]))
1645 $datarray["location"] = $address["address"];
1647 if (isset($address["lat"]) AND isset($address["lng"]))
1648 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1650 self::fetch_guid($datarray);
1651 $message_id = item_store($datarray);
1652 // print_r($datarray);
1654 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1659 /*******************************************************************************************
1660 * Here come all the functions that are needed to transmit data with the Diaspora protocol *
1661 *******************************************************************************************/
1663 private function get_my_handle($me) {
1664 if ($contact["addr"] != "")
1665 return $contact["addr"];
1667 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1668 // So - just in case - we build the the address here.
1669 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1672 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1674 logger("Message: ".$msg, LOGGER_DATA);
1676 $handle = self::get_my_handle($user);
1678 $b64url_data = base64url_encode($msg);
1680 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1682 $type = "application/xml";
1683 $encoding = "base64url";
1684 $alg = "RSA-SHA256";
1686 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1688 $signature = rsa_sign($signable_data,$prvkey);
1689 $sig = base64url_encode($signature);
1691 $magic_env = <<< EOT
1692 <?xml version='1.0' encoding='UTF-8'?>
1693 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1695 <author_id>$handle</author_id>
1698 <me:encoding>base64url</me:encoding>
1699 <me:alg>RSA-SHA256</me:alg>
1700 <me:data type="application/xml">$data</me:data>
1701 <me:sig>$sig</me:sig>
1706 logger("magic_env: ".$magic_env, LOGGER_DATA);
1710 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1712 logger("Message: ".$msg, LOGGER_DATA);
1714 // without a public key nothing will work
1717 logger("pubkey missing: contact id: ".$contact["id"]);
1721 $inner_aes_key = random_string(32);
1722 $b_inner_aes_key = base64_encode($inner_aes_key);
1723 $inner_iv = random_string(16);
1724 $b_inner_iv = base64_encode($inner_iv);
1726 $outer_aes_key = random_string(32);
1727 $b_outer_aes_key = base64_encode($outer_aes_key);
1728 $outer_iv = random_string(16);
1729 $b_outer_iv = base64_encode($outer_iv);
1731 $handle = self::get_my_handle($user);
1733 $padded_data = pkcs5_pad($msg,16);
1734 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1736 $b64_data = base64_encode($inner_encrypted);
1739 $b64url_data = base64url_encode($b64_data);
1740 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1742 $type = "application/xml";
1743 $encoding = "base64url";
1744 $alg = "RSA-SHA256";
1746 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1748 $signature = rsa_sign($signable_data,$prvkey);
1749 $sig = base64url_encode($signature);
1751 $decrypted_header = <<< EOT
1753 <iv>$b_inner_iv</iv>
1754 <aes_key>$b_inner_aes_key</aes_key>
1755 <author_id>$handle</author_id>
1759 $decrypted_header = pkcs5_pad($decrypted_header,16);
1761 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1763 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1765 $encrypted_outer_key_bundle = "";
1766 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1768 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1770 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1772 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1773 "ciphertext" => base64_encode($ciphertext)));
1774 $cipher_json = base64_encode($encrypted_header_json_object);
1776 $encrypted_header = "<encrypted_header>".$cipher_json."</encrypted_header>";
1778 $magic_env = <<< EOT
1779 <?xml version='1.0' encoding='UTF-8'?>
1780 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1783 <me:encoding>base64url</me:encoding>
1784 <me:alg>RSA-SHA256</me:alg>
1785 <me:data type="application/xml">$data</me:data>
1786 <me:sig>$sig</me:sig>
1791 logger("magic_env: ".$magic_env, LOGGER_DATA);
1795 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1798 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1800 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1802 // The data that will be transmitted is double encoded via "urlencode", strange ...
1803 $slap = "xml=".urlencode(urlencode($magic_env));
1807 private function get_signature($owner, $message) {
1809 unset($sigmsg["author_signature"]);
1810 unset($sigmsg["parent_author_signature"]);
1812 $signed_text = implode(";", $sigmsg);
1814 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
1817 private function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
1821 $enabled = intval(get_config("system", "diaspora_enabled"));
1825 $logid = random_string(4);
1826 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
1828 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
1832 logger("transmit: ".$logid."-".$guid." ".$dest_url);
1834 if (!$queue_run && was_recently_delayed($contact["id"])) {
1837 if (!intval(get_config("system", "diaspora_test"))) {
1838 post_url($dest_url."/", $slap);
1839 $return_code = $a->get_curl_code();
1841 logger("test_mode");
1846 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
1848 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
1849 logger("queue message");
1851 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
1852 intval($contact["id"]),
1853 dbesc(NETWORK_DIASPORA),
1855 intval($public_batch)
1858 logger("add_to_queue ignored - identical item already in queue");
1860 // queue message for redelivery
1861 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
1866 return(($return_code) ? $return_code : (-1));
1869 public static function send_share($me,$contact) {
1870 $myaddr = self::get_my_handle($me);
1871 $theiraddr = $contact["addr"];
1873 $data = array("XML" => array("post" => array("request" => array(
1874 "sender_handle" => $myaddr,
1875 "recipient_handle" => $theiraddr
1878 $msg = xml::from_array($data, $xml);
1880 $slap = self::build_message($msg, $me, $contact, $me["prvkey"], $contact["pubkey"]);
1882 return(self::transmit($owner,$contact,$slap, false));
1886 public static function send_unshare($me,$contact) {
1887 $myaddr = self::get_my_handle($me);
1889 $data = array("XML" => array("post" => array("retraction" => array(
1890 "post_guid" => $me["guid"],
1891 "diaspora_handle" => $myaddr,
1895 $msg = xml::from_array($data, $xml);
1897 $slap = self::build_message($msg, $me, $contact, $me["prvkey"], $contact["pubkey"]);
1899 return(self::transmit($owner,$contact,$slap, false));
1902 private function is_reshare($body) {
1903 $body = trim($body);
1905 // Skip if it isn't a pure repeated messages
1906 // Does it start with a share?
1907 if (strpos($body, "[share") > 0)
1910 // Does it end with a share?
1911 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1914 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1915 // Skip if there is no shared message in there
1916 if ($body == $attributes)
1920 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1921 if ($matches[1] != "")
1922 $guid = $matches[1];
1924 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1925 if ($matches[1] != "")
1926 $guid = $matches[1];
1929 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
1930 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
1933 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
1934 $ret["root_guid"] = $guid;
1940 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
1941 if ($matches[1] != "")
1942 $profile = $matches[1];
1944 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
1945 if ($matches[1] != "")
1946 $profile = $matches[1];
1950 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
1951 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
1955 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1956 if ($matches[1] != "")
1957 $link = $matches[1];
1959 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1960 if ($matches[1] != "")
1961 $link = $matches[1];
1963 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
1964 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
1969 public static function send_status($item, $owner, $contact, $public_batch = false) {
1971 $myaddr = self::get_my_handle($owner);
1972 $theiraddr = $contact["addr"];
1974 $title = $item["title"];
1975 $body = $item["body"];
1977 // convert to markdown
1978 $body = html_entity_decode(bb2diaspora($body));
1982 $body = "## ".html_entity_decode($title)."\n\n".$body;
1984 if ($item["attach"]) {
1985 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
1987 $body .= "\n".t("Attachments:")."\n";
1988 foreach($matches as $mtch)
1989 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
1994 $public = (($item["private"]) ? "false" : "true");
1996 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
1998 // Detect a share element and do a reshare
1999 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2000 $message = array("root_diaspora_id" => $ret["root_handle"],
2001 "root_guid" => $ret["root_guid"],
2002 "guid" => $item["guid"],
2003 "diaspora_handle" => $myaddr,
2004 "public" => $public,
2005 "created_at" => $created,
2006 "provider_display_name" => $item["app"]);
2008 $data = array("XML" => array("post" => array("reshare" => $message)));
2010 $location = array();
2012 if ($item["location"] != "")
2013 $location["address"] = $item["location"];
2015 if ($item["coord"] != "") {
2016 $coord = explode(" ", $item["coord"]);
2017 $location["lat"] = $coord[0];
2018 $location["lng"] = $coord[1];
2021 $message = array("raw_message" => $body,
2022 "location" => $location,
2023 "guid" => $item["guid"],
2024 "diaspora_handle" => $myaddr,
2025 "public" => $public,
2026 "created_at" => $created,
2027 "provider_display_name" => $item["app"]);
2029 if (count($location) == 0)
2030 unset($message["location"]);
2032 $data = array("XML" => array("post" => array("status_message" => $message)));
2035 $msg = xml::from_array($data, $xml);
2037 logger("status: ".$owner["username"]." -> ".$contact["name"]." base message: ".$msg, LOGGER_DATA);
2038 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2040 $slap = self::build_message($msg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], $public_batch);
2042 $return_code = self::transmit($owner,$contact,$slap, false);
2044 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2046 return $return_code;
2049 private function construct_like($item,$owner,$contact,$public_batch = false, $data = null) {
2051 if (is_array($data))
2054 $myaddr = self::get_my_handle($owner);
2056 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2057 dbesc($item["thr-parent"]));
2063 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2066 $message = array("positive" => $positive,
2067 "guid" => $item["guid"],
2068 "target_type" => $target_type,
2069 "parent_guid" => $parent["guid"],
2070 "author_signature" => $authorsig,
2071 "diaspora_handle" => $myaddr);
2074 $authorsig = self::get_signature($owner, $message);
2076 if ($message["author_signature"] == "")
2077 $message["author_signature"] = $authorsig;
2079 $message["parent_author_signature"] = $authorsig;
2081 $data = array("XML" => array("post" => array("like" => $message)));
2083 return xml::from_array($data, $xml);
2086 private function construct_comment($item,$owner,$contact,$public_batch = false, $data = null) {
2088 if (is_array($data))
2091 $myaddr = self::get_my_handle($owner);
2093 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2094 intval($item["parent"]),
2095 intval($item["parent"])
2103 $text = html_entity_decode(bb2diaspora($item["body"]));
2105 $message = array("guid" => $item["guid"],
2106 "parent_guid" => $parent["guid"],
2107 "author_signature" => "",
2109 "diaspora_handle" => $myaddr);
2112 $authorsig = self::get_signature($owner, $message);
2114 if ($message["author_signature"] == "")
2115 $message["author_signature"] = $authorsig;
2117 $message["parent_author_signature"] = $authorsig;
2119 $data = array("XML" => array("post" => array("comment" => $message)));
2121 return xml::from_array($data, $xml);
2124 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2126 if($item['verb'] === ACTIVITY_LIKE)
2127 $msg = self::construct_like($item, $owner, $contact, $public_batch);
2129 $msg = self::construct_comment($item, $owner, $contact, $public_batch);
2134 logger("base message: ".$msg, LOGGER_DATA);
2135 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2137 $slap = self::build_message($msg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], $public_batch);
2139 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $item["guid"]);
2141 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2143 return $return_code;
2146 function send_relay($item, $owner, $contact, $public_batch = false) {
2148 if ($item["deleted"])
2149 $sql_sign_id = "retract_iid";
2151 $sql_sign_id = "iid";
2153 // fetch the original signature if the relayable was created by a Diaspora
2156 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2162 $signed_text = $orig_sign['signed_text'];
2163 $authorsig = $orig_sign['signature'];
2164 $handle = $orig_sign['signer'];
2166 // Split the signed text
2167 $signed_parts = explode(";", $signed_text);
2169 if ($item['verb'] === ACTIVITY_LIKE) {
2170 $data = array("positive" => $signed_parts[0],
2171 "guid" => $signed_parts[1],
2172 "target_type" => $signed_parts[2],
2173 "parent_guid" => $signed_parts[3],
2174 "parent_author_signature" => "",
2175 "author_signature" => $orig_sign['signature'],
2176 "diaspora_handle" => $signed_parts[4]);
2178 // Remove the comment guid
2179 $guid = array_shift($signed_parts);
2181 // Remove the parent guid
2182 $parent_guid = array_shift($signed_parts);
2184 // Remove the handle
2185 $handle = array_pop($signed_parts);
2187 // Glue the parts together
2188 $text = implode(";", $signed_parts);
2190 $data = array("guid" => $guid,
2191 "parent_guid" => $parent_guid,
2192 "parent_author_signature" => "",
2193 "author_signature" => $orig_sign['signature'],
2194 "text" => implode(";", $signed_parts),
2195 "diaspora_handle" => $handle);
2199 if ($item['deleted'])
2200 ; // Relayed Retraction
2201 elseif($item['verb'] === ACTIVITY_LIKE)
2202 $msg = self::construct_like($item, $owner, $contact, $public_batch, $data);
2204 $msg = self::construct_comment($item, $owner, $contact, $public_batch, $data);
2207 logger('base message: '.$msg, LOGGER_DATA);
2208 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2210 $slap = self::build_message($msg,$owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2212 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $item['guid']);
2214 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2216 return $return_code;
2220 // Diaspora doesn't support threaded comments, but some
2221 // versions of Diaspora (i.e. Diaspora-pistos) support
2222 // likes on comments
2223 if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2224 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2225 dbesc($item['thr-parent'])
2229 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2230 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2231 // The only item with `parent` and `id` as the parent id is the parent item.
2232 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2233 intval($item['parent']),
2234 intval($item['parent'])
2243 $relay_retract = false;
2244 $sql_sign_id = 'iid';
2245 if( $item['deleted']) {
2246 $relay_retract = true;
2248 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2250 $sql_sign_id = 'retract_iid';
2251 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2253 elseif($item['verb'] === ACTIVITY_LIKE) {
2256 $target_type = ( $parent['uri'] === $parent['parent-uri'] ? 'Post' : 'Comment');
2257 // $positive = (($item['deleted']) ? 'false' : 'true');
2260 $tpl = get_markup_template('diaspora_like_relay.tpl');
2262 else { // item is a comment
2263 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2267 // fetch the original signature if the relayable was created by a Diaspora
2268 // or DFRN user. Relayables for other networks are not supported.
2270 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2275 $signed_text = $orig_sign['signed_text'];
2276 $authorsig = $orig_sign['signature'];
2277 $handle = $orig_sign['signer'];
2279 // Split the signed text
2280 $signed_parts = explode(";", $signed_text);
2282 // Remove the parent guid
2283 array_shift($signed_parts);
2285 // Remove the comment guid
2286 array_shift($signed_parts);
2288 // Remove the handle
2289 array_pop($signed_parts);
2291 // Glue the parts together
2292 $text = implode(";", $signed_parts);
2295 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2296 // This means that the comment won't be accepted by newer Diaspora servers
2298 $body = $item['body'];
2299 $text = html_entity_decode(bb2diaspora($body));
2301 $handle = diaspora_handle_from_contact($item['contact-id']);
2306 $signed_text = $item['guid'] . ';' . $target_type;
2308 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2310 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2312 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2315 // Sign the relayable with the top-level owner's signature
2316 $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2318 $msg = replace_macros($tpl,array(
2319 '$guid' => xmlify($item['guid']),
2320 '$parent_guid' => xmlify($parent['guid']),
2321 '$target_type' =>xmlify($target_type),
2322 '$authorsig' => xmlify($authorsig),
2323 '$parentsig' => xmlify($parentauthorsig),
2324 '$body' => xmlify($text),
2325 '$positive' => xmlify($positive),
2326 '$handle' => xmlify($handle)
2329 logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2330 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2332 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2333 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2335 return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2338 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2340 $myaddr = self::get_my_handle($owner);
2342 // Check whether the retraction is for a top-level post or whether it's a relayable
2343 if ($item["uri"] !== $item["parent-uri"]) {
2344 $msg_type = "relayable_retraction";
2345 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2347 $msg_type = "signed_retraction";
2348 $target_type = "StatusMessage";
2351 $signed_text = $item["guid"].";".$target_type;
2353 $message = array("target_guid" => $item['guid'],
2354 "target_type" => $target_type,
2355 "sender_handle" => $myaddr,
2356 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2358 $data = array("XML" => array("post" => array($msg_type => $message)));
2359 $msg = xml::from_array($data, $xml);
2361 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2363 $slap = self::build_message($msg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], $public_batch);
2365 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $item["guid"]);
2367 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2369 return $return_code;
2372 public static function send_mail($item,$owner,$contact) {
2374 $myaddr = self::get_my_handle($owner);
2376 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2377 intval($item["convid"]),
2378 intval($item["uid"])
2382 logger("conversation not found.");
2388 "guid" => $cnv["guid"],
2389 "subject" => $cnv["subject"],
2390 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2391 "diaspora_handle" => $cnv["creator"],
2392 "participant_handles" => $cnv["recips"]
2395 $body = bb2diaspora($item["body"]);
2396 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2398 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2400 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2403 "guid" => $item["guid"],
2404 "parent_guid" => $cnv["guid"],
2405 "parent_author_signature" => $sig,
2406 "author_signature" => $sig,
2408 "created_at" => $created,
2409 "diaspora_handle" => $myaddr,
2410 "conversation_guid" => $cnv["guid"]
2414 $data = array("XML" => array("post" => array("message" => $msg)));
2416 $message = array("guid" => $cnv["guid"],
2417 "subject" => $cnv["subject"],
2418 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2420 "diaspora_handle" => $cnv["creator"],
2421 "participant_handles" => $cnv["recips"]);
2423 $data = array("XML" => array("post" => array("conversation" => $message)));
2426 $xmsg = xml::from_array($data, $xml);
2428 logger("conversation: ".print_r($xmsg,true), LOGGER_DATA);
2429 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2431 $slap = self::build_message($xmsg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], false);
2433 $return_code = self::transmit($owner, $contact, $slap, false, false, $item["guid"]);
2435 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2437 return $return_code;