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");
16 require_once("include/queue_fn.php");
19 * @brief This class contain functions to create and send Diaspora XML files
24 public static function relay_list() {
26 $serverdata = get_config("system", "relay_server");
27 if ($serverdata == "")
32 $servers = explode(",", $serverdata);
34 foreach($servers AS $server) {
35 $server = trim($server);
36 $batch = $server."/receive/public";
38 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
41 $addr = "relay@".str_replace("http://", "", normalise_link($server));
43 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
44 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
49 dbesc(normalise_link($server)),
51 dbesc(NETWORK_DIASPORA),
52 intval(CONTACT_IS_FOLLOWER),
53 dbesc(datetime_convert()),
54 dbesc(datetime_convert()),
55 dbesc(datetime_convert())
58 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
60 $relay[] = $relais[0];
62 $relay[] = $relais[0];
68 function repair_signature($signature, $handle = "", $level = 1) {
73 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
74 $signature = base64_decode($signature);
75 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
77 // Do a recursive call to be able to fix even multiple levels
79 $signature = self::repair_signature($signature, $handle, ++$level);
86 * @brief: Decodes incoming Diaspora message
88 * @param array $importer from user table
89 * @param string $xml urldecoded Diaspora salmon
92 * 'message' -> decoded Diaspora XML message
93 * 'author' -> author diaspora handle
94 * 'key' -> author public key (converted to pkcs#8)
96 function decode($importer, $xml) {
99 $basedom = parse_xml_string($xml);
101 if (!is_object($basedom))
104 $children = $basedom->children('https://joindiaspora.com/protocol');
106 if($children->header) {
108 $author_link = str_replace('acct:','',$children->header->author_id);
111 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
113 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
114 $ciphertext = base64_decode($encrypted_header->ciphertext);
116 $outer_key_bundle = '';
117 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
119 $j_outer_key_bundle = json_decode($outer_key_bundle);
121 $outer_iv = base64_decode($j_outer_key_bundle->iv);
122 $outer_key = base64_decode($j_outer_key_bundle->key);
124 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
127 $decrypted = pkcs5_unpad($decrypted);
130 * $decrypted now contains something like
133 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
134 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
135 * <author_id>galaxor@diaspora.priateship.org</author_id>
136 * </decrypted_header>
139 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
140 $idom = parse_xml_string($decrypted,false);
142 $inner_iv = base64_decode($idom->iv);
143 $inner_aes_key = base64_decode($idom->aes_key);
145 $author_link = str_replace('acct:','',$idom->author_id);
148 $dom = $basedom->children(NAMESPACE_SALMON_ME);
150 // figure out where in the DOM tree our data is hiding
152 if($dom->provenance->data)
153 $base = $dom->provenance;
154 elseif($dom->env->data)
160 logger('unable to locate salmon data in xml');
161 http_status_exit(400);
165 // Stash the signature away for now. We have to find their key or it won't be good for anything.
166 $signature = base64url_decode($base->sig);
170 // strip whitespace so our data element will return to one big base64 blob
171 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
174 // stash away some other stuff for later
176 $type = $base->data[0]->attributes()->type[0];
177 $keyhash = $base->sig[0]->attributes()->keyhash[0];
178 $encoding = $base->encoding;
182 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
186 $data = base64url_decode($data);
190 $inner_decrypted = $data;
193 // Decode the encrypted blob
195 $inner_encrypted = base64_decode($data);
196 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
197 $inner_decrypted = pkcs5_unpad($inner_decrypted);
201 logger('Could not retrieve author URI.');
202 http_status_exit(400);
204 // Once we have the author URI, go to the web and try to find their public key
205 // (first this will look it up locally if it is in the fcontact cache)
206 // This will also convert diaspora public key from pkcs#1 to pkcs#8
208 logger('Fetching key for '.$author_link);
209 $key = self::key($author_link);
212 logger('Could not retrieve author key.');
213 http_status_exit(400);
216 $verify = rsa_verify($signed_data,$signature,$key);
219 logger('Message did not verify. Discarding.');
220 http_status_exit(400);
223 logger('Message verified.');
225 return array('message' => (string)$inner_decrypted,
226 'author' => unxmlify($author_link),
227 'key' => (string)$key);
233 * @brief Dispatches public messages and find the fitting receivers
235 * @param array $msg The post that will be dispatched
237 * @return bool Was the message accepted?
239 public static function dispatch_public($msg) {
241 $enabled = intval(get_config("system", "diaspora_enabled"));
243 logger("diaspora is disabled");
247 // Use a dummy importer to import the data for the public copy
248 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
249 $item_id = self::dispatch($importer,$msg);
251 // Now distribute it to the followers
252 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
253 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
254 AND NOT `account_expired` AND NOT `account_removed`",
255 dbesc(NETWORK_DIASPORA),
256 dbesc($msg["author"])
260 logger("delivering to: ".$rr["username"]);
261 self::dispatch($rr,$msg);
264 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
270 * @brief Dispatches the different message types to the different functions
272 * @param array $importer Array of the importer user
273 * @param array $msg The post that will be dispatched
275 * @return bool Was the message accepted?
277 public static function dispatch($importer, $msg) {
279 // The sender is the handle of the contact that sent the message.
280 // This will often be different with relayed messages (for example "like" and "comment")
281 $sender = $msg["author"];
283 if (!diaspora::valid_posting($msg, $fields)) {
284 logger("Invalid posting");
288 $type = $fields->getName();
290 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
293 case "account_deletion":
294 return self::receive_account_deletion($importer, $fields);
297 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
300 return self::receive_conversation($importer, $msg, $fields);
303 return self::receive_like($importer, $sender, $fields);
306 return self::receive_message($importer, $fields);
308 case "participation": // Not implemented
309 return self::receive_participation($importer, $fields);
311 case "photo": // Not implemented
312 return self::receive_photo($importer, $fields);
314 case "poll_participation": // Not implemented
315 return self::receive_poll_participation($importer, $fields);
318 return self::receive_profile($importer, $fields);
321 return self::receive_request($importer, $fields);
324 return self::receive_reshare($importer, $fields, $msg["message"]);
327 return self::receive_retraction($importer, $sender, $fields);
329 case "status_message":
330 return self::receive_status_message($importer, $fields, $msg["message"]);
333 logger("Unknown message type ".$type);
341 * @brief Checks if a posting is valid and fetches the data fields.
343 * This function does not only check the signature.
344 * It also does the conversion between the old and the new diaspora format.
346 * @param array $msg Array with the XML, the sender handle and the sender signature
347 * @param object $fields SimpleXML object that contains the posting when it is valid
349 * @return bool Is the posting valid?
351 private function valid_posting($msg, &$fields) {
353 $data = parse_xml_string($msg["message"], false);
355 if (!is_object($data))
358 $first_child = $data->getName();
360 // Is this the new or the old version?
361 if ($data->getName() == "XML") {
363 foreach ($data->post->children() as $child)
370 $type = $element->getName();
373 // All retractions are handled identically from now on.
374 // In the new version there will only be "retraction".
375 if (in_array($type, array("signed_retraction", "relayable_retraction")))
376 $type = "retraction";
378 $fields = new SimpleXMLElement("<".$type."/>");
382 foreach ($element->children() AS $fieldname => $entry) {
384 // Translation for the old XML structure
385 if ($fieldname == "diaspora_handle")
386 $fieldname = "author";
388 if ($fieldname == "participant_handles")
389 $fieldname = "participants";
391 if (in_array($type, array("like", "participation"))) {
392 if ($fieldname == "target_type")
393 $fieldname = "parent_type";
396 if ($fieldname == "sender_handle")
397 $fieldname = "author";
399 if ($fieldname == "recipient_handle")
400 $fieldname = "recipient";
402 if ($fieldname == "root_diaspora_id")
403 $fieldname = "root_author";
405 if ($type == "retraction") {
406 if ($fieldname == "post_guid")
407 $fieldname = "target_guid";
409 if ($fieldname == "type")
410 $fieldname = "target_type";
414 if ($fieldname == "author_signature")
415 $author_signature = base64_decode($entry);
416 elseif ($fieldname == "parent_author_signature")
417 $parent_author_signature = base64_decode($entry);
418 elseif ($fieldname != "target_author_signature") {
419 if ($signed_data != "") {
421 $signed_data_parent .= ";";
424 $signed_data .= $entry;
426 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
427 ($orig_type == "relayable_retraction"))
428 xml::copy($entry, $fields, $fieldname);
431 // This is something that shouldn't happen at all.
432 if (in_array($type, array("status_message", "reshare", "profile")))
433 if ($msg["author"] != $fields->author) {
434 logger("Message handle is not the same as envelope sender. Quitting this message.");
438 // Only some message types have signatures. So we quit here for the other types.
439 if (!in_array($type, array("comment", "message", "like")))
442 // No author_signature? This is a must, so we quit.
443 if (!isset($author_signature))
446 if (isset($parent_author_signature)) {
447 $key = self::key($msg["author"]);
449 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
453 $key = self::key($fields->author);
455 return rsa_verify($signed_data, $author_signature, $key, "sha256");
459 * @brief Fetches the public key for a given handle
461 * @param string $handle The handle
463 * @return string The public key
465 private function key($handle) {
466 $handle = strval($handle);
468 logger("Fetching diaspora key for: ".$handle);
470 $r = self::person_by_handle($handle);
478 * @brief Fetches data for a given handle
480 * @param string $handle The handle
482 * @return array the queried data
484 private function person_by_handle($handle) {
486 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
487 dbesc(NETWORK_DIASPORA),
492 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
494 // update record occasionally so it doesn't get stale
495 $d = strtotime($person["updated"]." +00:00");
496 if ($d < strtotime("now - 14 days"))
500 if (!$person OR $update) {
501 logger("create or refresh", LOGGER_DEBUG);
502 $r = probe_url($handle, PROBE_DIASPORA);
504 // Note that Friendica contacts will return a "Diaspora person"
505 // if Diaspora connectivity is enabled on their server
506 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
507 self::add_fcontact($r, $update);
515 * @brief Updates the fcontact table
517 * @param array $arr The fcontact data
518 * @param bool $update Update or insert?
520 * @return string The id of the fcontact entry
522 private function add_fcontact($arr, $update = false) {
525 $r = q("UPDATE `fcontact` SET
538 WHERE `url` = '%s' AND `network` = '%s'",
540 dbesc($arr["photo"]),
541 dbesc($arr["request"]),
544 dbesc($arr["batch"]),
545 dbesc($arr["notify"]),
547 dbesc($arr["confirm"]),
548 dbesc($arr["alias"]),
549 dbesc($arr["pubkey"]),
550 dbesc(datetime_convert()),
552 dbesc($arr["network"])
555 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
556 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
557 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
560 dbesc($arr["photo"]),
561 dbesc($arr["request"]),
564 dbesc($arr["batch"]),
565 dbesc($arr["notify"]),
567 dbesc($arr["confirm"]),
568 dbesc($arr["network"]),
569 dbesc($arr["alias"]),
570 dbesc($arr["pubkey"]),
571 dbesc(datetime_convert())
578 public static function handle_from_contact($contact_id) {
581 logger("contact id is ".$contact_id, LOGGER_DEBUG);
583 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
589 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
591 if($contact['addr'] != "")
592 $handle = $contact['addr'];
593 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
594 $baseurl_start = strpos($contact['url'],'://') + 3;
595 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
596 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
597 $handle = $contact['nick'].'@'.$baseurl;
604 private function contact_by_handle($uid, $handle) {
605 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
613 $handle_parts = explode("@", $handle);
614 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
615 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
626 private function post_allow($importer, $contact, $is_comment = false) {
628 // perhaps we were already sharing with this person. Now they're sharing with us.
629 // That makes us friends.
630 // Normally this should have handled by getting a request - but this could get lost
631 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
632 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
633 intval(CONTACT_IS_FRIEND),
634 intval($contact["id"]),
635 intval($importer["uid"])
637 $contact["rel"] = CONTACT_IS_FRIEND;
638 logger("defining user ".$contact["nick"]." as friend");
641 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
643 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
645 if($contact["rel"] == CONTACT_IS_FOLLOWER)
646 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
649 // Messages for the global users are always accepted
650 if ($importer["uid"] == 0)
656 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
657 $contact = self::contact_by_handle($importer["uid"], $handle);
659 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
663 if (!self::post_allow($importer, $contact, $is_comment)) {
664 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
670 private function message_exists($uid, $guid) {
671 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
677 logger("message ".$guid." already exists for user ".$uid);
684 private function fetch_guid($item) {
685 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
686 function ($match) use ($item){
687 return(self::fetch_guid_sub($match, $item));
691 private function fetch_guid_sub($match, $item) {
692 if (!self::store_by_guid($match[1], $item["author-link"]))
693 self::store_by_guid($match[1], $item["owner-link"]);
696 private function store_by_guid($guid, $server, $uid = 0) {
697 $serverparts = parse_url($server);
698 $server = $serverparts["scheme"]."://".$serverparts["host"];
700 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
702 $msg = self::message($guid, $server);
707 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
709 // Now call the dispatcher
710 return self::dispatch_public($msg);
713 private function message($guid, $server, $level = 0) {
718 // This will work for Diaspora and newer Friendica servers
719 $source_url = $server."/p/".$guid.".xml";
720 $x = fetch_url($source_url);
724 $source_xml = parse_xml_string($x, false);
726 if (!is_object($source_xml))
729 if ($source_xml->post->reshare) {
730 // Reshare of a reshare - old Diaspora version
731 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
732 } elseif ($source_xml->getName() == "reshare") {
733 // Reshare of a reshare - new Diaspora version
734 return self::message($source_xml->root_guid, $server, ++$level);
739 // Fetch the author - for the old and the new Diaspora version
740 if ($source_xml->post->status_message->diaspora_handle)
741 $author = (string)$source_xml->post->status_message->diaspora_handle;
742 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
743 $author = (string)$source_xml->author;
745 // If this isn't a "status_message" then quit
749 $msg = array("message" => $x, "author" => $author);
751 $msg["key"] = self::key($msg["author"]);
756 private function parent_item($uid, $guid, $author, $contact) {
757 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
758 `author-name`, `author-link`, `author-avatar`,
759 `owner-name`, `owner-link`, `owner-avatar`
760 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
761 intval($uid), dbesc($guid));
764 $result = self::store_by_guid($guid, $contact["url"], $uid);
767 $person = self::person_by_handle($author);
768 $result = self::store_by_guid($guid, $person["url"], $uid);
772 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
774 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
775 `author-name`, `author-link`, `author-avatar`,
776 `owner-name`, `owner-link`, `owner-avatar`
777 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
778 intval($uid), dbesc($guid));
783 logger("parent item not found: parent: ".$guid." - user: ".$uid);
786 logger("parent item found: parent: ".$guid." - user: ".$uid);
791 private function author_contact_by_url($contact, $person, $uid) {
793 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
794 dbesc(normalise_link($person["url"])), intval($uid));
797 $network = $r[0]["network"];
799 $cid = $contact["id"];
800 $network = NETWORK_DIASPORA;
803 return (array("cid" => $cid, "network" => $network));
806 public static function is_redmatrix($url) {
807 return(strstr($url, "/channel/"));
810 private function plink($addr, $guid) {
811 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
815 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
817 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
818 // So we try another way as well.
819 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
821 $r[0]["network"] = $s[0]["network"];
823 if ($r[0]["network"] == NETWORK_DFRN)
824 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
826 if (self::is_redmatrix($r[0]["url"]))
827 return $r[0]["url"]."/?f=&mid=".$guid;
829 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
832 private function receive_account_deletion($importer, $data) {
833 $author = notags(unxmlify($data->author));
835 $contact = self::contact_by_handle($importer["uid"], $author);
837 logger("cannot find contact for author: ".$author);
841 // We now remove the contact
842 contact_remove($contact["id"]);
846 private function receive_comment($importer, $sender, $data, $xml) {
847 $guid = notags(unxmlify($data->guid));
848 $parent_guid = notags(unxmlify($data->parent_guid));
849 $text = unxmlify($data->text);
850 $author = notags(unxmlify($data->author));
852 $contact = self::allowed_contact_by_handle($importer, $sender, true);
856 if (self::message_exists($importer["uid"], $guid))
859 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
863 $person = self::person_by_handle($author);
864 if (!is_array($person)) {
865 logger("unable to find author details");
869 // Fetch the contact id - if we know this contact
870 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
874 $datarray["uid"] = $importer["uid"];
875 $datarray["contact-id"] = $author_contact["cid"];
876 $datarray["network"] = $author_contact["network"];
878 $datarray["author-name"] = $person["name"];
879 $datarray["author-link"] = $person["url"];
880 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
882 $datarray["owner-name"] = $contact["name"];
883 $datarray["owner-link"] = $contact["url"];
884 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
886 $datarray["guid"] = $guid;
887 $datarray["uri"] = $author.":".$guid;
889 $datarray["type"] = "remote-comment";
890 $datarray["verb"] = ACTIVITY_POST;
891 $datarray["gravity"] = GRAVITY_COMMENT;
892 $datarray["parent-uri"] = $parent_item["uri"];
894 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
895 $datarray["object"] = $xml;
897 $datarray["body"] = diaspora2bb($text);
899 self::fetch_guid($datarray);
901 $message_id = item_store($datarray);
904 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
906 // If we are the origin of the parent we store the original data and notify our followers
907 if($message_id AND $parent_item["origin"]) {
909 // Formerly we stored the signed text, the signature and the author in different fields.
910 // We now store the raw data so that we are more flexible.
911 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
913 dbesc(json_encode($data))
917 proc_run("php", "include/notifier.php", "comment-import", $message_id);
923 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
924 $guid = notags(unxmlify($data->guid));
925 $subject = notags(unxmlify($data->subject));
926 $author = notags(unxmlify($data->author));
930 $msg_guid = notags(unxmlify($mesg->guid));
931 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
932 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
933 $msg_author_signature = notags(unxmlify($mesg->author_signature));
934 $msg_text = unxmlify($mesg->text);
935 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
937 // "diaspora_handle" is the element name from the old version
938 // "author" is the element name from the new version
940 $msg_author = notags(unxmlify($mesg->author));
941 elseif ($mesg->diaspora_handle)
942 $msg_author = notags(unxmlify($mesg->diaspora_handle));
946 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
948 if($msg_conversation_guid != $guid) {
949 logger("message conversation guid does not belong to the current conversation.");
953 $body = diaspora2bb($msg_text);
954 $message_uri = $msg_author.":".$msg_guid;
956 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
958 $author_signature = base64_decode($msg_author_signature);
960 if(strcasecmp($msg_author,$msg["author"]) == 0) {
964 $person = self::person_by_handle($msg_author);
966 if (is_array($person) && x($person, "pubkey"))
967 $key = $person["pubkey"];
969 logger("unable to find author details");
974 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
975 logger("verification failed.");
979 if($msg_parent_author_signature) {
980 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
982 $parent_author_signature = base64_decode($msg_parent_author_signature);
986 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
987 logger("owner verification failed.");
992 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
996 logger("duplicate message already delivered.", LOGGER_DEBUG);
1000 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1001 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1002 intval($importer["uid"]),
1004 intval($conversation["id"]),
1005 dbesc($person["name"]),
1006 dbesc($person["photo"]),
1007 dbesc($person["url"]),
1008 intval($contact["id"]),
1013 dbesc($message_uri),
1014 dbesc($author.":".$guid),
1015 dbesc($msg_created_at)
1018 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1019 dbesc(datetime_convert()),
1020 intval($conversation["id"])
1024 "type" => NOTIFY_MAIL,
1025 "notify_flags" => $importer["notify-flags"],
1026 "language" => $importer["language"],
1027 "to_name" => $importer["username"],
1028 "to_email" => $importer["email"],
1029 "uid" =>$importer["uid"],
1030 "item" => array("subject" => $subject, "body" => $body),
1031 "source_name" => $person["name"],
1032 "source_link" => $person["url"],
1033 "source_photo" => $person["thumb"],
1034 "verb" => ACTIVITY_POST,
1039 private function receive_conversation($importer, $msg, $data) {
1040 $guid = notags(unxmlify($data->guid));
1041 $subject = notags(unxmlify($data->subject));
1042 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1043 $author = notags(unxmlify($data->author));
1044 $participants = notags(unxmlify($data->participants));
1046 $messages = $data->message;
1048 if (!count($messages)) {
1049 logger("empty conversation");
1053 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1057 $conversation = null;
1059 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1060 intval($importer["uid"]),
1064 $conversation = $c[0];
1066 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1067 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1068 intval($importer["uid"]),
1071 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1072 dbesc(datetime_convert()),
1074 dbesc($participants)
1077 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1078 intval($importer["uid"]),
1083 $conversation = $c[0];
1085 if (!$conversation) {
1086 logger("unable to create conversation.");
1090 foreach($messages as $mesg)
1091 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1096 private function construct_like_body($contact, $parent_item, $guid) {
1097 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1099 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1100 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1101 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1103 return sprintf($bodyverb, $ulink, $alink, $plink);
1106 private function construct_like_object($importer, $parent_item) {
1107 $objtype = ACTIVITY_OBJ_NOTE;
1108 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1109 $parent_body = $parent_item["body"];
1111 $xmldata = array("object" => array("type" => $objtype,
1113 "id" => $parent_item["uri"],
1116 "content" => $parent_body));
1118 return xml::from_array($xmldata, $xml, true);
1121 private function receive_like($importer, $sender, $data) {
1122 $positive = notags(unxmlify($data->positive));
1123 $guid = notags(unxmlify($data->guid));
1124 $parent_type = notags(unxmlify($data->parent_type));
1125 $parent_guid = notags(unxmlify($data->parent_guid));
1126 $author = notags(unxmlify($data->author));
1128 // likes on comments aren't supported by Diaspora - only on posts
1129 // But maybe this will be supported in the future, so we will accept it.
1130 if (!in_array($parent_type, array("Post", "Comment")))
1133 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1137 if (self::message_exists($importer["uid"], $guid))
1140 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1144 $person = self::person_by_handle($author);
1145 if (!is_array($person)) {
1146 logger("unable to find author details");
1150 // Fetch the contact id - if we know this contact
1151 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1153 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1154 // We would accept this anyhow.
1155 if ($positive === "true")
1156 $verb = ACTIVITY_LIKE;
1158 $verb = ACTIVITY_DISLIKE;
1160 $datarray = array();
1162 $datarray["uid"] = $importer["uid"];
1163 $datarray["contact-id"] = $author_contact["cid"];
1164 $datarray["network"] = $author_contact["network"];
1166 $datarray["author-name"] = $person["name"];
1167 $datarray["author-link"] = $person["url"];
1168 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1170 $datarray["owner-name"] = $contact["name"];
1171 $datarray["owner-link"] = $contact["url"];
1172 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1174 $datarray["guid"] = $guid;
1175 $datarray["uri"] = $author.":".$guid;
1177 $datarray["type"] = "activity";
1178 $datarray["verb"] = $verb;
1179 $datarray["gravity"] = GRAVITY_LIKE;
1180 $datarray["parent-uri"] = $parent_item["uri"];
1182 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1183 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1185 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1187 $message_id = item_store($datarray);
1190 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1192 // If we are the origin of the parent we store the original data and notify our followers
1193 if($message_id AND $parent_item["origin"]) {
1195 // Formerly we stored the signed text, the signature and the author in different fields.
1196 // We now store the raw data so that we are more flexible.
1197 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1198 intval($message_id),
1199 dbesc(json_encode($data))
1203 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1209 private function receive_message($importer, $data) {
1210 $guid = notags(unxmlify($data->guid));
1211 $parent_guid = notags(unxmlify($data->parent_guid));
1212 $text = unxmlify($data->text);
1213 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1214 $author = notags(unxmlify($data->author));
1215 $conversation_guid = notags(unxmlify($data->conversation_guid));
1217 $contact = self::allowed_contact_by_handle($importer, $author, true);
1221 $conversation = null;
1223 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1224 intval($importer["uid"]),
1225 dbesc($conversation_guid)
1228 $conversation = $c[0];
1230 logger("conversation not available.");
1236 $body = diaspora2bb($text);
1237 $message_uri = $author.":".$guid;
1239 $person = self::person_by_handle($author);
1241 logger("unable to find author details");
1245 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1246 dbesc($message_uri),
1247 intval($importer["uid"])
1250 logger("duplicate message already delivered.", LOGGER_DEBUG);
1254 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1255 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1256 intval($importer["uid"]),
1258 intval($conversation["id"]),
1259 dbesc($person["name"]),
1260 dbesc($person["photo"]),
1261 dbesc($person["url"]),
1262 intval($contact["id"]),
1263 dbesc($conversation["subject"]),
1267 dbesc($message_uri),
1268 dbesc($author.":".$parent_guid),
1272 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1273 dbesc(datetime_convert()),
1274 intval($conversation["id"])
1280 private function receive_participation($importer, $data) {
1281 // I'm not sure if we can fully support this message type
1285 private function receive_photo($importer, $data) {
1286 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1290 private function receive_poll_participation($importer, $data) {
1291 // We don't support polls by now
1295 private function receive_profile($importer, $data) {
1296 $author = notags(unxmlify($data->author));
1298 $contact = self::contact_by_handle($importer["uid"], $author);
1302 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1303 $image_url = unxmlify($data->image_url);
1304 $birthday = unxmlify($data->birthday);
1305 $location = diaspora2bb(unxmlify($data->location));
1306 $about = diaspora2bb(unxmlify($data->bio));
1307 $gender = unxmlify($data->gender);
1308 $searchable = (unxmlify($data->searchable) == "true");
1309 $nsfw = (unxmlify($data->nsfw) == "true");
1310 $tags = unxmlify($data->tag_string);
1312 $tags = explode("#", $tags);
1314 $keywords = array();
1315 foreach ($tags as $tag) {
1316 $tag = trim(strtolower($tag));
1321 $keywords = implode(", ", $keywords);
1323 $handle_parts = explode("@", $author);
1324 $nick = $handle_parts[0];
1327 $name = $handle_parts[0];
1329 if( preg_match("|^https?://|", $image_url) === 0)
1330 $image_url = "http://".$handle_parts[1].$image_url;
1332 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1334 // Generic birthday. We don't know the timezone. The year is irrelevant.
1336 $birthday = str_replace("1000", "1901", $birthday);
1338 if ($birthday != "")
1339 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1341 // this is to prevent multiple birthday notifications in a single year
1342 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1344 if(substr($birthday,5) === substr($contact["bd"],5))
1345 $birthday = $contact["bd"];
1347 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1348 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1352 dbesc(datetime_convert()),
1358 intval($contact["id"]),
1359 intval($importer["uid"])
1363 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1364 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1367 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1368 "photo" => $image_url, "name" => $name, "location" => $location,
1369 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1370 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1371 "hide" => !$searchable, "nsfw" => $nsfw);
1373 update_gcontact($gcontact);
1375 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1380 private function receive_request_make_friend($importer, $contact) {
1384 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1385 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1386 intval(CONTACT_IS_FRIEND),
1387 intval($contact["id"]),
1388 intval($importer["uid"])
1391 // send notification
1393 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1394 intval($importer["uid"])
1397 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1399 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1400 intval($importer["uid"])
1403 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1405 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1408 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1409 $arr["uid"] = $importer["uid"];
1410 $arr["contact-id"] = $self[0]["id"];
1412 $arr["type"] = 'wall';
1413 $arr["gravity"] = 0;
1415 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1416 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1417 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1418 $arr["verb"] = ACTIVITY_FRIEND;
1419 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1421 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1422 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1423 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1424 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1426 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1427 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1428 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1429 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1430 $arr["object"] .= "</link></object>\n";
1431 $arr["last-child"] = 1;
1433 $arr["allow_cid"] = $user[0]["allow_cid"];
1434 $arr["allow_gid"] = $user[0]["allow_gid"];
1435 $arr["deny_cid"] = $user[0]["deny_cid"];
1436 $arr["deny_gid"] = $user[0]["deny_gid"];
1438 $i = item_store($arr);
1440 proc_run("php", "include/notifier.php", "activity", $i);
1447 private function receive_request($importer, $data) {
1448 $author = unxmlify($data->author);
1449 $recipient = unxmlify($data->recipient);
1451 if (!$author || !$recipient)
1454 $contact = self::contact_by_handle($importer["uid"],$author);
1458 // perhaps we were already sharing with this person. Now they're sharing with us.
1459 // That makes us friends.
1461 self::receive_request_make_friend($importer, $contact);
1465 $ret = self::person_by_handle($author);
1467 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1468 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1472 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1474 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1475 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1476 intval($importer["uid"]),
1477 dbesc($ret["network"]),
1478 dbesc($ret["addr"]),
1481 dbesc(normalise_link($ret["url"])),
1483 dbesc($ret["name"]),
1484 dbesc($ret["nick"]),
1485 dbesc($ret["photo"]),
1486 dbesc($ret["pubkey"]),
1487 dbesc($ret["notify"]),
1488 dbesc($ret["poll"]),
1493 // find the contact record we just created
1495 $contact_record = self::contact_by_handle($importer["uid"],$author);
1497 if (!$contact_record) {
1498 logger("unable to locate newly created contact record.");
1502 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1503 intval($importer["uid"])
1506 if($g && intval($g[0]["def_gid"]))
1507 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1509 if($importer["page-flags"] == PAGE_NORMAL) {
1511 $hash = random_string().(string)time(); // Generate a confirm_key
1513 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1514 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1515 intval($importer["uid"]),
1516 intval($contact_record["id"]),
1519 dbesc(t("Sharing notification from Diaspora network")),
1521 dbesc(datetime_convert())
1525 // automatic friend approval
1527 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1529 // technically they are sharing with us (CONTACT_IS_SHARING),
1530 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1531 // we are going to change the relationship and make them a follower.
1533 if($importer["page-flags"] == PAGE_FREELOVE)
1534 $new_relation = CONTACT_IS_FRIEND;
1536 $new_relation = CONTACT_IS_FOLLOWER;
1538 $r = q("UPDATE `contact` SET `rel` = %d,
1546 intval($new_relation),
1547 dbesc(datetime_convert()),
1548 dbesc(datetime_convert()),
1549 intval($contact_record["id"])
1552 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1554 $ret = self::send_share($u[0], $contact_record);
1560 private function original_item($guid, $orig_author, $author) {
1562 // Do we already have this item?
1563 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1564 `author-name`, `author-link`, `author-avatar`
1565 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1569 logger("reshared message ".$guid." already exists on system.");
1571 // Maybe it is already a reshared item?
1572 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1573 if (self::is_reshare($r[0]["body"]))
1580 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1581 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1582 $item_id = self::store_by_guid($guid, $server);
1585 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1586 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1587 $item_id = self::store_by_guid($guid, $server);
1590 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1592 $server = "https://".substr($author, strpos($author, "@") + 1);
1593 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1594 $item_id = self::store_by_guid($guid, $server);
1597 $server = "http://".substr($author, strpos($author, "@") + 1);
1598 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1599 $item_id = self::store_by_guid($guid, $server);
1603 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1604 `author-name`, `author-link`, `author-avatar`
1605 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1616 private function receive_reshare($importer, $data, $xml) {
1617 $root_author = notags(unxmlify($data->root_author));
1618 $root_guid = notags(unxmlify($data->root_guid));
1619 $guid = notags(unxmlify($data->guid));
1620 $author = notags(unxmlify($data->author));
1621 $public = notags(unxmlify($data->public));
1622 $created_at = notags(unxmlify($data->created_at));
1624 $contact = self::allowed_contact_by_handle($importer, $author, false);
1628 if (self::message_exists($importer["uid"], $guid))
1631 $original_item = self::original_item($root_guid, $root_author, $author);
1632 if (!$original_item)
1635 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1637 $datarray = array();
1639 $datarray["uid"] = $importer["uid"];
1640 $datarray["contact-id"] = $contact["id"];
1641 $datarray["network"] = NETWORK_DIASPORA;
1643 $datarray["author-name"] = $contact["name"];
1644 $datarray["author-link"] = $contact["url"];
1645 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1647 $datarray["owner-name"] = $datarray["author-name"];
1648 $datarray["owner-link"] = $datarray["author-link"];
1649 $datarray["owner-avatar"] = $datarray["author-avatar"];
1651 $datarray["guid"] = $guid;
1652 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1654 $datarray["verb"] = ACTIVITY_POST;
1655 $datarray["gravity"] = GRAVITY_PARENT;
1657 $datarray["object"] = $xml;
1659 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1660 $original_item["guid"], $original_item["created"], $orig_url);
1661 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1663 $datarray["tag"] = $original_item["tag"];
1664 $datarray["app"] = $original_item["app"];
1666 $datarray["plink"] = self::plink($author, $guid);
1667 $datarray["private"] = (($public == "false") ? 1 : 0);
1668 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1670 $datarray["object-type"] = $original_item["object-type"];
1672 self::fetch_guid($datarray);
1673 $message_id = item_store($datarray);
1676 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1681 private function item_retraction($importer, $contact, $data) {
1682 $target_type = notags(unxmlify($data->target_type));
1683 $target_guid = notags(unxmlify($data->target_guid));
1684 $author = notags(unxmlify($data->author));
1686 $person = self::person_by_handle($author);
1687 if (!is_array($person)) {
1688 logger("unable to find author detail for ".$author);
1692 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1693 dbesc($target_guid),
1694 intval($importer["uid"])
1699 // Only delete it if the author really fits
1700 if (!link_compare($r[0]["author-link"], $person["url"])) {
1701 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1705 // Check if the sender is the thread owner
1706 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1707 intval($r[0]["parent"]));
1709 // Only delete it if the parent author really fits
1710 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1711 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1715 // 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
1716 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1717 dbesc(datetime_convert()),
1718 dbesc(datetime_convert()),
1721 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1723 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1725 // Now check if the retraction needs to be relayed by us
1726 if($p[0]["origin"]) {
1728 // Formerly we stored the signed text, the signature and the author in different fields.
1729 // We now store the raw data so that we are more flexible.
1730 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1731 intval($r[0]["id"]),
1732 dbesc(json_encode($data))
1734 $s = q("select * from sign where retract_iid = %d", intval($r[0]["id"]));
1735 logger("Stored signatur for item ".$r[0]["id"]." - ".print_r($s, true), LOGGER_DEBUG);
1738 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1742 private function receive_retraction($importer, $sender, $data) {
1743 $target_type = notags(unxmlify($data->target_type));
1745 $contact = self::contact_by_handle($importer["uid"], $sender);
1747 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1751 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1753 switch ($target_type) {
1756 case "Post": // "Post" will be supported in a future version
1758 case "StatusMessage":
1759 return self::item_retraction($importer, $contact, $data);;
1762 /// @todo What should we do with an "unshare"?
1763 // Removing the contact isn't correct since we still can read the public items
1764 //contact_remove($contact["id"]);
1768 logger("Unknown target type ".$target_type);
1774 private function receive_status_message($importer, $data, $xml) {
1776 $raw_message = unxmlify($data->raw_message);
1777 $guid = notags(unxmlify($data->guid));
1778 $author = notags(unxmlify($data->author));
1779 $public = notags(unxmlify($data->public));
1780 $created_at = notags(unxmlify($data->created_at));
1781 $provider_display_name = notags(unxmlify($data->provider_display_name));
1783 /// @todo enable support for polls
1784 //if ($data->poll) {
1785 // foreach ($data->poll AS $poll)
1789 $contact = self::allowed_contact_by_handle($importer, $author, false);
1793 if (self::message_exists($importer["uid"], $guid))
1797 if ($data->location)
1798 foreach ($data->location->children() AS $fieldname => $data)
1799 $address[$fieldname] = notags(unxmlify($data));
1801 $body = diaspora2bb($raw_message);
1803 $datarray = array();
1806 foreach ($data->photo AS $photo)
1807 $body = "[img]".unxmlify($photo->remote_photo_path).
1808 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
1810 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1812 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1814 // Add OEmbed and other information to the body
1815 if (!self::is_redmatrix($contact["url"]))
1816 $body = add_page_info_to_body($body, false, true);
1819 $datarray["uid"] = $importer["uid"];
1820 $datarray["contact-id"] = $contact["id"];
1821 $datarray["network"] = NETWORK_DIASPORA;
1823 $datarray["author-name"] = $contact["name"];
1824 $datarray["author-link"] = $contact["url"];
1825 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1827 $datarray["owner-name"] = $datarray["author-name"];
1828 $datarray["owner-link"] = $datarray["author-link"];
1829 $datarray["owner-avatar"] = $datarray["author-avatar"];
1831 $datarray["guid"] = $guid;
1832 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1834 $datarray["verb"] = ACTIVITY_POST;
1835 $datarray["gravity"] = GRAVITY_PARENT;
1837 $datarray["object"] = $xml;
1839 $datarray["body"] = $body;
1841 if ($provider_display_name != "")
1842 $datarray["app"] = $provider_display_name;
1844 $datarray["plink"] = self::plink($author, $guid);
1845 $datarray["private"] = (($public == "false") ? 1 : 0);
1846 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1848 if (isset($address["address"]))
1849 $datarray["location"] = $address["address"];
1851 if (isset($address["lat"]) AND isset($address["lng"]))
1852 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1854 self::fetch_guid($datarray);
1855 $message_id = item_store($datarray);
1858 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1863 /******************************************************************************************
1864 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1865 ******************************************************************************************/
1867 private function my_handle($me) {
1868 if ($contact["addr"] != "")
1869 return $contact["addr"];
1871 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1872 // So - just in case - we build the the address here.
1873 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1876 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1878 logger("Message: ".$msg, LOGGER_DATA);
1880 $handle = self::my_handle($user);
1882 $b64url_data = base64url_encode($msg);
1884 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1886 $type = "application/xml";
1887 $encoding = "base64url";
1888 $alg = "RSA-SHA256";
1890 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1892 $signature = rsa_sign($signable_data,$prvkey);
1893 $sig = base64url_encode($signature);
1895 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1896 "me:env" => array("me:encoding" => "base64url",
1897 "me:alg" => "RSA-SHA256",
1899 "@attributes" => array("type" => "application/xml"),
1900 "me:sig" => $sig)));
1902 $namespaces = array("" => "https://joindiaspora.com/protocol",
1903 "me" => "http://salmon-protocol.org/ns/magic-env");
1905 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1907 logger("magic_env: ".$magic_env, LOGGER_DATA);
1911 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1913 logger("Message: ".$msg, LOGGER_DATA);
1915 // without a public key nothing will work
1918 logger("pubkey missing: contact id: ".$contact["id"]);
1922 $inner_aes_key = random_string(32);
1923 $b_inner_aes_key = base64_encode($inner_aes_key);
1924 $inner_iv = random_string(16);
1925 $b_inner_iv = base64_encode($inner_iv);
1927 $outer_aes_key = random_string(32);
1928 $b_outer_aes_key = base64_encode($outer_aes_key);
1929 $outer_iv = random_string(16);
1930 $b_outer_iv = base64_encode($outer_iv);
1932 $handle = self::my_handle($user);
1934 $padded_data = pkcs5_pad($msg,16);
1935 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1937 $b64_data = base64_encode($inner_encrypted);
1940 $b64url_data = base64url_encode($b64_data);
1941 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1943 $type = "application/xml";
1944 $encoding = "base64url";
1945 $alg = "RSA-SHA256";
1947 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1949 $signature = rsa_sign($signable_data,$prvkey);
1950 $sig = base64url_encode($signature);
1952 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1953 "aes_key" => $b_inner_aes_key,
1954 "author_id" => $handle));
1956 $decrypted_header = xml::from_array($xmldata, $xml, true);
1957 $decrypted_header = pkcs5_pad($decrypted_header,16);
1959 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1961 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1963 $encrypted_outer_key_bundle = "";
1964 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1966 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1968 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1970 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1971 "ciphertext" => base64_encode($ciphertext)));
1972 $cipher_json = base64_encode($encrypted_header_json_object);
1974 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1975 "me:env" => array("me:encoding" => "base64url",
1976 "me:alg" => "RSA-SHA256",
1978 "@attributes" => array("type" => "application/xml"),
1979 "me:sig" => $sig)));
1981 $namespaces = array("" => "https://joindiaspora.com/protocol",
1982 "me" => "http://salmon-protocol.org/ns/magic-env");
1984 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1986 logger("magic_env: ".$magic_env, LOGGER_DATA);
1990 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1993 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1995 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1997 // The data that will be transmitted is double encoded via "urlencode", strange ...
1998 $slap = "xml=".urlencode(urlencode($magic_env));
2002 private function signature($owner, $message) {
2004 unset($sigmsg["author_signature"]);
2005 unset($sigmsg["parent_author_signature"]);
2007 $signed_text = implode(";", $sigmsg);
2009 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2012 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2016 $enabled = intval(get_config("system", "diaspora_enabled"));
2020 $logid = random_string(4);
2021 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2023 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2027 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2029 if (!$queue_run && was_recently_delayed($contact["id"])) {
2032 if (!intval(get_config("system", "diaspora_test"))) {
2033 post_url($dest_url."/", $slap);
2034 $return_code = $a->get_curl_code();
2036 logger("test_mode");
2041 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2043 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2044 logger("queue message");
2046 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2047 intval($contact["id"]),
2048 dbesc(NETWORK_DIASPORA),
2050 intval($public_batch)
2053 logger("add_to_queue ignored - identical item already in queue");
2055 // queue message for redelivery
2056 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2060 return(($return_code) ? $return_code : (-1));
2064 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2066 $data = array("XML" => array("post" => array($type => $message)));
2068 $msg = xml::from_array($data, $xml);
2070 logger('message: '.$msg, LOGGER_DATA);
2071 logger('send guid '.$guid, LOGGER_DEBUG);
2073 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2076 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2079 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2081 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2083 return $return_code;
2086 public static function send_share($owner,$contact) {
2088 $message = array("sender_handle" => self::my_handle($owner),
2089 "recipient_handle" => $contact["addr"]);
2091 return self::build_and_transmit($owner, $contact, "request", $message);
2094 public static function send_unshare($owner,$contact) {
2096 $message = array("post_guid" => $owner["guid"],
2097 "diaspora_handle" => self::my_handle($owner),
2098 "type" => "Person");
2100 return self::build_and_transmit($owner, $contact, "retraction", $message);
2103 public static function is_reshare($body) {
2104 $body = trim($body);
2106 // Skip if it isn't a pure repeated messages
2107 // Does it start with a share?
2108 if (strpos($body, "[share") > 0)
2111 // Does it end with a share?
2112 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2115 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2116 // Skip if there is no shared message in there
2117 if ($body == $attributes)
2121 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2122 if ($matches[1] != "")
2123 $guid = $matches[1];
2125 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2126 if ($matches[1] != "")
2127 $guid = $matches[1];
2130 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2131 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2134 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2135 $ret["root_guid"] = $guid;
2141 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2142 if ($matches[1] != "")
2143 $profile = $matches[1];
2145 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2146 if ($matches[1] != "")
2147 $profile = $matches[1];
2151 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2152 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2156 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2157 if ($matches[1] != "")
2158 $link = $matches[1];
2160 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2161 if ($matches[1] != "")
2162 $link = $matches[1];
2164 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2165 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2170 public static function send_status($item, $owner, $contact, $public_batch = false) {
2172 $myaddr = self::my_handle($owner);
2174 $public = (($item["private"]) ? "false" : "true");
2176 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2178 // Detect a share element and do a reshare
2179 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2180 $message = array("root_diaspora_id" => $ret["root_handle"],
2181 "root_guid" => $ret["root_guid"],
2182 "guid" => $item["guid"],
2183 "diaspora_handle" => $myaddr,
2184 "public" => $public,
2185 "created_at" => $created,
2186 "provider_display_name" => $item["app"]);
2190 $title = $item["title"];
2191 $body = $item["body"];
2193 // convert to markdown
2194 $body = html_entity_decode(bb2diaspora($body));
2198 $body = "## ".html_entity_decode($title)."\n\n".$body;
2200 if ($item["attach"]) {
2201 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2203 $body .= "\n".t("Attachments:")."\n";
2204 foreach($matches as $mtch)
2205 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2209 $location = array();
2211 if ($item["location"] != "")
2212 $location["address"] = $item["location"];
2214 if ($item["coord"] != "") {
2215 $coord = explode(" ", $item["coord"]);
2216 $location["lat"] = $coord[0];
2217 $location["lng"] = $coord[1];
2220 $message = array("raw_message" => $body,
2221 "location" => $location,
2222 "guid" => $item["guid"],
2223 "diaspora_handle" => $myaddr,
2224 "public" => $public,
2225 "created_at" => $created,
2226 "provider_display_name" => $item["app"]);
2228 if (count($location) == 0)
2229 unset($message["location"]);
2231 $type = "status_message";
2234 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2237 private function construct_like($item, $owner) {
2239 $myaddr = self::my_handle($owner);
2241 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2242 dbesc($item["thr-parent"]));
2248 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2251 return(array("positive" => $positive,
2252 "guid" => $item["guid"],
2253 "target_type" => $target_type,
2254 "parent_guid" => $parent["guid"],
2255 "author_signature" => $authorsig,
2256 "diaspora_handle" => $myaddr));
2259 private function construct_comment($item, $owner) {
2261 $myaddr = self::my_handle($owner);
2263 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2264 intval($item["parent"]),
2265 intval($item["parent"])
2273 $text = html_entity_decode(bb2diaspora($item["body"]));
2275 return(array("guid" => $item["guid"],
2276 "parent_guid" => $parent["guid"],
2277 "author_signature" => "",
2279 "diaspora_handle" => $myaddr));
2282 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2284 if($item['verb'] === ACTIVITY_LIKE) {
2285 $message = self::construct_like($item, $owner);
2288 $message = self::construct_comment($item, $owner);
2295 $message["author_signature"] = self::signature($owner, $message);
2297 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2300 private function message_from_signatur($item, $signature) {
2302 // Split the signed text
2303 $signed_parts = explode(";", $signature['signed_text']);
2305 if ($item["deleted"])
2306 $message = array("parent_author_signature" => "",
2307 "target_guid" => $signed_parts[0],
2308 "target_type" => $signed_parts[1],
2309 "sender_handle" => $signature['signer'],
2310 "target_author_signature" => $signature['signature']);
2311 elseif ($item['verb'] === ACTIVITY_LIKE)
2312 $message = array("positive" => $signed_parts[0],
2313 "guid" => $signed_parts[1],
2314 "target_type" => $signed_parts[2],
2315 "parent_guid" => $signed_parts[3],
2316 "parent_author_signature" => "",
2317 "author_signature" => $signature['signature'],
2318 "diaspora_handle" => $signed_parts[4]);
2320 // Remove the comment guid
2321 $guid = array_shift($signed_parts);
2323 // Remove the parent guid
2324 $parent_guid = array_shift($signed_parts);
2326 // Remove the handle
2327 $handle = array_pop($signed_parts);
2329 // Glue the parts together
2330 $text = implode(";", $signed_parts);
2332 $message = array("guid" => $guid,
2333 "parent_guid" => $parent_guid,
2334 "parent_author_signature" => "",
2335 "author_signature" => $signature['signature'],
2336 "text" => implode(";", $signed_parts),
2337 "diaspora_handle" => $handle);
2342 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2344 if ($item["deleted"]) {
2345 $sql_sign_id = "retract_iid";
2346 $type = "relayable_retraction";
2347 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2348 $sql_sign_id = "iid";
2351 $sql_sign_id = "iid";
2355 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2357 // fetch the original signature
2359 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2360 intval($item["id"]));
2363 logger("Couldn't fetch signatur for contact ".$contact["addr"]." at item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2369 // Old way - is used by the internal Friendica functions
2370 /// @todo Change all signatur storing functions to the new format
2371 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2372 $message = self::message_from_signatur($item, $signature);
2374 $msg = json_decode($signature['signed_text'], true);
2377 foreach ($msg AS $field => $data) {
2378 if (!$item["deleted"]) {
2379 if ($field == "author")
2380 $field = "diaspora_handle";
2381 if ($field == "parent_type")
2382 $field = "target_type";
2385 $message[$field] = $data;
2389 if ($item["deleted"]) {
2390 $signed_text = $message["target_guid"].';'.$message["target_type"];
2391 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2393 $message["parent_author_signature"] = self::signature($owner, $message);
2395 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2397 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2400 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2402 $myaddr = self::my_handle($owner);
2404 // Check whether the retraction is for a top-level post or whether it's a relayable
2405 if ($item["uri"] !== $item["parent-uri"]) {
2406 $msg_type = "relayable_retraction";
2407 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2409 $msg_type = "signed_retraction";
2410 $target_type = "StatusMessage";
2413 $signed_text = $item["guid"].";".$target_type;
2415 $message = array("target_guid" => $item['guid'],
2416 "target_type" => $target_type,
2417 "sender_handle" => $myaddr,
2418 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2420 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2423 public static function send_mail($item, $owner, $contact) {
2425 $myaddr = self::my_handle($owner);
2427 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2428 intval($item["convid"]),
2429 intval($item["uid"])
2433 logger("conversation not found.");
2439 "guid" => $cnv["guid"],
2440 "subject" => $cnv["subject"],
2441 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2442 "diaspora_handle" => $cnv["creator"],
2443 "participant_handles" => $cnv["recips"]
2446 $body = bb2diaspora($item["body"]);
2447 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2449 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2450 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2453 "guid" => $item["guid"],
2454 "parent_guid" => $cnv["guid"],
2455 "parent_author_signature" => $sig,
2456 "author_signature" => $sig,
2458 "created_at" => $created,
2459 "diaspora_handle" => $myaddr,
2460 "conversation_guid" => $cnv["guid"]
2463 if ($item["reply"]) {
2467 $message = array("guid" => $cnv["guid"],
2468 "subject" => $cnv["subject"],
2469 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2471 "diaspora_handle" => $cnv["creator"],
2472 "participant_handles" => $cnv["recips"]);
2474 $type = "conversation";
2477 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2480 public static function send_profile($uid) {
2485 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2486 AND `uid` = %d AND `rel` != %d",
2487 dbesc(NETWORK_DIASPORA),
2489 intval(CONTACT_IS_SHARING)
2494 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2496 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2497 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2498 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2507 $handle = $profile["addr"];
2508 $first = ((strpos($profile['name'],' ')
2509 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2510 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2511 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2512 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2513 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
2514 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2516 if ($searchable === 'true') {
2517 $dob = '1000-00-00';
2519 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2520 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2522 $about = $profile['about'];
2523 $about = strip_tags(bbcode($about));
2525 $location = formatted_location($profile);
2527 if ($profile['pub_keywords']) {
2528 $kw = str_replace(',',' ',$profile['pub_keywords']);
2529 $kw = str_replace(' ',' ',$kw);
2530 $arr = explode(' ',$profile['pub_keywords']);
2532 for($x = 0; $x < 5; $x ++) {
2534 $tags .= '#'. trim($arr[$x]) .' ';
2538 $tags = trim($tags);
2541 $message = array("diaspora_handle" => $handle,
2542 "first_name" => $first,
2543 "last_name" => $last,
2544 "image_url" => $large,
2545 "image_url_medium" => $medium,
2546 "image_url_small" => $small,
2548 "gender" => $profile['gender'],
2550 "location" => $location,
2551 "searchable" => $searchable,
2552 "tag_string" => $tags);
2554 foreach($recips as $recip)
2555 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);