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
25 * @brief Return a list of relay servers
27 * This is an experimental Diaspora feature.
29 * @return array of relay servers
31 public static function relay_list() {
33 $serverdata = get_config("system", "relay_server");
34 if ($serverdata == "")
39 $servers = explode(",", $serverdata);
41 foreach($servers AS $server) {
42 $server = trim($server);
43 $batch = $server."/receive/public";
45 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
48 $addr = "relay@".str_replace("http://", "", normalise_link($server));
50 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
51 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
56 dbesc(normalise_link($server)),
58 dbesc(NETWORK_DIASPORA),
59 intval(CONTACT_IS_FOLLOWER),
60 dbesc(datetime_convert()),
61 dbesc(datetime_convert()),
62 dbesc(datetime_convert())
65 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
67 $relay[] = $relais[0];
69 $relay[] = $relais[0];
76 * @brief repairs a signature that was double encoded
78 * The function is unused at the moment. It was copied from the old implementation.
80 * @param string $signature The signature
81 * @param string $handle The handle of the signature owner
82 * @param integer $level This value is only set inside this function to avoid endless loops
84 * @return string the repaired signature
86 private function repair_signature($signature, $handle = "", $level = 1) {
91 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
92 $signature = base64_decode($signature);
93 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
95 // Do a recursive call to be able to fix even multiple levels
97 $signature = self::repair_signature($signature, $handle, ++$level);
104 * @brief verify the envelope and return the verified data
106 * @param string $envelope The magic envelope
108 * @return string verified data
110 private function verify_magic_envelope($envelope) {
112 $basedom = parse_xml_string($envelope, false);
114 if (!is_object($basedom)) {
115 logger("Envelope is no XML file");
119 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
121 if (sizeof($children) == 0) {
122 logger("XML has no children");
128 $data = base64url_decode($children->data);
129 $type = $children->data->attributes()->type[0];
131 $encoding = $children->encoding;
133 $alg = $children->alg;
135 $sig = base64url_decode($children->sig);
136 $key_id = $children->sig->attributes()->key_id[0];
138 $handle = base64url_decode($key_id);
140 $b64url_data = base64url_encode($data);
141 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
143 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
145 $key = self::key($handle);
147 $verify = rsa_verify($signable_data, $sig, $key);
149 logger('Message did not verify. Discarding.');
157 * @brief: Decodes incoming Diaspora message
159 * @param array $importer Array of the importer user
160 * @param string $xml urldecoded Diaspora salmon
163 * 'message' -> decoded Diaspora XML message
164 * 'author' -> author diaspora handle
165 * 'key' -> author public key (converted to pkcs#8)
167 public static function decode($importer, $xml) {
170 $basedom = parse_xml_string($xml);
172 if (!is_object($basedom))
175 $children = $basedom->children('https://joindiaspora.com/protocol');
177 if($children->header) {
179 $author_link = str_replace('acct:','',$children->header->author_id);
182 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
184 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
185 $ciphertext = base64_decode($encrypted_header->ciphertext);
187 $outer_key_bundle = '';
188 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
190 $j_outer_key_bundle = json_decode($outer_key_bundle);
192 $outer_iv = base64_decode($j_outer_key_bundle->iv);
193 $outer_key = base64_decode($j_outer_key_bundle->key);
195 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
198 $decrypted = pkcs5_unpad($decrypted);
200 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
201 $idom = parse_xml_string($decrypted,false);
203 $inner_iv = base64_decode($idom->iv);
204 $inner_aes_key = base64_decode($idom->aes_key);
206 $author_link = str_replace('acct:','',$idom->author_id);
209 $dom = $basedom->children(NAMESPACE_SALMON_ME);
211 // figure out where in the DOM tree our data is hiding
213 if($dom->provenance->data)
214 $base = $dom->provenance;
215 elseif($dom->env->data)
221 logger('unable to locate salmon data in xml');
222 http_status_exit(400);
226 // Stash the signature away for now. We have to find their key or it won't be good for anything.
227 $signature = base64url_decode($base->sig);
231 // strip whitespace so our data element will return to one big base64 blob
232 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
235 // stash away some other stuff for later
237 $type = $base->data[0]->attributes()->type[0];
238 $keyhash = $base->sig[0]->attributes()->keyhash[0];
239 $encoding = $base->encoding;
243 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
247 $data = base64url_decode($data);
251 $inner_decrypted = $data;
254 // Decode the encrypted blob
256 $inner_encrypted = base64_decode($data);
257 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
258 $inner_decrypted = pkcs5_unpad($inner_decrypted);
262 logger('Could not retrieve author URI.');
263 http_status_exit(400);
265 // Once we have the author URI, go to the web and try to find their public key
266 // (first this will look it up locally if it is in the fcontact cache)
267 // This will also convert diaspora public key from pkcs#1 to pkcs#8
269 logger('Fetching key for '.$author_link);
270 $key = self::key($author_link);
273 logger('Could not retrieve author key.');
274 http_status_exit(400);
277 $verify = rsa_verify($signed_data,$signature,$key);
280 logger('Message did not verify. Discarding.');
281 http_status_exit(400);
284 logger('Message verified.');
286 return array('message' => (string)$inner_decrypted,
287 'author' => unxmlify($author_link),
288 'key' => (string)$key);
293 * @brief Dispatches public messages and find the fitting receivers
295 * @param array $msg The post that will be dispatched
297 * @return int The message id of the generated message, "true" or "false" if there was an error
299 public static function dispatch_public($msg) {
301 $enabled = intval(get_config("system", "diaspora_enabled"));
303 logger("diaspora is disabled");
307 // Use a dummy importer to import the data for the public copy
308 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
309 $message_id = self::dispatch($importer,$msg);
311 // Now distribute it to the followers
312 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
313 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
314 AND NOT `account_expired` AND NOT `account_removed`",
315 dbesc(NETWORK_DIASPORA),
316 dbesc($msg["author"])
320 logger("delivering to: ".$rr["username"]);
321 self::dispatch($rr,$msg);
324 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
330 * @brief Dispatches the different message types to the different functions
332 * @param array $importer Array of the importer user
333 * @param array $msg The post that will be dispatched
335 * @return int The message id of the generated message, "true" or "false" if there was an error
337 public static function dispatch($importer, $msg) {
339 // The sender is the handle of the contact that sent the message.
340 // This will often be different with relayed messages (for example "like" and "comment")
341 $sender = $msg["author"];
343 if (!diaspora::valid_posting($msg, $fields)) {
344 logger("Invalid posting");
348 $type = $fields->getName();
350 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
353 case "account_deletion":
354 return self::receive_account_deletion($importer, $fields);
357 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
360 return self::receive_contact_request($importer, $fields);
363 return self::receive_conversation($importer, $msg, $fields);
366 return self::receive_like($importer, $sender, $fields);
369 return self::receive_message($importer, $fields);
371 case "participation": // Not implemented
372 return self::receive_participation($importer, $fields);
374 case "photo": // Not implemented
375 return self::receive_photo($importer, $fields);
377 case "poll_participation": // Not implemented
378 return self::receive_poll_participation($importer, $fields);
381 return self::receive_profile($importer, $fields);
384 return self::receive_reshare($importer, $fields, $msg["message"]);
387 return self::receive_retraction($importer, $sender, $fields);
389 case "status_message":
390 return self::receive_status_message($importer, $fields, $msg["message"]);
393 logger("Unknown message type ".$type);
401 * @brief Checks if a posting is valid and fetches the data fields.
403 * This function does not only check the signature.
404 * It also does the conversion between the old and the new diaspora format.
406 * @param array $msg Array with the XML, the sender handle and the sender signature
407 * @param object $fields SimpleXML object that contains the posting when it is valid
409 * @return bool Is the posting valid?
411 private function valid_posting($msg, &$fields) {
413 $data = parse_xml_string($msg["message"], false);
415 if (!is_object($data)) {
416 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
420 $first_child = $data->getName();
422 // Is this the new or the old version?
423 if ($data->getName() == "XML") {
425 foreach ($data->post->children() as $child)
432 $type = $element->getName();
435 // All retractions are handled identically from now on.
436 // In the new version there will only be "retraction".
437 if (in_array($type, array("signed_retraction", "relayable_retraction")))
438 $type = "retraction";
440 if ($type == "request")
443 $fields = new SimpleXMLElement("<".$type."/>");
447 foreach ($element->children() AS $fieldname => $entry) {
449 // Translation for the old XML structure
450 if ($fieldname == "diaspora_handle")
451 $fieldname = "author";
453 if ($fieldname == "participant_handles")
454 $fieldname = "participants";
456 if (in_array($type, array("like", "participation"))) {
457 if ($fieldname == "target_type")
458 $fieldname = "parent_type";
461 if ($fieldname == "sender_handle")
462 $fieldname = "author";
464 if ($fieldname == "recipient_handle")
465 $fieldname = "recipient";
467 if ($fieldname == "root_diaspora_id")
468 $fieldname = "root_author";
470 if ($type == "retraction") {
471 if ($fieldname == "post_guid")
472 $fieldname = "target_guid";
474 if ($fieldname == "type")
475 $fieldname = "target_type";
479 if (($fieldname == "author_signature") AND ($entry != ""))
480 $author_signature = base64_decode($entry);
481 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
482 $parent_author_signature = base64_decode($entry);
483 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
484 if ($signed_data != "") {
486 $signed_data_parent .= ";";
489 $signed_data .= $entry;
491 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
492 ($orig_type == "relayable_retraction"))
493 xml::copy($entry, $fields, $fieldname);
496 // This is something that shouldn't happen at all.
497 if (in_array($type, array("status_message", "reshare", "profile")))
498 if ($msg["author"] != $fields->author) {
499 logger("Message handle is not the same as envelope sender. Quitting this message.");
503 // Only some message types have signatures. So we quit here for the other types.
504 if (!in_array($type, array("comment", "message", "like")))
507 // No author_signature? This is a must, so we quit.
508 if (!isset($author_signature)) {
509 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
513 if (isset($parent_author_signature)) {
514 $key = self::key($msg["author"]);
516 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
517 logger("No valid parent author signature for author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
522 $key = self::key($fields->author);
524 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
525 logger("No valid author signature for author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
532 * @brief Fetches the public key for a given handle
534 * @param string $handle The handle
536 * @return string The public key
538 private function key($handle) {
539 $handle = strval($handle);
541 logger("Fetching diaspora key for: ".$handle);
543 $r = self::person_by_handle($handle);
551 * @brief Fetches data for a given handle
553 * @param string $handle The handle
555 * @return array the queried data
557 private function person_by_handle($handle) {
559 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
560 dbesc(NETWORK_DIASPORA),
565 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
567 // update record occasionally so it doesn't get stale
568 $d = strtotime($person["updated"]." +00:00");
569 if ($d < strtotime("now - 14 days"))
573 if (!$person OR $update) {
574 logger("create or refresh", LOGGER_DEBUG);
575 $r = probe_url($handle, PROBE_DIASPORA);
577 // Note that Friendica contacts will return a "Diaspora person"
578 // if Diaspora connectivity is enabled on their server
579 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
580 self::add_fcontact($r, $update);
588 * @brief Updates the fcontact table
590 * @param array $arr The fcontact data
591 * @param bool $update Update or insert?
593 * @return string The id of the fcontact entry
595 private function add_fcontact($arr, $update = false) {
598 $r = q("UPDATE `fcontact` SET
611 WHERE `url` = '%s' AND `network` = '%s'",
613 dbesc($arr["photo"]),
614 dbesc($arr["request"]),
617 dbesc($arr["batch"]),
618 dbesc($arr["notify"]),
620 dbesc($arr["confirm"]),
621 dbesc($arr["alias"]),
622 dbesc($arr["pubkey"]),
623 dbesc(datetime_convert()),
625 dbesc($arr["network"])
628 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
629 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
630 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
633 dbesc($arr["photo"]),
634 dbesc($arr["request"]),
637 dbesc($arr["batch"]),
638 dbesc($arr["notify"]),
640 dbesc($arr["confirm"]),
641 dbesc($arr["network"]),
642 dbesc($arr["alias"]),
643 dbesc($arr["pubkey"]),
644 dbesc(datetime_convert())
652 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
654 * @param int $contact_id The id in the contact table
655 * @param int $gcontact_id The id in the gcontact table
657 * @return string the handle
659 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
662 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
664 if ($gcontact_id != 0) {
665 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
666 intval($gcontact_id));
668 return $r[0]["addr"];
671 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
672 intval($contact_id));
676 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
678 if($contact['addr'] != "")
679 $handle = $contact['addr'];
681 $baseurl_start = strpos($contact['url'],'://') + 3;
682 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
683 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
684 $handle = $contact['nick'].'@'.$baseurl;
692 * @brief Get a contact id for a given handle
694 * @param int $uid The user id
695 * @param string $handle The handle in the format user@domain.tld
697 * @return The contact id
699 private function contact_by_handle($uid, $handle) {
700 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
708 $handle_parts = explode("@", $handle);
709 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
710 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
722 * @brief Check if posting is allowed for this contact
724 * @param array $importer Array of the importer user
725 * @param array $contact The contact that is checked
726 * @param bool $is_comment Is the check for a comment?
728 * @return bool is the contact allowed to post?
730 private function post_allow($importer, $contact, $is_comment = false) {
732 // perhaps we were already sharing with this person. Now they're sharing with us.
733 // That makes us friends.
734 // Normally this should have handled by getting a request - but this could get lost
735 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
736 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
737 intval(CONTACT_IS_FRIEND),
738 intval($contact["id"]),
739 intval($importer["uid"])
741 $contact["rel"] = CONTACT_IS_FRIEND;
742 logger("defining user ".$contact["nick"]." as friend");
745 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
747 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
749 if($contact["rel"] == CONTACT_IS_FOLLOWER)
750 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
753 // Messages for the global users are always accepted
754 if ($importer["uid"] == 0)
761 * @brief Fetches the contact id for a handle and checks if posting is allowed
763 * @param array $importer Array of the importer user
764 * @param string $handle The checked handle in the format user@domain.tld
765 * @param bool $is_comment Is the check for a comment?
767 * @return array The contact data
769 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
770 $contact = self::contact_by_handle($importer["uid"], $handle);
772 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
776 if (!self::post_allow($importer, $contact, $is_comment)) {
777 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
784 * @brief Does the message already exists on the system?
786 * @param int $uid The user id
787 * @param string $guid The guid of the message
789 * @return int|bool message id if the message already was stored into the system - or false.
791 private function message_exists($uid, $guid) {
792 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
798 logger("message ".$guid." already exists for user ".$uid);
806 * @brief Checks for links to posts in a message
808 * @param array $item The item array
810 private function fetch_guid($item) {
811 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
812 function ($match) use ($item){
813 return(self::fetch_guid_sub($match, $item));
818 * @brief sub function of "fetch_guid" which checks for links in messages
820 * @param array $match array containing a link that has to be checked for a message link
821 * @param array $item The item array
823 private function fetch_guid_sub($match, $item) {
824 if (!self::store_by_guid($match[1], $item["author-link"]))
825 self::store_by_guid($match[1], $item["owner-link"]);
829 * @brief Fetches an item with a given guid from a given server
831 * @param string $guid the message guid
832 * @param string $server The server address
833 * @param int $uid The user id of the user
835 * @return int the message id of the stored message or false
837 private function store_by_guid($guid, $server, $uid = 0) {
838 $serverparts = parse_url($server);
839 $server = $serverparts["scheme"]."://".$serverparts["host"];
841 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
843 $msg = self::message($guid, $server);
848 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
850 // Now call the dispatcher
851 return self::dispatch_public($msg);
855 * @brief Fetches a message from a server
857 * @param string $guid message guid
858 * @param string $server The url of the server
859 * @param int $level Endless loop prevention
862 * 'message' => The message XML
863 * 'author' => The author handle
864 * 'key' => The public key of the author
866 private function message($guid, $server, $level = 0) {
871 // This will work for new Diaspora servers and Friendica servers from 3.5
872 $source_url = $server."/fetch/post/".$guid;
873 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
875 $envelope = fetch_url($source_url);
877 logger("Envelope was fetched.", LOGGER_DEBUG);
878 $x = self::verify_magic_envelope($envelope);
880 logger("Envelope could not be verified.", LOGGER_DEBUG);
883 logger("Envelope was verified.", LOGGER_DEBUG);
885 // This will work for older Diaspora and Friendica servers
886 $source_url = $server."/p/".$guid.".xml";
887 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
889 $x = fetch_url($source_url);
894 $source_xml = parse_xml_string($x, false);
896 if (!is_object($source_xml))
899 if ($source_xml->post->reshare) {
900 // Reshare of a reshare - old Diaspora version
901 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
902 } elseif ($source_xml->getName() == "reshare") {
903 // Reshare of a reshare - new Diaspora version
904 return self::message($source_xml->root_guid, $server, ++$level);
909 // Fetch the author - for the old and the new Diaspora version
910 if ($source_xml->post->status_message->diaspora_handle)
911 $author = (string)$source_xml->post->status_message->diaspora_handle;
912 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
913 $author = (string)$source_xml->author;
915 // If this isn't a "status_message" then quit
919 $msg = array("message" => $x, "author" => $author);
921 $msg["key"] = self::key($msg["author"]);
927 * @brief Fetches the item record of a given guid
929 * @param int $uid The user id
930 * @param string $guid message guid
931 * @param string $author The handle of the item
932 * @param array $contact The contact of the item owner
934 * @return array the item record
936 private function parent_item($uid, $guid, $author, $contact) {
937 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
938 `author-name`, `author-link`, `author-avatar`,
939 `owner-name`, `owner-link`, `owner-avatar`
940 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
941 intval($uid), dbesc($guid));
944 $result = self::store_by_guid($guid, $contact["url"], $uid);
947 $person = self::person_by_handle($author);
948 $result = self::store_by_guid($guid, $person["url"], $uid);
952 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
954 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
955 `author-name`, `author-link`, `author-avatar`,
956 `owner-name`, `owner-link`, `owner-avatar`
957 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
958 intval($uid), dbesc($guid));
963 logger("parent item not found: parent: ".$guid." - user: ".$uid);
966 logger("parent item found: parent: ".$guid." - user: ".$uid);
972 * @brief returns contact details
974 * @param array $contact The default contact if the person isn't found
975 * @param array $person The record of the person
976 * @param int $uid The user id
979 * 'cid' => contact id
980 * 'network' => network type
982 private function author_contact_by_url($contact, $person, $uid) {
984 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
985 dbesc(normalise_link($person["url"])), intval($uid));
988 $network = $r[0]["network"];
990 $cid = $contact["id"];
991 $network = NETWORK_DIASPORA;
994 return (array("cid" => $cid, "network" => $network));
998 * @brief Is the profile a hubzilla profile?
1000 * @param string $url The profile link
1002 * @return bool is it a hubzilla server?
1004 public static function is_redmatrix($url) {
1005 return(strstr($url, "/channel/"));
1009 * @brief Generate a post link with a given handle and message guid
1011 * @param string $addr The user handle
1012 * @param string $guid message guid
1014 * @return string the post link
1016 private function plink($addr, $guid) {
1017 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1021 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1023 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1024 // So we try another way as well.
1025 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1027 $r[0]["network"] = $s[0]["network"];
1029 if ($r[0]["network"] == NETWORK_DFRN)
1030 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1032 if (self::is_redmatrix($r[0]["url"]))
1033 return $r[0]["url"]."/?f=&mid=".$guid;
1035 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1039 * @brief Processes an account deletion
1041 * @param array $importer Array of the importer user
1042 * @param object $data The message object
1044 * @return bool Success
1046 private function receive_account_deletion($importer, $data) {
1048 /// @todo Account deletion should remove the contact from the global contacts as well
1050 $author = notags(unxmlify($data->author));
1052 $contact = self::contact_by_handle($importer["uid"], $author);
1054 logger("cannot find contact for author: ".$author);
1058 // We now remove the contact
1059 contact_remove($contact["id"]);
1064 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1066 * @param string $author Author handle
1067 * @param string $guid Message guid
1069 * @return string The constructed uri or the one from our database
1071 private function get_uri_from_guid($author, $guid) {
1073 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1075 return $r[0]["uri"];
1077 return $author.":".$guid;
1081 * @brief Processes an incoming comment
1083 * @param array $importer Array of the importer user
1084 * @param string $sender The sender of the message
1085 * @param object $data The message object
1086 * @param string $xml The original XML of the message
1088 * @return int The message id of the generated comment or "false" if there was an error
1090 private function receive_comment($importer, $sender, $data, $xml) {
1091 $guid = notags(unxmlify($data->guid));
1092 $parent_guid = notags(unxmlify($data->parent_guid));
1093 $text = unxmlify($data->text);
1094 $author = notags(unxmlify($data->author));
1096 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1100 $message_id = self::message_exists($importer["uid"], $guid);
1104 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1108 $person = self::person_by_handle($author);
1109 if (!is_array($person)) {
1110 logger("unable to find author details");
1114 // Fetch the contact id - if we know this contact
1115 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1117 $datarray = array();
1119 $datarray["uid"] = $importer["uid"];
1120 $datarray["contact-id"] = $author_contact["cid"];
1121 $datarray["network"] = $author_contact["network"];
1123 $datarray["author-name"] = $person["name"];
1124 $datarray["author-link"] = $person["url"];
1125 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1127 $datarray["owner-name"] = $contact["name"];
1128 $datarray["owner-link"] = $contact["url"];
1129 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1131 $datarray["guid"] = $guid;
1132 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1134 $datarray["type"] = "remote-comment";
1135 $datarray["verb"] = ACTIVITY_POST;
1136 $datarray["gravity"] = GRAVITY_COMMENT;
1137 $datarray["parent-uri"] = $parent_item["uri"];
1139 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1140 $datarray["object"] = $xml;
1142 $datarray["body"] = diaspora2bb($text);
1144 self::fetch_guid($datarray);
1146 $message_id = item_store($datarray);
1149 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1151 // If we are the origin of the parent we store the original data and notify our followers
1152 if($message_id AND $parent_item["origin"]) {
1154 // Formerly we stored the signed text, the signature and the author in different fields.
1155 // We now store the raw data so that we are more flexible.
1156 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1157 intval($message_id),
1158 dbesc(json_encode($data))
1162 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1169 * @brief processes and stores private messages
1171 * @param array $importer Array of the importer user
1172 * @param array $contact The contact of the message
1173 * @param object $data The message object
1174 * @param array $msg Array of the processed message, author handle and key
1175 * @param object $mesg The private message
1176 * @param array $conversation The conversation record to which this message belongs
1178 * @return bool "true" if it was successful
1180 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1181 $guid = notags(unxmlify($data->guid));
1182 $subject = notags(unxmlify($data->subject));
1183 $author = notags(unxmlify($data->author));
1187 $msg_guid = notags(unxmlify($mesg->guid));
1188 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1189 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1190 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1191 $msg_text = unxmlify($mesg->text);
1192 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1194 // "diaspora_handle" is the element name from the old version
1195 // "author" is the element name from the new version
1197 $msg_author = notags(unxmlify($mesg->author));
1198 elseif ($mesg->diaspora_handle)
1199 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1203 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1205 if($msg_conversation_guid != $guid) {
1206 logger("message conversation guid does not belong to the current conversation.");
1210 $body = diaspora2bb($msg_text);
1211 $message_uri = $msg_author.":".$msg_guid;
1213 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1215 $author_signature = base64_decode($msg_author_signature);
1217 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1221 $person = self::person_by_handle($msg_author);
1223 if (is_array($person) && x($person, "pubkey"))
1224 $key = $person["pubkey"];
1226 logger("unable to find author details");
1231 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1232 logger("verification failed.");
1236 if($msg_parent_author_signature) {
1237 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1239 $parent_author_signature = base64_decode($msg_parent_author_signature);
1243 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1244 logger("owner verification failed.");
1249 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1253 logger("duplicate message already delivered.", LOGGER_DEBUG);
1257 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1258 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1259 intval($importer["uid"]),
1261 intval($conversation["id"]),
1262 dbesc($person["name"]),
1263 dbesc($person["photo"]),
1264 dbesc($person["url"]),
1265 intval($contact["id"]),
1270 dbesc($message_uri),
1271 dbesc($author.":".$guid),
1272 dbesc($msg_created_at)
1275 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1276 dbesc(datetime_convert()),
1277 intval($conversation["id"])
1281 "type" => NOTIFY_MAIL,
1282 "notify_flags" => $importer["notify-flags"],
1283 "language" => $importer["language"],
1284 "to_name" => $importer["username"],
1285 "to_email" => $importer["email"],
1286 "uid" =>$importer["uid"],
1287 "item" => array("subject" => $subject, "body" => $body),
1288 "source_name" => $person["name"],
1289 "source_link" => $person["url"],
1290 "source_photo" => $person["thumb"],
1291 "verb" => ACTIVITY_POST,
1298 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1300 * @param array $importer Array of the importer user
1301 * @param array $msg Array of the processed message, author handle and key
1302 * @param object $data The message object
1304 * @return bool Success
1306 private function receive_conversation($importer, $msg, $data) {
1307 $guid = notags(unxmlify($data->guid));
1308 $subject = notags(unxmlify($data->subject));
1309 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1310 $author = notags(unxmlify($data->author));
1311 $participants = notags(unxmlify($data->participants));
1313 $messages = $data->message;
1315 if (!count($messages)) {
1316 logger("empty conversation");
1320 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1324 $conversation = null;
1326 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1327 intval($importer["uid"]),
1331 $conversation = $c[0];
1333 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1334 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1335 intval($importer["uid"]),
1338 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1339 dbesc(datetime_convert()),
1341 dbesc($participants)
1344 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1345 intval($importer["uid"]),
1350 $conversation = $c[0];
1352 if (!$conversation) {
1353 logger("unable to create conversation.");
1357 foreach($messages as $mesg)
1358 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1364 * @brief Creates the body for a "like" message
1366 * @param array $contact The contact that send us the "like"
1367 * @param array $parent_item The item array of the parent item
1368 * @param string $guid message guid
1370 * @return string the body
1372 private function construct_like_body($contact, $parent_item, $guid) {
1373 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1375 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1376 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1377 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1379 return sprintf($bodyverb, $ulink, $alink, $plink);
1383 * @brief Creates a XML object for a "like"
1385 * @param array $importer Array of the importer user
1386 * @param array $parent_item The item array of the parent item
1388 * @return string The XML
1390 private function construct_like_object($importer, $parent_item) {
1391 $objtype = ACTIVITY_OBJ_NOTE;
1392 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1393 $parent_body = $parent_item["body"];
1395 $xmldata = array("object" => array("type" => $objtype,
1397 "id" => $parent_item["uri"],
1400 "content" => $parent_body));
1402 return xml::from_array($xmldata, $xml, true);
1406 * @brief Processes "like" messages
1408 * @param array $importer Array of the importer user
1409 * @param string $sender The sender of the message
1410 * @param object $data The message object
1412 * @return int The message id of the generated like or "false" if there was an error
1414 private function receive_like($importer, $sender, $data) {
1415 $positive = notags(unxmlify($data->positive));
1416 $guid = notags(unxmlify($data->guid));
1417 $parent_type = notags(unxmlify($data->parent_type));
1418 $parent_guid = notags(unxmlify($data->parent_guid));
1419 $author = notags(unxmlify($data->author));
1421 // likes on comments aren't supported by Diaspora - only on posts
1422 // But maybe this will be supported in the future, so we will accept it.
1423 if (!in_array($parent_type, array("Post", "Comment")))
1426 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1430 $message_id = self::message_exists($importer["uid"], $guid);
1434 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1438 $person = self::person_by_handle($author);
1439 if (!is_array($person)) {
1440 logger("unable to find author details");
1444 // Fetch the contact id - if we know this contact
1445 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1447 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1448 // We would accept this anyhow.
1449 if ($positive == "true")
1450 $verb = ACTIVITY_LIKE;
1452 $verb = ACTIVITY_DISLIKE;
1454 $datarray = array();
1456 $datarray["uid"] = $importer["uid"];
1457 $datarray["contact-id"] = $author_contact["cid"];
1458 $datarray["network"] = $author_contact["network"];
1460 $datarray["author-name"] = $person["name"];
1461 $datarray["author-link"] = $person["url"];
1462 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1464 $datarray["owner-name"] = $contact["name"];
1465 $datarray["owner-link"] = $contact["url"];
1466 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1468 $datarray["guid"] = $guid;
1469 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1471 $datarray["type"] = "activity";
1472 $datarray["verb"] = $verb;
1473 $datarray["gravity"] = GRAVITY_LIKE;
1474 $datarray["parent-uri"] = $parent_item["uri"];
1476 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1477 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1479 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1481 $message_id = item_store($datarray);
1484 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1486 // If we are the origin of the parent we store the original data and notify our followers
1487 if($message_id AND $parent_item["origin"]) {
1489 // Formerly we stored the signed text, the signature and the author in different fields.
1490 // We now store the raw data so that we are more flexible.
1491 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1492 intval($message_id),
1493 dbesc(json_encode($data))
1497 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1504 * @brief Processes private messages
1506 * @param array $importer Array of the importer user
1507 * @param object $data The message object
1509 * @return bool Success?
1511 private function receive_message($importer, $data) {
1512 $guid = notags(unxmlify($data->guid));
1513 $parent_guid = notags(unxmlify($data->parent_guid));
1514 $text = unxmlify($data->text);
1515 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1516 $author = notags(unxmlify($data->author));
1517 $conversation_guid = notags(unxmlify($data->conversation_guid));
1519 $contact = self::allowed_contact_by_handle($importer, $author, true);
1523 $conversation = null;
1525 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1526 intval($importer["uid"]),
1527 dbesc($conversation_guid)
1530 $conversation = $c[0];
1532 logger("conversation not available.");
1538 $body = diaspora2bb($text);
1539 $message_uri = $author.":".$guid;
1541 $person = self::person_by_handle($author);
1543 logger("unable to find author details");
1547 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1548 dbesc($message_uri),
1549 intval($importer["uid"])
1552 logger("duplicate message already delivered.", LOGGER_DEBUG);
1556 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1557 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1558 intval($importer["uid"]),
1560 intval($conversation["id"]),
1561 dbesc($person["name"]),
1562 dbesc($person["photo"]),
1563 dbesc($person["url"]),
1564 intval($contact["id"]),
1565 dbesc($conversation["subject"]),
1569 dbesc($message_uri),
1570 dbesc($author.":".$parent_guid),
1574 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1575 dbesc(datetime_convert()),
1576 intval($conversation["id"])
1583 * @brief Processes participations - unsupported by now
1585 * @param array $importer Array of the importer user
1586 * @param object $data The message object
1588 * @return bool always true
1590 private function receive_participation($importer, $data) {
1591 // I'm not sure if we can fully support this message type
1596 * @brief Processes photos - unneeded
1598 * @param array $importer Array of the importer user
1599 * @param object $data The message object
1601 * @return bool always true
1603 private function receive_photo($importer, $data) {
1604 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1609 * @brief Processes poll participations - unssupported
1611 * @param array $importer Array of the importer user
1612 * @param object $data The message object
1614 * @return bool always true
1616 private function receive_poll_participation($importer, $data) {
1617 // We don't support polls by now
1622 * @brief Processes incoming profile updates
1624 * @param array $importer Array of the importer user
1625 * @param object $data The message object
1627 * @return bool Success
1629 private function receive_profile($importer, $data) {
1630 $author = notags(unxmlify($data->author));
1632 $contact = self::contact_by_handle($importer["uid"], $author);
1636 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1637 $image_url = unxmlify($data->image_url);
1638 $birthday = unxmlify($data->birthday);
1639 $location = diaspora2bb(unxmlify($data->location));
1640 $about = diaspora2bb(unxmlify($data->bio));
1641 $gender = unxmlify($data->gender);
1642 $searchable = (unxmlify($data->searchable) == "true");
1643 $nsfw = (unxmlify($data->nsfw) == "true");
1644 $tags = unxmlify($data->tag_string);
1646 $tags = explode("#", $tags);
1648 $keywords = array();
1649 foreach ($tags as $tag) {
1650 $tag = trim(strtolower($tag));
1655 $keywords = implode(", ", $keywords);
1657 $handle_parts = explode("@", $author);
1658 $nick = $handle_parts[0];
1661 $name = $handle_parts[0];
1663 if( preg_match("|^https?://|", $image_url) === 0)
1664 $image_url = "http://".$handle_parts[1].$image_url;
1666 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1668 // Generic birthday. We don't know the timezone. The year is irrelevant.
1670 $birthday = str_replace("1000", "1901", $birthday);
1672 if ($birthday != "")
1673 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1675 // this is to prevent multiple birthday notifications in a single year
1676 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1678 if(substr($birthday,5) === substr($contact["bd"],5))
1679 $birthday = $contact["bd"];
1681 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1682 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1686 dbesc(datetime_convert()),
1692 intval($contact["id"]),
1693 intval($importer["uid"])
1697 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1698 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1701 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1702 "photo" => $image_url, "name" => $name, "location" => $location,
1703 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1704 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1705 "hide" => !$searchable, "nsfw" => $nsfw);
1707 update_gcontact($gcontact);
1709 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1715 * @brief Processes incoming friend requests
1717 * @param array $importer Array of the importer user
1718 * @param array $contact The contact that send the request
1720 private function receive_request_make_friend($importer, $contact) {
1724 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1725 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1726 intval(CONTACT_IS_FRIEND),
1727 intval($contact["id"]),
1728 intval($importer["uid"])
1731 // send notification
1733 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1734 intval($importer["uid"])
1737 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1739 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1740 intval($importer["uid"])
1743 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1745 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1748 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1749 $arr["uid"] = $importer["uid"];
1750 $arr["contact-id"] = $self[0]["id"];
1752 $arr["type"] = 'wall';
1753 $arr["gravity"] = 0;
1755 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1756 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1757 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1758 $arr["verb"] = ACTIVITY_FRIEND;
1759 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1761 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1762 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1763 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1764 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1766 $arr["object"] = self::construct_new_friend_object($contact);
1768 $arr["last-child"] = 1;
1770 $arr["allow_cid"] = $user[0]["allow_cid"];
1771 $arr["allow_gid"] = $user[0]["allow_gid"];
1772 $arr["deny_cid"] = $user[0]["deny_cid"];
1773 $arr["deny_gid"] = $user[0]["deny_gid"];
1775 $i = item_store($arr);
1777 proc_run("php", "include/notifier.php", "activity", $i);
1783 * @brief Creates a XML object for a "new friend" message
1785 * @param array $contact Array of the contact
1787 * @return string The XML
1789 private function construct_new_friend_object($contact) {
1790 $objtype = ACTIVITY_OBJ_PERSON;
1791 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1792 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1794 $xmldata = array("object" => array("type" => $objtype,
1795 "title" => $contact["name"],
1796 "id" => $contact["url"]."/".$contact["name"],
1799 return xml::from_array($xmldata, $xml, true);
1803 * @brief Processes incoming sharing notification
1805 * @param array $importer Array of the importer user
1806 * @param object $data The message object
1808 * @return bool Success
1810 private function receive_contact_request($importer, $data) {
1811 $author = unxmlify($data->author);
1812 $recipient = unxmlify($data->recipient);
1814 if (!$author || !$recipient)
1817 // the current protocol version doesn't know these fields
1818 // That means that we will assume their existance
1819 if (isset($data->following))
1820 $following = (unxmlify($data->following) == "true");
1824 if (isset($data->sharing))
1825 $sharing = (unxmlify($data->sharing) == "true");
1829 $contact = self::contact_by_handle($importer["uid"],$author);
1831 // perhaps we were already sharing with this person. Now they're sharing with us.
1832 // That makes us friends.
1834 if ($following AND $sharing) {
1835 self::receive_request_make_friend($importer, $contact);
1837 } else /// @todo Handle all possible variations of adding and retracting of permissions
1841 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1842 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1844 } elseif (!$following AND !$sharing) {
1845 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1849 $ret = self::person_by_handle($author);
1851 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1852 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1856 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1858 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1859 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1860 intval($importer["uid"]),
1861 dbesc($ret["network"]),
1862 dbesc($ret["addr"]),
1865 dbesc(normalise_link($ret["url"])),
1867 dbesc($ret["name"]),
1868 dbesc($ret["nick"]),
1869 dbesc($ret["photo"]),
1870 dbesc($ret["pubkey"]),
1871 dbesc($ret["notify"]),
1872 dbesc($ret["poll"]),
1877 // find the contact record we just created
1879 $contact_record = self::contact_by_handle($importer["uid"],$author);
1881 if (!$contact_record) {
1882 logger("unable to locate newly created contact record.");
1886 $def_gid = get_default_group($importer['uid'], $ret["network"]);
1888 if(intval($def_gid))
1889 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
1891 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
1893 if($importer["page-flags"] == PAGE_NORMAL) {
1895 $hash = random_string().(string)time(); // Generate a confirm_key
1897 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1898 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1899 intval($importer["uid"]),
1900 intval($contact_record["id"]),
1903 dbesc(t("Sharing notification from Diaspora network")),
1905 dbesc(datetime_convert())
1909 // automatic friend approval
1911 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1913 // technically they are sharing with us (CONTACT_IS_SHARING),
1914 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1915 // we are going to change the relationship and make them a follower.
1917 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
1918 $new_relation = CONTACT_IS_FRIEND;
1919 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
1920 $new_relation = CONTACT_IS_SHARING;
1922 $new_relation = CONTACT_IS_FOLLOWER;
1924 $r = q("UPDATE `contact` SET `rel` = %d,
1932 intval($new_relation),
1933 dbesc(datetime_convert()),
1934 dbesc(datetime_convert()),
1935 intval($contact_record["id"])
1938 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1940 $ret = self::send_share($u[0], $contact_record);
1947 * @brief Fetches a message with a given guid
1949 * @param string $guid message guid
1950 * @param string $orig_author handle of the original post
1951 * @param string $author handle of the sharer
1953 * @return array The fetched item
1955 private function original_item($guid, $orig_author, $author) {
1957 // Do we already have this item?
1958 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1959 `author-name`, `author-link`, `author-avatar`
1960 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1964 logger("reshared message ".$guid." already exists on system.");
1966 // Maybe it is already a reshared item?
1967 // Then refetch the content, if it is a reshare from a reshare.
1968 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
1969 if (self::is_reshare($r[0]["body"], true))
1971 elseif (self::is_reshare($r[0]["body"], false)) {
1972 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
1974 // Add OEmbed and other information to the body
1975 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
1983 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1984 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1985 $item_id = self::store_by_guid($guid, $server);
1988 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1989 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1990 $item_id = self::store_by_guid($guid, $server);
1993 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1995 $server = "https://".substr($author, strpos($author, "@") + 1);
1996 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1997 $item_id = self::store_by_guid($guid, $server);
2000 $server = "http://".substr($author, strpos($author, "@") + 1);
2001 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
2002 $item_id = self::store_by_guid($guid, $server);
2006 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2007 `author-name`, `author-link`, `author-avatar`
2008 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2012 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2013 if (self::is_reshare($r[0]["body"], false))
2014 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2025 * @brief Processes a reshare message
2027 * @param array $importer Array of the importer user
2028 * @param object $data The message object
2029 * @param string $xml The original XML of the message
2031 * @return int the message id
2033 private function receive_reshare($importer, $data, $xml) {
2034 $root_author = notags(unxmlify($data->root_author));
2035 $root_guid = notags(unxmlify($data->root_guid));
2036 $guid = notags(unxmlify($data->guid));
2037 $author = notags(unxmlify($data->author));
2038 $public = notags(unxmlify($data->public));
2039 $created_at = notags(unxmlify($data->created_at));
2041 $contact = self::allowed_contact_by_handle($importer, $author, false);
2045 $message_id = self::message_exists($importer["uid"], $guid);
2049 $original_item = self::original_item($root_guid, $root_author, $author);
2050 if (!$original_item)
2053 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2055 $datarray = array();
2057 $datarray["uid"] = $importer["uid"];
2058 $datarray["contact-id"] = $contact["id"];
2059 $datarray["network"] = NETWORK_DIASPORA;
2061 $datarray["author-name"] = $contact["name"];
2062 $datarray["author-link"] = $contact["url"];
2063 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2065 $datarray["owner-name"] = $datarray["author-name"];
2066 $datarray["owner-link"] = $datarray["author-link"];
2067 $datarray["owner-avatar"] = $datarray["author-avatar"];
2069 $datarray["guid"] = $guid;
2070 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2072 $datarray["verb"] = ACTIVITY_POST;
2073 $datarray["gravity"] = GRAVITY_PARENT;
2075 $datarray["object"] = $xml;
2077 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2078 $original_item["guid"], $original_item["created"], $orig_url);
2079 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2081 $datarray["tag"] = $original_item["tag"];
2082 $datarray["app"] = $original_item["app"];
2084 $datarray["plink"] = self::plink($author, $guid);
2085 $datarray["private"] = (($public == "false") ? 1 : 0);
2086 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2088 $datarray["object-type"] = $original_item["object-type"];
2090 self::fetch_guid($datarray);
2091 $message_id = item_store($datarray);
2094 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2100 * @brief Processes retractions
2102 * @param array $importer Array of the importer user
2103 * @param array $contact The contact of the item owner
2104 * @param object $data The message object
2106 * @return bool success
2108 private function item_retraction($importer, $contact, $data) {
2109 $target_type = notags(unxmlify($data->target_type));
2110 $target_guid = notags(unxmlify($data->target_guid));
2111 $author = notags(unxmlify($data->author));
2113 $person = self::person_by_handle($author);
2114 if (!is_array($person)) {
2115 logger("unable to find author detail for ".$author);
2119 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2120 dbesc($target_guid),
2121 intval($importer["uid"])
2126 // Only delete it if the author really fits
2127 if (!link_compare($r[0]["author-link"], $person["url"])) {
2128 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2132 // Check if the sender is the thread owner
2133 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2134 intval($r[0]["parent"]));
2136 // Only delete it if the parent author really fits
2137 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2138 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2142 // 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
2143 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2144 dbesc(datetime_convert()),
2145 dbesc(datetime_convert()),
2148 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2150 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2152 // Now check if the retraction needs to be relayed by us
2153 if($p[0]["origin"]) {
2155 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2162 * @brief Receives retraction messages
2164 * @param array $importer Array of the importer user
2165 * @param string $sender The sender of the message
2166 * @param object $data The message object
2168 * @return bool Success
2170 private function receive_retraction($importer, $sender, $data) {
2171 $target_type = notags(unxmlify($data->target_type));
2173 $contact = self::contact_by_handle($importer["uid"], $sender);
2175 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2179 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2181 switch ($target_type) {
2184 case "Post": // "Post" will be supported in a future version
2186 case "StatusMessage":
2187 return self::item_retraction($importer, $contact, $data);;
2191 /// @todo What should we do with an "unshare"?
2192 // Removing the contact isn't correct since we still can read the public items
2193 contact_remove($contact["id"]);
2197 logger("Unknown target type ".$target_type);
2204 * @brief Receives status messages
2206 * @param array $importer Array of the importer user
2207 * @param object $data The message object
2208 * @param string $xml The original XML of the message
2210 * @return int The message id of the newly created item
2212 private function receive_status_message($importer, $data, $xml) {
2214 $raw_message = unxmlify($data->raw_message);
2215 $guid = notags(unxmlify($data->guid));
2216 $author = notags(unxmlify($data->author));
2217 $public = notags(unxmlify($data->public));
2218 $created_at = notags(unxmlify($data->created_at));
2219 $provider_display_name = notags(unxmlify($data->provider_display_name));
2221 /// @todo enable support for polls
2222 //if ($data->poll) {
2223 // foreach ($data->poll AS $poll)
2227 $contact = self::allowed_contact_by_handle($importer, $author, false);
2231 $message_id = self::message_exists($importer["uid"], $guid);
2236 if ($data->location)
2237 foreach ($data->location->children() AS $fieldname => $data)
2238 $address[$fieldname] = notags(unxmlify($data));
2240 $body = diaspora2bb($raw_message);
2242 $datarray = array();
2244 // Attach embedded pictures to the body
2246 foreach ($data->photo AS $photo)
2247 $body = "[img]".unxmlify($photo->remote_photo_path).
2248 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2250 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2252 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2254 // Add OEmbed and other information to the body
2255 if (!self::is_redmatrix($contact["url"]))
2256 $body = add_page_info_to_body($body, false, true);
2259 $datarray["uid"] = $importer["uid"];
2260 $datarray["contact-id"] = $contact["id"];
2261 $datarray["network"] = NETWORK_DIASPORA;
2263 $datarray["author-name"] = $contact["name"];
2264 $datarray["author-link"] = $contact["url"];
2265 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2267 $datarray["owner-name"] = $datarray["author-name"];
2268 $datarray["owner-link"] = $datarray["author-link"];
2269 $datarray["owner-avatar"] = $datarray["author-avatar"];
2271 $datarray["guid"] = $guid;
2272 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2274 $datarray["verb"] = ACTIVITY_POST;
2275 $datarray["gravity"] = GRAVITY_PARENT;
2277 $datarray["object"] = $xml;
2279 $datarray["body"] = $body;
2281 if ($provider_display_name != "")
2282 $datarray["app"] = $provider_display_name;
2284 $datarray["plink"] = self::plink($author, $guid);
2285 $datarray["private"] = (($public == "false") ? 1 : 0);
2286 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2288 if (isset($address["address"]))
2289 $datarray["location"] = $address["address"];
2291 if (isset($address["lat"]) AND isset($address["lng"]))
2292 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2294 self::fetch_guid($datarray);
2295 $message_id = item_store($datarray);
2298 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2303 /* ************************************************************************************** *
2304 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2305 * ************************************************************************************** */
2308 * @brief returnes the handle of a contact
2310 * @param array $me contact array
2312 * @return string the handle in the format user@domain.tld
2314 private function my_handle($contact) {
2315 if ($contact["addr"] != "")
2316 return $contact["addr"];
2318 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2319 // So - just in case - we build the the address here.
2320 if ($contact["nickname"] != "")
2321 $nick = $contact["nickname"];
2323 $nick = $contact["nick"];
2325 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2329 * @brief Creates the envelope for the "fetch" endpoint
2331 * @param string $msg The message that is to be transmitted
2332 * @param array $user The record of the sender
2334 * @return string The envelope
2337 public static function build_magic_envelope($msg, $user) {
2339 $b64url_data = base64url_encode($msg);
2340 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2342 $key_id = base64url_encode(diaspora::my_handle($user));
2343 $type = "application/xml";
2344 $encoding = "base64url";
2345 $alg = "RSA-SHA256";
2346 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2347 $signature = rsa_sign($signable_data, $user["prvkey"]);
2348 $sig = base64url_encode($signature);
2350 $xmldata = array("me:env" => array("me:data" => $data,
2351 "@attributes" => array("type" => $type),
2352 "me:encoding" => $encoding,
2355 "@attributes2" => array("key_id" => $key_id)));
2357 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2359 return xml::from_array($xmldata, $xml, false, $namespaces);
2363 * @brief Creates the envelope for a public message
2365 * @param string $msg The message that is to be transmitted
2366 * @param array $user The record of the sender
2367 * @param array $contact Target of the communication
2368 * @param string $prvkey The private key of the sender
2369 * @param string $pubkey The public key of the receiver
2371 * @return string The envelope
2373 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2375 logger("Message: ".$msg, LOGGER_DATA);
2377 $handle = self::my_handle($user);
2379 $b64url_data = base64url_encode($msg);
2381 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2383 $type = "application/xml";
2384 $encoding = "base64url";
2385 $alg = "RSA-SHA256";
2387 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2389 $signature = rsa_sign($signable_data,$prvkey);
2390 $sig = base64url_encode($signature);
2392 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2393 "me:env" => array("me:encoding" => $encoding,
2396 "@attributes" => array("type" => $type),
2397 "me:sig" => $sig)));
2399 $namespaces = array("" => "https://joindiaspora.com/protocol",
2400 "me" => "http://salmon-protocol.org/ns/magic-env");
2402 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2404 logger("magic_env: ".$magic_env, LOGGER_DATA);
2409 * @brief Creates the envelope for a private message
2411 * @param string $msg The message that is to be transmitted
2412 * @param array $user The record of the sender
2413 * @param array $contact Target of the communication
2414 * @param string $prvkey The private key of the sender
2415 * @param string $pubkey The public key of the receiver
2417 * @return string The envelope
2419 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2421 logger("Message: ".$msg, LOGGER_DATA);
2423 // without a public key nothing will work
2426 logger("pubkey missing: contact id: ".$contact["id"]);
2430 $inner_aes_key = random_string(32);
2431 $b_inner_aes_key = base64_encode($inner_aes_key);
2432 $inner_iv = random_string(16);
2433 $b_inner_iv = base64_encode($inner_iv);
2435 $outer_aes_key = random_string(32);
2436 $b_outer_aes_key = base64_encode($outer_aes_key);
2437 $outer_iv = random_string(16);
2438 $b_outer_iv = base64_encode($outer_iv);
2440 $handle = self::my_handle($user);
2442 $padded_data = pkcs5_pad($msg,16);
2443 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2445 $b64_data = base64_encode($inner_encrypted);
2448 $b64url_data = base64url_encode($b64_data);
2449 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2451 $type = "application/xml";
2452 $encoding = "base64url";
2453 $alg = "RSA-SHA256";
2455 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2457 $signature = rsa_sign($signable_data,$prvkey);
2458 $sig = base64url_encode($signature);
2460 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2461 "aes_key" => $b_inner_aes_key,
2462 "author_id" => $handle));
2464 $decrypted_header = xml::from_array($xmldata, $xml, true);
2465 $decrypted_header = pkcs5_pad($decrypted_header,16);
2467 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2469 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2471 $encrypted_outer_key_bundle = "";
2472 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2474 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2476 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2478 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2479 "ciphertext" => base64_encode($ciphertext)));
2480 $cipher_json = base64_encode($encrypted_header_json_object);
2482 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2483 "me:env" => array("me:encoding" => $encoding,
2486 "@attributes" => array("type" => $type),
2487 "me:sig" => $sig)));
2489 $namespaces = array("" => "https://joindiaspora.com/protocol",
2490 "me" => "http://salmon-protocol.org/ns/magic-env");
2492 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2494 logger("magic_env: ".$magic_env, LOGGER_DATA);
2499 * @brief Create the envelope for a message
2501 * @param string $msg The message that is to be transmitted
2502 * @param array $user The record of the sender
2503 * @param array $contact Target of the communication
2504 * @param string $prvkey The private key of the sender
2505 * @param string $pubkey The public key of the receiver
2506 * @param bool $public Is the message public?
2508 * @return string The message that will be transmitted to other servers
2510 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2513 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2515 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2517 // The data that will be transmitted is double encoded via "urlencode", strange ...
2518 $slap = "xml=".urlencode(urlencode($magic_env));
2523 * @brief Creates a signature for a message
2525 * @param array $owner the array of the owner of the message
2526 * @param array $message The message that is to be signed
2528 * @return string The signature
2530 private function signature($owner, $message) {
2532 unset($sigmsg["author_signature"]);
2533 unset($sigmsg["parent_author_signature"]);
2535 $signed_text = implode(";", $sigmsg);
2537 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2541 * @brief Transmit a message to a target server
2543 * @param array $owner the array of the item owner
2544 * @param array $contact Target of the communication
2545 * @param string $slap The message that is to be transmitted
2546 * @param bool $public_batch Is it a public post?
2547 * @param bool $queue_run Is the transmission called from the queue?
2548 * @param string $guid message guid
2550 * @return int Result of the transmission
2552 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2556 $enabled = intval(get_config("system", "diaspora_enabled"));
2560 $logid = random_string(4);
2561 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2563 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2567 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2569 if (!$queue_run && was_recently_delayed($contact["id"])) {
2572 if (!intval(get_config("system", "diaspora_test"))) {
2573 post_url($dest_url."/", $slap);
2574 $return_code = $a->get_curl_code();
2576 logger("test_mode");
2581 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2583 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2584 logger("queue message");
2586 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2587 intval($contact["id"]),
2588 dbesc(NETWORK_DIASPORA),
2590 intval($public_batch)
2593 logger("add_to_queue ignored - identical item already in queue");
2595 // queue message for redelivery
2596 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2600 return(($return_code) ? $return_code : (-1));
2605 * @brief Build the post xml
2607 * @param string $type The message type
2608 * @param array $message The message data
2610 * @return string The post XML
2612 public static function build_post_xml($type, $message) {
2614 $data = array("XML" => array("post" => array($type => $message)));
2615 return xml::from_array($data, $xml);
2619 * @brief Builds and transmit messages
2621 * @param array $owner the array of the item owner
2622 * @param array $contact Target of the communication
2623 * @param string $type The message type
2624 * @param array $message The message data
2625 * @param bool $public_batch Is it a public post?
2626 * @param string $guid message guid
2627 * @param bool $spool Should the transmission be spooled or transmitted?
2629 * @return int Result of the transmission
2631 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2633 $msg = self::build_post_xml($type, $message);
2635 logger('message: '.$msg, LOGGER_DATA);
2636 logger('send guid '.$guid, LOGGER_DEBUG);
2638 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2641 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2644 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2646 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2648 return $return_code;
2652 * @brief Sends a "share" message
2654 * @param array $owner the array of the item owner
2655 * @param array $contact Target of the communication
2657 * @return int The result of the transmission
2659 public static function send_share($owner,$contact) {
2661 $message = array("sender_handle" => self::my_handle($owner),
2662 "recipient_handle" => $contact["addr"]);
2664 return self::build_and_transmit($owner, $contact, "request", $message);
2668 * @brief sends an "unshare"
2670 * @param array $owner the array of the item owner
2671 * @param array $contact Target of the communication
2673 * @return int The result of the transmission
2675 public static function send_unshare($owner,$contact) {
2677 $message = array("post_guid" => $owner["guid"],
2678 "diaspora_handle" => self::my_handle($owner),
2679 "type" => "Person");
2681 return self::build_and_transmit($owner, $contact, "retraction", $message);
2685 * @brief Checks a message body if it is a reshare
2687 * @param string $body The message body that is to be check
2688 * @param bool $complete Should it be a complete check or a simple check?
2690 * @return array|bool Reshare details or "false" if no reshare
2692 public static function is_reshare($body, $complete = true) {
2693 $body = trim($body);
2695 // Skip if it isn't a pure repeated messages
2696 // Does it start with a share?
2697 if ((strpos($body, "[share") > 0) AND $complete)
2700 // Does it end with a share?
2701 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2704 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2705 // Skip if there is no shared message in there
2706 if ($body == $attributes)
2709 // If we don't do the complete check we quit here
2714 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2715 if ($matches[1] != "")
2716 $guid = $matches[1];
2718 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2719 if ($matches[1] != "")
2720 $guid = $matches[1];
2723 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2724 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2727 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2728 $ret["root_guid"] = $guid;
2734 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2735 if ($matches[1] != "")
2736 $profile = $matches[1];
2738 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2739 if ($matches[1] != "")
2740 $profile = $matches[1];
2744 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2745 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2749 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2750 if ($matches[1] != "")
2751 $link = $matches[1];
2753 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2754 if ($matches[1] != "")
2755 $link = $matches[1];
2757 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2758 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2765 * @brief Create a post (status message or reshare)
2767 * @param array $item The item that will be exported
2768 * @param array $owner the array of the item owner
2771 * 'type' -> Message type ("status_message" or "reshare")
2772 * 'message' -> Array of XML elements of the status
2774 public static function build_status($item, $owner) {
2776 $myaddr = self::my_handle($owner);
2778 $public = (($item["private"]) ? "false" : "true");
2780 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2782 // Detect a share element and do a reshare
2783 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2784 $message = array("root_diaspora_id" => $ret["root_handle"],
2785 "root_guid" => $ret["root_guid"],
2786 "guid" => $item["guid"],
2787 "diaspora_handle" => $myaddr,
2788 "public" => $public,
2789 "created_at" => $created,
2790 "provider_display_name" => $item["app"]);
2794 $title = $item["title"];
2795 $body = $item["body"];
2797 // convert to markdown
2798 $body = html_entity_decode(bb2diaspora($body));
2802 $body = "## ".html_entity_decode($title)."\n\n".$body;
2804 if ($item["attach"]) {
2805 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2807 $body .= "\n".t("Attachments:")."\n";
2808 foreach($matches as $mtch)
2809 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2813 $location = array();
2815 if ($item["location"] != "")
2816 $location["address"] = $item["location"];
2818 if ($item["coord"] != "") {
2819 $coord = explode(" ", $item["coord"]);
2820 $location["lat"] = $coord[0];
2821 $location["lng"] = $coord[1];
2824 $message = array("raw_message" => $body,
2825 "location" => $location,
2826 "guid" => $item["guid"],
2827 "diaspora_handle" => $myaddr,
2828 "public" => $public,
2829 "created_at" => $created,
2830 "provider_display_name" => $item["app"]);
2832 if (count($location) == 0)
2833 unset($message["location"]);
2835 $type = "status_message";
2837 return array("type" => $type, "message" => $message);
2841 * @brief Sends a post
2843 * @param array $item The item that will be exported
2844 * @param array $owner the array of the item owner
2845 * @param array $contact Target of the communication
2846 * @param bool $public_batch Is it a public post?
2848 * @return int The result of the transmission
2850 public static function send_status($item, $owner, $contact, $public_batch = false) {
2852 $status = diaspora::build_status($item, $owner);
2854 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
2858 * @brief Creates a "like" object
2860 * @param array $item The item that will be exported
2861 * @param array $owner the array of the item owner
2863 * @return array The data for a "like"
2865 private function construct_like($item, $owner) {
2867 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2868 dbesc($item["thr-parent"]));
2874 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2877 return(array("positive" => $positive,
2878 "guid" => $item["guid"],
2879 "target_type" => $target_type,
2880 "parent_guid" => $parent["guid"],
2881 "author_signature" => "",
2882 "diaspora_handle" => self::my_handle($owner)));
2886 * @brief Creates the object for a comment
2888 * @param array $item The item that will be exported
2889 * @param array $owner the array of the item owner
2891 * @return array The data for a comment
2893 private function construct_comment($item, $owner) {
2895 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2896 intval($item["parent"]),
2897 intval($item["parent"])
2905 $text = html_entity_decode(bb2diaspora($item["body"]));
2907 return(array("guid" => $item["guid"],
2908 "parent_guid" => $parent["guid"],
2909 "author_signature" => "",
2911 "diaspora_handle" => self::my_handle($owner)));
2915 * @brief Send a like or a comment
2917 * @param array $item The item that will be exported
2918 * @param array $owner the array of the item owner
2919 * @param array $contact Target of the communication
2920 * @param bool $public_batch Is it a public post?
2922 * @return int The result of the transmission
2924 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2926 if($item['verb'] === ACTIVITY_LIKE) {
2927 $message = self::construct_like($item, $owner);
2930 $message = self::construct_comment($item, $owner);
2937 $message["author_signature"] = self::signature($owner, $message);
2939 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2943 * @brief Creates a message from a signature record entry
2945 * @param array $item The item that will be exported
2946 * @param array $signature The entry of the "sign" record
2948 * @return string The message
2950 private function message_from_signature($item, $signature) {
2952 // Split the signed text
2953 $signed_parts = explode(";", $signature['signed_text']);
2955 if ($item["deleted"])
2956 $message = array("parent_author_signature" => "",
2957 "target_guid" => $signed_parts[0],
2958 "target_type" => $signed_parts[1],
2959 "sender_handle" => $signature['signer'],
2960 "target_author_signature" => $signature['signature']);
2961 elseif ($item['verb'] === ACTIVITY_LIKE)
2962 $message = array("positive" => $signed_parts[0],
2963 "guid" => $signed_parts[1],
2964 "target_type" => $signed_parts[2],
2965 "parent_guid" => $signed_parts[3],
2966 "parent_author_signature" => "",
2967 "author_signature" => $signature['signature'],
2968 "diaspora_handle" => $signed_parts[4]);
2970 // Remove the comment guid
2971 $guid = array_shift($signed_parts);
2973 // Remove the parent guid
2974 $parent_guid = array_shift($signed_parts);
2976 // Remove the handle
2977 $handle = array_pop($signed_parts);
2979 // Glue the parts together
2980 $text = implode(";", $signed_parts);
2982 $message = array("guid" => $guid,
2983 "parent_guid" => $parent_guid,
2984 "parent_author_signature" => "",
2985 "author_signature" => $signature['signature'],
2986 "text" => implode(";", $signed_parts),
2987 "diaspora_handle" => $handle);
2993 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
2995 * @param array $item The item that will be exported
2996 * @param array $owner the array of the item owner
2997 * @param array $contact Target of the communication
2998 * @param bool $public_batch Is it a public post?
3000 * @return int The result of the transmission
3002 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3004 if ($item["deleted"])
3005 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3006 elseif ($item['verb'] === ACTIVITY_LIKE)
3011 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3013 // fetch the original signature
3015 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3016 intval($item["id"]));
3019 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3025 // Old way - is used by the internal Friendica functions
3026 /// @todo Change all signatur storing functions to the new format
3027 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3028 $message = self::message_from_signature($item, $signature);
3030 $msg = json_decode($signature['signed_text'], true);
3033 if (is_array($msg)) {
3034 foreach ($msg AS $field => $data) {
3035 if (!$item["deleted"]) {
3036 if ($field == "author")
3037 $field = "diaspora_handle";
3038 if ($field == "parent_type")
3039 $field = "target_type";
3042 $message[$field] = $data;
3045 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3048 $message["parent_author_signature"] = self::signature($owner, $message);
3050 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3052 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3056 * @brief Sends a retraction (deletion) of a message, like or comment
3058 * @param array $item The item that will be exported
3059 * @param array $owner the array of the item owner
3060 * @param array $contact Target of the communication
3061 * @param bool $public_batch Is it a public post?
3062 * @param bool $relay Is the retraction transmitted from a relay?
3064 * @return int The result of the transmission
3066 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3068 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3070 // Check whether the retraction is for a top-level post or whether it's a relayable
3071 if ($item["uri"] !== $item["parent-uri"]) {
3072 $msg_type = "relayable_retraction";
3073 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3075 $msg_type = "signed_retraction";
3076 $target_type = "StatusMessage";
3079 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3080 $signature = "parent_author_signature";
3082 $signature = "target_author_signature";
3084 $signed_text = $item["guid"].";".$target_type;
3086 $message = array("target_guid" => $item['guid'],
3087 "target_type" => $target_type,
3088 "sender_handle" => $itemaddr,
3089 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3091 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3093 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3097 * @brief Sends a mail
3099 * @param array $item The item that will be exported
3100 * @param array $owner The owner
3101 * @param array $contact Target of the communication
3103 * @return int The result of the transmission
3105 public static function send_mail($item, $owner, $contact) {
3107 $myaddr = self::my_handle($owner);
3109 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3110 intval($item["convid"]),
3111 intval($item["uid"])
3115 logger("conversation not found.");
3121 "guid" => $cnv["guid"],
3122 "subject" => $cnv["subject"],
3123 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3124 "diaspora_handle" => $cnv["creator"],
3125 "participant_handles" => $cnv["recips"]
3128 $body = bb2diaspora($item["body"]);
3129 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
3131 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3132 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3135 "guid" => $item["guid"],
3136 "parent_guid" => $cnv["guid"],
3137 "parent_author_signature" => $sig,
3138 "author_signature" => $sig,
3140 "created_at" => $created,
3141 "diaspora_handle" => $myaddr,
3142 "conversation_guid" => $cnv["guid"]
3145 if ($item["reply"]) {
3149 $message = array("guid" => $cnv["guid"],
3150 "subject" => $cnv["subject"],
3151 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3153 "diaspora_handle" => $cnv["creator"],
3154 "participant_handles" => $cnv["recips"]);
3156 $type = "conversation";
3159 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3163 * @brief Sends profile data
3165 * @param int $uid The user id
3167 public static function send_profile($uid) {
3172 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3173 AND `uid` = %d AND `rel` != %d",
3174 dbesc(NETWORK_DIASPORA),
3176 intval(CONTACT_IS_SHARING)
3181 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3183 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3184 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3185 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3194 $handle = $profile["addr"];
3195 $first = ((strpos($profile['name'],' ')
3196 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3197 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3198 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3199 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3200 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3201 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3203 if ($searchable === 'true') {
3204 $dob = '1000-00-00';
3206 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3207 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3209 $about = $profile['about'];
3210 $about = strip_tags(bbcode($about));
3212 $location = formatted_location($profile);
3214 if ($profile['pub_keywords']) {
3215 $kw = str_replace(',',' ',$profile['pub_keywords']);
3216 $kw = str_replace(' ',' ',$kw);
3217 $arr = explode(' ',$profile['pub_keywords']);
3219 for($x = 0; $x < 5; $x ++) {
3221 $tags .= '#'. trim($arr[$x]) .' ';
3225 $tags = trim($tags);
3228 $message = array("diaspora_handle" => $handle,
3229 "first_name" => $first,
3230 "last_name" => $last,
3231 "image_url" => $large,
3232 "image_url_medium" => $medium,
3233 "image_url_small" => $small,
3235 "gender" => $profile['gender'],
3237 "location" => $location,
3238 "searchable" => $searchable,
3239 "tag_string" => $tags);
3241 foreach($recips as $recip)
3242 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3246 * @brief Stores the signature for likes that are created on our system
3248 * @param array $contact The contact array of the "like"
3249 * @param int $post_id The post id of the "like"
3251 * @return bool Success
3253 public static function store_like_signature($contact, $post_id) {
3255 // Is the contact the owner? Then fetch the private key
3256 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3257 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3261 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3265 $contact["uprvkey"] = $r[0]['prvkey'];
3267 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3271 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3274 $message = self::construct_like($r[0], $contact);
3275 $message["author_signature"] = self::signature($contact, $message);
3277 // In the future we will store the signature more flexible to support new fields.
3278 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3279 // (We are transmitting this data here via DFRN)
3281 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3282 $message["parent_guid"].";".$message["diaspora_handle"];
3284 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3286 dbesc($signed_text),
3287 dbesc($message["author_signature"]),
3288 dbesc($message["diaspora_handle"])
3291 // This here will replace the lines above, once Diaspora changed its protocol
3292 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3293 // intval($message_id),
3294 // dbesc(json_encode($message))
3297 logger('Stored diaspora like signature');
3302 * @brief Stores the signature for comments that are created on our system
3304 * @param array $item The item array of the comment
3305 * @param array $contact The contact array of the item owner
3306 * @param string $uprvkey The private key of the sender
3307 * @param int $message_id The message id of the comment
3309 * @return bool Success
3311 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3313 if ($uprvkey == "") {
3314 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3318 $contact["uprvkey"] = $uprvkey;
3320 $message = self::construct_comment($item, $contact);
3321 $message["author_signature"] = self::signature($contact, $message);
3323 // In the future we will store the signature more flexible to support new fields.
3324 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3325 // (We are transmitting this data here via DFRN)
3326 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3327 $message["text"].";".$message["diaspora_handle"];
3329 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3330 intval($message_id),
3331 dbesc($signed_text),
3332 dbesc($message["author_signature"]),
3333 dbesc($message["diaspora_handle"])
3336 // This here will replace the lines above, once Diaspora changed its protocol
3337 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3338 // intval($message_id),
3339 // dbesc(json_encode($message))
3342 logger('Stored diaspora comment signature');