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 relay_list() {
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];
67 function repair_signature($signature, $handle = "", $level = 1) {
72 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
73 $signature = base64_decode($signature);
74 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
76 // Do a recursive call to be able to fix even multiple levels
78 $signature = self::repair_signature($signature, $handle, ++$level);
85 * @brief: Decodes incoming Diaspora message
87 * @param array $importer from user table
88 * @param string $xml urldecoded Diaspora salmon
91 * 'message' -> decoded Diaspora XML message
92 * 'author' -> author diaspora handle
93 * 'key' -> author public key (converted to pkcs#8)
95 function decode($importer, $xml) {
98 $basedom = parse_xml_string($xml);
100 if (!is_object($basedom))
103 $children = $basedom->children('https://joindiaspora.com/protocol');
105 if($children->header) {
107 $author_link = str_replace('acct:','',$children->header->author_id);
110 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
112 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
113 $ciphertext = base64_decode($encrypted_header->ciphertext);
115 $outer_key_bundle = '';
116 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
118 $j_outer_key_bundle = json_decode($outer_key_bundle);
120 $outer_iv = base64_decode($j_outer_key_bundle->iv);
121 $outer_key = base64_decode($j_outer_key_bundle->key);
123 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
126 $decrypted = pkcs5_unpad($decrypted);
129 * $decrypted now contains something like
132 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
133 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
134 * <author_id>galaxor@diaspora.priateship.org</author_id>
135 * </decrypted_header>
138 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
139 $idom = parse_xml_string($decrypted,false);
141 $inner_iv = base64_decode($idom->iv);
142 $inner_aes_key = base64_decode($idom->aes_key);
144 $author_link = str_replace('acct:','',$idom->author_id);
147 $dom = $basedom->children(NAMESPACE_SALMON_ME);
149 // figure out where in the DOM tree our data is hiding
151 if($dom->provenance->data)
152 $base = $dom->provenance;
153 elseif($dom->env->data)
159 logger('unable to locate salmon data in xml');
160 http_status_exit(400);
164 // Stash the signature away for now. We have to find their key or it won't be good for anything.
165 $signature = base64url_decode($base->sig);
169 // strip whitespace so our data element will return to one big base64 blob
170 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
173 // stash away some other stuff for later
175 $type = $base->data[0]->attributes()->type[0];
176 $keyhash = $base->sig[0]->attributes()->keyhash[0];
177 $encoding = $base->encoding;
181 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
185 $data = base64url_decode($data);
189 $inner_decrypted = $data;
192 // Decode the encrypted blob
194 $inner_encrypted = base64_decode($data);
195 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
196 $inner_decrypted = pkcs5_unpad($inner_decrypted);
200 logger('Could not retrieve author URI.');
201 http_status_exit(400);
203 // Once we have the author URI, go to the web and try to find their public key
204 // (first this will look it up locally if it is in the fcontact cache)
205 // This will also convert diaspora public key from pkcs#1 to pkcs#8
207 logger('Fetching key for '.$author_link);
208 $key = self::key($author_link);
211 logger('Could not retrieve author key.');
212 http_status_exit(400);
215 $verify = rsa_verify($signed_data,$signature,$key);
218 logger('Message did not verify. Discarding.');
219 http_status_exit(400);
222 logger('Message verified.');
224 return array('message' => (string)$inner_decrypted,
225 'author' => unxmlify($author_link),
226 'key' => (string)$key);
232 * @brief Dispatches public messages and find the fitting receivers
234 * @param array $msg The post that will be dispatched
236 * @return bool Was the message accepted?
238 public static function dispatch_public($msg) {
240 $enabled = intval(get_config("system", "diaspora_enabled"));
242 logger("diaspora is disabled");
246 // Use a dummy importer to import the data for the public copy
247 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
248 $item_id = self::dispatch($importer,$msg);
250 // Now distribute it to the followers
251 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
252 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
253 AND NOT `account_expired` AND NOT `account_removed`",
254 dbesc(NETWORK_DIASPORA),
255 dbesc($msg["author"])
259 logger("delivering to: ".$rr["username"]);
260 self::dispatch($rr,$msg);
263 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
269 * @brief Dispatches the different message types to the different functions
271 * @param array $importer Array of the importer user
272 * @param array $msg The post that will be dispatched
274 * @return bool Was the message accepted?
276 public static function dispatch($importer, $msg) {
278 // The sender is the handle of the contact that sent the message.
279 // This will often be different with relayed messages (for example "like" and "comment")
280 $sender = $msg["author"];
282 if (!diaspora::valid_posting($msg, $fields)) {
283 logger("Invalid posting");
287 $type = $fields->getName();
289 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
292 case "account_deletion":
293 return self::receive_account_deletion($importer, $fields);
296 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
299 return self::receive_conversation($importer, $msg, $fields);
302 return self::receive_like($importer, $sender, $fields);
305 return self::receive_message($importer, $fields);
307 case "participation": // Not implemented
308 return self::receive_participation($importer, $fields);
310 case "photo": // Not implemented
311 return self::receive_photo($importer, $fields);
313 case "poll_participation": // Not implemented
314 return self::receive_poll_participation($importer, $fields);
317 return self::receive_profile($importer, $fields);
320 return self::receive_request($importer, $fields);
323 return self::receive_reshare($importer, $fields, $msg["message"]);
326 return self::receive_retraction($importer, $sender, $fields);
328 case "status_message":
329 return self::receive_status_message($importer, $fields, $msg["message"]);
332 logger("Unknown message type ".$type);
340 * @brief Checks if a posting is valid and fetches the data fields.
342 * This function does not only check the signature.
343 * It also does the conversion between the old and the new diaspora format.
345 * @param array $msg Array with the XML, the sender handle and the sender signature
346 * @param object $fields SimpleXML object that contains the posting when it is valid
348 * @return bool Is the posting valid?
350 private function valid_posting($msg, &$fields) {
352 $data = parse_xml_string($msg["message"], false);
354 if (!is_object($data))
357 $first_child = $data->getName();
359 // Is this the new or the old version?
360 if ($data->getName() == "XML") {
362 foreach ($data->post->children() as $child)
369 $type = $element->getName();
372 // All retractions are handled identically from now on.
373 // In the new version there will only be "retraction".
374 if (in_array($type, array("signed_retraction", "relayable_retraction")))
375 $type = "retraction";
377 $fields = new SimpleXMLElement("<".$type."/>");
381 foreach ($element->children() AS $fieldname => $entry) {
383 // Translation for the old XML structure
384 if ($fieldname == "diaspora_handle")
385 $fieldname = "author";
387 if ($fieldname == "participant_handles")
388 $fieldname = "participants";
390 if (in_array($type, array("like", "participation"))) {
391 if ($fieldname == "target_type")
392 $fieldname = "parent_type";
395 if ($fieldname == "sender_handle")
396 $fieldname = "author";
398 if ($fieldname == "recipient_handle")
399 $fieldname = "recipient";
401 if ($fieldname == "root_diaspora_id")
402 $fieldname = "root_author";
404 if ($type == "retraction") {
405 if ($fieldname == "post_guid")
406 $fieldname = "target_guid";
408 if ($fieldname == "type")
409 $fieldname = "target_type";
413 if ($fieldname == "author_signature")
414 $author_signature = base64_decode($entry);
415 elseif ($fieldname == "parent_author_signature")
416 $parent_author_signature = base64_decode($entry);
417 elseif ($fieldname != "target_author_signature") {
418 if ($signed_data != "") {
420 $signed_data_parent .= ";";
423 $signed_data .= $entry;
425 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
426 ($orig_type == "relayable_retraction"))
427 xml::copy($entry, $fields, $fieldname);
430 // This is something that shouldn't happen at all.
431 if (in_array($type, array("status_message", "reshare", "profile")))
432 if ($msg["author"] != $fields->author) {
433 logger("Message handle is not the same as envelope sender. Quitting this message.");
437 // Only some message types have signatures. So we quit here for the other types.
438 if (!in_array($type, array("comment", "message", "like")))
441 // No author_signature? This is a must, so we quit.
442 if (!isset($author_signature))
445 if (isset($parent_author_signature)) {
446 $key = self::key($msg["author"]);
448 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
452 $key = self::key($fields->author);
454 return rsa_verify($signed_data, $author_signature, $key, "sha256");
458 * @brief Fetches the public key for a given handle
460 * @param string $handle The handle
462 * @return string The public key
464 private function key($handle) {
465 $handle = strval($handle);
467 logger("Fetching diaspora key for: ".$handle);
469 $r = self::person_by_handle($handle);
477 * @brief Fetches data for a given handle
479 * @param string $handle The handle
481 * @return array the queried data
483 private function person_by_handle($handle) {
485 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
486 dbesc(NETWORK_DIASPORA),
491 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
493 // update record occasionally so it doesn't get stale
494 $d = strtotime($person["updated"]." +00:00");
495 if ($d < strtotime("now - 14 days"))
499 if (!$person OR $update) {
500 logger("create or refresh", LOGGER_DEBUG);
501 $r = probe_url($handle, PROBE_DIASPORA);
503 // Note that Friendica contacts will return a "Diaspora person"
504 // if Diaspora connectivity is enabled on their server
505 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
506 self::add_fcontact($r, $update);
514 * @brief Updates the fcontact table
516 * @param array $arr The fcontact data
517 * @param bool $update Update or insert?
519 * @return string The id of the fcontact entry
521 private function add_fcontact($arr, $update = false) {
524 $r = q("UPDATE `fcontact` SET
537 WHERE `url` = '%s' AND `network` = '%s'",
539 dbesc($arr["photo"]),
540 dbesc($arr["request"]),
543 dbesc($arr["batch"]),
544 dbesc($arr["notify"]),
546 dbesc($arr["confirm"]),
547 dbesc($arr["alias"]),
548 dbesc($arr["pubkey"]),
549 dbesc(datetime_convert()),
551 dbesc($arr["network"])
554 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
555 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
556 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
559 dbesc($arr["photo"]),
560 dbesc($arr["request"]),
563 dbesc($arr["batch"]),
564 dbesc($arr["notify"]),
566 dbesc($arr["confirm"]),
567 dbesc($arr["network"]),
568 dbesc($arr["alias"]),
569 dbesc($arr["pubkey"]),
570 dbesc(datetime_convert())
577 public static function handle_from_contact($contact_id) {
580 logger("contact id is ".$contact_id, LOGGER_DEBUG);
582 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
588 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
590 if($contact['addr'] != "")
591 $handle = $contact['addr'];
592 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
593 $baseurl_start = strpos($contact['url'],'://') + 3;
594 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
595 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
596 $handle = $contact['nick'].'@'.$baseurl;
603 private function contact_by_handle($uid, $handle) {
604 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
612 $handle_parts = explode("@", $handle);
613 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
614 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
625 private function post_allow($importer, $contact, $is_comment = false) {
627 // perhaps we were already sharing with this person. Now they're sharing with us.
628 // That makes us friends.
629 // Normally this should have handled by getting a request - but this could get lost
630 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
631 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
632 intval(CONTACT_IS_FRIEND),
633 intval($contact["id"]),
634 intval($importer["uid"])
636 $contact["rel"] = CONTACT_IS_FRIEND;
637 logger("defining user ".$contact["nick"]." as friend");
640 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
642 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
644 if($contact["rel"] == CONTACT_IS_FOLLOWER)
645 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
648 // Messages for the global users are always accepted
649 if ($importer["uid"] == 0)
655 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
656 $contact = self::contact_by_handle($importer["uid"], $handle);
658 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
662 if (!self::post_allow($importer, $contact, $is_comment)) {
663 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
669 private function message_exists($uid, $guid) {
670 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
676 logger("message ".$guid." already exists for user ".$uid);
683 private function fetch_guid($item) {
684 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
685 function ($match) use ($item){
686 return(self::fetch_guid_sub($match, $item));
690 private function fetch_guid_sub($match, $item) {
691 if (!self::store_by_guid($match[1], $item["author-link"]))
692 self::store_by_guid($match[1], $item["owner-link"]);
695 private function store_by_guid($guid, $server, $uid = 0) {
696 $serverparts = parse_url($server);
697 $server = $serverparts["scheme"]."://".$serverparts["host"];
699 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
701 $msg = self::message($guid, $server);
706 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
708 // Now call the dispatcher
709 return self::dispatch_public($msg);
712 private function message($guid, $server, $level = 0) {
717 // This will work for Diaspora and newer Friendica servers
718 $source_url = $server."/p/".$guid.".xml";
719 $x = fetch_url($source_url);
723 $source_xml = parse_xml_string($x, false);
725 if (!is_object($source_xml))
728 if ($source_xml->post->reshare) {
729 // Reshare of a reshare - old Diaspora version
730 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
731 } elseif ($source_xml->getName() == "reshare") {
732 // Reshare of a reshare - new Diaspora version
733 return self::message($source_xml->root_guid, $server, ++$level);
738 // Fetch the author - for the old and the new Diaspora version
739 if ($source_xml->post->status_message->diaspora_handle)
740 $author = (string)$source_xml->post->status_message->diaspora_handle;
741 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
742 $author = (string)$source_xml->author;
744 // If this isn't a "status_message" then quit
748 $msg = array("message" => $x, "author" => $author);
750 $msg["key"] = self::key($msg["author"]);
755 private function parent_item($uid, $guid, $author, $contact) {
756 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
757 `author-name`, `author-link`, `author-avatar`,
758 `owner-name`, `owner-link`, `owner-avatar`
759 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
760 intval($uid), dbesc($guid));
763 $result = self::store_by_guid($guid, $contact["url"], $uid);
766 $person = self::person_by_handle($author);
767 $result = self::store_by_guid($guid, $person["url"], $uid);
771 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
773 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
774 `author-name`, `author-link`, `author-avatar`,
775 `owner-name`, `owner-link`, `owner-avatar`
776 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
777 intval($uid), dbesc($guid));
782 logger("parent item not found: parent: ".$guid." - user: ".$uid);
785 logger("parent item found: parent: ".$guid." - user: ".$uid);
790 private function author_contact_by_url($contact, $person, $uid) {
792 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
793 dbesc(normalise_link($person["url"])), intval($uid));
796 $network = $r[0]["network"];
798 $cid = $contact["id"];
799 $network = NETWORK_DIASPORA;
802 return (array("cid" => $cid, "network" => $network));
805 public static function is_redmatrix($url) {
806 return(strstr($url, "/channel/"));
809 private function plink($addr, $guid) {
810 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
814 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
816 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
817 // So we try another way as well.
818 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
820 $r[0]["network"] = $s[0]["network"];
822 if ($r[0]["network"] == NETWORK_DFRN)
823 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
825 if (self::is_redmatrix($r[0]["url"]))
826 return $r[0]["url"]."/?f=&mid=".$guid;
828 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
831 private function receive_account_deletion($importer, $data) {
832 $author = notags(unxmlify($data->author));
834 $contact = self::contact_by_handle($importer["uid"], $author);
836 logger("cannot find contact for author: ".$author);
840 // We now remove the contact
841 contact_remove($contact["id"]);
845 private function receive_comment($importer, $sender, $data, $xml) {
846 $guid = notags(unxmlify($data->guid));
847 $parent_guid = notags(unxmlify($data->parent_guid));
848 $text = unxmlify($data->text);
849 $author = notags(unxmlify($data->author));
851 $contact = self::allowed_contact_by_handle($importer, $sender, true);
855 if (self::message_exists($importer["uid"], $guid))
858 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
862 $person = self::person_by_handle($author);
863 if (!is_array($person)) {
864 logger("unable to find author details");
868 // Fetch the contact id - if we know this contact
869 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
873 $datarray["uid"] = $importer["uid"];
874 $datarray["contact-id"] = $author_contact["cid"];
875 $datarray["network"] = $author_contact["network"];
877 $datarray["author-name"] = $person["name"];
878 $datarray["author-link"] = $person["url"];
879 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
881 $datarray["owner-name"] = $contact["name"];
882 $datarray["owner-link"] = $contact["url"];
883 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
885 $datarray["guid"] = $guid;
886 $datarray["uri"] = $author.":".$guid;
888 $datarray["type"] = "remote-comment";
889 $datarray["verb"] = ACTIVITY_POST;
890 $datarray["gravity"] = GRAVITY_COMMENT;
891 $datarray["parent-uri"] = $parent_item["uri"];
893 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
894 $datarray["object"] = $xml;
896 $datarray["body"] = diaspora2bb($text);
898 self::fetch_guid($datarray);
900 $message_id = item_store($datarray);
903 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
905 // If we are the origin of the parent we store the original data and notify our followers
906 if($message_id AND $parent_item["origin"]) {
908 // Formerly we stored the signed text, the signature and the author in different fields.
909 // We now store the raw data so that we are more flexible.
910 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
912 dbesc(json_encode($data))
916 proc_run("php", "include/notifier.php", "comment-import", $message_id);
922 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
923 $guid = notags(unxmlify($data->guid));
924 $subject = notags(unxmlify($data->subject));
925 $author = notags(unxmlify($data->author));
929 $msg_guid = notags(unxmlify($mesg->guid));
930 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
931 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
932 $msg_author_signature = notags(unxmlify($mesg->author_signature));
933 $msg_text = unxmlify($mesg->text);
934 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
936 // "diaspora_handle" is the element name from the old version
937 // "author" is the element name from the new version
939 $msg_author = notags(unxmlify($mesg->author));
940 elseif ($mesg->diaspora_handle)
941 $msg_author = notags(unxmlify($mesg->diaspora_handle));
945 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
947 if($msg_conversation_guid != $guid) {
948 logger("message conversation guid does not belong to the current conversation.");
952 $body = diaspora2bb($msg_text);
953 $message_uri = $msg_author.":".$msg_guid;
955 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
957 $author_signature = base64_decode($msg_author_signature);
959 if(strcasecmp($msg_author,$msg["author"]) == 0) {
963 $person = self::person_by_handle($msg_author);
965 if (is_array($person) && x($person, "pubkey"))
966 $key = $person["pubkey"];
968 logger("unable to find author details");
973 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
974 logger("verification failed.");
978 if($msg_parent_author_signature) {
979 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
981 $parent_author_signature = base64_decode($msg_parent_author_signature);
985 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
986 logger("owner verification failed.");
991 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
995 logger("duplicate message already delivered.", LOGGER_DEBUG);
999 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1000 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1001 intval($importer["uid"]),
1003 intval($conversation["id"]),
1004 dbesc($person["name"]),
1005 dbesc($person["photo"]),
1006 dbesc($person["url"]),
1007 intval($contact["id"]),
1012 dbesc($message_uri),
1013 dbesc($author.":".$guid),
1014 dbesc($msg_created_at)
1017 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1018 dbesc(datetime_convert()),
1019 intval($conversation["id"])
1023 "type" => NOTIFY_MAIL,
1024 "notify_flags" => $importer["notify-flags"],
1025 "language" => $importer["language"],
1026 "to_name" => $importer["username"],
1027 "to_email" => $importer["email"],
1028 "uid" =>$importer["uid"],
1029 "item" => array("subject" => $subject, "body" => $body),
1030 "source_name" => $person["name"],
1031 "source_link" => $person["url"],
1032 "source_photo" => $person["thumb"],
1033 "verb" => ACTIVITY_POST,
1038 private function receive_conversation($importer, $msg, $data) {
1039 $guid = notags(unxmlify($data->guid));
1040 $subject = notags(unxmlify($data->subject));
1041 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1042 $author = notags(unxmlify($data->author));
1043 $participants = notags(unxmlify($data->participants));
1045 $messages = $data->message;
1047 if (!count($messages)) {
1048 logger("empty conversation");
1052 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1056 $conversation = null;
1058 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1059 intval($importer["uid"]),
1063 $conversation = $c[0];
1065 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1066 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1067 intval($importer["uid"]),
1070 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1071 dbesc(datetime_convert()),
1073 dbesc($participants)
1076 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1077 intval($importer["uid"]),
1082 $conversation = $c[0];
1084 if (!$conversation) {
1085 logger("unable to create conversation.");
1089 foreach($messages as $mesg)
1090 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1095 private function construct_like_body($contact, $parent_item, $guid) {
1096 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1098 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1099 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1100 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1102 return sprintf($bodyverb, $ulink, $alink, $plink);
1105 private function construct_like_object($importer, $parent_item) {
1106 $objtype = ACTIVITY_OBJ_NOTE;
1107 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1108 $parent_body = $parent_item["body"];
1110 $xmldata = array("object" => array("type" => $objtype,
1112 "id" => $parent_item["uri"],
1115 "content" => $parent_body));
1117 return xml::from_array($xmldata, $xml, true);
1120 private function receive_like($importer, $sender, $data) {
1121 $positive = notags(unxmlify($data->positive));
1122 $guid = notags(unxmlify($data->guid));
1123 $parent_type = notags(unxmlify($data->parent_type));
1124 $parent_guid = notags(unxmlify($data->parent_guid));
1125 $author = notags(unxmlify($data->author));
1127 // likes on comments aren't supported by Diaspora - only on posts
1128 // But maybe this will be supported in the future, so we will accept it.
1129 if (!in_array($parent_type, array("Post", "Comment")))
1132 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1136 if (self::message_exists($importer["uid"], $guid))
1139 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1143 $person = self::person_by_handle($author);
1144 if (!is_array($person)) {
1145 logger("unable to find author details");
1149 // Fetch the contact id - if we know this contact
1150 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1152 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1153 // We would accept this anyhow.
1154 if ($positive === "true")
1155 $verb = ACTIVITY_LIKE;
1157 $verb = ACTIVITY_DISLIKE;
1159 $datarray = array();
1161 $datarray["uid"] = $importer["uid"];
1162 $datarray["contact-id"] = $author_contact["cid"];
1163 $datarray["network"] = $author_contact["network"];
1165 $datarray["author-name"] = $person["name"];
1166 $datarray["author-link"] = $person["url"];
1167 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1169 $datarray["owner-name"] = $contact["name"];
1170 $datarray["owner-link"] = $contact["url"];
1171 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1173 $datarray["guid"] = $guid;
1174 $datarray["uri"] = $author.":".$guid;
1176 $datarray["type"] = "activity";
1177 $datarray["verb"] = $verb;
1178 $datarray["gravity"] = GRAVITY_LIKE;
1179 $datarray["parent-uri"] = $parent_item["uri"];
1181 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1182 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1184 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1186 $message_id = item_store($datarray);
1189 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1191 // If we are the origin of the parent we store the original data and notify our followers
1192 if($message_id AND $parent_item["origin"]) {
1194 // Formerly we stored the signed text, the signature and the author in different fields.
1195 // We now store the raw data so that we are more flexible.
1196 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1197 intval($message_id),
1198 dbesc(json_encode($data))
1202 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1208 private function receive_message($importer, $data) {
1209 $guid = notags(unxmlify($data->guid));
1210 $parent_guid = notags(unxmlify($data->parent_guid));
1211 $text = unxmlify($data->text);
1212 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1213 $author = notags(unxmlify($data->author));
1214 $conversation_guid = notags(unxmlify($data->conversation_guid));
1216 $contact = self::allowed_contact_by_handle($importer, $author, true);
1220 $conversation = null;
1222 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1223 intval($importer["uid"]),
1224 dbesc($conversation_guid)
1227 $conversation = $c[0];
1229 logger("conversation not available.");
1235 $body = diaspora2bb($text);
1236 $message_uri = $author.":".$guid;
1238 $person = self::person_by_handle($author);
1240 logger("unable to find author details");
1244 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1245 dbesc($message_uri),
1246 intval($importer["uid"])
1249 logger("duplicate message already delivered.", LOGGER_DEBUG);
1253 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1254 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1255 intval($importer["uid"]),
1257 intval($conversation["id"]),
1258 dbesc($person["name"]),
1259 dbesc($person["photo"]),
1260 dbesc($person["url"]),
1261 intval($contact["id"]),
1262 dbesc($conversation["subject"]),
1266 dbesc($message_uri),
1267 dbesc($author.":".$parent_guid),
1271 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1272 dbesc(datetime_convert()),
1273 intval($conversation["id"])
1279 private function receive_participation($importer, $data) {
1280 // I'm not sure if we can fully support this message type
1284 private function receive_photo($importer, $data) {
1285 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1289 private function receive_poll_participation($importer, $data) {
1290 // We don't support polls by now
1294 private function receive_profile($importer, $data) {
1295 $author = notags(unxmlify($data->author));
1297 $contact = self::contact_by_handle($importer["uid"], $author);
1301 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1302 $image_url = unxmlify($data->image_url);
1303 $birthday = unxmlify($data->birthday);
1304 $location = diaspora2bb(unxmlify($data->location));
1305 $about = diaspora2bb(unxmlify($data->bio));
1306 $gender = unxmlify($data->gender);
1307 $searchable = (unxmlify($data->searchable) == "true");
1308 $nsfw = (unxmlify($data->nsfw) == "true");
1309 $tags = unxmlify($data->tag_string);
1311 $tags = explode("#", $tags);
1313 $keywords = array();
1314 foreach ($tags as $tag) {
1315 $tag = trim(strtolower($tag));
1320 $keywords = implode(", ", $keywords);
1322 $handle_parts = explode("@", $author);
1323 $nick = $handle_parts[0];
1326 $name = $handle_parts[0];
1328 if( preg_match("|^https?://|", $image_url) === 0)
1329 $image_url = "http://".$handle_parts[1].$image_url;
1331 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1333 // Generic birthday. We don't know the timezone. The year is irrelevant.
1335 $birthday = str_replace("1000", "1901", $birthday);
1337 if ($birthday != "")
1338 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1340 // this is to prevent multiple birthday notifications in a single year
1341 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1343 if(substr($birthday,5) === substr($contact["bd"],5))
1344 $birthday = $contact["bd"];
1346 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1347 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1351 dbesc(datetime_convert()),
1357 intval($contact["id"]),
1358 intval($importer["uid"])
1362 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1363 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1366 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1367 "photo" => $image_url, "name" => $name, "location" => $location,
1368 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1369 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1370 "hide" => !$searchable, "nsfw" => $nsfw);
1372 update_gcontact($gcontact);
1374 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1379 private function receive_request_make_friend($importer, $contact) {
1383 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1384 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1385 intval(CONTACT_IS_FRIEND),
1386 intval($contact["id"]),
1387 intval($importer["uid"])
1390 // send notification
1392 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1393 intval($importer["uid"])
1396 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1398 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1399 intval($importer["uid"])
1402 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1404 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1407 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1408 $arr["uid"] = $importer["uid"];
1409 $arr["contact-id"] = $self[0]["id"];
1411 $arr["type"] = 'wall';
1412 $arr["gravity"] = 0;
1414 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1415 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1416 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1417 $arr["verb"] = ACTIVITY_FRIEND;
1418 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1420 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1421 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1422 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1423 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1425 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1426 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1427 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1428 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1429 $arr["object"] .= "</link></object>\n";
1430 $arr["last-child"] = 1;
1432 $arr["allow_cid"] = $user[0]["allow_cid"];
1433 $arr["allow_gid"] = $user[0]["allow_gid"];
1434 $arr["deny_cid"] = $user[0]["deny_cid"];
1435 $arr["deny_gid"] = $user[0]["deny_gid"];
1437 $i = item_store($arr);
1439 proc_run("php", "include/notifier.php", "activity", $i);
1446 private function receive_request($importer, $data) {
1447 $author = unxmlify($data->author);
1448 $recipient = unxmlify($data->recipient);
1450 if (!$author || !$recipient)
1453 $contact = self::contact_by_handle($importer["uid"],$author);
1457 // perhaps we were already sharing with this person. Now they're sharing with us.
1458 // That makes us friends.
1460 self::receive_request_make_friend($importer, $contact);
1464 $ret = self::person_by_handle($author);
1466 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1467 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1471 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1473 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1474 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1475 intval($importer["uid"]),
1476 dbesc($ret["network"]),
1477 dbesc($ret["addr"]),
1480 dbesc(normalise_link($ret["url"])),
1482 dbesc($ret["name"]),
1483 dbesc($ret["nick"]),
1484 dbesc($ret["photo"]),
1485 dbesc($ret["pubkey"]),
1486 dbesc($ret["notify"]),
1487 dbesc($ret["poll"]),
1492 // find the contact record we just created
1494 $contact_record = self::contact_by_handle($importer["uid"],$author);
1496 if (!$contact_record) {
1497 logger("unable to locate newly created contact record.");
1501 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1502 intval($importer["uid"])
1505 if($g && intval($g[0]["def_gid"]))
1506 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1508 if($importer["page-flags"] == PAGE_NORMAL) {
1510 $hash = random_string().(string)time(); // Generate a confirm_key
1512 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1513 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1514 intval($importer["uid"]),
1515 intval($contact_record["id"]),
1518 dbesc(t("Sharing notification from Diaspora network")),
1520 dbesc(datetime_convert())
1524 // automatic friend approval
1526 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1528 // technically they are sharing with us (CONTACT_IS_SHARING),
1529 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1530 // we are going to change the relationship and make them a follower.
1532 if($importer["page-flags"] == PAGE_FREELOVE)
1533 $new_relation = CONTACT_IS_FRIEND;
1535 $new_relation = CONTACT_IS_FOLLOWER;
1537 $r = q("UPDATE `contact` SET `rel` = %d,
1545 intval($new_relation),
1546 dbesc(datetime_convert()),
1547 dbesc(datetime_convert()),
1548 intval($contact_record["id"])
1551 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1553 $ret = self::send_share($u[0], $contact_record);
1559 private function original_item($guid, $orig_author, $author) {
1561 // Do we already have this item?
1562 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1563 `author-name`, `author-link`, `author-avatar`
1564 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1568 logger("reshared message ".$guid." already exists on system.");
1570 // Maybe it is already a reshared item?
1571 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1572 if (self::is_reshare($r[0]["body"]))
1579 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1580 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1581 $item_id = self::store_by_guid($guid, $server);
1584 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1585 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1586 $item_id = self::store_by_guid($guid, $server);
1589 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1591 $server = "https://".substr($author, strpos($author, "@") + 1);
1592 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1593 $item_id = self::store_by_guid($guid, $server);
1596 $server = "http://".substr($author, strpos($author, "@") + 1);
1597 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1598 $item_id = self::store_by_guid($guid, $server);
1602 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1603 `author-name`, `author-link`, `author-avatar`
1604 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1615 private function receive_reshare($importer, $data, $xml) {
1616 $root_author = notags(unxmlify($data->root_author));
1617 $root_guid = notags(unxmlify($data->root_guid));
1618 $guid = notags(unxmlify($data->guid));
1619 $author = notags(unxmlify($data->author));
1620 $public = notags(unxmlify($data->public));
1621 $created_at = notags(unxmlify($data->created_at));
1623 $contact = self::allowed_contact_by_handle($importer, $author, false);
1627 if (self::message_exists($importer["uid"], $guid))
1630 $original_item = self::original_item($root_guid, $root_author, $author);
1631 if (!$original_item)
1634 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1636 $datarray = array();
1638 $datarray["uid"] = $importer["uid"];
1639 $datarray["contact-id"] = $contact["id"];
1640 $datarray["network"] = NETWORK_DIASPORA;
1642 $datarray["author-name"] = $contact["name"];
1643 $datarray["author-link"] = $contact["url"];
1644 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1646 $datarray["owner-name"] = $datarray["author-name"];
1647 $datarray["owner-link"] = $datarray["author-link"];
1648 $datarray["owner-avatar"] = $datarray["author-avatar"];
1650 $datarray["guid"] = $guid;
1651 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1653 $datarray["verb"] = ACTIVITY_POST;
1654 $datarray["gravity"] = GRAVITY_PARENT;
1656 $datarray["object"] = $xml;
1658 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1659 $original_item["guid"], $original_item["created"], $orig_url);
1660 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1662 $datarray["tag"] = $original_item["tag"];
1663 $datarray["app"] = $original_item["app"];
1665 $datarray["plink"] = self::plink($author, $guid);
1666 $datarray["private"] = (($public == "false") ? 1 : 0);
1667 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1669 $datarray["object-type"] = $original_item["object-type"];
1671 self::fetch_guid($datarray);
1672 $message_id = item_store($datarray);
1675 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1680 private function item_retraction($importer, $contact, $data) {
1681 $target_type = notags(unxmlify($data->target_type));
1682 $target_guid = notags(unxmlify($data->target_guid));
1683 $author = notags(unxmlify($data->author));
1685 $person = self::person_by_handle($author);
1686 if (!is_array($person)) {
1687 logger("unable to find author detail for ".$author);
1691 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1692 dbesc($target_guid),
1693 intval($importer["uid"])
1698 // Only delete it if the author really fits
1699 if (!link_compare($r[0]["author-link"], $person["url"])) {
1700 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
1704 // Check if the sender is the thread owner
1705 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
1706 intval($r[0]["parent"]));
1708 // Only delete it if the parent author really fits
1709 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
1710 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
1714 // 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
1715 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1716 dbesc(datetime_convert()),
1717 dbesc(datetime_convert()),
1720 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1722 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
1724 // Now check if the retraction needs to be relayed by us
1725 if($p[0]["origin"]) {
1727 // Formerly we stored the signed text, the signature and the author in different fields.
1728 // We now store the raw data so that we are more flexible.
1729 q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1730 intval($r[0]["id"]),
1731 dbesc(json_encode($data))
1733 $s = q("select * from sign where retract_iid = %d", intval($r[0]["id"]));
1734 logger("Stored signatur for item ".$r[0]["id"]." - ".print_r($s, true), LOGGER_DEBUG);
1737 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1741 private function receive_retraction($importer, $sender, $data) {
1742 $target_type = notags(unxmlify($data->target_type));
1744 $contact = self::contact_by_handle($importer["uid"], $sender);
1746 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1750 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
1752 switch ($target_type) {
1755 case "Post": // "Post" will be supported in a future version
1757 case "StatusMessage":
1758 return self::item_retraction($importer, $contact, $data);;
1761 /// @todo What should we do with an "unshare"?
1762 // Removing the contact isn't correct since we still can read the public items
1763 //contact_remove($contact["id"]);
1767 logger("Unknown target type ".$target_type);
1773 private function receive_status_message($importer, $data, $xml) {
1775 $raw_message = unxmlify($data->raw_message);
1776 $guid = notags(unxmlify($data->guid));
1777 $author = notags(unxmlify($data->author));
1778 $public = notags(unxmlify($data->public));
1779 $created_at = notags(unxmlify($data->created_at));
1780 $provider_display_name = notags(unxmlify($data->provider_display_name));
1782 /// @todo enable support for polls
1783 //if ($data->poll) {
1784 // foreach ($data->poll AS $poll)
1788 $contact = self::allowed_contact_by_handle($importer, $author, false);
1792 if (self::message_exists($importer["uid"], $guid))
1796 if ($data->location)
1797 foreach ($data->location->children() AS $fieldname => $data)
1798 $address[$fieldname] = notags(unxmlify($data));
1800 $body = diaspora2bb($raw_message);
1802 $datarray = array();
1805 foreach ($data->photo AS $photo)
1806 $body = "[img]".unxmlify($photo->remote_photo_path).
1807 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
1809 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1811 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1813 // Add OEmbed and other information to the body
1814 if (!self::is_redmatrix($contact["url"]))
1815 $body = add_page_info_to_body($body, false, true);
1818 $datarray["uid"] = $importer["uid"];
1819 $datarray["contact-id"] = $contact["id"];
1820 $datarray["network"] = NETWORK_DIASPORA;
1822 $datarray["author-name"] = $contact["name"];
1823 $datarray["author-link"] = $contact["url"];
1824 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1826 $datarray["owner-name"] = $datarray["author-name"];
1827 $datarray["owner-link"] = $datarray["author-link"];
1828 $datarray["owner-avatar"] = $datarray["author-avatar"];
1830 $datarray["guid"] = $guid;
1831 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1833 $datarray["verb"] = ACTIVITY_POST;
1834 $datarray["gravity"] = GRAVITY_PARENT;
1836 $datarray["object"] = $xml;
1838 $datarray["body"] = $body;
1840 if ($provider_display_name != "")
1841 $datarray["app"] = $provider_display_name;
1843 $datarray["plink"] = self::plink($author, $guid);
1844 $datarray["private"] = (($public == "false") ? 1 : 0);
1845 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1847 if (isset($address["address"]))
1848 $datarray["location"] = $address["address"];
1850 if (isset($address["lat"]) AND isset($address["lng"]))
1851 $datarray["coord"] = $address["lat"]." ".$address["lng"];
1853 self::fetch_guid($datarray);
1854 $message_id = item_store($datarray);
1857 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1862 /******************************************************************************************
1863 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1864 ******************************************************************************************/
1866 private function my_handle($me) {
1867 if ($contact["addr"] != "")
1868 return $contact["addr"];
1870 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1871 // So - just in case - we build the the address here.
1872 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1875 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1877 logger("Message: ".$msg, LOGGER_DATA);
1879 $handle = self::my_handle($user);
1881 $b64url_data = base64url_encode($msg);
1883 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1885 $type = "application/xml";
1886 $encoding = "base64url";
1887 $alg = "RSA-SHA256";
1889 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1891 $signature = rsa_sign($signable_data,$prvkey);
1892 $sig = base64url_encode($signature);
1894 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1895 "me:env" => array("me:encoding" => "base64url",
1896 "me:alg" => "RSA-SHA256",
1898 "@attributes" => array("type" => "application/xml"),
1899 "me:sig" => $sig)));
1901 $namespaces = array("" => "https://joindiaspora.com/protocol",
1902 "me" => "http://salmon-protocol.org/ns/magic-env");
1904 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1906 logger("magic_env: ".$magic_env, LOGGER_DATA);
1910 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1912 logger("Message: ".$msg, LOGGER_DATA);
1914 // without a public key nothing will work
1917 logger("pubkey missing: contact id: ".$contact["id"]);
1921 $inner_aes_key = random_string(32);
1922 $b_inner_aes_key = base64_encode($inner_aes_key);
1923 $inner_iv = random_string(16);
1924 $b_inner_iv = base64_encode($inner_iv);
1926 $outer_aes_key = random_string(32);
1927 $b_outer_aes_key = base64_encode($outer_aes_key);
1928 $outer_iv = random_string(16);
1929 $b_outer_iv = base64_encode($outer_iv);
1931 $handle = self::my_handle($user);
1933 $padded_data = pkcs5_pad($msg,16);
1934 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1936 $b64_data = base64_encode($inner_encrypted);
1939 $b64url_data = base64url_encode($b64_data);
1940 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1942 $type = "application/xml";
1943 $encoding = "base64url";
1944 $alg = "RSA-SHA256";
1946 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1948 $signature = rsa_sign($signable_data,$prvkey);
1949 $sig = base64url_encode($signature);
1951 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1952 "aes_key" => $b_inner_aes_key,
1953 "author_id" => $handle));
1955 $decrypted_header = xml::from_array($xmldata, $xml, true);
1956 $decrypted_header = pkcs5_pad($decrypted_header,16);
1958 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1960 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1962 $encrypted_outer_key_bundle = "";
1963 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1965 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1967 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1969 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1970 "ciphertext" => base64_encode($ciphertext)));
1971 $cipher_json = base64_encode($encrypted_header_json_object);
1973 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1974 "me:env" => array("me:encoding" => "base64url",
1975 "me:alg" => "RSA-SHA256",
1977 "@attributes" => array("type" => "application/xml"),
1978 "me:sig" => $sig)));
1980 $namespaces = array("" => "https://joindiaspora.com/protocol",
1981 "me" => "http://salmon-protocol.org/ns/magic-env");
1983 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1985 logger("magic_env: ".$magic_env, LOGGER_DATA);
1989 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1992 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1994 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1996 // The data that will be transmitted is double encoded via "urlencode", strange ...
1997 $slap = "xml=".urlencode(urlencode($magic_env));
2001 private function signature($owner, $message) {
2003 unset($sigmsg["author_signature"]);
2004 unset($sigmsg["parent_author_signature"]);
2006 $signed_text = implode(";", $sigmsg);
2008 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2011 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2015 $enabled = intval(get_config("system", "diaspora_enabled"));
2019 $logid = random_string(4);
2020 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2022 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2026 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2028 if (!$queue_run && was_recently_delayed($contact["id"])) {
2031 if (!intval(get_config("system", "diaspora_test"))) {
2032 post_url($dest_url."/", $slap);
2033 $return_code = $a->get_curl_code();
2035 logger("test_mode");
2040 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2042 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2043 logger("queue message");
2045 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2046 intval($contact["id"]),
2047 dbesc(NETWORK_DIASPORA),
2049 intval($public_batch)
2052 logger("add_to_queue ignored - identical item already in queue");
2054 // queue message for redelivery
2055 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2059 return(($return_code) ? $return_code : (-1));
2063 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2065 $data = array("XML" => array("post" => array($type => $message)));
2067 $msg = xml::from_array($data, $xml);
2069 logger('message: '.$msg, LOGGER_DATA);
2070 logger('send guid '.$guid, LOGGER_DEBUG);
2072 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2075 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2078 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2080 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2082 return $return_code;
2085 public static function send_share($owner,$contact) {
2087 $message = array("sender_handle" => self::my_handle($owner),
2088 "recipient_handle" => $contact["addr"]);
2090 return self::build_and_transmit($owner, $contact, "request", $message);
2093 public static function send_unshare($owner,$contact) {
2095 $message = array("post_guid" => $owner["guid"],
2096 "diaspora_handle" => self::my_handle($owner),
2097 "type" => "Person");
2099 return self::build_and_transmit($owner, $contact, "retraction", $message);
2102 public static function is_reshare($body) {
2103 $body = trim($body);
2105 // Skip if it isn't a pure repeated messages
2106 // Does it start with a share?
2107 if (strpos($body, "[share") > 0)
2110 // Does it end with a share?
2111 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2114 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2115 // Skip if there is no shared message in there
2116 if ($body == $attributes)
2120 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2121 if ($matches[1] != "")
2122 $guid = $matches[1];
2124 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2125 if ($matches[1] != "")
2126 $guid = $matches[1];
2129 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2130 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2133 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2134 $ret["root_guid"] = $guid;
2140 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2141 if ($matches[1] != "")
2142 $profile = $matches[1];
2144 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2145 if ($matches[1] != "")
2146 $profile = $matches[1];
2150 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2151 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2155 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2156 if ($matches[1] != "")
2157 $link = $matches[1];
2159 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2160 if ($matches[1] != "")
2161 $link = $matches[1];
2163 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2164 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2169 public static function send_status($item, $owner, $contact, $public_batch = false) {
2171 $myaddr = self::my_handle($owner);
2173 $public = (($item["private"]) ? "false" : "true");
2175 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2177 // Detect a share element and do a reshare
2178 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2179 $message = array("root_diaspora_id" => $ret["root_handle"],
2180 "root_guid" => $ret["root_guid"],
2181 "guid" => $item["guid"],
2182 "diaspora_handle" => $myaddr,
2183 "public" => $public,
2184 "created_at" => $created,
2185 "provider_display_name" => $item["app"]);
2189 $title = $item["title"];
2190 $body = $item["body"];
2192 // convert to markdown
2193 $body = html_entity_decode(bb2diaspora($body));
2197 $body = "## ".html_entity_decode($title)."\n\n".$body;
2199 if ($item["attach"]) {
2200 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2202 $body .= "\n".t("Attachments:")."\n";
2203 foreach($matches as $mtch)
2204 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2208 $location = array();
2210 if ($item["location"] != "")
2211 $location["address"] = $item["location"];
2213 if ($item["coord"] != "") {
2214 $coord = explode(" ", $item["coord"]);
2215 $location["lat"] = $coord[0];
2216 $location["lng"] = $coord[1];
2219 $message = array("raw_message" => $body,
2220 "location" => $location,
2221 "guid" => $item["guid"],
2222 "diaspora_handle" => $myaddr,
2223 "public" => $public,
2224 "created_at" => $created,
2225 "provider_display_name" => $item["app"]);
2227 if (count($location) == 0)
2228 unset($message["location"]);
2230 $type = "status_message";
2233 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2236 private function construct_like($item, $owner) {
2238 $myaddr = self::my_handle($owner);
2240 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2241 dbesc($item["thr-parent"]));
2247 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2250 return(array("positive" => $positive,
2251 "guid" => $item["guid"],
2252 "target_type" => $target_type,
2253 "parent_guid" => $parent["guid"],
2254 "author_signature" => $authorsig,
2255 "diaspora_handle" => $myaddr));
2258 private function construct_comment($item, $owner) {
2260 $myaddr = self::my_handle($owner);
2262 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2263 intval($item["parent"]),
2264 intval($item["parent"])
2272 $text = html_entity_decode(bb2diaspora($item["body"]));
2274 return(array("guid" => $item["guid"],
2275 "parent_guid" => $parent["guid"],
2276 "author_signature" => "",
2278 "diaspora_handle" => $myaddr));
2281 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2283 if($item['verb'] === ACTIVITY_LIKE) {
2284 $message = self::construct_like($item, $owner);
2287 $message = self::construct_comment($item, $owner);
2294 $message["author_signature"] = self::signature($owner, $message);
2296 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2299 private function message_from_signatur($item, $signature) {
2301 // Split the signed text
2302 $signed_parts = explode(";", $signature['signed_text']);
2304 if ($item["deleted"])
2305 $message = array("parent_author_signature" => "",
2306 "target_guid" => $signed_parts[0],
2307 "target_type" => $signed_parts[1],
2308 "sender_handle" => $signature['signer'],
2309 "target_author_signature" => $signature['signature']);
2310 elseif ($item['verb'] === ACTIVITY_LIKE)
2311 $message = array("positive" => $signed_parts[0],
2312 "guid" => $signed_parts[1],
2313 "target_type" => $signed_parts[2],
2314 "parent_guid" => $signed_parts[3],
2315 "parent_author_signature" => "",
2316 "author_signature" => $signature['signature'],
2317 "diaspora_handle" => $signed_parts[4]);
2319 // Remove the comment guid
2320 $guid = array_shift($signed_parts);
2322 // Remove the parent guid
2323 $parent_guid = array_shift($signed_parts);
2325 // Remove the handle
2326 $handle = array_pop($signed_parts);
2328 // Glue the parts together
2329 $text = implode(";", $signed_parts);
2331 $message = array("guid" => $guid,
2332 "parent_guid" => $parent_guid,
2333 "parent_author_signature" => "",
2334 "author_signature" => $signature['signature'],
2335 "text" => implode(";", $signed_parts),
2336 "diaspora_handle" => $handle);
2341 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2343 if ($item["deleted"]) {
2344 $sql_sign_id = "retract_iid";
2345 $type = "relayable_retraction";
2346 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2347 $sql_sign_id = "iid";
2350 $sql_sign_id = "iid";
2354 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2356 // fetch the original signature
2358 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2359 intval($item["id"]));
2362 logger("Couldn't fetch signatur for contact ".$contact["addr"]." at item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2368 // Old way - is used by the internal Friendica functions
2369 /// @todo Change all signatur storing functions to the new format
2370 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2371 $message = self::message_from_signatur($item, $signature);
2373 $msg = json_decode($signature['signed_text'], true);
2376 foreach ($msg AS $field => $data) {
2377 if (!$item["deleted"]) {
2378 if ($field == "author")
2379 $field = "diaspora_handle";
2380 if ($field == "parent_type")
2381 $field = "target_type";
2384 $message[$field] = $data;
2388 if ($item["deleted"]) {
2389 $signed_text = $message["target_guid"].';'.$message["target_type"];
2390 $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2392 $message["parent_author_signature"] = self::signature($owner, $message);
2394 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2396 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2399 public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2401 $myaddr = self::my_handle($owner);
2403 // Check whether the retraction is for a top-level post or whether it's a relayable
2404 if ($item["uri"] !== $item["parent-uri"]) {
2405 $msg_type = "relayable_retraction";
2406 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2408 $msg_type = "signed_retraction";
2409 $target_type = "StatusMessage";
2412 $signed_text = $item["guid"].";".$target_type;
2414 $message = array("target_guid" => $item['guid'],
2415 "target_type" => $target_type,
2416 "sender_handle" => $myaddr,
2417 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2419 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2422 public static function send_mail($item, $owner, $contact) {
2424 $myaddr = self::my_handle($owner);
2426 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2427 intval($item["convid"]),
2428 intval($item["uid"])
2432 logger("conversation not found.");
2438 "guid" => $cnv["guid"],
2439 "subject" => $cnv["subject"],
2440 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2441 "diaspora_handle" => $cnv["creator"],
2442 "participant_handles" => $cnv["recips"]
2445 $body = bb2diaspora($item["body"]);
2446 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2448 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2449 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2452 "guid" => $item["guid"],
2453 "parent_guid" => $cnv["guid"],
2454 "parent_author_signature" => $sig,
2455 "author_signature" => $sig,
2457 "created_at" => $created,
2458 "diaspora_handle" => $myaddr,
2459 "conversation_guid" => $cnv["guid"]
2462 if ($item["reply"]) {
2466 $message = array("guid" => $cnv["guid"],
2467 "subject" => $cnv["subject"],
2468 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2470 "diaspora_handle" => $cnv["creator"],
2471 "participant_handles" => $cnv["recips"]);
2473 $type = "conversation";
2476 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2479 public static function send_profile($uid) {
2484 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2485 AND `uid` = %d AND `rel` != %d",
2486 dbesc(NETWORK_DIASPORA),
2488 intval(CONTACT_IS_SHARING)
2493 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2495 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2496 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2497 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
2506 $handle = $profile["addr"];
2507 $first = ((strpos($profile['name'],' ')
2508 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
2509 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
2510 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
2511 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
2512 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
2513 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
2515 if ($searchable === 'true') {
2516 $dob = '1000-00-00';
2518 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
2519 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
2521 $about = $profile['about'];
2522 $about = strip_tags(bbcode($about));
2524 $location = formatted_location($profile);
2526 if ($profile['pub_keywords']) {
2527 $kw = str_replace(',',' ',$profile['pub_keywords']);
2528 $kw = str_replace(' ',' ',$kw);
2529 $arr = explode(' ',$profile['pub_keywords']);
2531 for($x = 0; $x < 5; $x ++) {
2533 $tags .= '#'. trim($arr[$x]) .' ';
2537 $tags = trim($tags);
2540 $message = array("diaspora_handle" => $handle,
2541 "first_name" => $first,
2542 "last_name" => $last,
2543 "image_url" => $large,
2544 "image_url_medium" => $medium,
2545 "image_url_small" => $small,
2547 "gender" => $profile['gender'],
2549 "location" => $location,
2550 "searchable" => $searchable,
2551 "tag_string" => $tags);
2553 foreach($recips as $recip)
2554 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);