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 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
437 // All retractions are handled identically from now on.
438 // In the new version there will only be "retraction".
439 if (in_array($type, array("signed_retraction", "relayable_retraction")))
440 $type = "retraction";
442 if ($type == "request")
445 $fields = new SimpleXMLElement("<".$type."/>");
449 foreach ($element->children() AS $fieldname => $entry) {
451 // Translation for the old XML structure
452 if ($fieldname == "diaspora_handle")
453 $fieldname = "author";
455 if ($fieldname == "participant_handles")
456 $fieldname = "participants";
458 if (in_array($type, array("like", "participation"))) {
459 if ($fieldname == "target_type")
460 $fieldname = "parent_type";
463 if ($fieldname == "sender_handle")
464 $fieldname = "author";
466 if ($fieldname == "recipient_handle")
467 $fieldname = "recipient";
469 if ($fieldname == "root_diaspora_id")
470 $fieldname = "root_author";
472 if ($type == "retraction") {
473 if ($fieldname == "post_guid")
474 $fieldname = "target_guid";
476 if ($fieldname == "type")
477 $fieldname = "target_type";
481 if (($fieldname == "author_signature") AND ($entry != ""))
482 $author_signature = base64_decode($entry);
483 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
484 $parent_author_signature = base64_decode($entry);
485 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
486 if ($signed_data != "") {
488 $signed_data_parent .= ";";
491 $signed_data .= $entry;
493 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
494 ($orig_type == "relayable_retraction"))
495 xml::copy($entry, $fields, $fieldname);
498 // This is something that shouldn't happen at all.
499 if (in_array($type, array("status_message", "reshare", "profile")))
500 if ($msg["author"] != $fields->author) {
501 logger("Message handle is not the same as envelope sender. Quitting this message.");
505 // Only some message types have signatures. So we quit here for the other types.
506 if (!in_array($type, array("comment", "message", "like")))
509 // No author_signature? This is a must, so we quit.
510 if (!isset($author_signature)) {
511 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
515 if (isset($parent_author_signature)) {
516 $key = self::key($msg["author"]);
518 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
519 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);
524 $key = self::key($fields->author);
526 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
527 logger("No valid author signature for author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
534 * @brief Fetches the public key for a given handle
536 * @param string $handle The handle
538 * @return string The public key
540 private function key($handle) {
541 $handle = strval($handle);
543 logger("Fetching diaspora key for: ".$handle);
545 $r = self::person_by_handle($handle);
553 * @brief Fetches data for a given handle
555 * @param string $handle The handle
557 * @return array the queried data
559 private function person_by_handle($handle) {
561 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
562 dbesc(NETWORK_DIASPORA),
567 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
569 // update record occasionally so it doesn't get stale
570 $d = strtotime($person["updated"]." +00:00");
571 if ($d < strtotime("now - 14 days"))
574 if ($person["guid"] == "")
578 if (!$person OR $update) {
579 logger("create or refresh", LOGGER_DEBUG);
580 $r = probe_url($handle, PROBE_DIASPORA);
582 // Note that Friendica contacts will return a "Diaspora person"
583 // if Diaspora connectivity is enabled on their server
584 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
585 self::add_fcontact($r, $update);
593 * @brief Updates the fcontact table
595 * @param array $arr The fcontact data
596 * @param bool $update Update or insert?
598 * @return string The id of the fcontact entry
600 private function add_fcontact($arr, $update = false) {
603 $r = q("UPDATE `fcontact` SET
617 WHERE `url` = '%s' AND `network` = '%s'",
619 dbesc($arr["photo"]),
620 dbesc($arr["request"]),
624 dbesc($arr["batch"]),
625 dbesc($arr["notify"]),
627 dbesc($arr["confirm"]),
628 dbesc($arr["alias"]),
629 dbesc($arr["pubkey"]),
630 dbesc(datetime_convert()),
632 dbesc($arr["network"])
635 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
636 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
637 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
640 dbesc($arr["photo"]),
641 dbesc($arr["request"]),
645 dbesc($arr["batch"]),
646 dbesc($arr["notify"]),
648 dbesc($arr["confirm"]),
649 dbesc($arr["network"]),
650 dbesc($arr["alias"]),
651 dbesc($arr["pubkey"]),
652 dbesc(datetime_convert())
660 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
662 * @param int $contact_id The id in the contact table
663 * @param int $gcontact_id The id in the gcontact table
665 * @return string the handle
667 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
670 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
672 if ($gcontact_id != 0) {
673 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
674 intval($gcontact_id));
676 return $r[0]["addr"];
679 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
680 intval($contact_id));
684 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
686 if($contact['addr'] != "")
687 $handle = $contact['addr'];
689 $baseurl_start = strpos($contact['url'],'://') + 3;
690 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
691 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
692 $handle = $contact['nick'].'@'.$baseurl;
700 * @brief Get a contact id for a given handle
702 * @param int $uid The user id
703 * @param string $handle The handle in the format user@domain.tld
705 * @return The contact id
707 private function contact_by_handle($uid, $handle) {
708 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
716 $handle_parts = explode("@", $handle);
717 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
718 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
730 * @brief Check if posting is allowed for this contact
732 * @param array $importer Array of the importer user
733 * @param array $contact The contact that is checked
734 * @param bool $is_comment Is the check for a comment?
736 * @return bool is the contact allowed to post?
738 private function post_allow($importer, $contact, $is_comment = false) {
740 // perhaps we were already sharing with this person. Now they're sharing with us.
741 // That makes us friends.
742 // Normally this should have handled by getting a request - but this could get lost
743 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
744 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
745 intval(CONTACT_IS_FRIEND),
746 intval($contact["id"]),
747 intval($importer["uid"])
749 $contact["rel"] = CONTACT_IS_FRIEND;
750 logger("defining user ".$contact["nick"]." as friend");
753 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
755 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
757 if($contact["rel"] == CONTACT_IS_FOLLOWER)
758 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
761 // Messages for the global users are always accepted
762 if ($importer["uid"] == 0)
769 * @brief Fetches the contact id for a handle and checks if posting is allowed
771 * @param array $importer Array of the importer user
772 * @param string $handle The checked handle in the format user@domain.tld
773 * @param bool $is_comment Is the check for a comment?
775 * @return array The contact data
777 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
778 $contact = self::contact_by_handle($importer["uid"], $handle);
780 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
784 if (!self::post_allow($importer, $contact, $is_comment)) {
785 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
792 * @brief Does the message already exists on the system?
794 * @param int $uid The user id
795 * @param string $guid The guid of the message
797 * @return int|bool message id if the message already was stored into the system - or false.
799 private function message_exists($uid, $guid) {
800 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
806 logger("message ".$guid." already exists for user ".$uid);
814 * @brief Checks for links to posts in a message
816 * @param array $item The item array
818 private function fetch_guid($item) {
819 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
820 function ($match) use ($item){
821 return(self::fetch_guid_sub($match, $item));
826 * @brief sub function of "fetch_guid" which checks for links in messages
828 * @param array $match array containing a link that has to be checked for a message link
829 * @param array $item The item array
831 private function fetch_guid_sub($match, $item) {
832 if (!self::store_by_guid($match[1], $item["author-link"]))
833 self::store_by_guid($match[1], $item["owner-link"]);
837 * @brief Fetches an item with a given guid from a given server
839 * @param string $guid the message guid
840 * @param string $server The server address
841 * @param int $uid The user id of the user
843 * @return int the message id of the stored message or false
845 private function store_by_guid($guid, $server, $uid = 0) {
846 $serverparts = parse_url($server);
847 $server = $serverparts["scheme"]."://".$serverparts["host"];
849 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
851 $msg = self::message($guid, $server);
856 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
858 // Now call the dispatcher
859 return self::dispatch_public($msg);
863 * @brief Fetches a message from a server
865 * @param string $guid message guid
866 * @param string $server The url of the server
867 * @param int $level Endless loop prevention
870 * 'message' => The message XML
871 * 'author' => The author handle
872 * 'key' => The public key of the author
874 private function message($guid, $server, $level = 0) {
879 // This will work for new Diaspora servers and Friendica servers from 3.5
880 $source_url = $server."/fetch/post/".$guid;
881 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
883 $envelope = fetch_url($source_url);
885 logger("Envelope was fetched.", LOGGER_DEBUG);
886 $x = self::verify_magic_envelope($envelope);
888 logger("Envelope could not be verified.", LOGGER_DEBUG);
890 logger("Envelope was verified.", LOGGER_DEBUG);
894 // This will work for older Diaspora and Friendica servers
896 $source_url = $server."/p/".$guid.".xml";
897 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
899 $x = fetch_url($source_url);
904 $source_xml = parse_xml_string($x, false);
906 if (!is_object($source_xml))
909 if ($source_xml->post->reshare) {
910 // Reshare of a reshare - old Diaspora version
911 logger("Message is a reshare", LOGGER_DEBUG);
912 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
913 } elseif ($source_xml->getName() == "reshare") {
914 // Reshare of a reshare - new Diaspora version
915 logger("Message is a new reshare", LOGGER_DEBUG);
916 return self::message($source_xml->root_guid, $server, ++$level);
921 // Fetch the author - for the old and the new Diaspora version
922 if ($source_xml->post->status_message->diaspora_handle)
923 $author = (string)$source_xml->post->status_message->diaspora_handle;
924 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
925 $author = (string)$source_xml->author;
927 // If this isn't a "status_message" then quit
929 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
933 $msg = array("message" => $x, "author" => $author);
935 $msg["key"] = self::key($msg["author"]);
941 * @brief Fetches the item record of a given guid
943 * @param int $uid The user id
944 * @param string $guid message guid
945 * @param string $author The handle of the item
946 * @param array $contact The contact of the item owner
948 * @return array the item record
950 private function parent_item($uid, $guid, $author, $contact) {
951 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
952 `author-name`, `author-link`, `author-avatar`,
953 `owner-name`, `owner-link`, `owner-avatar`
954 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
955 intval($uid), dbesc($guid));
958 $result = self::store_by_guid($guid, $contact["url"], $uid);
961 $person = self::person_by_handle($author);
962 $result = self::store_by_guid($guid, $person["url"], $uid);
966 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
968 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
969 `author-name`, `author-link`, `author-avatar`,
970 `owner-name`, `owner-link`, `owner-avatar`
971 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
972 intval($uid), dbesc($guid));
977 logger("parent item not found: parent: ".$guid." - user: ".$uid);
980 logger("parent item found: parent: ".$guid." - user: ".$uid);
986 * @brief returns contact details
988 * @param array $contact The default contact if the person isn't found
989 * @param array $person The record of the person
990 * @param int $uid The user id
993 * 'cid' => contact id
994 * 'network' => network type
996 private function author_contact_by_url($contact, $person, $uid) {
998 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
999 dbesc(normalise_link($person["url"])), intval($uid));
1002 $network = $r[0]["network"];
1004 $cid = $contact["id"];
1005 $network = NETWORK_DIASPORA;
1008 return (array("cid" => $cid, "network" => $network));
1012 * @brief Is the profile a hubzilla profile?
1014 * @param string $url The profile link
1016 * @return bool is it a hubzilla server?
1018 public static function is_redmatrix($url) {
1019 return(strstr($url, "/channel/"));
1023 * @brief Generate a post link with a given handle and message guid
1025 * @param string $addr The user handle
1026 * @param string $guid message guid
1028 * @return string the post link
1030 private function plink($addr, $guid) {
1031 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1035 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1037 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1038 // So we try another way as well.
1039 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1041 $r[0]["network"] = $s[0]["network"];
1043 if ($r[0]["network"] == NETWORK_DFRN)
1044 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1046 if (self::is_redmatrix($r[0]["url"]))
1047 return $r[0]["url"]."/?f=&mid=".$guid;
1049 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1053 * @brief Processes an account deletion
1055 * @param array $importer Array of the importer user
1056 * @param object $data The message object
1058 * @return bool Success
1060 private function receive_account_deletion($importer, $data) {
1062 /// @todo Account deletion should remove the contact from the global contacts as well
1064 $author = notags(unxmlify($data->author));
1066 $contact = self::contact_by_handle($importer["uid"], $author);
1068 logger("cannot find contact for author: ".$author);
1072 // We now remove the contact
1073 contact_remove($contact["id"]);
1078 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1080 * @param string $author Author handle
1081 * @param string $guid Message guid
1083 * @return string The constructed uri or the one from our database
1085 private function get_uri_from_guid($author, $guid) {
1087 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1089 return $r[0]["uri"];
1091 return $author.":".$guid;
1095 * @brief Processes an incoming comment
1097 * @param array $importer Array of the importer user
1098 * @param string $sender The sender of the message
1099 * @param object $data The message object
1100 * @param string $xml The original XML of the message
1102 * @return int The message id of the generated comment or "false" if there was an error
1104 private function receive_comment($importer, $sender, $data, $xml) {
1105 $guid = notags(unxmlify($data->guid));
1106 $parent_guid = notags(unxmlify($data->parent_guid));
1107 $text = unxmlify($data->text);
1108 $author = notags(unxmlify($data->author));
1110 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1114 $message_id = self::message_exists($importer["uid"], $guid);
1118 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1122 $person = self::person_by_handle($author);
1123 if (!is_array($person)) {
1124 logger("unable to find author details");
1128 // Fetch the contact id - if we know this contact
1129 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1131 $datarray = array();
1133 $datarray["uid"] = $importer["uid"];
1134 $datarray["contact-id"] = $author_contact["cid"];
1135 $datarray["network"] = $author_contact["network"];
1137 $datarray["author-name"] = $person["name"];
1138 $datarray["author-link"] = $person["url"];
1139 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1141 $datarray["owner-name"] = $contact["name"];
1142 $datarray["owner-link"] = $contact["url"];
1143 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1145 $datarray["guid"] = $guid;
1146 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1148 $datarray["type"] = "remote-comment";
1149 $datarray["verb"] = ACTIVITY_POST;
1150 $datarray["gravity"] = GRAVITY_COMMENT;
1151 $datarray["parent-uri"] = $parent_item["uri"];
1153 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1154 $datarray["object"] = $xml;
1156 $datarray["body"] = diaspora2bb($text);
1158 self::fetch_guid($datarray);
1160 $message_id = item_store($datarray);
1163 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1165 // If we are the origin of the parent we store the original data and notify our followers
1166 if($message_id AND $parent_item["origin"]) {
1168 // Formerly we stored the signed text, the signature and the author in different fields.
1169 // We now store the raw data so that we are more flexible.
1170 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1171 intval($message_id),
1172 dbesc(json_encode($data))
1176 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1183 * @brief processes and stores private messages
1185 * @param array $importer Array of the importer user
1186 * @param array $contact The contact of the message
1187 * @param object $data The message object
1188 * @param array $msg Array of the processed message, author handle and key
1189 * @param object $mesg The private message
1190 * @param array $conversation The conversation record to which this message belongs
1192 * @return bool "true" if it was successful
1194 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1195 $guid = notags(unxmlify($data->guid));
1196 $subject = notags(unxmlify($data->subject));
1197 $author = notags(unxmlify($data->author));
1201 $msg_guid = notags(unxmlify($mesg->guid));
1202 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1203 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1204 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1205 $msg_text = unxmlify($mesg->text);
1206 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1208 // "diaspora_handle" is the element name from the old version
1209 // "author" is the element name from the new version
1211 $msg_author = notags(unxmlify($mesg->author));
1212 elseif ($mesg->diaspora_handle)
1213 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1217 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1219 if($msg_conversation_guid != $guid) {
1220 logger("message conversation guid does not belong to the current conversation.");
1224 $body = diaspora2bb($msg_text);
1225 $message_uri = $msg_author.":".$msg_guid;
1227 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1229 $author_signature = base64_decode($msg_author_signature);
1231 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1235 $person = self::person_by_handle($msg_author);
1237 if (is_array($person) && x($person, "pubkey"))
1238 $key = $person["pubkey"];
1240 logger("unable to find author details");
1245 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1246 logger("verification failed.");
1250 if($msg_parent_author_signature) {
1251 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1253 $parent_author_signature = base64_decode($msg_parent_author_signature);
1257 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1258 logger("owner verification failed.");
1263 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1267 logger("duplicate message already delivered.", LOGGER_DEBUG);
1271 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1272 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1273 intval($importer["uid"]),
1275 intval($conversation["id"]),
1276 dbesc($person["name"]),
1277 dbesc($person["photo"]),
1278 dbesc($person["url"]),
1279 intval($contact["id"]),
1284 dbesc($message_uri),
1285 dbesc($author.":".$guid),
1286 dbesc($msg_created_at)
1289 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1290 dbesc(datetime_convert()),
1291 intval($conversation["id"])
1295 "type" => NOTIFY_MAIL,
1296 "notify_flags" => $importer["notify-flags"],
1297 "language" => $importer["language"],
1298 "to_name" => $importer["username"],
1299 "to_email" => $importer["email"],
1300 "uid" =>$importer["uid"],
1301 "item" => array("subject" => $subject, "body" => $body),
1302 "source_name" => $person["name"],
1303 "source_link" => $person["url"],
1304 "source_photo" => $person["thumb"],
1305 "verb" => ACTIVITY_POST,
1312 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1314 * @param array $importer Array of the importer user
1315 * @param array $msg Array of the processed message, author handle and key
1316 * @param object $data The message object
1318 * @return bool Success
1320 private function receive_conversation($importer, $msg, $data) {
1321 $guid = notags(unxmlify($data->guid));
1322 $subject = notags(unxmlify($data->subject));
1323 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1324 $author = notags(unxmlify($data->author));
1325 $participants = notags(unxmlify($data->participants));
1327 $messages = $data->message;
1329 if (!count($messages)) {
1330 logger("empty conversation");
1334 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1338 $conversation = null;
1340 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1341 intval($importer["uid"]),
1345 $conversation = $c[0];
1347 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1348 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1349 intval($importer["uid"]),
1352 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1353 dbesc(datetime_convert()),
1355 dbesc($participants)
1358 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1359 intval($importer["uid"]),
1364 $conversation = $c[0];
1366 if (!$conversation) {
1367 logger("unable to create conversation.");
1371 foreach($messages as $mesg)
1372 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1378 * @brief Creates the body for a "like" message
1380 * @param array $contact The contact that send us the "like"
1381 * @param array $parent_item The item array of the parent item
1382 * @param string $guid message guid
1384 * @return string the body
1386 private function construct_like_body($contact, $parent_item, $guid) {
1387 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1389 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1390 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1391 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1393 return sprintf($bodyverb, $ulink, $alink, $plink);
1397 * @brief Creates a XML object for a "like"
1399 * @param array $importer Array of the importer user
1400 * @param array $parent_item The item array of the parent item
1402 * @return string The XML
1404 private function construct_like_object($importer, $parent_item) {
1405 $objtype = ACTIVITY_OBJ_NOTE;
1406 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1407 $parent_body = $parent_item["body"];
1409 $xmldata = array("object" => array("type" => $objtype,
1411 "id" => $parent_item["uri"],
1414 "content" => $parent_body));
1416 return xml::from_array($xmldata, $xml, true);
1420 * @brief Processes "like" messages
1422 * @param array $importer Array of the importer user
1423 * @param string $sender The sender of the message
1424 * @param object $data The message object
1426 * @return int The message id of the generated like or "false" if there was an error
1428 private function receive_like($importer, $sender, $data) {
1429 $positive = notags(unxmlify($data->positive));
1430 $guid = notags(unxmlify($data->guid));
1431 $parent_type = notags(unxmlify($data->parent_type));
1432 $parent_guid = notags(unxmlify($data->parent_guid));
1433 $author = notags(unxmlify($data->author));
1435 // likes on comments aren't supported by Diaspora - only on posts
1436 // But maybe this will be supported in the future, so we will accept it.
1437 if (!in_array($parent_type, array("Post", "Comment")))
1440 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1444 $message_id = self::message_exists($importer["uid"], $guid);
1448 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1452 $person = self::person_by_handle($author);
1453 if (!is_array($person)) {
1454 logger("unable to find author details");
1458 // Fetch the contact id - if we know this contact
1459 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1461 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1462 // We would accept this anyhow.
1463 if ($positive == "true")
1464 $verb = ACTIVITY_LIKE;
1466 $verb = ACTIVITY_DISLIKE;
1468 $datarray = array();
1470 $datarray["uid"] = $importer["uid"];
1471 $datarray["contact-id"] = $author_contact["cid"];
1472 $datarray["network"] = $author_contact["network"];
1474 $datarray["author-name"] = $person["name"];
1475 $datarray["author-link"] = $person["url"];
1476 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1478 $datarray["owner-name"] = $contact["name"];
1479 $datarray["owner-link"] = $contact["url"];
1480 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1482 $datarray["guid"] = $guid;
1483 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1485 $datarray["type"] = "activity";
1486 $datarray["verb"] = $verb;
1487 $datarray["gravity"] = GRAVITY_LIKE;
1488 $datarray["parent-uri"] = $parent_item["uri"];
1490 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1491 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1493 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1495 $message_id = item_store($datarray);
1498 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1500 // If we are the origin of the parent we store the original data and notify our followers
1501 if($message_id AND $parent_item["origin"]) {
1503 // Formerly we stored the signed text, the signature and the author in different fields.
1504 // We now store the raw data so that we are more flexible.
1505 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1506 intval($message_id),
1507 dbesc(json_encode($data))
1511 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1518 * @brief Processes private messages
1520 * @param array $importer Array of the importer user
1521 * @param object $data The message object
1523 * @return bool Success?
1525 private function receive_message($importer, $data) {
1526 $guid = notags(unxmlify($data->guid));
1527 $parent_guid = notags(unxmlify($data->parent_guid));
1528 $text = unxmlify($data->text);
1529 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1530 $author = notags(unxmlify($data->author));
1531 $conversation_guid = notags(unxmlify($data->conversation_guid));
1533 $contact = self::allowed_contact_by_handle($importer, $author, true);
1537 $conversation = null;
1539 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1540 intval($importer["uid"]),
1541 dbesc($conversation_guid)
1544 $conversation = $c[0];
1546 logger("conversation not available.");
1552 $body = diaspora2bb($text);
1553 $message_uri = $author.":".$guid;
1555 $person = self::person_by_handle($author);
1557 logger("unable to find author details");
1561 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1562 dbesc($message_uri),
1563 intval($importer["uid"])
1566 logger("duplicate message already delivered.", LOGGER_DEBUG);
1570 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1571 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1572 intval($importer["uid"]),
1574 intval($conversation["id"]),
1575 dbesc($person["name"]),
1576 dbesc($person["photo"]),
1577 dbesc($person["url"]),
1578 intval($contact["id"]),
1579 dbesc($conversation["subject"]),
1583 dbesc($message_uri),
1584 dbesc($author.":".$parent_guid),
1588 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1589 dbesc(datetime_convert()),
1590 intval($conversation["id"])
1597 * @brief Processes participations - unsupported by now
1599 * @param array $importer Array of the importer user
1600 * @param object $data The message object
1602 * @return bool always true
1604 private function receive_participation($importer, $data) {
1605 // I'm not sure if we can fully support this message type
1610 * @brief Processes photos - unneeded
1612 * @param array $importer Array of the importer user
1613 * @param object $data The message object
1615 * @return bool always true
1617 private function receive_photo($importer, $data) {
1618 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1623 * @brief Processes poll participations - unssupported
1625 * @param array $importer Array of the importer user
1626 * @param object $data The message object
1628 * @return bool always true
1630 private function receive_poll_participation($importer, $data) {
1631 // We don't support polls by now
1636 * @brief Processes incoming profile updates
1638 * @param array $importer Array of the importer user
1639 * @param object $data The message object
1641 * @return bool Success
1643 private function receive_profile($importer, $data) {
1644 $author = notags(unxmlify($data->author));
1646 $contact = self::contact_by_handle($importer["uid"], $author);
1650 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1651 $image_url = unxmlify($data->image_url);
1652 $birthday = unxmlify($data->birthday);
1653 $location = diaspora2bb(unxmlify($data->location));
1654 $about = diaspora2bb(unxmlify($data->bio));
1655 $gender = unxmlify($data->gender);
1656 $searchable = (unxmlify($data->searchable) == "true");
1657 $nsfw = (unxmlify($data->nsfw) == "true");
1658 $tags = unxmlify($data->tag_string);
1660 $tags = explode("#", $tags);
1662 $keywords = array();
1663 foreach ($tags as $tag) {
1664 $tag = trim(strtolower($tag));
1669 $keywords = implode(", ", $keywords);
1671 $handle_parts = explode("@", $author);
1672 $nick = $handle_parts[0];
1675 $name = $handle_parts[0];
1677 if( preg_match("|^https?://|", $image_url) === 0)
1678 $image_url = "http://".$handle_parts[1].$image_url;
1680 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1682 // Generic birthday. We don't know the timezone. The year is irrelevant.
1684 $birthday = str_replace("1000", "1901", $birthday);
1686 if ($birthday != "")
1687 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1689 // this is to prevent multiple birthday notifications in a single year
1690 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1692 if(substr($birthday,5) === substr($contact["bd"],5))
1693 $birthday = $contact["bd"];
1695 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1696 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1700 dbesc(datetime_convert()),
1706 intval($contact["id"]),
1707 intval($importer["uid"])
1711 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1712 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1715 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1716 "photo" => $image_url, "name" => $name, "location" => $location,
1717 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1718 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1719 "hide" => !$searchable, "nsfw" => $nsfw);
1721 update_gcontact($gcontact);
1723 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1729 * @brief Processes incoming friend requests
1731 * @param array $importer Array of the importer user
1732 * @param array $contact The contact that send the request
1734 private function receive_request_make_friend($importer, $contact) {
1738 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1739 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1740 intval(CONTACT_IS_FRIEND),
1741 intval($contact["id"]),
1742 intval($importer["uid"])
1745 // send notification
1747 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1748 intval($importer["uid"])
1751 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1753 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1754 intval($importer["uid"])
1757 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1759 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1762 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1763 $arr["uid"] = $importer["uid"];
1764 $arr["contact-id"] = $self[0]["id"];
1766 $arr["type"] = 'wall';
1767 $arr["gravity"] = 0;
1769 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1770 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1771 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1772 $arr["verb"] = ACTIVITY_FRIEND;
1773 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1775 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1776 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1777 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1778 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1780 $arr["object"] = self::construct_new_friend_object($contact);
1782 $arr["last-child"] = 1;
1784 $arr["allow_cid"] = $user[0]["allow_cid"];
1785 $arr["allow_gid"] = $user[0]["allow_gid"];
1786 $arr["deny_cid"] = $user[0]["deny_cid"];
1787 $arr["deny_gid"] = $user[0]["deny_gid"];
1789 $i = item_store($arr);
1791 proc_run("php", "include/notifier.php", "activity", $i);
1797 * @brief Creates a XML object for a "new friend" message
1799 * @param array $contact Array of the contact
1801 * @return string The XML
1803 private function construct_new_friend_object($contact) {
1804 $objtype = ACTIVITY_OBJ_PERSON;
1805 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1806 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1808 $xmldata = array("object" => array("type" => $objtype,
1809 "title" => $contact["name"],
1810 "id" => $contact["url"]."/".$contact["name"],
1813 return xml::from_array($xmldata, $xml, true);
1817 * @brief Processes incoming sharing notification
1819 * @param array $importer Array of the importer user
1820 * @param object $data The message object
1822 * @return bool Success
1824 private function receive_contact_request($importer, $data) {
1825 $author = unxmlify($data->author);
1826 $recipient = unxmlify($data->recipient);
1828 if (!$author || !$recipient)
1831 // the current protocol version doesn't know these fields
1832 // That means that we will assume their existance
1833 if (isset($data->following))
1834 $following = (unxmlify($data->following) == "true");
1838 if (isset($data->sharing))
1839 $sharing = (unxmlify($data->sharing) == "true");
1843 $contact = self::contact_by_handle($importer["uid"],$author);
1845 // perhaps we were already sharing with this person. Now they're sharing with us.
1846 // That makes us friends.
1848 if ($following AND $sharing) {
1849 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1850 self::receive_request_make_friend($importer, $contact);
1852 // refetch the contact array
1853 $contact = self::contact_by_handle($importer["uid"],$author);
1855 // If we are now friends, we are sending a share message.
1856 // Normally we needn't to do so, but the first message could have been vanished.
1857 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1858 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1860 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
1861 $ret = self::send_share($u[0], $contact);
1865 } else { /// @todo Handle all possible variations of adding and retracting of permissions
1866 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
1871 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1872 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1874 } elseif (!$following AND !$sharing) {
1875 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1877 } elseif (!$following AND $sharing) {
1878 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
1879 } elseif ($following AND $sharing) {
1880 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
1881 } elseif ($following AND !$sharing) {
1882 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
1885 $ret = self::person_by_handle($author);
1887 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1888 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1892 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1894 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1895 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1896 intval($importer["uid"]),
1897 dbesc($ret["network"]),
1898 dbesc($ret["addr"]),
1901 dbesc(normalise_link($ret["url"])),
1903 dbesc($ret["name"]),
1904 dbesc($ret["nick"]),
1905 dbesc($ret["photo"]),
1906 dbesc($ret["pubkey"]),
1907 dbesc($ret["notify"]),
1908 dbesc($ret["poll"]),
1913 // find the contact record we just created
1915 $contact_record = self::contact_by_handle($importer["uid"],$author);
1917 if (!$contact_record) {
1918 logger("unable to locate newly created contact record.");
1922 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
1924 $def_gid = get_default_group($importer['uid'], $ret["network"]);
1926 if(intval($def_gid))
1927 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
1929 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
1931 if($importer["page-flags"] == PAGE_NORMAL) {
1933 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
1935 $hash = random_string().(string)time(); // Generate a confirm_key
1937 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1938 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1939 intval($importer["uid"]),
1940 intval($contact_record["id"]),
1943 dbesc(t("Sharing notification from Diaspora network")),
1945 dbesc(datetime_convert())
1949 // automatic friend approval
1951 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
1953 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1955 // technically they are sharing with us (CONTACT_IS_SHARING),
1956 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1957 // we are going to change the relationship and make them a follower.
1959 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
1960 $new_relation = CONTACT_IS_FRIEND;
1961 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
1962 $new_relation = CONTACT_IS_SHARING;
1964 $new_relation = CONTACT_IS_FOLLOWER;
1966 $r = q("UPDATE `contact` SET `rel` = %d,
1974 intval($new_relation),
1975 dbesc(datetime_convert()),
1976 dbesc(datetime_convert()),
1977 intval($contact_record["id"])
1980 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1982 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
1983 $ret = self::send_share($u[0], $contact_record);
1985 // Send the profile data, maybe it weren't transmitted before
1986 self::send_profile($importer["uid"], array($contact_record));
1994 * @brief Fetches a message with a given guid
1996 * @param string $guid message guid
1997 * @param string $orig_author handle of the original post
1998 * @param string $author handle of the sharer
2000 * @return array The fetched item
2002 private function original_item($guid, $orig_author, $author) {
2004 // Do we already have this item?
2005 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2006 `author-name`, `author-link`, `author-avatar`
2007 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2011 logger("reshared message ".$guid." already exists on system.");
2013 // Maybe it is already a reshared item?
2014 // Then refetch the content, if it is a reshare from a reshare.
2015 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2016 if (self::is_reshare($r[0]["body"], true))
2018 elseif (self::is_reshare($r[0]["body"], false)) {
2019 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2021 // Add OEmbed and other information to the body
2022 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2030 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2031 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2032 $item_id = self::store_by_guid($guid, $server);
2035 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2036 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2037 $item_id = self::store_by_guid($guid, $server);
2041 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2042 `author-name`, `author-link`, `author-avatar`
2043 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2047 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2048 if (self::is_reshare($r[0]["body"], false))
2049 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2060 * @brief Processes a reshare message
2062 * @param array $importer Array of the importer user
2063 * @param object $data The message object
2064 * @param string $xml The original XML of the message
2066 * @return int the message id
2068 private function receive_reshare($importer, $data, $xml) {
2069 $root_author = notags(unxmlify($data->root_author));
2070 $root_guid = notags(unxmlify($data->root_guid));
2071 $guid = notags(unxmlify($data->guid));
2072 $author = notags(unxmlify($data->author));
2073 $public = notags(unxmlify($data->public));
2074 $created_at = notags(unxmlify($data->created_at));
2076 $contact = self::allowed_contact_by_handle($importer, $author, false);
2080 $message_id = self::message_exists($importer["uid"], $guid);
2084 $original_item = self::original_item($root_guid, $root_author, $author);
2085 if (!$original_item)
2088 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2090 $datarray = array();
2092 $datarray["uid"] = $importer["uid"];
2093 $datarray["contact-id"] = $contact["id"];
2094 $datarray["network"] = NETWORK_DIASPORA;
2096 $datarray["author-name"] = $contact["name"];
2097 $datarray["author-link"] = $contact["url"];
2098 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2100 $datarray["owner-name"] = $datarray["author-name"];
2101 $datarray["owner-link"] = $datarray["author-link"];
2102 $datarray["owner-avatar"] = $datarray["author-avatar"];
2104 $datarray["guid"] = $guid;
2105 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2107 $datarray["verb"] = ACTIVITY_POST;
2108 $datarray["gravity"] = GRAVITY_PARENT;
2110 $datarray["object"] = $xml;
2112 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2113 $original_item["guid"], $original_item["created"], $orig_url);
2114 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2116 $datarray["tag"] = $original_item["tag"];
2117 $datarray["app"] = $original_item["app"];
2119 $datarray["plink"] = self::plink($author, $guid);
2120 $datarray["private"] = (($public == "false") ? 1 : 0);
2121 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2123 $datarray["object-type"] = $original_item["object-type"];
2125 self::fetch_guid($datarray);
2126 $message_id = item_store($datarray);
2129 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2135 * @brief Processes retractions
2137 * @param array $importer Array of the importer user
2138 * @param array $contact The contact of the item owner
2139 * @param object $data The message object
2141 * @return bool success
2143 private function item_retraction($importer, $contact, $data) {
2144 $target_type = notags(unxmlify($data->target_type));
2145 $target_guid = notags(unxmlify($data->target_guid));
2146 $author = notags(unxmlify($data->author));
2148 $person = self::person_by_handle($author);
2149 if (!is_array($person)) {
2150 logger("unable to find author detail for ".$author);
2154 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2155 dbesc($target_guid),
2156 intval($importer["uid"])
2161 // Check if the sender is the thread owner
2162 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2163 intval($r[0]["parent"]));
2165 // Only delete it if the parent author really fits
2166 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2167 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2171 // 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
2172 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2173 dbesc(datetime_convert()),
2174 dbesc(datetime_convert()),
2177 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2179 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2181 // Now check if the retraction needs to be relayed by us
2182 if($p[0]["origin"]) {
2184 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2191 * @brief Receives retraction messages
2193 * @param array $importer Array of the importer user
2194 * @param string $sender The sender of the message
2195 * @param object $data The message object
2197 * @return bool Success
2199 private function receive_retraction($importer, $sender, $data) {
2200 $target_type = notags(unxmlify($data->target_type));
2202 $contact = self::contact_by_handle($importer["uid"], $sender);
2204 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2208 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2210 switch ($target_type) {
2213 case "Post": // "Post" will be supported in a future version
2215 case "StatusMessage":
2216 return self::item_retraction($importer, $contact, $data);;
2220 /// @todo What should we do with an "unshare"?
2221 // Removing the contact isn't correct since we still can read the public items
2222 contact_remove($contact["id"]);
2226 logger("Unknown target type ".$target_type);
2233 * @brief Receives status messages
2235 * @param array $importer Array of the importer user
2236 * @param object $data The message object
2237 * @param string $xml The original XML of the message
2239 * @return int The message id of the newly created item
2241 private function receive_status_message($importer, $data, $xml) {
2243 $raw_message = unxmlify($data->raw_message);
2244 $guid = notags(unxmlify($data->guid));
2245 $author = notags(unxmlify($data->author));
2246 $public = notags(unxmlify($data->public));
2247 $created_at = notags(unxmlify($data->created_at));
2248 $provider_display_name = notags(unxmlify($data->provider_display_name));
2250 /// @todo enable support for polls
2251 //if ($data->poll) {
2252 // foreach ($data->poll AS $poll)
2256 $contact = self::allowed_contact_by_handle($importer, $author, false);
2260 $message_id = self::message_exists($importer["uid"], $guid);
2265 if ($data->location)
2266 foreach ($data->location->children() AS $fieldname => $data)
2267 $address[$fieldname] = notags(unxmlify($data));
2269 $body = diaspora2bb($raw_message);
2271 $datarray = array();
2273 // Attach embedded pictures to the body
2275 foreach ($data->photo AS $photo)
2276 $body = "[img]".unxmlify($photo->remote_photo_path).
2277 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2279 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2281 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2283 // Add OEmbed and other information to the body
2284 if (!self::is_redmatrix($contact["url"]))
2285 $body = add_page_info_to_body($body, false, true);
2288 $datarray["uid"] = $importer["uid"];
2289 $datarray["contact-id"] = $contact["id"];
2290 $datarray["network"] = NETWORK_DIASPORA;
2292 $datarray["author-name"] = $contact["name"];
2293 $datarray["author-link"] = $contact["url"];
2294 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2296 $datarray["owner-name"] = $datarray["author-name"];
2297 $datarray["owner-link"] = $datarray["author-link"];
2298 $datarray["owner-avatar"] = $datarray["author-avatar"];
2300 $datarray["guid"] = $guid;
2301 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2303 $datarray["verb"] = ACTIVITY_POST;
2304 $datarray["gravity"] = GRAVITY_PARENT;
2306 $datarray["object"] = $xml;
2308 $datarray["body"] = $body;
2310 if ($provider_display_name != "")
2311 $datarray["app"] = $provider_display_name;
2313 $datarray["plink"] = self::plink($author, $guid);
2314 $datarray["private"] = (($public == "false") ? 1 : 0);
2315 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2317 if (isset($address["address"]))
2318 $datarray["location"] = $address["address"];
2320 if (isset($address["lat"]) AND isset($address["lng"]))
2321 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2323 self::fetch_guid($datarray);
2324 $message_id = item_store($datarray);
2327 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2332 /* ************************************************************************************** *
2333 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2334 * ************************************************************************************** */
2337 * @brief returnes the handle of a contact
2339 * @param array $me contact array
2341 * @return string the handle in the format user@domain.tld
2343 private function my_handle($contact) {
2344 if ($contact["addr"] != "")
2345 return $contact["addr"];
2347 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2348 // So - just in case - we build the the address here.
2349 if ($contact["nickname"] != "")
2350 $nick = $contact["nickname"];
2352 $nick = $contact["nick"];
2354 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2358 * @brief Creates the envelope for the "fetch" endpoint
2360 * @param string $msg The message that is to be transmitted
2361 * @param array $user The record of the sender
2363 * @return string The envelope
2366 public static function build_magic_envelope($msg, $user) {
2368 $b64url_data = base64url_encode($msg);
2369 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2371 $key_id = base64url_encode(diaspora::my_handle($user));
2372 $type = "application/xml";
2373 $encoding = "base64url";
2374 $alg = "RSA-SHA256";
2375 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2376 $signature = rsa_sign($signable_data, $user["prvkey"]);
2377 $sig = base64url_encode($signature);
2379 $xmldata = array("me:env" => array("me:data" => $data,
2380 "@attributes" => array("type" => $type),
2381 "me:encoding" => $encoding,
2384 "@attributes2" => array("key_id" => $key_id)));
2386 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2388 return xml::from_array($xmldata, $xml, false, $namespaces);
2392 * @brief Creates the envelope for a public message
2394 * @param string $msg The message that is to be transmitted
2395 * @param array $user The record of the sender
2396 * @param array $contact Target of the communication
2397 * @param string $prvkey The private key of the sender
2398 * @param string $pubkey The public key of the receiver
2400 * @return string The envelope
2402 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2404 logger("Message: ".$msg, LOGGER_DATA);
2406 $handle = self::my_handle($user);
2408 $b64url_data = base64url_encode($msg);
2410 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2412 $type = "application/xml";
2413 $encoding = "base64url";
2414 $alg = "RSA-SHA256";
2416 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2418 $signature = rsa_sign($signable_data,$prvkey);
2419 $sig = base64url_encode($signature);
2421 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2422 "me:env" => array("me:encoding" => $encoding,
2425 "@attributes" => array("type" => $type),
2426 "me:sig" => $sig)));
2428 $namespaces = array("" => "https://joindiaspora.com/protocol",
2429 "me" => "http://salmon-protocol.org/ns/magic-env");
2431 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2433 logger("magic_env: ".$magic_env, LOGGER_DATA);
2438 * @brief Creates the envelope for a private message
2440 * @param string $msg The message that is to be transmitted
2441 * @param array $user The record of the sender
2442 * @param array $contact Target of the communication
2443 * @param string $prvkey The private key of the sender
2444 * @param string $pubkey The public key of the receiver
2446 * @return string The envelope
2448 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2450 logger("Message: ".$msg, LOGGER_DATA);
2452 // without a public key nothing will work
2455 logger("pubkey missing: contact id: ".$contact["id"]);
2459 $inner_aes_key = random_string(32);
2460 $b_inner_aes_key = base64_encode($inner_aes_key);
2461 $inner_iv = random_string(16);
2462 $b_inner_iv = base64_encode($inner_iv);
2464 $outer_aes_key = random_string(32);
2465 $b_outer_aes_key = base64_encode($outer_aes_key);
2466 $outer_iv = random_string(16);
2467 $b_outer_iv = base64_encode($outer_iv);
2469 $handle = self::my_handle($user);
2471 $padded_data = pkcs5_pad($msg,16);
2472 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2474 $b64_data = base64_encode($inner_encrypted);
2477 $b64url_data = base64url_encode($b64_data);
2478 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2480 $type = "application/xml";
2481 $encoding = "base64url";
2482 $alg = "RSA-SHA256";
2484 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2486 $signature = rsa_sign($signable_data,$prvkey);
2487 $sig = base64url_encode($signature);
2489 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2490 "aes_key" => $b_inner_aes_key,
2491 "author_id" => $handle));
2493 $decrypted_header = xml::from_array($xmldata, $xml, true);
2494 $decrypted_header = pkcs5_pad($decrypted_header,16);
2496 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2498 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2500 $encrypted_outer_key_bundle = "";
2501 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2503 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2505 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2507 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2508 "ciphertext" => base64_encode($ciphertext)));
2509 $cipher_json = base64_encode($encrypted_header_json_object);
2511 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2512 "me:env" => array("me:encoding" => $encoding,
2515 "@attributes" => array("type" => $type),
2516 "me:sig" => $sig)));
2518 $namespaces = array("" => "https://joindiaspora.com/protocol",
2519 "me" => "http://salmon-protocol.org/ns/magic-env");
2521 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2523 logger("magic_env: ".$magic_env, LOGGER_DATA);
2528 * @brief Create the envelope for a message
2530 * @param string $msg The message that is to be transmitted
2531 * @param array $user The record of the sender
2532 * @param array $contact Target of the communication
2533 * @param string $prvkey The private key of the sender
2534 * @param string $pubkey The public key of the receiver
2535 * @param bool $public Is the message public?
2537 * @return string The message that will be transmitted to other servers
2539 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2542 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2544 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2546 // The data that will be transmitted is double encoded via "urlencode", strange ...
2547 $slap = "xml=".urlencode(urlencode($magic_env));
2552 * @brief Creates a signature for a message
2554 * @param array $owner the array of the owner of the message
2555 * @param array $message The message that is to be signed
2557 * @return string The signature
2559 private function signature($owner, $message) {
2561 unset($sigmsg["author_signature"]);
2562 unset($sigmsg["parent_author_signature"]);
2564 $signed_text = implode(";", $sigmsg);
2566 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2570 * @brief Transmit a message to a target server
2572 * @param array $owner the array of the item owner
2573 * @param array $contact Target of the communication
2574 * @param string $slap The message that is to be transmitted
2575 * @param bool $public_batch Is it a public post?
2576 * @param bool $queue_run Is the transmission called from the queue?
2577 * @param string $guid message guid
2579 * @return int Result of the transmission
2581 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2585 $enabled = intval(get_config("system", "diaspora_enabled"));
2589 $logid = random_string(4);
2590 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2592 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2596 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2598 if (!$queue_run && was_recently_delayed($contact["id"])) {
2601 if (!intval(get_config("system", "diaspora_test"))) {
2602 post_url($dest_url."/", $slap);
2603 $return_code = $a->get_curl_code();
2605 logger("test_mode");
2610 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2612 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2613 logger("queue message");
2615 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2616 intval($contact["id"]),
2617 dbesc(NETWORK_DIASPORA),
2619 intval($public_batch)
2622 logger("add_to_queue ignored - identical item already in queue");
2624 // queue message for redelivery
2625 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2629 return(($return_code) ? $return_code : (-1));
2634 * @brief Build the post xml
2636 * @param string $type The message type
2637 * @param array $message The message data
2639 * @return string The post XML
2641 public static function build_post_xml($type, $message) {
2643 $data = array("XML" => array("post" => array($type => $message)));
2644 return xml::from_array($data, $xml);
2648 * @brief Builds and transmit messages
2650 * @param array $owner the array of the item owner
2651 * @param array $contact Target of the communication
2652 * @param string $type The message type
2653 * @param array $message The message data
2654 * @param bool $public_batch Is it a public post?
2655 * @param string $guid message guid
2656 * @param bool $spool Should the transmission be spooled or transmitted?
2658 * @return int Result of the transmission
2660 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2662 $msg = self::build_post_xml($type, $message);
2664 logger('message: '.$msg, LOGGER_DATA);
2665 logger('send guid '.$guid, LOGGER_DEBUG);
2667 // Fallback if the private key wasn't transmitted in the expected field
2668 if ($owner['uprvkey'] == "")
2669 $owner['uprvkey'] = $owner['prvkey'];
2671 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2674 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2677 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2679 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2681 return $return_code;
2685 * @brief Sends a "share" message
2687 * @param array $owner the array of the item owner
2688 * @param array $contact Target of the communication
2690 * @return int The result of the transmission
2692 public static function send_share($owner,$contact) {
2694 $message = array("sender_handle" => self::my_handle($owner),
2695 "recipient_handle" => $contact["addr"]);
2697 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2699 return self::build_and_transmit($owner, $contact, "request", $message);
2703 * @brief sends an "unshare"
2705 * @param array $owner the array of the item owner
2706 * @param array $contact Target of the communication
2708 * @return int The result of the transmission
2710 public static function send_unshare($owner,$contact) {
2712 $message = array("post_guid" => $owner["guid"],
2713 "diaspora_handle" => self::my_handle($owner),
2714 "type" => "Person");
2716 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2718 return self::build_and_transmit($owner, $contact, "retraction", $message);
2722 * @brief Checks a message body if it is a reshare
2724 * @param string $body The message body that is to be check
2725 * @param bool $complete Should it be a complete check or a simple check?
2727 * @return array|bool Reshare details or "false" if no reshare
2729 public static function is_reshare($body, $complete = true) {
2730 $body = trim($body);
2732 // Skip if it isn't a pure repeated messages
2733 // Does it start with a share?
2734 if ((strpos($body, "[share") > 0) AND $complete)
2737 // Does it end with a share?
2738 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2741 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2742 // Skip if there is no shared message in there
2743 if ($body == $attributes)
2746 // If we don't do the complete check we quit here
2751 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2752 if ($matches[1] != "")
2753 $guid = $matches[1];
2755 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2756 if ($matches[1] != "")
2757 $guid = $matches[1];
2760 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2761 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2764 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2765 $ret["root_guid"] = $guid;
2771 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2772 if ($matches[1] != "")
2773 $profile = $matches[1];
2775 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2776 if ($matches[1] != "")
2777 $profile = $matches[1];
2781 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2782 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2786 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2787 if ($matches[1] != "")
2788 $link = $matches[1];
2790 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2791 if ($matches[1] != "")
2792 $link = $matches[1];
2794 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2795 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2802 * @brief Create a post (status message or reshare)
2804 * @param array $item The item that will be exported
2805 * @param array $owner the array of the item owner
2808 * 'type' -> Message type ("status_message" or "reshare")
2809 * 'message' -> Array of XML elements of the status
2811 public static function build_status($item, $owner) {
2813 $myaddr = self::my_handle($owner);
2815 $public = (($item["private"]) ? "false" : "true");
2817 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2819 // Detect a share element and do a reshare
2820 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2821 $message = array("root_diaspora_id" => $ret["root_handle"],
2822 "root_guid" => $ret["root_guid"],
2823 "guid" => $item["guid"],
2824 "diaspora_handle" => $myaddr,
2825 "public" => $public,
2826 "created_at" => $created,
2827 "provider_display_name" => $item["app"]);
2831 $title = $item["title"];
2832 $body = $item["body"];
2834 // convert to markdown
2835 $body = html_entity_decode(bb2diaspora($body));
2839 $body = "## ".html_entity_decode($title)."\n\n".$body;
2841 if ($item["attach"]) {
2842 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2844 $body .= "\n".t("Attachments:")."\n";
2845 foreach($matches as $mtch)
2846 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2850 $location = array();
2852 if ($item["location"] != "")
2853 $location["address"] = $item["location"];
2855 if ($item["coord"] != "") {
2856 $coord = explode(" ", $item["coord"]);
2857 $location["lat"] = $coord[0];
2858 $location["lng"] = $coord[1];
2861 $message = array("raw_message" => $body,
2862 "location" => $location,
2863 "guid" => $item["guid"],
2864 "diaspora_handle" => $myaddr,
2865 "public" => $public,
2866 "created_at" => $created,
2867 "provider_display_name" => $item["app"]);
2869 if (count($location) == 0)
2870 unset($message["location"]);
2872 $type = "status_message";
2874 return array("type" => $type, "message" => $message);
2878 * @brief Sends a post
2880 * @param array $item The item that will be exported
2881 * @param array $owner the array of the item owner
2882 * @param array $contact Target of the communication
2883 * @param bool $public_batch Is it a public post?
2885 * @return int The result of the transmission
2887 public static function send_status($item, $owner, $contact, $public_batch = false) {
2889 $status = diaspora::build_status($item, $owner);
2891 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
2895 * @brief Creates a "like" object
2897 * @param array $item The item that will be exported
2898 * @param array $owner the array of the item owner
2900 * @return array The data for a "like"
2902 private function construct_like($item, $owner) {
2904 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2905 dbesc($item["thr-parent"]));
2911 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2914 return(array("positive" => $positive,
2915 "guid" => $item["guid"],
2916 "target_type" => $target_type,
2917 "parent_guid" => $parent["guid"],
2918 "author_signature" => "",
2919 "diaspora_handle" => self::my_handle($owner)));
2923 * @brief Creates the object for a comment
2925 * @param array $item The item that will be exported
2926 * @param array $owner the array of the item owner
2928 * @return array The data for a comment
2930 private function construct_comment($item, $owner) {
2932 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2933 intval($item["parent"]),
2934 intval($item["parent"])
2942 $text = html_entity_decode(bb2diaspora($item["body"]));
2944 return(array("guid" => $item["guid"],
2945 "parent_guid" => $parent["guid"],
2946 "author_signature" => "",
2948 "diaspora_handle" => self::my_handle($owner)));
2952 * @brief Send a like or a comment
2954 * @param array $item The item that will be exported
2955 * @param array $owner the array of the item owner
2956 * @param array $contact Target of the communication
2957 * @param bool $public_batch Is it a public post?
2959 * @return int The result of the transmission
2961 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2963 if($item['verb'] === ACTIVITY_LIKE) {
2964 $message = self::construct_like($item, $owner);
2967 $message = self::construct_comment($item, $owner);
2974 $message["author_signature"] = self::signature($owner, $message);
2976 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2980 * @brief Creates a message from a signature record entry
2982 * @param array $item The item that will be exported
2983 * @param array $signature The entry of the "sign" record
2985 * @return string The message
2987 private function message_from_signature($item, $signature) {
2989 // Split the signed text
2990 $signed_parts = explode(";", $signature['signed_text']);
2992 if ($item["deleted"])
2993 $message = array("parent_author_signature" => "",
2994 "target_guid" => $signed_parts[0],
2995 "target_type" => $signed_parts[1],
2996 "sender_handle" => $signature['signer'],
2997 "target_author_signature" => $signature['signature']);
2998 elseif ($item['verb'] === ACTIVITY_LIKE)
2999 $message = array("positive" => $signed_parts[0],
3000 "guid" => $signed_parts[1],
3001 "target_type" => $signed_parts[2],
3002 "parent_guid" => $signed_parts[3],
3003 "parent_author_signature" => "",
3004 "author_signature" => $signature['signature'],
3005 "diaspora_handle" => $signed_parts[4]);
3007 // Remove the comment guid
3008 $guid = array_shift($signed_parts);
3010 // Remove the parent guid
3011 $parent_guid = array_shift($signed_parts);
3013 // Remove the handle
3014 $handle = array_pop($signed_parts);
3016 // Glue the parts together
3017 $text = implode(";", $signed_parts);
3019 $message = array("guid" => $guid,
3020 "parent_guid" => $parent_guid,
3021 "parent_author_signature" => "",
3022 "author_signature" => $signature['signature'],
3023 "text" => implode(";", $signed_parts),
3024 "diaspora_handle" => $handle);
3030 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3032 * @param array $item The item that will be exported
3033 * @param array $owner the array of the item owner
3034 * @param array $contact Target of the communication
3035 * @param bool $public_batch Is it a public post?
3037 * @return int The result of the transmission
3039 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3041 if ($item["deleted"])
3042 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3043 elseif ($item['verb'] === ACTIVITY_LIKE)
3048 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3050 // fetch the original signature
3052 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3053 intval($item["id"]));
3056 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3062 // Old way - is used by the internal Friendica functions
3063 /// @todo Change all signatur storing functions to the new format
3064 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3065 $message = self::message_from_signature($item, $signature);
3067 $msg = json_decode($signature['signed_text'], true);
3070 if (is_array($msg)) {
3071 foreach ($msg AS $field => $data) {
3072 if (!$item["deleted"]) {
3073 if ($field == "author")
3074 $field = "diaspora_handle";
3075 if ($field == "parent_type")
3076 $field = "target_type";
3079 $message[$field] = $data;
3082 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3085 $message["parent_author_signature"] = self::signature($owner, $message);
3087 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3089 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3093 * @brief Sends a retraction (deletion) of a message, like or comment
3095 * @param array $item The item that will be exported
3096 * @param array $owner the array of the item owner
3097 * @param array $contact Target of the communication
3098 * @param bool $public_batch Is it a public post?
3099 * @param bool $relay Is the retraction transmitted from a relay?
3101 * @return int The result of the transmission
3103 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3105 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3107 // Check whether the retraction is for a top-level post or whether it's a relayable
3108 if ($item["uri"] !== $item["parent-uri"]) {
3109 $msg_type = "relayable_retraction";
3110 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3112 $msg_type = "signed_retraction";
3113 $target_type = "StatusMessage";
3116 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3117 $signature = "parent_author_signature";
3119 $signature = "target_author_signature";
3121 $signed_text = $item["guid"].";".$target_type;
3123 $message = array("target_guid" => $item['guid'],
3124 "target_type" => $target_type,
3125 "sender_handle" => $itemaddr,
3126 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3128 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3130 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3134 * @brief Sends a mail
3136 * @param array $item The item that will be exported
3137 * @param array $owner The owner
3138 * @param array $contact Target of the communication
3140 * @return int The result of the transmission
3142 public static function send_mail($item, $owner, $contact) {
3144 $myaddr = self::my_handle($owner);
3146 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3147 intval($item["convid"]),
3148 intval($item["uid"])
3152 logger("conversation not found.");
3158 "guid" => $cnv["guid"],
3159 "subject" => $cnv["subject"],
3160 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3161 "diaspora_handle" => $cnv["creator"],
3162 "participant_handles" => $cnv["recips"]
3165 $body = bb2diaspora($item["body"]);
3166 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
3168 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3169 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3172 "guid" => $item["guid"],
3173 "parent_guid" => $cnv["guid"],
3174 "parent_author_signature" => $sig,
3175 "author_signature" => $sig,
3177 "created_at" => $created,
3178 "diaspora_handle" => $myaddr,
3179 "conversation_guid" => $cnv["guid"]
3182 if ($item["reply"]) {
3186 $message = array("guid" => $cnv["guid"],
3187 "subject" => $cnv["subject"],
3188 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3190 "diaspora_handle" => $cnv["creator"],
3191 "participant_handles" => $cnv["recips"]);
3193 $type = "conversation";
3196 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3200 * @brief Sends profile data
3202 * @param int $uid The user id
3204 public static function send_profile($uid, $recips = false) {
3210 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3211 AND `uid` = %d AND `rel` != %d",
3212 dbesc(NETWORK_DIASPORA),
3214 intval(CONTACT_IS_SHARING)
3219 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3221 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3222 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3223 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3232 $handle = $profile["addr"];
3233 $first = ((strpos($profile['name'],' ')
3234 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3235 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3236 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3237 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3238 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3239 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3241 if ($searchable === 'true') {
3242 $dob = '1000-00-00';
3244 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3245 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3247 $about = $profile['about'];
3248 $about = strip_tags(bbcode($about));
3250 $location = formatted_location($profile);
3252 if ($profile['pub_keywords']) {
3253 $kw = str_replace(',',' ',$profile['pub_keywords']);
3254 $kw = str_replace(' ',' ',$kw);
3255 $arr = explode(' ',$profile['pub_keywords']);
3257 for($x = 0; $x < 5; $x ++) {
3259 $tags .= '#'. trim($arr[$x]) .' ';
3263 $tags = trim($tags);
3266 $message = array("diaspora_handle" => $handle,
3267 "first_name" => $first,
3268 "last_name" => $last,
3269 "image_url" => $large,
3270 "image_url_medium" => $medium,
3271 "image_url_small" => $small,
3273 "gender" => $profile['gender'],
3275 "location" => $location,
3276 "searchable" => $searchable,
3277 "tag_string" => $tags);
3279 foreach($recips as $recip) {
3280 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3281 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3286 * @brief Stores the signature for likes that are created on our system
3288 * @param array $contact The contact array of the "like"
3289 * @param int $post_id The post id of the "like"
3291 * @return bool Success
3293 public static function store_like_signature($contact, $post_id) {
3295 // Is the contact the owner? Then fetch the private key
3296 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3297 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3301 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3305 $contact["uprvkey"] = $r[0]['prvkey'];
3307 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3311 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3314 $message = self::construct_like($r[0], $contact);
3315 $message["author_signature"] = self::signature($contact, $message);
3317 // In the future we will store the signature more flexible to support new fields.
3318 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3319 // (We are transmitting this data here via DFRN)
3321 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3322 $message["parent_guid"].";".$message["diaspora_handle"];
3324 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3326 dbesc($signed_text),
3327 dbesc($message["author_signature"]),
3328 dbesc($message["diaspora_handle"])
3331 // This here will replace the lines above, once Diaspora changed its protocol
3332 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3333 // intval($message_id),
3334 // dbesc(json_encode($message))
3337 logger('Stored diaspora like signature');
3342 * @brief Stores the signature for comments that are created on our system
3344 * @param array $item The item array of the comment
3345 * @param array $contact The contact array of the item owner
3346 * @param string $uprvkey The private key of the sender
3347 * @param int $message_id The message id of the comment
3349 * @return bool Success
3351 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3353 if ($uprvkey == "") {
3354 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3358 $contact["uprvkey"] = $uprvkey;
3360 $message = self::construct_comment($item, $contact);
3361 $message["author_signature"] = self::signature($contact, $message);
3363 // In the future we will store the signature more flexible to support new fields.
3364 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3365 // (We are transmitting this data here via DFRN)
3366 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3367 $message["text"].";".$message["diaspora_handle"];
3369 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3370 intval($message_id),
3371 dbesc($signed_text),
3372 dbesc($message["author_signature"]),
3373 dbesc($message["diaspora_handle"])
3376 // This here will replace the lines above, once Diaspora changed its protocol
3377 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3378 // intval($message_id),
3379 // dbesc(json_encode($message))
3382 logger('Stored diaspora comment signature');