3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 require_once("include/items.php");
12 require_once("include/bb2diaspora.php");
13 require_once("include/Scrape.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
16 require_once("include/socgraph.php");
17 require_once("include/group.php");
18 require_once("include/xml.php");
19 require_once("include/datetime.php");
20 require_once("include/queue_fn.php");
23 * @brief This class contain functions to create and send Diaspora XML files
29 * @brief Return a list of relay servers
31 * This is an experimental Diaspora feature.
33 * @return array of relay servers
35 public static function relay_list() {
37 $serverdata = get_config("system", "relay_server");
38 if ($serverdata == "")
43 $servers = explode(",", $serverdata);
45 foreach($servers AS $server) {
46 $server = trim($server);
47 $batch = $server."/receive/public";
49 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
52 $addr = "relay@".str_replace("http://", "", normalise_link($server));
54 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
55 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
60 dbesc(normalise_link($server)),
62 dbesc(NETWORK_DIASPORA),
63 intval(CONTACT_IS_FOLLOWER),
64 dbesc(datetime_convert()),
65 dbesc(datetime_convert()),
66 dbesc(datetime_convert())
69 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
71 $relay[] = $relais[0];
73 $relay[] = $relais[0];
80 * @brief repairs a signature that was double encoded
82 * The function is unused at the moment. It was copied from the old implementation.
84 * @param string $signature The signature
85 * @param string $handle The handle of the signature owner
86 * @param integer $level This value is only set inside this function to avoid endless loops
88 * @return string the repaired signature
90 private function repair_signature($signature, $handle = "", $level = 1) {
95 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
96 $signature = base64_decode($signature);
97 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
99 // Do a recursive call to be able to fix even multiple levels
101 $signature = self::repair_signature($signature, $handle, ++$level);
108 * @brief verify the envelope and return the verified data
110 * @param string $envelope The magic envelope
112 * @return string verified data
114 private function verify_magic_envelope($envelope) {
116 $basedom = parse_xml_string($envelope, false);
118 if (!is_object($basedom)) {
119 logger("Envelope is no XML file");
123 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
125 if (sizeof($children) == 0) {
126 logger("XML has no children");
132 $data = base64url_decode($children->data);
133 $type = $children->data->attributes()->type[0];
135 $encoding = $children->encoding;
137 $alg = $children->alg;
139 $sig = base64url_decode($children->sig);
140 $key_id = $children->sig->attributes()->key_id[0];
142 $handle = base64url_decode($key_id);
144 $b64url_data = base64url_encode($data);
145 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
147 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
149 $key = self::key($handle);
151 $verify = rsa_verify($signable_data, $sig, $key);
153 logger('Message did not verify. Discarding.');
161 * @brief: Decodes incoming Diaspora message
163 * @param array $importer Array of the importer user
164 * @param string $xml urldecoded Diaspora salmon
167 * 'message' -> decoded Diaspora XML message
168 * 'author' -> author diaspora handle
169 * 'key' -> author public key (converted to pkcs#8)
171 public static function decode($importer, $xml) {
174 $basedom = parse_xml_string($xml);
176 if (!is_object($basedom))
179 $children = $basedom->children('https://joindiaspora.com/protocol');
181 if($children->header) {
183 $author_link = str_replace('acct:','',$children->header->author_id);
186 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
188 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
189 $ciphertext = base64_decode($encrypted_header->ciphertext);
191 $outer_key_bundle = '';
192 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
194 $j_outer_key_bundle = json_decode($outer_key_bundle);
196 $outer_iv = base64_decode($j_outer_key_bundle->iv);
197 $outer_key = base64_decode($j_outer_key_bundle->key);
199 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
202 $decrypted = pkcs5_unpad($decrypted);
204 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
205 $idom = parse_xml_string($decrypted,false);
207 $inner_iv = base64_decode($idom->iv);
208 $inner_aes_key = base64_decode($idom->aes_key);
210 $author_link = str_replace('acct:','',$idom->author_id);
213 $dom = $basedom->children(NAMESPACE_SALMON_ME);
215 // figure out where in the DOM tree our data is hiding
217 if($dom->provenance->data)
218 $base = $dom->provenance;
219 elseif($dom->env->data)
225 logger('unable to locate salmon data in xml');
226 http_status_exit(400);
230 // Stash the signature away for now. We have to find their key or it won't be good for anything.
231 $signature = base64url_decode($base->sig);
235 // strip whitespace so our data element will return to one big base64 blob
236 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
239 // stash away some other stuff for later
241 $type = $base->data[0]->attributes()->type[0];
242 $keyhash = $base->sig[0]->attributes()->keyhash[0];
243 $encoding = $base->encoding;
247 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
251 $data = base64url_decode($data);
255 $inner_decrypted = $data;
258 // Decode the encrypted blob
260 $inner_encrypted = base64_decode($data);
261 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
262 $inner_decrypted = pkcs5_unpad($inner_decrypted);
266 logger('Could not retrieve author URI.');
267 http_status_exit(400);
269 // Once we have the author URI, go to the web and try to find their public key
270 // (first this will look it up locally if it is in the fcontact cache)
271 // This will also convert diaspora public key from pkcs#1 to pkcs#8
273 logger('Fetching key for '.$author_link);
274 $key = self::key($author_link);
277 logger('Could not retrieve author key.');
278 http_status_exit(400);
281 $verify = rsa_verify($signed_data,$signature,$key);
284 logger('Message did not verify. Discarding.');
285 http_status_exit(400);
288 logger('Message verified.');
290 return array('message' => (string)$inner_decrypted,
291 'author' => unxmlify($author_link),
292 'key' => (string)$key);
297 * @brief Dispatches public messages and find the fitting receivers
299 * @param array $msg The post that will be dispatched
301 * @return int The message id of the generated message, "true" or "false" if there was an error
303 public static function dispatch_public($msg) {
305 $enabled = intval(get_config("system", "diaspora_enabled"));
307 logger("diaspora is disabled");
311 // Use a dummy importer to import the data for the public copy
312 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
313 $message_id = self::dispatch($importer,$msg);
315 // Now distribute it to the followers
316 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
317 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
318 AND NOT `account_expired` AND NOT `account_removed`",
319 dbesc(NETWORK_DIASPORA),
320 dbesc($msg["author"])
324 logger("delivering to: ".$rr["username"]);
325 self::dispatch($rr,$msg);
328 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
334 * @brief Dispatches the different message types to the different functions
336 * @param array $importer Array of the importer user
337 * @param array $msg The post that will be dispatched
339 * @return int The message id of the generated message, "true" or "false" if there was an error
341 public static function dispatch($importer, $msg) {
343 // The sender is the handle of the contact that sent the message.
344 // This will often be different with relayed messages (for example "like" and "comment")
345 $sender = $msg["author"];
347 if (!self::valid_posting($msg, $fields)) {
348 logger("Invalid posting");
352 $type = $fields->getName();
354 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
357 case "account_deletion":
358 return self::receive_account_deletion($importer, $fields);
361 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
364 return self::receive_contact_request($importer, $fields);
367 return self::receive_conversation($importer, $msg, $fields);
370 return self::receive_like($importer, $sender, $fields);
373 return self::receive_message($importer, $fields);
375 case "participation": // Not implemented
376 return self::receive_participation($importer, $fields);
378 case "photo": // Not implemented
379 return self::receive_photo($importer, $fields);
381 case "poll_participation": // Not implemented
382 return self::receive_poll_participation($importer, $fields);
385 return self::receive_profile($importer, $fields);
388 return self::receive_reshare($importer, $fields, $msg["message"]);
391 return self::receive_retraction($importer, $sender, $fields);
393 case "status_message":
394 return self::receive_status_message($importer, $fields, $msg["message"]);
397 logger("Unknown message type ".$type);
405 * @brief Checks if a posting is valid and fetches the data fields.
407 * This function does not only check the signature.
408 * It also does the conversion between the old and the new diaspora format.
410 * @param array $msg Array with the XML, the sender handle and the sender signature
411 * @param object $fields SimpleXML object that contains the posting when it is valid
413 * @return bool Is the posting valid?
415 private function valid_posting($msg, &$fields) {
417 $data = parse_xml_string($msg["message"], false);
419 if (!is_object($data)) {
420 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
424 $first_child = $data->getName();
426 // Is this the new or the old version?
427 if ($data->getName() == "XML") {
429 foreach ($data->post->children() as $child)
436 $type = $element->getName();
439 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
441 // All retractions are handled identically from now on.
442 // In the new version there will only be "retraction".
443 if (in_array($type, array("signed_retraction", "relayable_retraction")))
444 $type = "retraction";
446 if ($type == "request")
449 $fields = new SimpleXMLElement("<".$type."/>");
453 foreach ($element->children() AS $fieldname => $entry) {
455 // Translation for the old XML structure
456 if ($fieldname == "diaspora_handle")
457 $fieldname = "author";
459 if ($fieldname == "participant_handles")
460 $fieldname = "participants";
462 if (in_array($type, array("like", "participation"))) {
463 if ($fieldname == "target_type")
464 $fieldname = "parent_type";
467 if ($fieldname == "sender_handle")
468 $fieldname = "author";
470 if ($fieldname == "recipient_handle")
471 $fieldname = "recipient";
473 if ($fieldname == "root_diaspora_id")
474 $fieldname = "root_author";
476 if ($type == "retraction") {
477 if ($fieldname == "post_guid")
478 $fieldname = "target_guid";
480 if ($fieldname == "type")
481 $fieldname = "target_type";
485 if (($fieldname == "author_signature") AND ($entry != ""))
486 $author_signature = base64_decode($entry);
487 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
488 $parent_author_signature = base64_decode($entry);
489 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
490 if ($signed_data != "") {
492 $signed_data_parent .= ";";
495 $signed_data .= $entry;
497 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
498 ($orig_type == "relayable_retraction"))
499 xml::copy($entry, $fields, $fieldname);
502 // This is something that shouldn't happen at all.
503 if (in_array($type, array("status_message", "reshare", "profile")))
504 if ($msg["author"] != $fields->author) {
505 logger("Message handle is not the same as envelope sender. Quitting this message.");
509 // Only some message types have signatures. So we quit here for the other types.
510 if (!in_array($type, array("comment", "message", "like")))
513 // No author_signature? This is a must, so we quit.
514 if (!isset($author_signature)) {
515 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
519 if (isset($parent_author_signature)) {
520 $key = self::key($msg["author"]);
522 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
523 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);
528 $key = self::key($fields->author);
530 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
531 logger("No valid author signature for author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
538 * @brief Fetches the public key for a given handle
540 * @param string $handle The handle
542 * @return string The public key
544 private function key($handle) {
545 $handle = strval($handle);
547 logger("Fetching diaspora key for: ".$handle);
549 $r = self::person_by_handle($handle);
557 * @brief Fetches data for a given handle
559 * @param string $handle The handle
561 * @return array the queried data
563 private function person_by_handle($handle) {
565 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
566 dbesc(NETWORK_DIASPORA),
571 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
573 // update record occasionally so it doesn't get stale
574 $d = strtotime($person["updated"]." +00:00");
575 if ($d < strtotime("now - 14 days"))
578 if ($person["guid"] == "")
582 if (!$person OR $update) {
583 logger("create or refresh", LOGGER_DEBUG);
584 $r = probe_url($handle, PROBE_DIASPORA);
586 // Note that Friendica contacts will return a "Diaspora person"
587 // if Diaspora connectivity is enabled on their server
588 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
589 self::add_fcontact($r, $update);
597 * @brief Updates the fcontact table
599 * @param array $arr The fcontact data
600 * @param bool $update Update or insert?
602 * @return string The id of the fcontact entry
604 private function add_fcontact($arr, $update = false) {
607 $r = q("UPDATE `fcontact` SET
621 WHERE `url` = '%s' AND `network` = '%s'",
623 dbesc($arr["photo"]),
624 dbesc($arr["request"]),
626 dbesc(strtolower($arr["addr"])),
628 dbesc($arr["batch"]),
629 dbesc($arr["notify"]),
631 dbesc($arr["confirm"]),
632 dbesc($arr["alias"]),
633 dbesc($arr["pubkey"]),
634 dbesc(datetime_convert()),
636 dbesc($arr["network"])
639 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
640 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
641 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
644 dbesc($arr["photo"]),
645 dbesc($arr["request"]),
649 dbesc($arr["batch"]),
650 dbesc($arr["notify"]),
652 dbesc($arr["confirm"]),
653 dbesc($arr["network"]),
654 dbesc($arr["alias"]),
655 dbesc($arr["pubkey"]),
656 dbesc(datetime_convert())
664 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
666 * @param int $contact_id The id in the contact table
667 * @param int $gcontact_id The id in the gcontact table
669 * @return string the handle
671 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
674 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
676 if ($gcontact_id != 0) {
677 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
678 intval($gcontact_id));
680 return strtolower($r[0]["addr"]);
683 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
684 intval($contact_id));
688 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
690 if($contact['addr'] != "")
691 $handle = $contact['addr'];
693 $baseurl_start = strpos($contact['url'],'://') + 3;
694 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
695 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
696 $handle = $contact['nick'].'@'.$baseurl;
700 return strtolower($handle);
704 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora
705 * fcontact id or guid
707 * @param mixed $contact_id Either the numeric id or the string guid
709 * @return string the url
711 public static function url_from_fcontact($contact_id) {
714 logger("fcontact id is ".$contact_id, LOGGER_DEBUG);
716 if (is_numeric($contact_id)) {
717 $r = q("SELECT `url` FROM `fcontact` WHERE `id` = %d AND `network` = 'dspr' `url` != ''",
718 intval($contact_id));
720 $r = q("SELECT `url` FROM `fcontact` WHERE `guid` = '%s' AND `network` = 'dspr' AND `url` != ''",
731 * @brief Get a contact id for a given handle
733 * @param int $uid The user id
734 * @param string $handle The handle in the format user@domain.tld
736 * @return The contact id
738 private function contact_by_handle($uid, $handle) {
739 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
747 $handle_parts = explode("@", $handle);
748 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
749 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
761 * @brief Check if posting is allowed for this contact
763 * @param array $importer Array of the importer user
764 * @param array $contact The contact that is checked
765 * @param bool $is_comment Is the check for a comment?
767 * @return bool is the contact allowed to post?
769 private function post_allow($importer, $contact, $is_comment = false) {
771 // perhaps we were already sharing with this person. Now they're sharing with us.
772 // That makes us friends.
773 // Normally this should have handled by getting a request - but this could get lost
774 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
775 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
776 intval(CONTACT_IS_FRIEND),
777 intval($contact["id"]),
778 intval($importer["uid"])
780 $contact["rel"] = CONTACT_IS_FRIEND;
781 logger("defining user ".$contact["nick"]." as friend");
784 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
786 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
788 if($contact["rel"] == CONTACT_IS_FOLLOWER)
789 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
792 // Messages for the global users are always accepted
793 if ($importer["uid"] == 0)
800 * @brief Fetches the contact id for a handle and checks if posting is allowed
802 * @param array $importer Array of the importer user
803 * @param string $handle The checked handle in the format user@domain.tld
804 * @param bool $is_comment Is the check for a comment?
806 * @return array The contact data
808 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
809 $contact = self::contact_by_handle($importer["uid"], $handle);
811 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
815 if (!self::post_allow($importer, $contact, $is_comment)) {
816 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
823 * @brief Does the message already exists on the system?
825 * @param int $uid The user id
826 * @param string $guid The guid of the message
828 * @return int|bool message id if the message already was stored into the system - or false.
830 private function message_exists($uid, $guid) {
831 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
837 logger("message ".$guid." already exists for user ".$uid);
845 * @brief Checks for links to posts in a message
847 * @param array $item The item array
849 private function fetch_guid($item) {
850 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
851 function ($match) use ($item){
852 return(self::fetch_guid_sub($match, $item));
857 * @brief Checks for relative /people/* links to match local contacts or
858 * prepends the remote host taken from the author link
860 * @param string $body The item body to replace links from
861 * @param string $author_link The author link for missing local contact fallback
863 public function replace_people_guid($body, $author_link) {
864 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
865 function ($match) use ($author_link){
867 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
868 // 1 => '0123456789abcdef'
870 $handle = self::url_from_fcontact($match[1]);
873 $return = '@[url='.$handle.']'.$match[2].'[/url]';
875 // No local match, restoring absolute remote URL from author scheme and host
876 $author_url = parse_url($author_link);
877 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
888 * @brief sub function of "fetch_guid" which checks for links in messages
890 * @param array $match array containing a link that has to be checked for a message link
891 * @param array $item The item array
893 private function fetch_guid_sub($match, $item) {
894 if (!self::store_by_guid($match[1], $item["author-link"]))
895 self::store_by_guid($match[1], $item["owner-link"]);
899 * @brief Fetches an item with a given guid from a given server
901 * @param string $guid the message guid
902 * @param string $server The server address
903 * @param int $uid The user id of the user
905 * @return int the message id of the stored message or false
907 private function store_by_guid($guid, $server, $uid = 0) {
908 $serverparts = parse_url($server);
909 $server = $serverparts["scheme"]."://".$serverparts["host"];
911 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
913 $msg = self::message($guid, $server);
918 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
920 // Now call the dispatcher
921 return self::dispatch_public($msg);
925 * @brief Fetches a message from a server
927 * @param string $guid message guid
928 * @param string $server The url of the server
929 * @param int $level Endless loop prevention
932 * 'message' => The message XML
933 * 'author' => The author handle
934 * 'key' => The public key of the author
936 private function message($guid, $server, $level = 0) {
941 // This will work for new Diaspora servers and Friendica servers from 3.5
942 $source_url = $server."/fetch/post/".$guid;
943 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
945 $envelope = fetch_url($source_url);
947 logger("Envelope was fetched.", LOGGER_DEBUG);
948 $x = self::verify_magic_envelope($envelope);
950 logger("Envelope could not be verified.", LOGGER_DEBUG);
952 logger("Envelope was verified.", LOGGER_DEBUG);
956 // This will work for older Diaspora and Friendica servers
958 $source_url = $server."/p/".$guid.".xml";
959 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
961 $x = fetch_url($source_url);
966 $source_xml = parse_xml_string($x, false);
968 if (!is_object($source_xml))
971 if ($source_xml->post->reshare) {
972 // Reshare of a reshare - old Diaspora version
973 logger("Message is a reshare", LOGGER_DEBUG);
974 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
975 } elseif ($source_xml->getName() == "reshare") {
976 // Reshare of a reshare - new Diaspora version
977 logger("Message is a new reshare", LOGGER_DEBUG);
978 return self::message($source_xml->root_guid, $server, ++$level);
983 // Fetch the author - for the old and the new Diaspora version
984 if ($source_xml->post->status_message->diaspora_handle)
985 $author = (string)$source_xml->post->status_message->diaspora_handle;
986 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
987 $author = (string)$source_xml->author;
989 // If this isn't a "status_message" then quit
991 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
995 $msg = array("message" => $x, "author" => $author);
997 $msg["key"] = self::key($msg["author"]);
1003 * @brief Fetches the item record of a given guid
1005 * @param int $uid The user id
1006 * @param string $guid message guid
1007 * @param string $author The handle of the item
1008 * @param array $contact The contact of the item owner
1010 * @return array the item record
1012 private function parent_item($uid, $guid, $author, $contact) {
1013 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1014 `author-name`, `author-link`, `author-avatar`,
1015 `owner-name`, `owner-link`, `owner-avatar`
1016 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1017 intval($uid), dbesc($guid));
1020 $result = self::store_by_guid($guid, $contact["url"], $uid);
1023 $person = self::person_by_handle($author);
1024 $result = self::store_by_guid($guid, $person["url"], $uid);
1028 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1030 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1031 `author-name`, `author-link`, `author-avatar`,
1032 `owner-name`, `owner-link`, `owner-avatar`
1033 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1034 intval($uid), dbesc($guid));
1039 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1042 logger("parent item found: parent: ".$guid." - user: ".$uid);
1048 * @brief returns contact details
1050 * @param array $contact The default contact if the person isn't found
1051 * @param array $person The record of the person
1052 * @param int $uid The user id
1055 * 'cid' => contact id
1056 * 'network' => network type
1058 private function author_contact_by_url($contact, $person, $uid) {
1060 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1061 dbesc(normalise_link($person["url"])), intval($uid));
1064 $network = $r[0]["network"];
1066 // We are receiving content from a user that is about to be terminated
1067 // This means the user is vital, so we remove a possible termination date.
1068 unmark_for_death($contact);
1070 $cid = $contact["id"];
1071 $network = NETWORK_DIASPORA;
1074 return array("cid" => $cid, "network" => $network);
1078 * @brief Is the profile a hubzilla profile?
1080 * @param string $url The profile link
1082 * @return bool is it a hubzilla server?
1084 public static function is_redmatrix($url) {
1085 return(strstr($url, "/channel/"));
1089 * @brief Generate a post link with a given handle and message guid
1091 * @param string $addr The user handle
1092 * @param string $guid message guid
1094 * @return string the post link
1096 private function plink($addr, $guid) {
1097 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1101 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1103 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1104 // So we try another way as well.
1105 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1107 $r[0]["network"] = $s[0]["network"];
1109 if ($r[0]["network"] == NETWORK_DFRN)
1110 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1112 if (self::is_redmatrix($r[0]["url"]))
1113 return $r[0]["url"]."/?f=&mid=".$guid;
1115 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1119 * @brief Processes an account deletion
1121 * @param array $importer Array of the importer user
1122 * @param object $data The message object
1124 * @return bool Success
1126 private function receive_account_deletion($importer, $data) {
1128 /// @todo Account deletion should remove the contact from the global contacts as well
1130 $author = notags(unxmlify($data->author));
1132 $contact = self::contact_by_handle($importer["uid"], $author);
1134 logger("cannot find contact for author: ".$author);
1138 // We now remove the contact
1139 contact_remove($contact["id"]);
1144 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1146 * @param string $author Author handle
1147 * @param string $guid Message guid
1149 * @return string The constructed uri or the one from our database
1151 private function get_uri_from_guid($author, $guid) {
1153 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1155 return $r[0]["uri"];
1157 return $author.":".$guid;
1161 * @brief Processes an incoming comment
1163 * @param array $importer Array of the importer user
1164 * @param string $sender The sender of the message
1165 * @param object $data The message object
1166 * @param string $xml The original XML of the message
1168 * @return int The message id of the generated comment or "false" if there was an error
1170 private function receive_comment($importer, $sender, $data, $xml) {
1171 $guid = notags(unxmlify($data->guid));
1172 $parent_guid = notags(unxmlify($data->parent_guid));
1173 $text = unxmlify($data->text);
1174 $author = notags(unxmlify($data->author));
1176 if (isset($data->created_at))
1177 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1179 $created_at = datetime_convert();
1181 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1185 $message_id = self::message_exists($importer["uid"], $guid);
1189 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1193 $person = self::person_by_handle($author);
1194 if (!is_array($person)) {
1195 logger("unable to find author details");
1199 // Fetch the contact id - if we know this contact
1200 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1202 $datarray = array();
1204 $datarray["uid"] = $importer["uid"];
1205 $datarray["contact-id"] = $author_contact["cid"];
1206 $datarray["network"] = $author_contact["network"];
1208 $datarray["author-name"] = $person["name"];
1209 $datarray["author-link"] = $person["url"];
1210 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1212 $datarray["owner-name"] = $contact["name"];
1213 $datarray["owner-link"] = $contact["url"];
1214 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1216 $datarray["guid"] = $guid;
1217 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1219 $datarray["type"] = "remote-comment";
1220 $datarray["verb"] = ACTIVITY_POST;
1221 $datarray["gravity"] = GRAVITY_COMMENT;
1222 $datarray["parent-uri"] = $parent_item["uri"];
1224 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1225 $datarray["object"] = $xml;
1227 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1229 $datarray["body"] = diaspora2bb($text);
1231 $datarray["body"] = self::replace_people_gui($datarray);
1233 self::fetch_guid($datarray);
1235 $message_id = item_store($datarray);
1238 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1240 // If we are the origin of the parent we store the original data and notify our followers
1241 if($message_id AND $parent_item["origin"]) {
1243 // Formerly we stored the signed text, the signature and the author in different fields.
1244 // We now store the raw data so that we are more flexible.
1245 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1246 intval($message_id),
1247 dbesc(json_encode($data))
1251 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1258 * @brief processes and stores private messages
1260 * @param array $importer Array of the importer user
1261 * @param array $contact The contact of the message
1262 * @param object $data The message object
1263 * @param array $msg Array of the processed message, author handle and key
1264 * @param object $mesg The private message
1265 * @param array $conversation The conversation record to which this message belongs
1267 * @return bool "true" if it was successful
1269 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1270 $guid = notags(unxmlify($data->guid));
1271 $subject = notags(unxmlify($data->subject));
1272 $author = notags(unxmlify($data->author));
1276 $msg_guid = notags(unxmlify($mesg->guid));
1277 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1278 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1279 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1280 $msg_text = unxmlify($mesg->text);
1281 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1283 // "diaspora_handle" is the element name from the old version
1284 // "author" is the element name from the new version
1286 $msg_author = notags(unxmlify($mesg->author));
1287 elseif ($mesg->diaspora_handle)
1288 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1292 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1294 if($msg_conversation_guid != $guid) {
1295 logger("message conversation guid does not belong to the current conversation.");
1299 $body = diaspora2bb($msg_text);
1300 $message_uri = $msg_author.":".$msg_guid;
1302 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1304 $author_signature = base64_decode($msg_author_signature);
1306 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1310 $person = self::person_by_handle($msg_author);
1312 if (is_array($person) && x($person, "pubkey"))
1313 $key = $person["pubkey"];
1315 logger("unable to find author details");
1320 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1321 logger("verification failed.");
1325 if($msg_parent_author_signature) {
1326 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1328 $parent_author_signature = base64_decode($msg_parent_author_signature);
1332 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1333 logger("owner verification failed.");
1338 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1342 logger("duplicate message already delivered.", LOGGER_DEBUG);
1346 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1347 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1348 intval($importer["uid"]),
1350 intval($conversation["id"]),
1351 dbesc($person["name"]),
1352 dbesc($person["photo"]),
1353 dbesc($person["url"]),
1354 intval($contact["id"]),
1359 dbesc($message_uri),
1360 dbesc($author.":".$guid),
1361 dbesc($msg_created_at)
1364 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1365 dbesc(datetime_convert()),
1366 intval($conversation["id"])
1370 "type" => NOTIFY_MAIL,
1371 "notify_flags" => $importer["notify-flags"],
1372 "language" => $importer["language"],
1373 "to_name" => $importer["username"],
1374 "to_email" => $importer["email"],
1375 "uid" =>$importer["uid"],
1376 "item" => array("subject" => $subject, "body" => $body),
1377 "source_name" => $person["name"],
1378 "source_link" => $person["url"],
1379 "source_photo" => $person["thumb"],
1380 "verb" => ACTIVITY_POST,
1387 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1389 * @param array $importer Array of the importer user
1390 * @param array $msg Array of the processed message, author handle and key
1391 * @param object $data The message object
1393 * @return bool Success
1395 private function receive_conversation($importer, $msg, $data) {
1396 $guid = notags(unxmlify($data->guid));
1397 $subject = notags(unxmlify($data->subject));
1398 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1399 $author = notags(unxmlify($data->author));
1400 $participants = notags(unxmlify($data->participants));
1402 $messages = $data->message;
1404 if (!count($messages)) {
1405 logger("empty conversation");
1409 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1413 $conversation = null;
1415 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1416 intval($importer["uid"]),
1420 $conversation = $c[0];
1422 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1423 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1424 intval($importer["uid"]),
1428 dbesc(datetime_convert()),
1430 dbesc($participants)
1433 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1434 intval($importer["uid"]),
1439 $conversation = $c[0];
1441 if (!$conversation) {
1442 logger("unable to create conversation.");
1446 foreach($messages as $mesg)
1447 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1453 * @brief Creates the body for a "like" message
1455 * @param array $contact The contact that send us the "like"
1456 * @param array $parent_item The item array of the parent item
1457 * @param string $guid message guid
1459 * @return string the body
1461 private function construct_like_body($contact, $parent_item, $guid) {
1462 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1464 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1465 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1466 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1468 return sprintf($bodyverb, $ulink, $alink, $plink);
1472 * @brief Creates a XML object for a "like"
1474 * @param array $importer Array of the importer user
1475 * @param array $parent_item The item array of the parent item
1477 * @return string The XML
1479 private function construct_like_object($importer, $parent_item) {
1480 $objtype = ACTIVITY_OBJ_NOTE;
1481 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1482 $parent_body = $parent_item["body"];
1484 $xmldata = array("object" => array("type" => $objtype,
1486 "id" => $parent_item["uri"],
1489 "content" => $parent_body));
1491 return xml::from_array($xmldata, $xml, true);
1495 * @brief Processes "like" messages
1497 * @param array $importer Array of the importer user
1498 * @param string $sender The sender of the message
1499 * @param object $data The message object
1501 * @return int The message id of the generated like or "false" if there was an error
1503 private function receive_like($importer, $sender, $data) {
1504 $positive = notags(unxmlify($data->positive));
1505 $guid = notags(unxmlify($data->guid));
1506 $parent_type = notags(unxmlify($data->parent_type));
1507 $parent_guid = notags(unxmlify($data->parent_guid));
1508 $author = notags(unxmlify($data->author));
1510 // likes on comments aren't supported by Diaspora - only on posts
1511 // But maybe this will be supported in the future, so we will accept it.
1512 if (!in_array($parent_type, array("Post", "Comment")))
1515 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1519 $message_id = self::message_exists($importer["uid"], $guid);
1523 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1527 $person = self::person_by_handle($author);
1528 if (!is_array($person)) {
1529 logger("unable to find author details");
1533 // Fetch the contact id - if we know this contact
1534 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1536 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1537 // We would accept this anyhow.
1538 if ($positive == "true")
1539 $verb = ACTIVITY_LIKE;
1541 $verb = ACTIVITY_DISLIKE;
1543 $datarray = array();
1545 $datarray["uid"] = $importer["uid"];
1546 $datarray["contact-id"] = $author_contact["cid"];
1547 $datarray["network"] = $author_contact["network"];
1549 $datarray["author-name"] = $person["name"];
1550 $datarray["author-link"] = $person["url"];
1551 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1553 $datarray["owner-name"] = $contact["name"];
1554 $datarray["owner-link"] = $contact["url"];
1555 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1557 $datarray["guid"] = $guid;
1558 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1560 $datarray["type"] = "activity";
1561 $datarray["verb"] = $verb;
1562 $datarray["gravity"] = GRAVITY_LIKE;
1563 $datarray["parent-uri"] = $parent_item["uri"];
1565 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1566 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1568 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1570 $message_id = item_store($datarray);
1573 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1575 // If we are the origin of the parent we store the original data and notify our followers
1576 if($message_id AND $parent_item["origin"]) {
1578 // Formerly we stored the signed text, the signature and the author in different fields.
1579 // We now store the raw data so that we are more flexible.
1580 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1581 intval($message_id),
1582 dbesc(json_encode($data))
1586 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1593 * @brief Processes private messages
1595 * @param array $importer Array of the importer user
1596 * @param object $data The message object
1598 * @return bool Success?
1600 private function receive_message($importer, $data) {
1601 $guid = notags(unxmlify($data->guid));
1602 $parent_guid = notags(unxmlify($data->parent_guid));
1603 $text = unxmlify($data->text);
1604 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1605 $author = notags(unxmlify($data->author));
1606 $conversation_guid = notags(unxmlify($data->conversation_guid));
1608 $contact = self::allowed_contact_by_handle($importer, $author, true);
1612 $conversation = null;
1614 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1615 intval($importer["uid"]),
1616 dbesc($conversation_guid)
1619 $conversation = $c[0];
1621 logger("conversation not available.");
1627 $body = self::replace_people_guid(diaspora2bb($text), $person["url"]);
1629 $message_uri = $author.":".$guid;
1631 $person = self::person_by_handle($author);
1633 logger("unable to find author details");
1637 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1638 dbesc($message_uri),
1639 intval($importer["uid"])
1642 logger("duplicate message already delivered.", LOGGER_DEBUG);
1646 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1647 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1648 intval($importer["uid"]),
1650 intval($conversation["id"]),
1651 dbesc($person["name"]),
1652 dbesc($person["photo"]),
1653 dbesc($person["url"]),
1654 intval($contact["id"]),
1655 dbesc($conversation["subject"]),
1659 dbesc($message_uri),
1660 dbesc($author.":".$parent_guid),
1664 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1665 dbesc(datetime_convert()),
1666 intval($conversation["id"])
1673 * @brief Processes participations - unsupported by now
1675 * @param array $importer Array of the importer user
1676 * @param object $data The message object
1678 * @return bool always true
1680 private function receive_participation($importer, $data) {
1681 // I'm not sure if we can fully support this message type
1686 * @brief Processes photos - unneeded
1688 * @param array $importer Array of the importer user
1689 * @param object $data The message object
1691 * @return bool always true
1693 private function receive_photo($importer, $data) {
1694 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1699 * @brief Processes poll participations - unssupported
1701 * @param array $importer Array of the importer user
1702 * @param object $data The message object
1704 * @return bool always true
1706 private function receive_poll_participation($importer, $data) {
1707 // We don't support polls by now
1712 * @brief Processes incoming profile updates
1714 * @param array $importer Array of the importer user
1715 * @param object $data The message object
1717 * @return bool Success
1719 private function receive_profile($importer, $data) {
1720 $author = strtolower(notags(unxmlify($data->author)));
1722 $contact = self::contact_by_handle($importer["uid"], $author);
1726 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1727 $image_url = unxmlify($data->image_url);
1728 $birthday = unxmlify($data->birthday);
1729 $location = diaspora2bb(unxmlify($data->location));
1730 $about = diaspora2bb(unxmlify($data->bio));
1731 $gender = unxmlify($data->gender);
1732 $searchable = (unxmlify($data->searchable) == "true");
1733 $nsfw = (unxmlify($data->nsfw) == "true");
1734 $tags = unxmlify($data->tag_string);
1736 $tags = explode("#", $tags);
1738 $keywords = array();
1739 foreach ($tags as $tag) {
1740 $tag = trim(strtolower($tag));
1745 $keywords = implode(", ", $keywords);
1747 $handle_parts = explode("@", $author);
1748 $nick = $handle_parts[0];
1751 $name = $handle_parts[0];
1753 if( preg_match("|^https?://|", $image_url) === 0)
1754 $image_url = "http://".$handle_parts[1].$image_url;
1756 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1758 // Generic birthday. We don't know the timezone. The year is irrelevant.
1760 $birthday = str_replace("1000", "1901", $birthday);
1762 if ($birthday != "")
1763 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1765 // this is to prevent multiple birthday notifications in a single year
1766 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1768 if(substr($birthday,5) === substr($contact["bd"],5))
1769 $birthday = $contact["bd"];
1771 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1772 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1776 dbesc(datetime_convert()),
1782 intval($contact["id"]),
1783 intval($importer["uid"])
1787 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1788 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1791 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1792 "photo" => $image_url, "name" => $name, "location" => $location,
1793 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1794 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1795 "hide" => !$searchable, "nsfw" => $nsfw);
1797 update_gcontact($gcontact);
1799 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1805 * @brief Processes incoming friend requests
1807 * @param array $importer Array of the importer user
1808 * @param array $contact The contact that send the request
1810 private function receive_request_make_friend($importer, $contact) {
1814 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1815 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1816 intval(CONTACT_IS_FRIEND),
1817 intval($contact["id"]),
1818 intval($importer["uid"])
1821 // send notification
1823 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1824 intval($importer["uid"])
1827 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1829 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1830 intval($importer["uid"])
1833 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1835 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1838 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1839 $arr["uid"] = $importer["uid"];
1840 $arr["contact-id"] = $self[0]["id"];
1842 $arr["type"] = 'wall';
1843 $arr["gravity"] = 0;
1845 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1846 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1847 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1848 $arr["verb"] = ACTIVITY_FRIEND;
1849 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1851 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1852 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1853 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1854 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1856 $arr["object"] = self::construct_new_friend_object($contact);
1858 $arr["last-child"] = 1;
1860 $arr["allow_cid"] = $user[0]["allow_cid"];
1861 $arr["allow_gid"] = $user[0]["allow_gid"];
1862 $arr["deny_cid"] = $user[0]["deny_cid"];
1863 $arr["deny_gid"] = $user[0]["deny_gid"];
1865 $i = item_store($arr);
1867 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1873 * @brief Creates a XML object for a "new friend" message
1875 * @param array $contact Array of the contact
1877 * @return string The XML
1879 private function construct_new_friend_object($contact) {
1880 $objtype = ACTIVITY_OBJ_PERSON;
1881 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1882 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1884 $xmldata = array("object" => array("type" => $objtype,
1885 "title" => $contact["name"],
1886 "id" => $contact["url"]."/".$contact["name"],
1889 return xml::from_array($xmldata, $xml, true);
1893 * @brief Processes incoming sharing notification
1895 * @param array $importer Array of the importer user
1896 * @param object $data The message object
1898 * @return bool Success
1900 private function receive_contact_request($importer, $data) {
1901 $author = unxmlify($data->author);
1902 $recipient = unxmlify($data->recipient);
1904 if (!$author || !$recipient)
1907 // the current protocol version doesn't know these fields
1908 // That means that we will assume their existance
1909 if (isset($data->following))
1910 $following = (unxmlify($data->following) == "true");
1914 if (isset($data->sharing))
1915 $sharing = (unxmlify($data->sharing) == "true");
1919 $contact = self::contact_by_handle($importer["uid"],$author);
1921 // perhaps we were already sharing with this person. Now they're sharing with us.
1922 // That makes us friends.
1924 if ($following AND $sharing) {
1925 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1926 self::receive_request_make_friend($importer, $contact);
1928 // refetch the contact array
1929 $contact = self::contact_by_handle($importer["uid"],$author);
1931 // If we are now friends, we are sending a share message.
1932 // Normally we needn't to do so, but the first message could have been vanished.
1933 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1934 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1936 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
1937 $ret = self::send_share($u[0], $contact);
1941 } else { /// @todo Handle all possible variations of adding and retracting of permissions
1942 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
1947 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1948 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1950 } elseif (!$following AND !$sharing) {
1951 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1953 } elseif (!$following AND $sharing) {
1954 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
1955 } elseif ($following AND $sharing) {
1956 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
1957 } elseif ($following AND !$sharing) {
1958 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
1961 $ret = self::person_by_handle($author);
1963 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1964 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1968 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1970 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1971 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1972 intval($importer["uid"]),
1973 dbesc($ret["network"]),
1974 dbesc($ret["addr"]),
1977 dbesc(normalise_link($ret["url"])),
1979 dbesc($ret["name"]),
1980 dbesc($ret["nick"]),
1981 dbesc($ret["photo"]),
1982 dbesc($ret["pubkey"]),
1983 dbesc($ret["notify"]),
1984 dbesc($ret["poll"]),
1989 // find the contact record we just created
1991 $contact_record = self::contact_by_handle($importer["uid"],$author);
1993 if (!$contact_record) {
1994 logger("unable to locate newly created contact record.");
1998 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2000 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2002 if(intval($def_gid))
2003 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2005 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2007 if($importer["page-flags"] == PAGE_NORMAL) {
2009 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2011 $hash = random_string().(string)time(); // Generate a confirm_key
2013 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2014 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2015 intval($importer["uid"]),
2016 intval($contact_record["id"]),
2019 dbesc(t("Sharing notification from Diaspora network")),
2021 dbesc(datetime_convert())
2025 // automatic friend approval
2027 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2029 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2031 // technically they are sharing with us (CONTACT_IS_SHARING),
2032 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2033 // we are going to change the relationship and make them a follower.
2035 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2036 $new_relation = CONTACT_IS_FRIEND;
2037 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2038 $new_relation = CONTACT_IS_SHARING;
2040 $new_relation = CONTACT_IS_FOLLOWER;
2042 $r = q("UPDATE `contact` SET `rel` = %d,
2050 intval($new_relation),
2051 dbesc(datetime_convert()),
2052 dbesc(datetime_convert()),
2053 intval($contact_record["id"])
2056 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2058 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2059 $ret = self::send_share($u[0], $contact_record);
2061 // Send the profile data, maybe it weren't transmitted before
2062 self::send_profile($importer["uid"], array($contact_record));
2070 * @brief Fetches a message with a given guid
2072 * @param string $guid message guid
2073 * @param string $orig_author handle of the original post
2074 * @param string $author handle of the sharer
2076 * @return array The fetched item
2078 private function original_item($guid, $orig_author, $author) {
2080 // Do we already have this item?
2081 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2082 `author-name`, `author-link`, `author-avatar`
2083 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2087 logger("reshared message ".$guid." already exists on system.");
2089 // Maybe it is already a reshared item?
2090 // Then refetch the content, if it is a reshare from a reshare.
2091 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2092 if (self::is_reshare($r[0]["body"], true))
2094 elseif (self::is_reshare($r[0]["body"], false)) {
2095 $r[0]["body"] = self::replace_people_guid(diaspora2bb(bb2diaspora($r[0]["body"])), $r[0]["author-link"]);
2097 // Add OEmbed and other information to the body
2098 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2106 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2107 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2108 $item_id = self::store_by_guid($guid, $server);
2111 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2112 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2113 $item_id = self::store_by_guid($guid, $server);
2117 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2118 `author-name`, `author-link`, `author-avatar`
2119 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2123 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2124 if (self::is_reshare($r[0]["body"], false)) {
2125 $r[0]["body"] = self::replace_people_guid(diaspora2bb(bb2diaspora($r[0]["body"])), $r[0]["author-link"]);
2137 * @brief Processes a reshare message
2139 * @param array $importer Array of the importer user
2140 * @param object $data The message object
2141 * @param string $xml The original XML of the message
2143 * @return int the message id
2145 private function receive_reshare($importer, $data, $xml) {
2146 $root_author = notags(unxmlify($data->root_author));
2147 $root_guid = notags(unxmlify($data->root_guid));
2148 $guid = notags(unxmlify($data->guid));
2149 $author = notags(unxmlify($data->author));
2150 $public = notags(unxmlify($data->public));
2151 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2153 $contact = self::allowed_contact_by_handle($importer, $author, false);
2157 $message_id = self::message_exists($importer["uid"], $guid);
2161 $original_item = self::original_item($root_guid, $root_author, $author);
2162 if (!$original_item)
2165 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2167 $datarray = array();
2169 $datarray["uid"] = $importer["uid"];
2170 $datarray["contact-id"] = $contact["id"];
2171 $datarray["network"] = NETWORK_DIASPORA;
2173 $datarray["author-name"] = $contact["name"];
2174 $datarray["author-link"] = $contact["url"];
2175 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2177 $datarray["owner-name"] = $datarray["author-name"];
2178 $datarray["owner-link"] = $datarray["author-link"];
2179 $datarray["owner-avatar"] = $datarray["author-avatar"];
2181 $datarray["guid"] = $guid;
2182 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2184 $datarray["verb"] = ACTIVITY_POST;
2185 $datarray["gravity"] = GRAVITY_PARENT;
2187 $datarray["object"] = $xml;
2189 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2190 $original_item["guid"], $original_item["created"], $orig_url);
2191 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2193 $datarray["tag"] = $original_item["tag"];
2194 $datarray["app"] = $original_item["app"];
2196 $datarray["plink"] = self::plink($author, $guid);
2197 $datarray["private"] = (($public == "false") ? 1 : 0);
2198 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2200 $datarray["object-type"] = $original_item["object-type"];
2202 self::fetch_guid($datarray);
2203 $message_id = item_store($datarray);
2206 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2212 * @brief Processes retractions
2214 * @param array $importer Array of the importer user
2215 * @param array $contact The contact of the item owner
2216 * @param object $data The message object
2218 * @return bool success
2220 private function item_retraction($importer, $contact, $data) {
2221 $target_type = notags(unxmlify($data->target_type));
2222 $target_guid = notags(unxmlify($data->target_guid));
2223 $author = notags(unxmlify($data->author));
2225 $person = self::person_by_handle($author);
2226 if (!is_array($person)) {
2227 logger("unable to find author detail for ".$author);
2231 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2232 dbesc($target_guid),
2233 intval($importer["uid"])
2238 // Check if the sender is the thread owner
2239 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2240 intval($r[0]["parent"]));
2242 // Only delete it if the parent author really fits
2243 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2244 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2248 // 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
2249 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2250 dbesc(datetime_convert()),
2251 dbesc(datetime_convert()),
2254 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2256 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2258 // Now check if the retraction needs to be relayed by us
2259 if($p[0]["origin"]) {
2261 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2268 * @brief Receives retraction messages
2270 * @param array $importer Array of the importer user
2271 * @param string $sender The sender of the message
2272 * @param object $data The message object
2274 * @return bool Success
2276 private function receive_retraction($importer, $sender, $data) {
2277 $target_type = notags(unxmlify($data->target_type));
2279 $contact = self::contact_by_handle($importer["uid"], $sender);
2281 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2285 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2287 switch ($target_type) {
2290 case "Post": // "Post" will be supported in a future version
2292 case "StatusMessage":
2293 return self::item_retraction($importer, $contact, $data);;
2297 /// @todo What should we do with an "unshare"?
2298 // Removing the contact isn't correct since we still can read the public items
2299 contact_remove($contact["id"]);
2303 logger("Unknown target type ".$target_type);
2310 * @brief Receives status messages
2312 * @param array $importer Array of the importer user
2313 * @param object $data The message object
2314 * @param string $xml The original XML of the message
2316 * @return int The message id of the newly created item
2318 private function receive_status_message($importer, $data, $xml) {
2319 $raw_message = unxmlify($data->raw_message);
2320 $guid = notags(unxmlify($data->guid));
2321 $author = notags(unxmlify($data->author));
2322 $public = notags(unxmlify($data->public));
2323 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2324 $provider_display_name = notags(unxmlify($data->provider_display_name));
2326 /// @todo enable support for polls
2327 //if ($data->poll) {
2328 // foreach ($data->poll AS $poll)
2332 $contact = self::allowed_contact_by_handle($importer, $author, false);
2336 $message_id = self::message_exists($importer["uid"], $guid);
2341 if ($data->location)
2342 foreach ($data->location->children() AS $fieldname => $data)
2343 $address[$fieldname] = notags(unxmlify($data));
2345 $body = diaspora2bb($raw_message);
2347 $datarray = array();
2349 // Attach embedded pictures to the body
2351 foreach ($data->photo AS $photo)
2352 $body = "[img]".unxmlify($photo->remote_photo_path).
2353 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2355 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2357 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2359 // Add OEmbed and other information to the body
2360 if (!self::is_redmatrix($contact["url"]))
2361 $body = add_page_info_to_body($body, false, true);
2364 $datarray["uid"] = $importer["uid"];
2365 $datarray["contact-id"] = $contact["id"];
2366 $datarray["network"] = NETWORK_DIASPORA;
2368 $datarray["author-name"] = $contact["name"];
2369 $datarray["author-link"] = $contact["url"];
2370 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2372 $datarray["owner-name"] = $datarray["author-name"];
2373 $datarray["owner-link"] = $datarray["author-link"];
2374 $datarray["owner-avatar"] = $datarray["author-avatar"];
2376 $datarray["guid"] = $guid;
2377 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2379 $datarray["verb"] = ACTIVITY_POST;
2380 $datarray["gravity"] = GRAVITY_PARENT;
2382 $datarray["object"] = $xml;
2384 $datarray["body"] = self::replace_people_guid($body, $datarray["author-link"]);
2386 if ($provider_display_name != "")
2387 $datarray["app"] = $provider_display_name;
2389 $datarray["plink"] = self::plink($author, $guid);
2390 $datarray["private"] = (($public == "false") ? 1 : 0);
2391 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2393 if (isset($address["address"]))
2394 $datarray["location"] = $address["address"];
2396 if (isset($address["lat"]) AND isset($address["lng"]))
2397 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2399 self::fetch_guid($datarray);
2400 $message_id = item_store($datarray);
2403 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2408 /* ************************************************************************************** *
2409 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2410 * ************************************************************************************** */
2413 * @brief returnes the handle of a contact
2415 * @param array $me contact array
2417 * @return string the handle in the format user@domain.tld
2419 private function my_handle($contact) {
2420 if ($contact["addr"] != "")
2421 return $contact["addr"];
2423 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2424 // So - just in case - we build the the address here.
2425 if ($contact["nickname"] != "")
2426 $nick = $contact["nickname"];
2428 $nick = $contact["nick"];
2430 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2434 * @brief Creates the envelope for the "fetch" endpoint
2436 * @param string $msg The message that is to be transmitted
2437 * @param array $user The record of the sender
2439 * @return string The envelope
2442 public static function build_magic_envelope($msg, $user) {
2444 $b64url_data = base64url_encode($msg);
2445 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2447 $key_id = base64url_encode(self::my_handle($user));
2448 $type = "application/xml";
2449 $encoding = "base64url";
2450 $alg = "RSA-SHA256";
2451 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2452 $signature = rsa_sign($signable_data, $user["prvkey"]);
2453 $sig = base64url_encode($signature);
2455 $xmldata = array("me:env" => array("me:data" => $data,
2456 "@attributes" => array("type" => $type),
2457 "me:encoding" => $encoding,
2460 "@attributes2" => array("key_id" => $key_id)));
2462 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2464 return xml::from_array($xmldata, $xml, false, $namespaces);
2468 * @brief Creates the envelope for a public message
2470 * @param string $msg The message that is to be transmitted
2471 * @param array $user The record of the sender
2472 * @param array $contact Target of the communication
2473 * @param string $prvkey The private key of the sender
2474 * @param string $pubkey The public key of the receiver
2476 * @return string The envelope
2478 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2480 logger("Message: ".$msg, LOGGER_DATA);
2482 $handle = self::my_handle($user);
2484 $b64url_data = base64url_encode($msg);
2486 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2488 $type = "application/xml";
2489 $encoding = "base64url";
2490 $alg = "RSA-SHA256";
2492 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2494 $signature = rsa_sign($signable_data,$prvkey);
2495 $sig = base64url_encode($signature);
2497 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2498 "me:env" => array("me:encoding" => $encoding,
2501 "@attributes" => array("type" => $type),
2502 "me:sig" => $sig)));
2504 $namespaces = array("" => "https://joindiaspora.com/protocol",
2505 "me" => "http://salmon-protocol.org/ns/magic-env");
2507 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2509 logger("magic_env: ".$magic_env, LOGGER_DATA);
2514 * @brief Creates the envelope for a private message
2516 * @param string $msg The message that is to be transmitted
2517 * @param array $user The record of the sender
2518 * @param array $contact Target of the communication
2519 * @param string $prvkey The private key of the sender
2520 * @param string $pubkey The public key of the receiver
2522 * @return string The envelope
2524 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2526 logger("Message: ".$msg, LOGGER_DATA);
2528 // without a public key nothing will work
2531 logger("pubkey missing: contact id: ".$contact["id"]);
2535 $inner_aes_key = random_string(32);
2536 $b_inner_aes_key = base64_encode($inner_aes_key);
2537 $inner_iv = random_string(16);
2538 $b_inner_iv = base64_encode($inner_iv);
2540 $outer_aes_key = random_string(32);
2541 $b_outer_aes_key = base64_encode($outer_aes_key);
2542 $outer_iv = random_string(16);
2543 $b_outer_iv = base64_encode($outer_iv);
2545 $handle = self::my_handle($user);
2547 $padded_data = pkcs5_pad($msg,16);
2548 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2550 $b64_data = base64_encode($inner_encrypted);
2553 $b64url_data = base64url_encode($b64_data);
2554 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2556 $type = "application/xml";
2557 $encoding = "base64url";
2558 $alg = "RSA-SHA256";
2560 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2562 $signature = rsa_sign($signable_data,$prvkey);
2563 $sig = base64url_encode($signature);
2565 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2566 "aes_key" => $b_inner_aes_key,
2567 "author_id" => $handle));
2569 $decrypted_header = xml::from_array($xmldata, $xml, true);
2570 $decrypted_header = pkcs5_pad($decrypted_header,16);
2572 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2574 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2576 $encrypted_outer_key_bundle = "";
2577 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2579 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2581 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2583 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2584 "ciphertext" => base64_encode($ciphertext)));
2585 $cipher_json = base64_encode($encrypted_header_json_object);
2587 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2588 "me:env" => array("me:encoding" => $encoding,
2591 "@attributes" => array("type" => $type),
2592 "me:sig" => $sig)));
2594 $namespaces = array("" => "https://joindiaspora.com/protocol",
2595 "me" => "http://salmon-protocol.org/ns/magic-env");
2597 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2599 logger("magic_env: ".$magic_env, LOGGER_DATA);
2604 * @brief Create the envelope for a message
2606 * @param string $msg The message that is to be transmitted
2607 * @param array $user The record of the sender
2608 * @param array $contact Target of the communication
2609 * @param string $prvkey The private key of the sender
2610 * @param string $pubkey The public key of the receiver
2611 * @param bool $public Is the message public?
2613 * @return string The message that will be transmitted to other servers
2615 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2618 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2620 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2622 // The data that will be transmitted is double encoded via "urlencode", strange ...
2623 $slap = "xml=".urlencode(urlencode($magic_env));
2628 * @brief Creates a signature for a message
2630 * @param array $owner the array of the owner of the message
2631 * @param array $message The message that is to be signed
2633 * @return string The signature
2635 private function signature($owner, $message) {
2637 unset($sigmsg["author_signature"]);
2638 unset($sigmsg["parent_author_signature"]);
2640 $signed_text = implode(";", $sigmsg);
2642 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2646 * @brief Transmit a message to a target server
2648 * @param array $owner the array of the item owner
2649 * @param array $contact Target of the communication
2650 * @param string $slap The message that is to be transmitted
2651 * @param bool $public_batch Is it a public post?
2652 * @param bool $queue_run Is the transmission called from the queue?
2653 * @param string $guid message guid
2655 * @return int Result of the transmission
2657 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2661 $enabled = intval(get_config("system", "diaspora_enabled"));
2665 $logid = random_string(4);
2666 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2668 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2672 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2674 if (!$queue_run && was_recently_delayed($contact["id"])) {
2677 if (!intval(get_config("system", "diaspora_test"))) {
2678 post_url($dest_url."/", $slap);
2679 $return_code = $a->get_curl_code();
2681 logger("test_mode");
2686 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2688 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2689 logger("queue message");
2691 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2692 intval($contact["id"]),
2693 dbesc(NETWORK_DIASPORA),
2695 intval($public_batch)
2698 logger("add_to_queue ignored - identical item already in queue");
2700 // queue message for redelivery
2701 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2703 // The message could not be delivered. We mark the contact as "dead"
2704 mark_for_death($contact);
2706 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2707 // We successfully delivered a message, the contact is alive
2708 unmark_for_death($contact);
2711 return(($return_code) ? $return_code : (-1));
2716 * @brief Build the post xml
2718 * @param string $type The message type
2719 * @param array $message The message data
2721 * @return string The post XML
2723 public static function build_post_xml($type, $message) {
2725 $data = array("XML" => array("post" => array($type => $message)));
2726 return xml::from_array($data, $xml);
2730 * @brief Builds and transmit messages
2732 * @param array $owner the array of the item owner
2733 * @param array $contact Target of the communication
2734 * @param string $type The message type
2735 * @param array $message The message data
2736 * @param bool $public_batch Is it a public post?
2737 * @param string $guid message guid
2738 * @param bool $spool Should the transmission be spooled or transmitted?
2740 * @return int Result of the transmission
2742 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2744 $msg = self::build_post_xml($type, $message);
2746 logger('message: '.$msg, LOGGER_DATA);
2747 logger('send guid '.$guid, LOGGER_DEBUG);
2749 // Fallback if the private key wasn't transmitted in the expected field
2750 if ($owner['uprvkey'] == "")
2751 $owner['uprvkey'] = $owner['prvkey'];
2753 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2756 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2759 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2761 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2763 return $return_code;
2767 * @brief Sends a "share" message
2769 * @param array $owner the array of the item owner
2770 * @param array $contact Target of the communication
2772 * @return int The result of the transmission
2774 public static function send_share($owner,$contact) {
2776 $message = array("sender_handle" => self::my_handle($owner),
2777 "recipient_handle" => $contact["addr"]);
2779 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2781 return self::build_and_transmit($owner, $contact, "request", $message);
2785 * @brief sends an "unshare"
2787 * @param array $owner the array of the item owner
2788 * @param array $contact Target of the communication
2790 * @return int The result of the transmission
2792 public static function send_unshare($owner,$contact) {
2794 $message = array("post_guid" => $owner["guid"],
2795 "diaspora_handle" => self::my_handle($owner),
2796 "type" => "Person");
2798 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2800 return self::build_and_transmit($owner, $contact, "retraction", $message);
2804 * @brief Checks a message body if it is a reshare
2806 * @param string $body The message body that is to be check
2807 * @param bool $complete Should it be a complete check or a simple check?
2809 * @return array|bool Reshare details or "false" if no reshare
2811 public static function is_reshare($body, $complete = true) {
2812 $body = trim($body);
2814 // Skip if it isn't a pure repeated messages
2815 // Does it start with a share?
2816 if ((strpos($body, "[share") > 0) AND $complete)
2819 // Does it end with a share?
2820 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2823 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2824 // Skip if there is no shared message in there
2825 if ($body == $attributes)
2828 // If we don't do the complete check we quit here
2833 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2834 if ($matches[1] != "")
2835 $guid = $matches[1];
2837 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2838 if ($matches[1] != "")
2839 $guid = $matches[1];
2842 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2843 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2846 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2847 $ret["root_guid"] = $guid;
2853 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2854 if ($matches[1] != "")
2855 $profile = $matches[1];
2857 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2858 if ($matches[1] != "")
2859 $profile = $matches[1];
2863 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2864 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2868 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2869 if ($matches[1] != "")
2870 $link = $matches[1];
2872 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2873 if ($matches[1] != "")
2874 $link = $matches[1];
2876 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2877 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2884 * @brief Create a post (status message or reshare)
2886 * @param array $item The item that will be exported
2887 * @param array $owner the array of the item owner
2890 * 'type' -> Message type ("status_message" or "reshare")
2891 * 'message' -> Array of XML elements of the status
2893 public static function build_status($item, $owner) {
2895 $myaddr = self::my_handle($owner);
2897 $public = (($item["private"]) ? "false" : "true");
2899 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2901 // Detect a share element and do a reshare
2902 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2903 $message = array("root_diaspora_id" => $ret["root_handle"],
2904 "root_guid" => $ret["root_guid"],
2905 "guid" => $item["guid"],
2906 "diaspora_handle" => $myaddr,
2907 "public" => $public,
2908 "created_at" => $created,
2909 "provider_display_name" => $item["app"]);
2913 $title = $item["title"];
2914 $body = $item["body"];
2916 // convert to markdown
2917 $body = html_entity_decode(bb2diaspora($body));
2921 $body = "## ".html_entity_decode($title)."\n\n".$body;
2923 if ($item["attach"]) {
2924 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2926 $body .= "\n".t("Attachments:")."\n";
2927 foreach($matches as $mtch)
2928 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2932 $location = array();
2934 if ($item["location"] != "")
2935 $location["address"] = $item["location"];
2937 if ($item["coord"] != "") {
2938 $coord = explode(" ", $item["coord"]);
2939 $location["lat"] = $coord[0];
2940 $location["lng"] = $coord[1];
2943 $message = array("raw_message" => $body,
2944 "location" => $location,
2945 "guid" => $item["guid"],
2946 "diaspora_handle" => $myaddr,
2947 "public" => $public,
2948 "created_at" => $created,
2949 "provider_display_name" => $item["app"]);
2951 // Diaspora rejects messages when they contain a location without "lat" or "lng"
2952 if (!isset($location["lat"]) OR !isset($location["lng"])) {
2953 unset($message["location"]);
2956 $type = "status_message";
2958 return array("type" => $type, "message" => $message);
2962 * @brief Sends a post
2964 * @param array $item The item that will be exported
2965 * @param array $owner the array of the item owner
2966 * @param array $contact Target of the communication
2967 * @param bool $public_batch Is it a public post?
2969 * @return int The result of the transmission
2971 public static function send_status($item, $owner, $contact, $public_batch = false) {
2973 $status = self::build_status($item, $owner);
2975 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
2979 * @brief Creates a "like" object
2981 * @param array $item The item that will be exported
2982 * @param array $owner the array of the item owner
2984 * @return array The data for a "like"
2986 private function construct_like($item, $owner) {
2988 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2989 dbesc($item["thr-parent"]));
2995 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2998 return(array("positive" => $positive,
2999 "guid" => $item["guid"],
3000 "target_type" => $target_type,
3001 "parent_guid" => $parent["guid"],
3002 "author_signature" => "",
3003 "diaspora_handle" => self::my_handle($owner)));
3007 * @brief Creates the object for a comment
3009 * @param array $item The item that will be exported
3010 * @param array $owner the array of the item owner
3012 * @return array The data for a comment
3014 private function construct_comment($item, $owner) {
3016 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3017 intval($item["parent"]),
3018 intval($item["parent"])
3026 $text = html_entity_decode(bb2diaspora($item["body"]));
3028 return(array("guid" => $item["guid"],
3029 "parent_guid" => $parent["guid"],
3030 "author_signature" => "",
3032 "diaspora_handle" => self::my_handle($owner)));
3036 * @brief Send a like or a comment
3038 * @param array $item The item that will be exported
3039 * @param array $owner the array of the item owner
3040 * @param array $contact Target of the communication
3041 * @param bool $public_batch Is it a public post?
3043 * @return int The result of the transmission
3045 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3047 if($item['verb'] === ACTIVITY_LIKE) {
3048 $message = self::construct_like($item, $owner);
3051 $message = self::construct_comment($item, $owner);
3058 $message["author_signature"] = self::signature($owner, $message);
3060 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3064 * @brief Creates a message from a signature record entry
3066 * @param array $item The item that will be exported
3067 * @param array $signature The entry of the "sign" record
3069 * @return string The message
3071 private function message_from_signature($item, $signature) {
3073 // Split the signed text
3074 $signed_parts = explode(";", $signature['signed_text']);
3076 if ($item["deleted"])
3077 $message = array("parent_author_signature" => "",
3078 "target_guid" => $signed_parts[0],
3079 "target_type" => $signed_parts[1],
3080 "sender_handle" => $signature['signer'],
3081 "target_author_signature" => $signature['signature']);
3082 elseif ($item['verb'] === ACTIVITY_LIKE)
3083 $message = array("positive" => $signed_parts[0],
3084 "guid" => $signed_parts[1],
3085 "target_type" => $signed_parts[2],
3086 "parent_guid" => $signed_parts[3],
3087 "parent_author_signature" => "",
3088 "author_signature" => $signature['signature'],
3089 "diaspora_handle" => $signed_parts[4]);
3091 // Remove the comment guid
3092 $guid = array_shift($signed_parts);
3094 // Remove the parent guid
3095 $parent_guid = array_shift($signed_parts);
3097 // Remove the handle
3098 $handle = array_pop($signed_parts);
3100 // Glue the parts together
3101 $text = implode(";", $signed_parts);
3103 $message = array("guid" => $guid,
3104 "parent_guid" => $parent_guid,
3105 "parent_author_signature" => "",
3106 "author_signature" => $signature['signature'],
3107 "text" => implode(";", $signed_parts),
3108 "diaspora_handle" => $handle);
3114 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3116 * @param array $item The item that will be exported
3117 * @param array $owner the array of the item owner
3118 * @param array $contact Target of the communication
3119 * @param bool $public_batch Is it a public post?
3121 * @return int The result of the transmission
3123 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3125 if ($item["deleted"])
3126 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3127 elseif ($item['verb'] === ACTIVITY_LIKE)
3132 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3134 // fetch the original signature
3136 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3137 intval($item["id"]));
3140 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3146 // Old way - is used by the internal Friendica functions
3147 /// @todo Change all signatur storing functions to the new format
3148 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3149 $message = self::message_from_signature($item, $signature);
3151 $msg = json_decode($signature['signed_text'], true);
3154 if (is_array($msg)) {
3155 foreach ($msg AS $field => $data) {
3156 if (!$item["deleted"]) {
3157 if ($field == "author")
3158 $field = "diaspora_handle";
3159 if ($field == "parent_type")
3160 $field = "target_type";
3163 $message[$field] = $data;
3166 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3169 $message["parent_author_signature"] = self::signature($owner, $message);
3171 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3173 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3177 * @brief Sends a retraction (deletion) of a message, like or comment
3179 * @param array $item The item that will be exported
3180 * @param array $owner the array of the item owner
3181 * @param array $contact Target of the communication
3182 * @param bool $public_batch Is it a public post?
3183 * @param bool $relay Is the retraction transmitted from a relay?
3185 * @return int The result of the transmission
3187 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3189 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3191 // Check whether the retraction is for a top-level post or whether it's a relayable
3192 if ($item["uri"] !== $item["parent-uri"]) {
3193 $msg_type = "relayable_retraction";
3194 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3196 $msg_type = "signed_retraction";
3197 $target_type = "StatusMessage";
3200 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3201 $signature = "parent_author_signature";
3203 $signature = "target_author_signature";
3205 $signed_text = $item["guid"].";".$target_type;
3207 $message = array("target_guid" => $item['guid'],
3208 "target_type" => $target_type,
3209 "sender_handle" => $itemaddr,
3210 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3212 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3214 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3218 * @brief Sends a mail
3220 * @param array $item The item that will be exported
3221 * @param array $owner The owner
3222 * @param array $contact Target of the communication
3224 * @return int The result of the transmission
3226 public static function send_mail($item, $owner, $contact) {
3228 $myaddr = self::my_handle($owner);
3230 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3231 intval($item["convid"]),
3232 intval($item["uid"])
3236 logger("conversation not found.");
3242 "guid" => $cnv["guid"],
3243 "subject" => $cnv["subject"],
3244 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3245 "diaspora_handle" => $cnv["creator"],
3246 "participant_handles" => $cnv["recips"]
3249 $body = bb2diaspora($item["body"]);
3250 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
3252 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3253 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3256 "guid" => $item["guid"],
3257 "parent_guid" => $cnv["guid"],
3258 "parent_author_signature" => $sig,
3259 "author_signature" => $sig,
3261 "created_at" => $created,
3262 "diaspora_handle" => $myaddr,
3263 "conversation_guid" => $cnv["guid"]
3266 if ($item["reply"]) {
3270 $message = array("guid" => $cnv["guid"],
3271 "subject" => $cnv["subject"],
3272 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
3274 "diaspora_handle" => $cnv["creator"],
3275 "participant_handles" => $cnv["recips"]);
3277 $type = "conversation";
3280 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3284 * @brief Sends profile data
3286 * @param int $uid The user id
3288 public static function send_profile($uid, $recips = false) {
3294 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3295 AND `uid` = %d AND `rel` != %d",
3296 dbesc(NETWORK_DIASPORA),
3298 intval(CONTACT_IS_SHARING)
3303 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3305 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3306 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3307 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3316 $handle = $profile["addr"];
3317 $first = ((strpos($profile['name'],' ')
3318 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3319 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3320 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3321 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3322 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3323 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3325 if ($searchable === 'true') {
3326 $dob = '1000-00-00';
3328 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3329 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3331 $about = $profile['about'];
3332 $about = strip_tags(bbcode($about));
3334 $location = formatted_location($profile);
3336 if ($profile['pub_keywords']) {
3337 $kw = str_replace(',',' ',$profile['pub_keywords']);
3338 $kw = str_replace(' ',' ',$kw);
3339 $arr = explode(' ',$profile['pub_keywords']);
3341 for($x = 0; $x < 5; $x ++) {
3343 $tags .= '#'. trim($arr[$x]) .' ';
3347 $tags = trim($tags);
3350 $message = array("diaspora_handle" => $handle,
3351 "first_name" => $first,
3352 "last_name" => $last,
3353 "image_url" => $large,
3354 "image_url_medium" => $medium,
3355 "image_url_small" => $small,
3357 "gender" => $profile['gender'],
3359 "location" => $location,
3360 "searchable" => $searchable,
3361 "tag_string" => $tags);
3363 foreach($recips as $recip) {
3364 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3365 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3370 * @brief Stores the signature for likes that are created on our system
3372 * @param array $contact The contact array of the "like"
3373 * @param int $post_id The post id of the "like"
3375 * @return bool Success
3377 public static function store_like_signature($contact, $post_id) {
3379 // Is the contact the owner? Then fetch the private key
3380 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3381 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3385 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3389 $contact["uprvkey"] = $r[0]['prvkey'];
3391 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3395 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3398 $message = self::construct_like($r[0], $contact);
3399 $message["author_signature"] = self::signature($contact, $message);
3401 // In the future we will store the signature more flexible to support new fields.
3402 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3403 // (We are transmitting this data here via DFRN)
3405 $signed_text = $message["positive"].";".$message["guid"].";".$message["target_type"].";".
3406 $message["parent_guid"].";".$message["diaspora_handle"];
3408 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3410 dbesc($signed_text),
3411 dbesc($message["author_signature"]),
3412 dbesc($message["diaspora_handle"])
3415 // This here will replace the lines above, once Diaspora changed its protocol
3416 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3417 // intval($message_id),
3418 // dbesc(json_encode($message))
3421 logger('Stored diaspora like signature');
3426 * @brief Stores the signature for comments that are created on our system
3428 * @param array $item The item array of the comment
3429 * @param array $contact The contact array of the item owner
3430 * @param string $uprvkey The private key of the sender
3431 * @param int $message_id The message id of the comment
3433 * @return bool Success
3435 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3437 if ($uprvkey == "") {
3438 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3442 $contact["uprvkey"] = $uprvkey;
3444 $message = self::construct_comment($item, $contact);
3445 $message["author_signature"] = self::signature($contact, $message);
3447 // In the future we will store the signature more flexible to support new fields.
3448 // Right now we cannot change this since old Friendica versions (prior to 3.5) can only handle this format.
3449 // (We are transmitting this data here via DFRN)
3450 $signed_text = $message["guid"].";".$message["parent_guid"].";".
3451 $message["text"].";".$message["diaspora_handle"];
3453 q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) VALUES (%d,'%s','%s','%s')",
3454 intval($message_id),
3455 dbesc($signed_text),
3456 dbesc($message["author_signature"]),
3457 dbesc($message["diaspora_handle"])
3460 // This here will replace the lines above, once Diaspora changed its protocol
3461 //q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3462 // intval($message_id),
3463 // dbesc(json_encode($message))
3466 logger('Stored diaspora comment signature');