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.
12 use Friendica\Core\Config;
14 require_once 'include/items.php';
15 require_once 'include/bb2diaspora.php';
16 require_once 'include/Scrape.php';
17 require_once 'include/Contact.php';
18 require_once 'include/Photo.php';
19 require_once 'include/socgraph.php';
20 require_once 'include/group.php';
21 require_once 'include/xml.php';
22 require_once 'include/datetime.php';
23 require_once 'include/queue_fn.php';
24 require_once 'include/cache.php';
27 * @brief This class contain functions to create and send Diaspora XML files
33 * @brief Return a list of relay servers
35 * This is an experimental Diaspora feature.
37 * @return array of relay servers
39 public static function relay_list() {
41 $serverdata = get_config("system", "relay_server");
42 if ($serverdata == "")
47 $servers = explode(",", $serverdata);
49 foreach ($servers AS $server) {
50 $server = trim($server);
51 $addr = "relay@".str_replace("http://", "", normalise_link($server));
52 $batch = $server."/receive/public";
54 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
55 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
58 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
59 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
64 dbesc(normalise_link($server)),
66 dbesc(NETWORK_DIASPORA),
67 intval(CONTACT_IS_FOLLOWER),
68 dbesc(datetime_convert()),
69 dbesc(datetime_convert()),
70 dbesc(datetime_convert())
73 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
75 $relay[] = $relais[0];
77 $relay[] = $relais[0];
84 * @brief repairs a signature that was double encoded
86 * The function is unused at the moment. It was copied from the old implementation.
88 * @param string $signature The signature
89 * @param string $handle The handle of the signature owner
90 * @param integer $level This value is only set inside this function to avoid endless loops
92 * @return string the repaired signature
94 private static function repair_signature($signature, $handle = "", $level = 1) {
99 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
100 $signature = base64_decode($signature);
101 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
103 // Do a recursive call to be able to fix even multiple levels
105 $signature = self::repair_signature($signature, $handle, ++$level);
112 * @brief verify the envelope and return the verified data
114 * @param string $envelope The magic envelope
116 * @return string verified data
118 private static function verify_magic_envelope($envelope) {
120 $basedom = parse_xml_string($envelope, false);
122 if (!is_object($basedom)) {
123 logger("Envelope is no XML file");
127 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
129 if (sizeof($children) == 0) {
130 logger("XML has no children");
136 $data = base64url_decode($children->data);
137 $type = $children->data->attributes()->type[0];
139 $encoding = $children->encoding;
141 $alg = $children->alg;
143 $sig = base64url_decode($children->sig);
144 $key_id = $children->sig->attributes()->key_id[0];
146 $handle = base64url_decode($key_id);
148 $b64url_data = base64url_encode($data);
149 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
151 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
153 $key = self::key($handle);
155 $verify = rsa_verify($signable_data, $sig, $key);
157 logger('Message did not verify. Discarding.');
165 * @brief encrypts data via AES
167 * @param string $key The AES key
168 * @param string $iv The IV (is used for CBC encoding)
169 * @param string $data The data that is to be encrypted
171 * @return string encrypted data
173 private static function aes_encrypt($key, $iv, $data) {
174 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
178 * @brief decrypts data via AES
180 * @param string $key The AES key
181 * @param string $iv The IV (is used for CBC encoding)
182 * @param string $encrypted The encrypted data
184 * @return string decrypted data
186 private static function aes_decrypt($key, $iv, $encrypted) {
187 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
191 * @brief: Decodes incoming Diaspora message in the new format
193 * @param array $importer Array of the importer user
194 * @param string $raw raw post message
197 * 'message' -> decoded Diaspora XML message
198 * 'author' -> author diaspora handle
199 * 'key' -> author public key (converted to pkcs#8)
201 public static function decode_raw($importer, $raw) {
202 $data = json_decode($raw);
204 // Is it a private post? Then decrypt the outer Salmon
205 if (is_object($data)) {
206 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
207 $ciphertext = base64_decode($data->encrypted_magic_envelope);
209 $outer_key_bundle = '';
210 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
211 $j_outer_key_bundle = json_decode($outer_key_bundle);
213 if (!is_object($j_outer_key_bundle)) {
214 logger('Outer Salmon did not verify. Discarding.');
215 http_status_exit(400);
218 $outer_iv = base64_decode($j_outer_key_bundle->iv);
219 $outer_key = base64_decode($j_outer_key_bundle->key);
221 $xml = diaspora::aes_decrypt($outer_key, $outer_iv, $ciphertext);
226 $basedom = parse_xml_string($xml);
228 if (!is_object($basedom)) {
229 logger('Received data does not seem to be an XML. Discarding.');
230 http_status_exit(400);
233 $base = $basedom->children(NAMESPACE_SALMON_ME);
235 // Not sure if this cleaning is needed
236 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
238 // Build the signed data
239 $type = $base->data[0]->attributes()->type[0];
240 $encoding = $base->encoding;
242 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
244 // This is the signature
245 $signature = base64url_decode($base->sig);
247 // Get the senders' public key
248 $key_id = $base->sig[0]->attributes()->key_id[0];
249 $author_addr = base64_decode($key_id);
250 $key = diaspora::key($author_addr);
252 $verify = rsa_verify($signed_data, $signature, $key);
254 logger('Message did not verify. Discarding.');
255 http_status_exit(400);
258 return array('message' => (string)base64url_decode($base->data),
259 'author' => unxmlify($author_addr),
260 'key' => (string)$key);
264 * @brief: Decodes incoming Diaspora message in the deprecated format
266 * @param array $importer Array of the importer user
267 * @param string $xml urldecoded Diaspora salmon
270 * 'message' -> decoded Diaspora XML message
271 * 'author' -> author diaspora handle
272 * 'key' -> author public key (converted to pkcs#8)
274 public static function decode($importer, $xml) {
277 $basedom = parse_xml_string($xml);
279 if (!is_object($basedom)) {
280 logger("XML is not parseable.");
283 $children = $basedom->children('https://joindiaspora.com/protocol');
285 if ($children->header) {
287 $author_link = str_replace('acct:','',$children->header->author_id);
290 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
292 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
293 $ciphertext = base64_decode($encrypted_header->ciphertext);
295 $outer_key_bundle = '';
296 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
298 $j_outer_key_bundle = json_decode($outer_key_bundle);
300 $outer_iv = base64_decode($j_outer_key_bundle->iv);
301 $outer_key = base64_decode($j_outer_key_bundle->key);
303 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
305 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
306 $idom = parse_xml_string($decrypted,false);
308 $inner_iv = base64_decode($idom->iv);
309 $inner_aes_key = base64_decode($idom->aes_key);
311 $author_link = str_replace('acct:','',$idom->author_id);
314 $dom = $basedom->children(NAMESPACE_SALMON_ME);
316 // figure out where in the DOM tree our data is hiding
318 if ($dom->provenance->data)
319 $base = $dom->provenance;
320 elseif ($dom->env->data)
326 logger('unable to locate salmon data in xml');
327 http_status_exit(400);
331 // Stash the signature away for now. We have to find their key or it won't be good for anything.
332 $signature = base64url_decode($base->sig);
336 // strip whitespace so our data element will return to one big base64 blob
337 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
340 // stash away some other stuff for later
342 $type = $base->data[0]->attributes()->type[0];
343 $keyhash = $base->sig[0]->attributes()->keyhash[0];
344 $encoding = $base->encoding;
348 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
352 $data = base64url_decode($data);
356 $inner_decrypted = $data;
359 // Decode the encrypted blob
361 $inner_encrypted = base64_decode($data);
362 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
366 logger('Could not retrieve author URI.');
367 http_status_exit(400);
369 // Once we have the author URI, go to the web and try to find their public key
370 // (first this will look it up locally if it is in the fcontact cache)
371 // This will also convert diaspora public key from pkcs#1 to pkcs#8
373 logger('Fetching key for '.$author_link);
374 $key = self::key($author_link);
377 logger('Could not retrieve author key.');
378 http_status_exit(400);
381 $verify = rsa_verify($signed_data,$signature,$key);
384 logger('Message did not verify. Discarding.');
385 http_status_exit(400);
388 logger('Message verified.');
390 return array('message' => (string)$inner_decrypted,
391 'author' => unxmlify($author_link),
392 'key' => (string)$key);
397 * @brief Dispatches public messages and find the fitting receivers
399 * @param array $msg The post that will be dispatched
401 * @return int The message id of the generated message, "true" or "false" if there was an error
403 public static function dispatch_public($msg) {
405 $enabled = intval(get_config("system", "diaspora_enabled"));
407 logger("diaspora is disabled");
411 if (!($postdata = self::valid_posting($msg))) {
412 logger("Invalid posting");
416 $fields = $postdata['fields'];
418 // Is it a an action (comment, like, ...) for our own post?
419 if (isset($fields->parent_guid) AND !$postdata["relayed"]) {
420 $guid = notags(unxmlify($fields->parent_guid));
421 $importer = self::importer_for_guid($guid);
422 if (is_array($importer)) {
423 logger("delivering to origin: ".$importer["name"]);
424 $message_id = self::dispatch($importer, $msg, $fields);
429 // Now distribute it to the followers
430 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
431 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
432 AND NOT `account_expired` AND NOT `account_removed`",
433 dbesc(NETWORK_DIASPORA),
434 dbesc($msg["author"])
437 if (dbm::is_result($r)) {
438 foreach ($r as $rr) {
439 logger("delivering to: ".$rr["username"]);
440 self::dispatch($rr, $msg, $fields);
442 } elseif (!Config::get('system', 'relay_subscribe', false)) {
443 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
445 // Use a dummy importer to import the data for the public copy
446 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
447 $message_id = self::dispatch($importer, $msg, $fields);
454 * @brief Dispatches the different message types to the different functions
456 * @param array $importer Array of the importer user
457 * @param array $msg The post that will be dispatched
458 * @param object $fields SimpleXML object that contains the message
460 * @return int The message id of the generated message, "true" or "false" if there was an error
462 public static function dispatch($importer, $msg, $fields = null) {
464 // The sender is the handle of the contact that sent the message.
465 // This will often be different with relayed messages (for example "like" and "comment")
466 $sender = $msg["author"];
468 // This is only needed for private postings since this is already done for public ones before
469 if (is_null($fields)) {
470 if (!($postdata = self::valid_posting($msg))) {
471 logger("Invalid posting");
474 $fields = $postdata['fields'];
477 $type = $fields->getName();
479 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
482 case "account_deletion":
483 return self::receive_account_deletion($importer, $fields);
486 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
489 return self::receive_contact_request($importer, $fields);
492 return self::receive_conversation($importer, $msg, $fields);
495 return self::receive_like($importer, $sender, $fields);
498 return self::receive_message($importer, $fields);
500 case "participation": // Not implemented
501 return self::receive_participation($importer, $fields);
503 case "photo": // Not implemented
504 return self::receive_photo($importer, $fields);
506 case "poll_participation": // Not implemented
507 return self::receive_poll_participation($importer, $fields);
510 return self::receive_profile($importer, $fields);
513 return self::receive_reshare($importer, $fields, $msg["message"]);
516 return self::receive_retraction($importer, $sender, $fields);
518 case "status_message":
519 return self::receive_status_message($importer, $fields, $msg["message"]);
522 logger("Unknown message type ".$type);
530 * @brief Checks if a posting is valid and fetches the data fields.
532 * This function does not only check the signature.
533 * It also does the conversion between the old and the new diaspora format.
535 * @param array $msg Array with the XML, the sender handle and the sender signature
537 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
539 private static function valid_posting($msg) {
541 $data = parse_xml_string($msg["message"], false);
543 if (!is_object($data)) {
544 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
548 $first_child = $data->getName();
550 // Is this the new or the old version?
551 if ($data->getName() == "XML") {
553 foreach ($data->post->children() as $child)
560 $type = $element->getName();
563 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
565 // All retractions are handled identically from now on.
566 // In the new version there will only be "retraction".
567 if (in_array($type, array("signed_retraction", "relayable_retraction")))
568 $type = "retraction";
570 if ($type == "request")
573 $fields = new SimpleXMLElement("<".$type."/>");
577 foreach ($element->children() AS $fieldname => $entry) {
579 // Translation for the old XML structure
580 if ($fieldname == "diaspora_handle") {
581 $fieldname = "author";
583 if ($fieldname == "participant_handles") {
584 $fieldname = "participants";
586 if (in_array($type, array("like", "participation"))) {
587 if ($fieldname == "target_type") {
588 $fieldname = "parent_type";
591 if ($fieldname == "sender_handle") {
592 $fieldname = "author";
594 if ($fieldname == "recipient_handle") {
595 $fieldname = "recipient";
597 if ($fieldname == "root_diaspora_id") {
598 $fieldname = "root_author";
600 if ($type == "status_message") {
601 if ($fieldname == "raw_message") {
605 if ($type == "retraction") {
606 if ($fieldname == "post_guid") {
607 $fieldname = "target_guid";
609 if ($fieldname == "type") {
610 $fieldname = "target_type";
615 if (($fieldname == "author_signature") AND ($entry != ""))
616 $author_signature = base64_decode($entry);
617 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
618 $parent_author_signature = base64_decode($entry);
619 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
620 if ($signed_data != "") {
622 $signed_data_parent .= ";";
625 $signed_data .= $entry;
627 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
628 ($orig_type == "relayable_retraction"))
629 xml::copy($entry, $fields, $fieldname);
632 // This is something that shouldn't happen at all.
633 if (in_array($type, array("status_message", "reshare", "profile")))
634 if ($msg["author"] != $fields->author) {
635 logger("Message handle is not the same as envelope sender. Quitting this message.");
639 // Only some message types have signatures. So we quit here for the other types.
640 if (!in_array($type, array("comment", "like"))) {
641 return array("fields" => $fields, "relayed" => false);
643 // No author_signature? This is a must, so we quit.
644 if (!isset($author_signature)) {
645 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
649 if (isset($parent_author_signature)) {
652 $key = self::key($msg["author"]);
654 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
655 logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
662 $key = self::key($fields->author);
664 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
665 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
668 return array("fields" => $fields, "relayed" => $relayed);
673 * @brief Fetches the public key for a given handle
675 * @param string $handle The handle
677 * @return string The public key
679 private static function key($handle) {
680 $handle = strval($handle);
682 logger("Fetching diaspora key for: ".$handle);
684 $r = self::person_by_handle($handle);
692 * @brief Fetches data for a given handle
694 * @param string $handle The handle
696 * @return array the queried data
698 public static function person_by_handle($handle) {
700 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
701 dbesc(NETWORK_DIASPORA),
706 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
708 // update record occasionally so it doesn't get stale
709 $d = strtotime($person["updated"]." +00:00");
710 if ($d < strtotime("now - 14 days"))
713 if ($person["guid"] == "")
717 if (!$person OR $update) {
718 logger("create or refresh", LOGGER_DEBUG);
719 $r = probe_url($handle, PROBE_DIASPORA);
721 // Note that Friendica contacts will return a "Diaspora person"
722 // if Diaspora connectivity is enabled on their server
723 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
724 self::add_fcontact($r, $update);
732 * @brief Updates the fcontact table
734 * @param array $arr The fcontact data
735 * @param bool $update Update or insert?
737 * @return string The id of the fcontact entry
739 private static function add_fcontact($arr, $update = false) {
742 $r = q("UPDATE `fcontact` SET
756 WHERE `url` = '%s' AND `network` = '%s'",
758 dbesc($arr["photo"]),
759 dbesc($arr["request"]),
761 dbesc(strtolower($arr["addr"])),
763 dbesc($arr["batch"]),
764 dbesc($arr["notify"]),
766 dbesc($arr["confirm"]),
767 dbesc($arr["alias"]),
768 dbesc($arr["pubkey"]),
769 dbesc(datetime_convert()),
771 dbesc($arr["network"])
774 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
775 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
776 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
779 dbesc($arr["photo"]),
780 dbesc($arr["request"]),
784 dbesc($arr["batch"]),
785 dbesc($arr["notify"]),
787 dbesc($arr["confirm"]),
788 dbesc($arr["network"]),
789 dbesc($arr["alias"]),
790 dbesc($arr["pubkey"]),
791 dbesc(datetime_convert())
799 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
801 * @param int $contact_id The id in the contact table
802 * @param int $gcontact_id The id in the gcontact table
804 * @return string the handle
806 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
809 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
811 if ($gcontact_id != 0) {
812 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
813 intval($gcontact_id));
815 if (dbm::is_result($r)) {
816 return strtolower($r[0]["addr"]);
820 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
821 intval($contact_id));
823 if (dbm::is_result($r)) {
826 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
828 if ($contact['addr'] != "") {
829 $handle = $contact['addr'];
831 $baseurl_start = strpos($contact['url'],'://') + 3;
832 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
833 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
834 $handle = $contact['nick'].'@'.$baseurl;
838 return strtolower($handle);
842 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
845 * @param mixed $fcontact_guid Hexadecimal string guid
847 * @return string the contact url or null
849 public static function url_from_contact_guid($fcontact_guid) {
850 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
852 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
853 dbesc(NETWORK_DIASPORA),
854 dbesc($fcontact_guid)
857 if (dbm::is_result($r)) {
865 * @brief Get a contact id for a given handle
867 * @param int $uid The user id
868 * @param string $handle The handle in the format user@domain.tld
870 * @return The contact id
872 private static function contact_by_handle($uid, $handle) {
874 // First do a direct search on the contact table
875 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
880 if (dbm::is_result($r)) {
883 // We haven't found it?
884 // We use another function for it that will possibly create a contact entry
885 $cid = get_contact($handle, $uid);
888 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
890 if (dbm::is_result($r)) {
896 $handle_parts = explode("@", $handle);
897 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
898 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
903 if (dbm::is_result($r)) {
907 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
912 * @brief Check if posting is allowed for this contact
914 * @param array $importer Array of the importer user
915 * @param array $contact The contact that is checked
916 * @param bool $is_comment Is the check for a comment?
918 * @return bool is the contact allowed to post?
920 private static function post_allow($importer, $contact, $is_comment = false) {
922 // perhaps we were already sharing with this person. Now they're sharing with us.
923 // That makes us friends.
924 // Normally this should have handled by getting a request - but this could get lost
925 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
926 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
927 intval(CONTACT_IS_FRIEND),
928 intval($contact["id"]),
929 intval($importer["uid"])
931 $contact["rel"] = CONTACT_IS_FRIEND;
932 logger("defining user ".$contact["nick"]." as friend");
935 // We don't seem to like that person
936 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
938 // We are following this person? Then it is okay
939 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
941 // Is it a post to a community? That's good
942 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
945 // Messages for the global users and comments are always accepted
946 if (($importer["uid"] == 0) || $is_comment) {
954 * @brief Fetches the contact id for a handle and checks if posting is allowed
956 * @param array $importer Array of the importer user
957 * @param string $handle The checked handle in the format user@domain.tld
958 * @param bool $is_comment Is the check for a comment?
960 * @return array The contact data
962 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
963 $contact = self::contact_by_handle($importer["uid"], $handle);
965 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
966 // If a contact isn't found, we accept it anyway if it is a comment
974 if (!self::post_allow($importer, $contact, $is_comment)) {
975 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
982 * @brief Does the message already exists on the system?
984 * @param int $uid The user id
985 * @param string $guid The guid of the message
987 * @return int|bool message id if the message already was stored into the system - or false.
989 private static function message_exists($uid, $guid) {
990 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
995 if (dbm::is_result($r)) {
996 logger("message ".$guid." already exists for user ".$uid);
1004 * @brief Checks for links to posts in a message
1006 * @param array $item The item array
1008 private static function fetch_guid($item) {
1009 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1010 function ($match) use ($item){
1011 return(self::fetch_guid_sub($match, $item));
1016 * @brief Checks for relative /people/* links in an item body to match local
1017 * contacts or prepends the remote host taken from the author link.
1019 * @param string $body The item body to replace links from
1020 * @param string $author_link The author link for missing local contact fallback
1022 * @return the replaced string
1024 public function replace_people_guid($body, $author_link) {
1025 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1026 function ($match) use ($author_link) {
1028 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1029 // 1 => '0123456789abcdef'
1031 $handle = self::url_from_contact_guid($match[1]);
1034 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1036 // No local match, restoring absolute remote URL from author scheme and host
1037 $author_url = parse_url($author_link);
1038 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1048 * @brief sub function of "fetch_guid" which checks for links in messages
1050 * @param array $match array containing a link that has to be checked for a message link
1051 * @param array $item The item array
1053 private static function fetch_guid_sub($match, $item) {
1054 if (!self::store_by_guid($match[1], $item["author-link"]))
1055 self::store_by_guid($match[1], $item["owner-link"]);
1059 * @brief Fetches an item with a given guid from a given server
1061 * @param string $guid the message guid
1062 * @param string $server The server address
1063 * @param int $uid The user id of the user
1065 * @return int the message id of the stored message or false
1067 private static function store_by_guid($guid, $server, $uid = 0) {
1068 $serverparts = parse_url($server);
1069 $server = $serverparts["scheme"]."://".$serverparts["host"];
1071 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1073 $msg = self::message($guid, $server);
1078 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1080 // Now call the dispatcher
1081 return self::dispatch_public($msg);
1085 * @brief Fetches a message from a server
1087 * @param string $guid message guid
1088 * @param string $server The url of the server
1089 * @param int $level Endless loop prevention
1092 * 'message' => The message XML
1093 * 'author' => The author handle
1094 * 'key' => The public key of the author
1096 private static function message($guid, $server, $level = 0) {
1101 // This will work for new Diaspora servers and Friendica servers from 3.5
1102 $source_url = $server."/fetch/post/".$guid;
1103 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1105 $envelope = fetch_url($source_url);
1107 logger("Envelope was fetched.", LOGGER_DEBUG);
1108 $x = self::verify_magic_envelope($envelope);
1110 logger("Envelope could not be verified.", LOGGER_DEBUG);
1112 logger("Envelope was verified.", LOGGER_DEBUG);
1116 // This will work for older Diaspora and Friendica servers
1118 $source_url = $server."/p/".$guid.".xml";
1119 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1121 $x = fetch_url($source_url);
1126 $source_xml = parse_xml_string($x, false);
1128 if (!is_object($source_xml))
1131 if ($source_xml->post->reshare) {
1132 // Reshare of a reshare - old Diaspora version
1133 logger("Message is a reshare", LOGGER_DEBUG);
1134 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1135 } elseif ($source_xml->getName() == "reshare") {
1136 // Reshare of a reshare - new Diaspora version
1137 logger("Message is a new reshare", LOGGER_DEBUG);
1138 return self::message($source_xml->root_guid, $server, ++$level);
1143 // Fetch the author - for the old and the new Diaspora version
1144 if ($source_xml->post->status_message->diaspora_handle)
1145 $author = (string)$source_xml->post->status_message->diaspora_handle;
1146 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1147 $author = (string)$source_xml->author;
1149 // If this isn't a "status_message" then quit
1151 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1155 $msg = array("message" => $x, "author" => $author);
1157 $msg["key"] = self::key($msg["author"]);
1163 * @brief Fetches the item record of a given guid
1165 * @param int $uid The user id
1166 * @param string $guid message guid
1167 * @param string $author The handle of the item
1168 * @param array $contact The contact of the item owner
1170 * @return array the item record
1172 private static function parent_item($uid, $guid, $author, $contact) {
1173 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1174 `author-name`, `author-link`, `author-avatar`,
1175 `owner-name`, `owner-link`, `owner-avatar`
1176 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1177 intval($uid), dbesc($guid));
1180 $result = self::store_by_guid($guid, $contact["url"], $uid);
1183 $person = self::person_by_handle($author);
1184 $result = self::store_by_guid($guid, $person["url"], $uid);
1188 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1190 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1191 `author-name`, `author-link`, `author-avatar`,
1192 `owner-name`, `owner-link`, `owner-avatar`
1193 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1194 intval($uid), dbesc($guid));
1199 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1202 logger("parent item found: parent: ".$guid." - user: ".$uid);
1208 * @brief returns contact details
1210 * @param array $contact The default contact if the person isn't found
1211 * @param array $person The record of the person
1212 * @param int $uid The user id
1215 * 'cid' => contact id
1216 * 'network' => network type
1218 private static function author_contact_by_url($contact, $person, $uid) {
1220 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1221 dbesc(normalise_link($person["url"])), intval($uid));
1224 $network = $r[0]["network"];
1226 // We are receiving content from a user that possibly is about to be terminated
1227 // This means the user is vital, so we remove a possible termination date.
1228 unmark_for_death($r[0]);
1230 $cid = $contact["id"];
1231 $network = NETWORK_DIASPORA;
1234 return array("cid" => $cid, "network" => $network);
1238 * @brief Is the profile a hubzilla profile?
1240 * @param string $url The profile link
1242 * @return bool is it a hubzilla server?
1244 public static function is_redmatrix($url) {
1245 return(strstr($url, "/channel/"));
1249 * @brief Generate a post link with a given handle and message guid
1251 * @param string $addr The user handle
1252 * @param string $guid message guid
1254 * @return string the post link
1256 private static function plink($addr, $guid) {
1257 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1261 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1263 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1264 // So we try another way as well.
1265 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1267 $r[0]["network"] = $s[0]["network"];
1269 if ($r[0]["network"] == NETWORK_DFRN)
1270 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1272 if (self::is_redmatrix($r[0]["url"]))
1273 return $r[0]["url"]."/?f=&mid=".$guid;
1275 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1279 * @brief Processes an account deletion
1281 * @param array $importer Array of the importer user
1282 * @param object $data The message object
1284 * @return bool Success
1286 private static function receive_account_deletion($importer, $data) {
1288 /// @todo Account deletion should remove the contact from the global contacts as well
1290 $author = notags(unxmlify($data->author));
1292 $contact = self::contact_by_handle($importer["uid"], $author);
1294 logger("cannot find contact for author: ".$author);
1298 // We now remove the contact
1299 contact_remove($contact["id"]);
1304 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1306 * @param string $author Author handle
1307 * @param string $guid Message guid
1308 * @param boolean $onlyfound Only return uri when found in the database
1310 * @return string The constructed uri or the one from our database
1312 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1314 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1315 if (dbm::is_result($r)) {
1316 return $r[0]["uri"];
1317 } elseif (!$onlyfound) {
1318 return $author.":".$guid;
1325 * @brief Fetch the guid from our database with a given uri
1327 * @param string $author Author handle
1328 * @param string $uri Message uri
1330 * @return string The post guid
1332 private static function get_guid_from_uri($uri, $uid) {
1334 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1335 if (dbm::is_result($r)) {
1336 return $r[0]["guid"];
1343 * @brief Find the best importer for a comment, like, ...
1345 * @param string $guid The guid of the item
1347 * @return array|boolean the origin owner of that post - or false
1349 private static function importer_for_guid($guid) {
1350 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1352 if (dbm::is_result($item)) {
1353 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1354 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1355 if (dbm::is_result($contact)) {
1363 * @brief Processes an incoming comment
1365 * @param array $importer Array of the importer user
1366 * @param string $sender The sender of the message
1367 * @param object $data The message object
1368 * @param string $xml The original XML of the message
1370 * @return int The message id of the generated comment or "false" if there was an error
1372 private static function receive_comment($importer, $sender, $data, $xml) {
1373 $author = notags(unxmlify($data->author));
1374 $guid = notags(unxmlify($data->guid));
1375 $parent_guid = notags(unxmlify($data->parent_guid));
1376 $text = unxmlify($data->text);
1378 if (isset($data->created_at)) {
1379 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1381 $created_at = datetime_convert();
1384 if (isset($data->thread_parent_guid)) {
1385 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1386 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1391 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1396 $message_id = self::message_exists($importer["uid"], $guid);
1401 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1402 if (!$parent_item) {
1406 $person = self::person_by_handle($author);
1407 if (!is_array($person)) {
1408 logger("unable to find author details");
1412 // Fetch the contact id - if we know this contact
1413 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1415 $datarray = array();
1417 $datarray["uid"] = $importer["uid"];
1418 $datarray["contact-id"] = $author_contact["cid"];
1419 $datarray["network"] = $author_contact["network"];
1421 $datarray["author-name"] = $person["name"];
1422 $datarray["author-link"] = $person["url"];
1423 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1425 $datarray["owner-name"] = $contact["name"];
1426 $datarray["owner-link"] = $contact["url"];
1427 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1429 $datarray["guid"] = $guid;
1430 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1432 $datarray["type"] = "remote-comment";
1433 $datarray["verb"] = ACTIVITY_POST;
1434 $datarray["gravity"] = GRAVITY_COMMENT;
1436 if ($thr_uri != "") {
1437 $datarray["parent-uri"] = $thr_uri;
1439 $datarray["parent-uri"] = $parent_item["uri"];
1442 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1444 $datarray["protocol"] = PROTOCOL_DIASPORA;
1445 $datarray["source"] = $xml;
1447 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1449 $body = diaspora2bb($text);
1451 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1453 self::fetch_guid($datarray);
1455 $message_id = item_store($datarray);
1458 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1461 // If we are the origin of the parent we store the original data and notify our followers
1462 if ($message_id AND $parent_item["origin"]) {
1464 // Formerly we stored the signed text, the signature and the author in different fields.
1465 // We now store the raw data so that we are more flexible.
1466 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1467 intval($message_id),
1468 dbesc(json_encode($data))
1472 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1479 * @brief processes and stores private messages
1481 * @param array $importer Array of the importer user
1482 * @param array $contact The contact of the message
1483 * @param object $data The message object
1484 * @param array $msg Array of the processed message, author handle and key
1485 * @param object $mesg The private message
1486 * @param array $conversation The conversation record to which this message belongs
1488 * @return bool "true" if it was successful
1490 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1491 $author = notags(unxmlify($data->author));
1492 $guid = notags(unxmlify($data->guid));
1493 $subject = notags(unxmlify($data->subject));
1495 // "diaspora_handle" is the element name from the old version
1496 // "author" is the element name from the new version
1497 if ($mesg->author) {
1498 $msg_author = notags(unxmlify($mesg->author));
1499 } elseif ($mesg->diaspora_handle) {
1500 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1505 $msg_guid = notags(unxmlify($mesg->guid));
1506 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1507 $msg_text = unxmlify($mesg->text);
1508 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1510 if ($msg_conversation_guid != $guid) {
1511 logger("message conversation guid does not belong to the current conversation.");
1515 $body = diaspora2bb($msg_text);
1516 $message_uri = $msg_author.":".$msg_guid;
1518 $person = self::person_by_handle($msg_author);
1520 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1523 if (dbm::is_result($r)) {
1524 logger("duplicate message already delivered.", LOGGER_DEBUG);
1528 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1529 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1530 intval($importer["uid"]),
1532 intval($conversation["id"]),
1533 dbesc($person["name"]),
1534 dbesc($person["photo"]),
1535 dbesc($person["url"]),
1536 intval($contact["id"]),
1541 dbesc($message_uri),
1542 dbesc($author.":".$guid),
1543 dbesc($msg_created_at)
1546 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1547 dbesc(datetime_convert()),
1548 intval($conversation["id"])
1552 "type" => NOTIFY_MAIL,
1553 "notify_flags" => $importer["notify-flags"],
1554 "language" => $importer["language"],
1555 "to_name" => $importer["username"],
1556 "to_email" => $importer["email"],
1557 "uid" =>$importer["uid"],
1558 "item" => array("subject" => $subject, "body" => $body),
1559 "source_name" => $person["name"],
1560 "source_link" => $person["url"],
1561 "source_photo" => $person["thumb"],
1562 "verb" => ACTIVITY_POST,
1569 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1571 * @param array $importer Array of the importer user
1572 * @param array $msg Array of the processed message, author handle and key
1573 * @param object $data The message object
1575 * @return bool Success
1577 private static function receive_conversation($importer, $msg, $data) {
1578 $author = notags(unxmlify($data->author));
1579 $guid = notags(unxmlify($data->guid));
1580 $subject = notags(unxmlify($data->subject));
1581 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1582 $participants = notags(unxmlify($data->participants));
1584 $messages = $data->message;
1586 if (!count($messages)) {
1587 logger("empty conversation");
1591 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1595 $conversation = null;
1597 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1598 intval($importer["uid"]),
1602 $conversation = $c[0];
1604 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1605 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1606 intval($importer["uid"]),
1610 dbesc(datetime_convert()),
1612 dbesc($participants)
1615 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1616 intval($importer["uid"]),
1621 $conversation = $c[0];
1623 if (!$conversation) {
1624 logger("unable to create conversation.");
1628 foreach ($messages as $mesg)
1629 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1635 * @brief Creates the body for a "like" message
1637 * @param array $contact The contact that send us the "like"
1638 * @param array $parent_item The item array of the parent item
1639 * @param string $guid message guid
1641 * @return string the body
1643 private static function construct_like_body($contact, $parent_item, $guid) {
1644 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1646 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1647 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1648 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1650 return sprintf($bodyverb, $ulink, $alink, $plink);
1654 * @brief Creates a XML object for a "like"
1656 * @param array $importer Array of the importer user
1657 * @param array $parent_item The item array of the parent item
1659 * @return string The XML
1661 private static function construct_like_object($importer, $parent_item) {
1662 $objtype = ACTIVITY_OBJ_NOTE;
1663 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1664 $parent_body = $parent_item["body"];
1666 $xmldata = array("object" => array("type" => $objtype,
1668 "id" => $parent_item["uri"],
1671 "content" => $parent_body));
1673 return xml::from_array($xmldata, $xml, true);
1677 * @brief Processes "like" messages
1679 * @param array $importer Array of the importer user
1680 * @param string $sender The sender of the message
1681 * @param object $data The message object
1683 * @return int The message id of the generated like or "false" if there was an error
1685 private static function receive_like($importer, $sender, $data) {
1686 $author = notags(unxmlify($data->author));
1687 $guid = notags(unxmlify($data->guid));
1688 $parent_guid = notags(unxmlify($data->parent_guid));
1689 $parent_type = notags(unxmlify($data->parent_type));
1690 $positive = notags(unxmlify($data->positive));
1692 // likes on comments aren't supported by Diaspora - only on posts
1693 // But maybe this will be supported in the future, so we will accept it.
1694 if (!in_array($parent_type, array("Post", "Comment")))
1697 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1701 $message_id = self::message_exists($importer["uid"], $guid);
1705 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1709 $person = self::person_by_handle($author);
1710 if (!is_array($person)) {
1711 logger("unable to find author details");
1715 // Fetch the contact id - if we know this contact
1716 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1718 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1719 // We would accept this anyhow.
1720 if ($positive == "true")
1721 $verb = ACTIVITY_LIKE;
1723 $verb = ACTIVITY_DISLIKE;
1725 $datarray = array();
1727 $datarray["protocol"] = PROTOCOL_DIASPORA;
1729 $datarray["uid"] = $importer["uid"];
1730 $datarray["contact-id"] = $author_contact["cid"];
1731 $datarray["network"] = $author_contact["network"];
1733 $datarray["author-name"] = $person["name"];
1734 $datarray["author-link"] = $person["url"];
1735 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1737 $datarray["owner-name"] = $contact["name"];
1738 $datarray["owner-link"] = $contact["url"];
1739 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1741 $datarray["guid"] = $guid;
1742 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1744 $datarray["type"] = "activity";
1745 $datarray["verb"] = $verb;
1746 $datarray["gravity"] = GRAVITY_LIKE;
1747 $datarray["parent-uri"] = $parent_item["uri"];
1749 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1750 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1752 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1754 $message_id = item_store($datarray);
1757 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1759 // If we are the origin of the parent we store the original data and notify our followers
1760 if ($message_id AND $parent_item["origin"]) {
1762 // Formerly we stored the signed text, the signature and the author in different fields.
1763 // We now store the raw data so that we are more flexible.
1764 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1765 intval($message_id),
1766 dbesc(json_encode($data))
1770 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1777 * @brief Processes private messages
1779 * @param array $importer Array of the importer user
1780 * @param object $data The message object
1782 * @return bool Success?
1784 private static function receive_message($importer, $data) {
1785 $author = notags(unxmlify($data->author));
1786 $guid = notags(unxmlify($data->guid));
1787 $conversation_guid = notags(unxmlify($data->conversation_guid));
1788 $text = unxmlify($data->text);
1789 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1791 $contact = self::allowed_contact_by_handle($importer, $author, true);
1796 $conversation = null;
1798 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1799 intval($importer["uid"]),
1800 dbesc($conversation_guid)
1803 $conversation = $c[0];
1805 logger("conversation not available.");
1809 $message_uri = $author.":".$guid;
1811 $person = self::person_by_handle($author);
1813 logger("unable to find author details");
1817 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1818 dbesc($message_uri),
1819 intval($importer["uid"])
1821 if (dbm::is_result($r)) {
1822 logger("duplicate message already delivered.", LOGGER_DEBUG);
1826 $body = diaspora2bb($text);
1828 $body = self::replace_people_guid($body, $person["url"]);
1830 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1831 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1832 intval($importer["uid"]),
1834 intval($conversation["id"]),
1835 dbesc($person["name"]),
1836 dbesc($person["photo"]),
1837 dbesc($person["url"]),
1838 intval($contact["id"]),
1839 dbesc($conversation["subject"]),
1843 dbesc($message_uri),
1844 dbesc($author.":".$conversation["guid"]),
1848 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1849 dbesc(datetime_convert()),
1850 intval($conversation["id"])
1857 * @brief Processes participations - unsupported by now
1859 * @param array $importer Array of the importer user
1860 * @param object $data The message object
1862 * @return bool always true
1864 private static function receive_participation($importer, $data) {
1865 // I'm not sure if we can fully support this message type
1870 * @brief Processes photos - unneeded
1872 * @param array $importer Array of the importer user
1873 * @param object $data The message object
1875 * @return bool always true
1877 private static function receive_photo($importer, $data) {
1878 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1883 * @brief Processes poll participations - unssupported
1885 * @param array $importer Array of the importer user
1886 * @param object $data The message object
1888 * @return bool always true
1890 private static function receive_poll_participation($importer, $data) {
1891 // We don't support polls by now
1896 * @brief Processes incoming profile updates
1898 * @param array $importer Array of the importer user
1899 * @param object $data The message object
1901 * @return bool Success
1903 private static function receive_profile($importer, $data) {
1904 $author = strtolower(notags(unxmlify($data->author)));
1906 $contact = self::contact_by_handle($importer["uid"], $author);
1910 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1911 $image_url = unxmlify($data->image_url);
1912 $birthday = unxmlify($data->birthday);
1913 $gender = unxmlify($data->gender);
1914 $about = diaspora2bb(unxmlify($data->bio));
1915 $location = diaspora2bb(unxmlify($data->location));
1916 $searchable = (unxmlify($data->searchable) == "true");
1917 $nsfw = (unxmlify($data->nsfw) == "true");
1918 $tags = unxmlify($data->tag_string);
1920 $tags = explode("#", $tags);
1922 $keywords = array();
1923 foreach ($tags as $tag) {
1924 $tag = trim(strtolower($tag));
1929 $keywords = implode(", ", $keywords);
1931 $handle_parts = explode("@", $author);
1932 $nick = $handle_parts[0];
1935 $name = $handle_parts[0];
1937 if ( preg_match("|^https?://|", $image_url) === 0)
1938 $image_url = "http://".$handle_parts[1].$image_url;
1940 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1942 // Generic birthday. We don't know the timezone. The year is irrelevant.
1944 $birthday = str_replace("1000", "1901", $birthday);
1946 if ($birthday != "")
1947 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1949 // this is to prevent multiple birthday notifications in a single year
1950 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1952 if (substr($birthday,5) === substr($contact["bd"],5))
1953 $birthday = $contact["bd"];
1955 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1956 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1960 dbesc(datetime_convert()),
1966 intval($contact["id"]),
1967 intval($importer["uid"])
1970 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1971 "photo" => $image_url, "name" => $name, "location" => $location,
1972 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1973 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1974 "hide" => !$searchable, "nsfw" => $nsfw);
1976 $gcid = update_gcontact($gcontact);
1978 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1980 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1986 * @brief Processes incoming friend requests
1988 * @param array $importer Array of the importer user
1989 * @param array $contact The contact that send the request
1991 private static function receive_request_make_friend($importer, $contact) {
1995 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1996 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1997 intval(CONTACT_IS_FRIEND),
1998 intval($contact["id"]),
1999 intval($importer["uid"])
2002 // send notification
2004 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2005 intval($importer["uid"])
2008 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
2010 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2011 intval($importer["uid"])
2014 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2016 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2019 $arr["protocol"] = PROTOCOL_DIASPORA;
2020 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2021 $arr["uid"] = $importer["uid"];
2022 $arr["contact-id"] = $self[0]["id"];
2024 $arr["type"] = 'wall';
2025 $arr["gravity"] = 0;
2027 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2028 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2029 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2030 $arr["verb"] = ACTIVITY_FRIEND;
2031 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2033 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2034 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2035 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2036 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2038 $arr["object"] = self::construct_new_friend_object($contact);
2040 $arr["last-child"] = 1;
2042 $arr["allow_cid"] = $user[0]["allow_cid"];
2043 $arr["allow_gid"] = $user[0]["allow_gid"];
2044 $arr["deny_cid"] = $user[0]["deny_cid"];
2045 $arr["deny_gid"] = $user[0]["deny_gid"];
2047 $i = item_store($arr);
2049 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2055 * @brief Creates a XML object for a "new friend" message
2057 * @param array $contact Array of the contact
2059 * @return string The XML
2061 private static function construct_new_friend_object($contact) {
2062 $objtype = ACTIVITY_OBJ_PERSON;
2063 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2064 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2066 $xmldata = array("object" => array("type" => $objtype,
2067 "title" => $contact["name"],
2068 "id" => $contact["url"]."/".$contact["name"],
2071 return xml::from_array($xmldata, $xml, true);
2075 * @brief Processes incoming sharing notification
2077 * @param array $importer Array of the importer user
2078 * @param object $data The message object
2080 * @return bool Success
2082 private static function receive_contact_request($importer, $data) {
2083 $author = unxmlify($data->author);
2084 $recipient = unxmlify($data->recipient);
2086 if (!$author || !$recipient) {
2090 // the current protocol version doesn't know these fields
2091 // That means that we will assume their existance
2092 if (isset($data->following)) {
2093 $following = (unxmlify($data->following) == "true");
2098 if (isset($data->sharing)) {
2099 $sharing = (unxmlify($data->sharing) == "true");
2104 $contact = self::contact_by_handle($importer["uid"],$author);
2106 // perhaps we were already sharing with this person. Now they're sharing with us.
2107 // That makes us friends.
2109 if ($following AND $sharing) {
2110 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2111 self::receive_request_make_friend($importer, $contact);
2113 // refetch the contact array
2114 $contact = self::contact_by_handle($importer["uid"],$author);
2116 // If we are now friends, we are sending a share message.
2117 // Normally we needn't to do so, but the first message could have been vanished.
2118 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2119 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2121 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2122 $ret = self::send_share($u[0], $contact);
2126 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2127 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2132 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2133 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2135 } elseif (!$following AND !$sharing) {
2136 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2138 } elseif (!$following AND $sharing) {
2139 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2140 } elseif ($following AND $sharing) {
2141 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2142 } elseif ($following AND !$sharing) {
2143 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2146 $ret = self::person_by_handle($author);
2148 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2149 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2153 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2155 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2156 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2157 intval($importer["uid"]),
2158 dbesc($ret["network"]),
2159 dbesc($ret["addr"]),
2162 dbesc(normalise_link($ret["url"])),
2164 dbesc($ret["name"]),
2165 dbesc($ret["nick"]),
2166 dbesc($ret["photo"]),
2167 dbesc($ret["pubkey"]),
2168 dbesc($ret["notify"]),
2169 dbesc($ret["poll"]),
2174 // find the contact record we just created
2176 $contact_record = self::contact_by_handle($importer["uid"],$author);
2178 if (!$contact_record) {
2179 logger("unable to locate newly created contact record.");
2183 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2185 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2187 if (intval($def_gid))
2188 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2190 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2192 if ($importer["page-flags"] == PAGE_NORMAL) {
2194 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2196 $hash = random_string().(string)time(); // Generate a confirm_key
2198 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2199 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2200 intval($importer["uid"]),
2201 intval($contact_record["id"]),
2204 dbesc(t("Sharing notification from Diaspora network")),
2206 dbesc(datetime_convert())
2210 // automatic friend approval
2212 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2214 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2216 // technically they are sharing with us (CONTACT_IS_SHARING),
2217 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2218 // we are going to change the relationship and make them a follower.
2220 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2221 $new_relation = CONTACT_IS_FRIEND;
2222 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2223 $new_relation = CONTACT_IS_SHARING;
2225 $new_relation = CONTACT_IS_FOLLOWER;
2227 $r = q("UPDATE `contact` SET `rel` = %d,
2235 intval($new_relation),
2236 dbesc(datetime_convert()),
2237 dbesc(datetime_convert()),
2238 intval($contact_record["id"])
2241 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2243 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2244 $ret = self::send_share($u[0], $contact_record);
2246 // Send the profile data, maybe it weren't transmitted before
2247 self::send_profile($importer["uid"], array($contact_record));
2255 * @brief Fetches a message with a given guid
2257 * @param string $guid message guid
2258 * @param string $orig_author handle of the original post
2259 * @param string $author handle of the sharer
2261 * @return array The fetched item
2263 private static function original_item($guid, $orig_author, $author) {
2265 // Do we already have this item?
2266 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2267 `author-name`, `author-link`, `author-avatar`
2268 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2271 if (dbm::is_result($r)) {
2272 logger("reshared message ".$guid." already exists on system.");
2274 // Maybe it is already a reshared item?
2275 // Then refetch the content, if it is a reshare from a reshare.
2276 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2277 if (self::is_reshare($r[0]["body"], true)) {
2279 } elseif (self::is_reshare($r[0]["body"], false)) {
2280 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2282 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2284 // Add OEmbed and other information to the body
2285 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2293 if (!dbm::is_result($r)) {
2294 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2295 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2296 $item_id = self::store_by_guid($guid, $server);
2299 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2300 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2301 $item_id = self::store_by_guid($guid, $server);
2305 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2306 `author-name`, `author-link`, `author-avatar`
2307 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2310 if (dbm::is_result($r)) {
2311 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2312 if (self::is_reshare($r[0]["body"], false)) {
2313 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2314 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2326 * @brief Processes a reshare message
2328 * @param array $importer Array of the importer user
2329 * @param object $data The message object
2330 * @param string $xml The original XML of the message
2332 * @return int the message id
2334 private static function receive_reshare($importer, $data, $xml) {
2335 $author = notags(unxmlify($data->author));
2336 $guid = notags(unxmlify($data->guid));
2337 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2338 $root_author = notags(unxmlify($data->root_author));
2339 $root_guid = notags(unxmlify($data->root_guid));
2340 /// @todo handle unprocessed property "provider_display_name"
2341 $public = notags(unxmlify($data->public));
2343 $contact = self::allowed_contact_by_handle($importer, $author, false);
2348 $message_id = self::message_exists($importer["uid"], $guid);
2353 $original_item = self::original_item($root_guid, $root_author, $author);
2354 if (!$original_item) {
2358 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2360 $datarray = array();
2362 $datarray["uid"] = $importer["uid"];
2363 $datarray["contact-id"] = $contact["id"];
2364 $datarray["network"] = NETWORK_DIASPORA;
2366 $datarray["author-name"] = $contact["name"];
2367 $datarray["author-link"] = $contact["url"];
2368 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2370 $datarray["owner-name"] = $datarray["author-name"];
2371 $datarray["owner-link"] = $datarray["author-link"];
2372 $datarray["owner-avatar"] = $datarray["author-avatar"];
2374 $datarray["guid"] = $guid;
2375 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2377 $datarray["verb"] = ACTIVITY_POST;
2378 $datarray["gravity"] = GRAVITY_PARENT;
2380 $datarray["protocol"] = PROTOCOL_DIASPORA;
2381 $datarray["source"] = $xml;
2383 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2384 $original_item["guid"], $original_item["created"], $orig_url);
2385 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2387 $datarray["tag"] = $original_item["tag"];
2388 $datarray["app"] = $original_item["app"];
2390 $datarray["plink"] = self::plink($author, $guid);
2391 $datarray["private"] = (($public == "false") ? 1 : 0);
2392 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2394 $datarray["object-type"] = $original_item["object-type"];
2396 self::fetch_guid($datarray);
2397 $message_id = item_store($datarray);
2400 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2407 * @brief Processes retractions
2409 * @param array $importer Array of the importer user
2410 * @param array $contact The contact of the item owner
2411 * @param object $data The message object
2413 * @return bool success
2415 private static function item_retraction($importer, $contact, $data) {
2416 $author = notags(unxmlify($data->author));
2417 $target_guid = notags(unxmlify($data->target_guid));
2418 $target_type = notags(unxmlify($data->target_type));
2420 $person = self::person_by_handle($author);
2421 if (!is_array($person)) {
2422 logger("unable to find author detail for ".$author);
2426 if (!isset($contact["url"])) {
2427 $contact["url"] = $person["url"];
2430 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2431 dbesc($target_guid),
2432 intval($importer["uid"])
2435 logger("Target guid ".$target_guid." was not found for user ".$importer["uid"]);
2439 // Check if the sender is the thread owner
2440 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2441 intval($r[0]["parent"]));
2443 // Only delete it if the parent author really fits
2444 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2445 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2449 // 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
2450 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2451 dbesc(datetime_convert()),
2452 dbesc(datetime_convert()),
2455 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2457 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2459 // Now check if the retraction needs to be relayed by us
2460 if ($p[0]["origin"]) {
2462 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2469 * @brief Receives retraction messages
2471 * @param array $importer Array of the importer user
2472 * @param string $sender The sender of the message
2473 * @param object $data The message object
2475 * @return bool Success
2477 private static function receive_retraction($importer, $sender, $data) {
2478 $target_type = notags(unxmlify($data->target_type));
2480 $contact = self::contact_by_handle($importer["uid"], $sender);
2481 if (!$contact AND (in_array($target_type, array("Contact", "Person")))) {
2482 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2486 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2488 switch ($target_type) {
2491 case "Post": // "Post" will be supported in a future version
2493 case "StatusMessage":
2494 return self::item_retraction($importer, $contact, $data);
2498 /// @todo What should we do with an "unshare"?
2499 // Removing the contact isn't correct since we still can read the public items
2500 contact_remove($contact["id"]);
2504 logger("Unknown target type ".$target_type);
2511 * @brief Receives status messages
2513 * @param array $importer Array of the importer user
2514 * @param object $data The message object
2515 * @param string $xml The original XML of the message
2517 * @return int The message id of the newly created item
2519 private static function receive_status_message($importer, $data, $xml) {
2520 $author = notags(unxmlify($data->author));
2521 $guid = notags(unxmlify($data->guid));
2522 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2523 $public = notags(unxmlify($data->public));
2524 $text = unxmlify($data->text);
2525 $provider_display_name = notags(unxmlify($data->provider_display_name));
2527 $contact = self::allowed_contact_by_handle($importer, $author, false);
2532 $message_id = self::message_exists($importer["uid"], $guid);
2538 if ($data->location) {
2539 foreach ($data->location->children() AS $fieldname => $data) {
2540 $address[$fieldname] = notags(unxmlify($data));
2544 $body = diaspora2bb($text);
2546 $datarray = array();
2548 // Attach embedded pictures to the body
2550 foreach ($data->photo AS $photo) {
2551 $body = "[img]".unxmlify($photo->remote_photo_path).
2552 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2555 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2557 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2559 // Add OEmbed and other information to the body
2560 if (!self::is_redmatrix($contact["url"])) {
2561 $body = add_page_info_to_body($body, false, true);
2565 /// @todo enable support for polls
2566 //if ($data->poll) {
2567 // foreach ($data->poll AS $poll)
2572 /// @todo enable support for events
2574 $datarray["uid"] = $importer["uid"];
2575 $datarray["contact-id"] = $contact["id"];
2576 $datarray["network"] = NETWORK_DIASPORA;
2578 $datarray["author-name"] = $contact["name"];
2579 $datarray["author-link"] = $contact["url"];
2580 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2582 $datarray["owner-name"] = $datarray["author-name"];
2583 $datarray["owner-link"] = $datarray["author-link"];
2584 $datarray["owner-avatar"] = $datarray["author-avatar"];
2586 $datarray["guid"] = $guid;
2587 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2589 $datarray["verb"] = ACTIVITY_POST;
2590 $datarray["gravity"] = GRAVITY_PARENT;
2592 $datarray["protocol"] = PROTOCOL_DIASPORA;
2593 $datarray["source"] = $xml;
2595 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2597 if ($provider_display_name != "") {
2598 $datarray["app"] = $provider_display_name;
2601 $datarray["plink"] = self::plink($author, $guid);
2602 $datarray["private"] = (($public == "false") ? 1 : 0);
2603 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2605 if (isset($address["address"])) {
2606 $datarray["location"] = $address["address"];
2609 if (isset($address["lat"]) AND isset($address["lng"])) {
2610 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2613 self::fetch_guid($datarray);
2614 $message_id = item_store($datarray);
2617 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2623 /* ************************************************************************************** *
2624 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2625 * ************************************************************************************** */
2628 * @brief returnes the handle of a contact
2630 * @param array $me contact array
2632 * @return string the handle in the format user@domain.tld
2634 private static function my_handle($contact) {
2635 if ($contact["addr"] != "") {
2636 return $contact["addr"];
2639 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2640 // So - just in case - we build the the address here.
2641 if ($contact["nickname"] != "") {
2642 $nick = $contact["nickname"];
2644 $nick = $contact["nick"];
2647 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2651 * @brief Creates the envelope for the "fetch" endpoint
2653 * @param string $msg The message that is to be transmitted
2654 * @param array $user The record of the sender
2656 * @return string The envelope
2659 public static function build_magic_envelope($msg, $user) {
2661 $b64url_data = base64url_encode($msg);
2662 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2664 $key_id = base64url_encode(self::my_handle($user));
2665 $type = "application/xml";
2666 $encoding = "base64url";
2667 $alg = "RSA-SHA256";
2668 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2669 $signature = rsa_sign($signable_data, $user["prvkey"]);
2670 $sig = base64url_encode($signature);
2672 $xmldata = array("me:env" => array("me:data" => $data,
2673 "@attributes" => array("type" => $type),
2674 "me:encoding" => $encoding,
2677 "@attributes2" => array("key_id" => $key_id)));
2679 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2681 return xml::from_array($xmldata, $xml, false, $namespaces);
2685 * @brief Creates the envelope for a public message
2687 * @param string $msg The message that is to be transmitted
2688 * @param array $user The record of the sender
2689 * @param array $contact Target of the communication
2690 * @param string $prvkey The private key of the sender
2691 * @param string $pubkey The public key of the receiver
2693 * @return string The envelope
2695 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2697 logger("Message: ".$msg, LOGGER_DATA);
2699 $handle = self::my_handle($user);
2701 $b64url_data = base64url_encode($msg);
2703 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2705 $type = "application/xml";
2706 $encoding = "base64url";
2707 $alg = "RSA-SHA256";
2709 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2711 $signature = rsa_sign($signable_data,$prvkey);
2712 $sig = base64url_encode($signature);
2714 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2715 "me:env" => array("me:encoding" => $encoding,
2718 "@attributes" => array("type" => $type),
2719 "me:sig" => $sig)));
2721 $namespaces = array("" => "https://joindiaspora.com/protocol",
2722 "me" => "http://salmon-protocol.org/ns/magic-env");
2724 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2726 logger("magic_env: ".$magic_env, LOGGER_DATA);
2731 * @brief Creates the envelope for a private message
2733 * @param string $msg The message that is to be transmitted
2734 * @param array $user The record of the sender
2735 * @param array $contact Target of the communication
2736 * @param string $prvkey The private key of the sender
2737 * @param string $pubkey The public key of the receiver
2739 * @return string The envelope
2741 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2743 logger("Message: ".$msg, LOGGER_DATA);
2745 // without a public key nothing will work
2748 logger("pubkey missing: contact id: ".$contact["id"]);
2752 $inner_aes_key = openssl_random_pseudo_bytes(32);
2753 $b_inner_aes_key = base64_encode($inner_aes_key);
2754 $inner_iv = openssl_random_pseudo_bytes(16);
2755 $b_inner_iv = base64_encode($inner_iv);
2757 $outer_aes_key = openssl_random_pseudo_bytes(32);
2758 $b_outer_aes_key = base64_encode($outer_aes_key);
2759 $outer_iv = openssl_random_pseudo_bytes(16);
2760 $b_outer_iv = base64_encode($outer_iv);
2762 $handle = self::my_handle($user);
2764 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2766 $b64_data = base64_encode($inner_encrypted);
2769 $b64url_data = base64url_encode($b64_data);
2770 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2772 $type = "application/xml";
2773 $encoding = "base64url";
2774 $alg = "RSA-SHA256";
2776 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2778 $signature = rsa_sign($signable_data,$prvkey);
2779 $sig = base64url_encode($signature);
2781 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2782 "aes_key" => $b_inner_aes_key,
2783 "author_id" => $handle));
2785 $decrypted_header = xml::from_array($xmldata, $xml, true);
2787 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2789 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2791 $encrypted_outer_key_bundle = "";
2792 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2794 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2796 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2798 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2799 "ciphertext" => base64_encode($ciphertext)));
2800 $cipher_json = base64_encode($encrypted_header_json_object);
2802 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2803 "me:env" => array("me:encoding" => $encoding,
2806 "@attributes" => array("type" => $type),
2807 "me:sig" => $sig)));
2809 $namespaces = array("" => "https://joindiaspora.com/protocol",
2810 "me" => "http://salmon-protocol.org/ns/magic-env");
2812 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2814 logger("magic_env: ".$magic_env, LOGGER_DATA);
2819 * @brief Create the envelope for a message
2821 * @param string $msg The message that is to be transmitted
2822 * @param array $user The record of the sender
2823 * @param array $contact Target of the communication
2824 * @param string $prvkey The private key of the sender
2825 * @param string $pubkey The public key of the receiver
2826 * @param bool $public Is the message public?
2828 * @return string The message that will be transmitted to other servers
2830 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2833 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2835 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2837 // The data that will be transmitted is double encoded via "urlencode", strange ...
2838 $slap = "xml=".urlencode(urlencode($magic_env));
2843 * @brief Creates a signature for a message
2845 * @param array $owner the array of the owner of the message
2846 * @param array $message The message that is to be signed
2848 * @return string The signature
2850 private static function signature($owner, $message) {
2852 unset($sigmsg["author_signature"]);
2853 unset($sigmsg["parent_author_signature"]);
2855 $signed_text = implode(";", $sigmsg);
2857 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2861 * @brief Transmit a message to a target server
2863 * @param array $owner the array of the item owner
2864 * @param array $contact Target of the communication
2865 * @param string $slap The message that is to be transmitted
2866 * @param bool $public_batch Is it a public post?
2867 * @param bool $queue_run Is the transmission called from the queue?
2868 * @param string $guid message guid
2870 * @return int Result of the transmission
2872 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2876 $enabled = intval(get_config("system", "diaspora_enabled"));
2880 $logid = random_string(4);
2881 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2883 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2887 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2889 if (!$queue_run && was_recently_delayed($contact["id"])) {
2892 if (!intval(get_config("system", "diaspora_test"))) {
2893 post_url($dest_url."/", $slap);
2894 $return_code = $a->get_curl_code();
2896 logger("test_mode");
2901 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2903 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2904 logger("queue message");
2906 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2907 intval($contact["id"]),
2908 dbesc(NETWORK_DIASPORA),
2910 intval($public_batch)
2913 logger("add_to_queue ignored - identical item already in queue");
2915 // queue message for redelivery
2916 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2918 // The message could not be delivered. We mark the contact as "dead"
2919 mark_for_death($contact);
2921 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2922 // We successfully delivered a message, the contact is alive
2923 unmark_for_death($contact);
2926 return(($return_code) ? $return_code : (-1));
2931 * @brief Build the post xml
2933 * @param string $type The message type
2934 * @param array $message The message data
2936 * @return string The post XML
2938 public static function build_post_xml($type, $message) {
2940 $data = array("XML" => array("post" => array($type => $message)));
2941 return xml::from_array($data, $xml);
2945 * @brief Builds and transmit messages
2947 * @param array $owner the array of the item owner
2948 * @param array $contact Target of the communication
2949 * @param string $type The message type
2950 * @param array $message The message data
2951 * @param bool $public_batch Is it a public post?
2952 * @param string $guid message guid
2953 * @param bool $spool Should the transmission be spooled or transmitted?
2955 * @return int Result of the transmission
2957 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2959 $msg = self::build_post_xml($type, $message);
2961 logger('message: '.$msg, LOGGER_DATA);
2962 logger('send guid '.$guid, LOGGER_DEBUG);
2964 // Fallback if the private key wasn't transmitted in the expected field
2965 if ($owner['uprvkey'] == "")
2966 $owner['uprvkey'] = $owner['prvkey'];
2968 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2971 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2974 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2976 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2978 return $return_code;
2982 * @brief Sends a "share" message
2984 * @param array $owner the array of the item owner
2985 * @param array $contact Target of the communication
2987 * @return int The result of the transmission
2989 public static function send_share($owner,$contact) {
2991 $message = array("sender_handle" => self::my_handle($owner),
2992 "recipient_handle" => $contact["addr"]);
2994 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2996 return self::build_and_transmit($owner, $contact, "request", $message);
3000 * @brief sends an "unshare"
3002 * @param array $owner the array of the item owner
3003 * @param array $contact Target of the communication
3005 * @return int The result of the transmission
3007 public static function send_unshare($owner,$contact) {
3009 $message = array("post_guid" => $owner["guid"],
3010 "diaspora_handle" => self::my_handle($owner),
3011 "type" => "Person");
3013 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3015 return self::build_and_transmit($owner, $contact, "retraction", $message);
3019 * @brief Checks a message body if it is a reshare
3021 * @param string $body The message body that is to be check
3022 * @param bool $complete Should it be a complete check or a simple check?
3024 * @return array|bool Reshare details or "false" if no reshare
3026 public static function is_reshare($body, $complete = true) {
3027 $body = trim($body);
3029 // Skip if it isn't a pure repeated messages
3030 // Does it start with a share?
3031 if ((strpos($body, "[share") > 0) AND $complete)
3034 // Does it end with a share?
3035 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3038 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3039 // Skip if there is no shared message in there
3040 if ($body == $attributes)
3043 // If we don't do the complete check we quit here
3048 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3049 if ($matches[1] != "")
3050 $guid = $matches[1];
3052 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3053 if ($matches[1] != "")
3054 $guid = $matches[1];
3057 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3058 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3061 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3062 $ret["root_guid"] = $guid;
3068 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3069 if ($matches[1] != "")
3070 $profile = $matches[1];
3072 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3073 if ($matches[1] != "")
3074 $profile = $matches[1];
3078 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3079 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3083 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3084 if ($matches[1] != "")
3085 $link = $matches[1];
3087 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3088 if ($matches[1] != "")
3089 $link = $matches[1];
3091 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3092 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3099 * @brief Create an event array
3101 * @param integer $event_id The id of the event
3103 * @return array with event data
3105 private static function build_event($event_id) {
3107 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3108 if (!dbm::is_result($r)) {
3114 $eventdata = array();
3116 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3117 if (!dbm::is_result($r)) {
3123 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3124 if (!dbm::is_result($r)) {
3130 $eventdata['author'] = self::my_handle($owner);
3132 if ($event['guid']) {
3133 $eventdata['guid'] = $event['guid'];
3136 $mask = 'Y-m-d\TH:i:s\Z';
3138 /// @todo - establish "all day" events in Friendica
3139 $eventdata["all_day"] = "false";
3141 if (!$event['adjust']) {
3142 $eventdata['timezone'] = $user['timezone'];
3144 if ($eventdata['timezone'] == "") {
3145 $eventdata['timezone'] = 'UTC';
3149 if ($event['start']) {
3150 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3152 if ($event['finish'] AND !$event['nofinish']) {
3153 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3155 if ($event['summary']) {
3156 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3158 if ($event['desc']) {
3159 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3161 if ($event['location']) {
3162 $location = array();
3163 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3164 $location["lat"] = 0;
3165 $location["lng"] = 0;
3166 $eventdata['location'] = $location;
3173 * @brief Create a post (status message or reshare)
3175 * @param array $item The item that will be exported
3176 * @param array $owner the array of the item owner
3179 * 'type' -> Message type ("status_message" or "reshare")
3180 * 'message' -> Array of XML elements of the status
3182 public static function build_status($item, $owner) {
3184 $cachekey = "diaspora:build_status:".$item['guid'];
3186 $result = Cache::get($cachekey);
3187 if (!is_null($result)) {
3191 $myaddr = self::my_handle($owner);
3193 $public = (($item["private"]) ? "false" : "true");
3195 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3197 // Detect a share element and do a reshare
3198 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3199 $message = array("root_diaspora_id" => $ret["root_handle"],
3200 "root_guid" => $ret["root_guid"],
3201 "guid" => $item["guid"],
3202 "diaspora_handle" => $myaddr,
3203 "public" => $public,
3204 "created_at" => $created,
3205 "provider_display_name" => $item["app"]);
3209 $title = $item["title"];
3210 $body = $item["body"];
3212 // convert to markdown
3213 $body = html_entity_decode(bb2diaspora($body));
3217 $body = "## ".html_entity_decode($title)."\n\n".$body;
3219 if ($item["attach"]) {
3220 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3222 $body .= "\n".t("Attachments:")."\n";
3223 foreach ($matches as $mtch)
3224 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3228 $location = array();
3230 if ($item["location"] != "")
3231 $location["address"] = $item["location"];
3233 if ($item["coord"] != "") {
3234 $coord = explode(" ", $item["coord"]);
3235 $location["lat"] = $coord[0];
3236 $location["lng"] = $coord[1];
3239 $message = array("raw_message" => $body,
3240 "location" => $location,
3241 "guid" => $item["guid"],
3242 "diaspora_handle" => $myaddr,
3243 "public" => $public,
3244 "created_at" => $created,
3245 "provider_display_name" => $item["app"]);
3247 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3248 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3249 unset($message["location"]);
3252 if ($item['event-id'] > 0) {
3253 $event = self::build_event($item['event-id']);
3254 if (count($event)) {
3255 $message['event'] = $event;
3257 /// @todo Once Diaspora supports it, we will remove the body
3258 // $message['raw_message'] = '';
3262 $type = "status_message";
3265 $msg = array("type" => $type, "message" => $message);
3267 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3273 * @brief Sends a post
3275 * @param array $item The item that will be exported
3276 * @param array $owner the array of the item owner
3277 * @param array $contact Target of the communication
3278 * @param bool $public_batch Is it a public post?
3280 * @return int The result of the transmission
3282 public static function send_status($item, $owner, $contact, $public_batch = false) {
3284 $status = self::build_status($item, $owner);
3286 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3290 * @brief Creates a "like" object
3292 * @param array $item The item that will be exported
3293 * @param array $owner the array of the item owner
3295 * @return array The data for a "like"
3297 private static function construct_like($item, $owner) {
3299 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3300 dbesc($item["thr-parent"]));
3301 if (!dbm::is_result($p))
3306 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3307 if ($item['verb'] === ACTIVITY_LIKE) {
3309 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3310 $positive = "false";
3313 return(array("positive" => $positive,
3314 "guid" => $item["guid"],
3315 "target_type" => $target_type,
3316 "parent_guid" => $parent["guid"],
3317 "author_signature" => "",
3318 "diaspora_handle" => self::my_handle($owner)));
3322 * @brief Creates an "EventParticipation" object
3324 * @param array $item The item that will be exported
3325 * @param array $owner the array of the item owner
3327 * @return array The data for an "EventParticipation"
3329 private static function construct_attend($item, $owner) {
3331 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3332 dbesc($item["thr-parent"]));
3333 if (!dbm::is_result($p))
3338 switch ($item['verb']) {
3339 case ACTIVITY_ATTEND:
3340 $attend_answer = 'accepted';
3342 case ACTIVITY_ATTENDNO:
3343 $attend_answer = 'declined';
3345 case ACTIVITY_ATTENDMAYBE:
3346 $attend_answer = 'tentative';
3349 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3353 return(array("author" => self::my_handle($owner),
3354 "guid" => $item["guid"],
3355 "parent_guid" => $parent["guid"],
3356 "status" => $attend_answer,
3357 "author_signature" => ""));
3361 * @brief Creates the object for a comment
3363 * @param array $item The item that will be exported
3364 * @param array $owner the array of the item owner
3366 * @return array The data for a comment
3368 private static function construct_comment($item, $owner) {
3370 $cachekey = "diaspora:construct_comment:".$item['guid'];
3372 $result = Cache::get($cachekey);
3373 if (!is_null($result)) {
3377 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3378 intval($item["parent"]),
3379 intval($item["parent"])
3382 if (!dbm::is_result($p))
3387 $text = html_entity_decode(bb2diaspora($item["body"]));
3388 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3390 $comment = array("guid" => $item["guid"],
3391 "parent_guid" => $parent["guid"],
3392 "author_signature" => "",
3394 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3395 "diaspora_handle" => self::my_handle($owner));
3397 // Send the thread parent guid only if it is a threaded comment
3398 if ($item['thr-parent'] != $item['parent-uri']) {
3399 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3402 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3408 * @brief Send a like or a comment
3410 * @param array $item The item that will be exported
3411 * @param array $owner the array of the item owner
3412 * @param array $contact Target of the communication
3413 * @param bool $public_batch Is it a public post?
3415 * @return int The result of the transmission
3417 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3419 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3420 $message = self::construct_attend($item, $owner);
3421 $type = "event_participation";
3422 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3423 $message = self::construct_like($item, $owner);
3426 $message = self::construct_comment($item, $owner);
3433 $message["author_signature"] = self::signature($owner, $message);
3435 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3439 * @brief Creates a message from a signature record entry
3441 * @param array $item The item that will be exported
3442 * @param array $signature The entry of the "sign" record
3444 * @return string The message
3446 private static function message_from_signature($item, $signature) {
3448 // Split the signed text
3449 $signed_parts = explode(";", $signature['signed_text']);
3451 if ($item["deleted"])
3452 $message = array("parent_author_signature" => "",
3453 "target_guid" => $signed_parts[0],
3454 "target_type" => $signed_parts[1],
3455 "sender_handle" => $signature['signer'],
3456 "target_author_signature" => $signature['signature']);
3457 elseif ($item['verb'] === ACTIVITY_LIKE)
3458 $message = array("positive" => $signed_parts[0],
3459 "guid" => $signed_parts[1],
3460 "target_type" => $signed_parts[2],
3461 "parent_guid" => $signed_parts[3],
3462 "parent_author_signature" => "",
3463 "author_signature" => $signature['signature'],
3464 "diaspora_handle" => $signed_parts[4]);
3466 // Remove the comment guid
3467 $guid = array_shift($signed_parts);
3469 // Remove the parent guid
3470 $parent_guid = array_shift($signed_parts);
3472 // Remove the handle
3473 $handle = array_pop($signed_parts);
3475 // Glue the parts together
3476 $text = implode(";", $signed_parts);
3478 $message = array("guid" => $guid,
3479 "parent_guid" => $parent_guid,
3480 "parent_author_signature" => "",
3481 "author_signature" => $signature['signature'],
3482 "text" => implode(";", $signed_parts),
3483 "diaspora_handle" => $handle);
3489 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3491 * @param array $item The item that will be exported
3492 * @param array $owner the array of the item owner
3493 * @param array $contact Target of the communication
3494 * @param bool $public_batch Is it a public post?
3496 * @return int The result of the transmission
3498 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3500 if ($item["deleted"])
3501 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3502 elseif ($item['verb'] === ACTIVITY_LIKE)
3507 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3509 // fetch the original signature
3511 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3512 intval($item["id"]));
3515 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3521 // Old way - is used by the internal Friendica functions
3522 /// @todo Change all signatur storing functions to the new format
3523 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3524 $message = self::message_from_signature($item, $signature);
3526 $msg = json_decode($signature['signed_text'], true);
3529 if (is_array($msg)) {
3530 foreach ($msg AS $field => $data) {
3531 if (!$item["deleted"]) {
3532 if ($field == "author")
3533 $field = "diaspora_handle";
3534 if ($field == "parent_type")
3535 $field = "target_type";
3538 $message[$field] = $data;
3541 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3544 $message["parent_author_signature"] = self::signature($owner, $message);
3546 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3548 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3552 * @brief Sends a retraction (deletion) of a message, like or comment
3554 * @param array $item The item that will be exported
3555 * @param array $owner the array of the item owner
3556 * @param array $contact Target of the communication
3557 * @param bool $public_batch Is it a public post?
3558 * @param bool $relay Is the retraction transmitted from a relay?
3560 * @return int The result of the transmission
3562 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3564 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3566 // Check whether the retraction is for a top-level post or whether it's a relayable
3567 if ($item["uri"] !== $item["parent-uri"]) {
3568 $msg_type = "relayable_retraction";
3569 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3571 $msg_type = "signed_retraction";
3572 $target_type = "StatusMessage";
3575 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3576 $signature = "parent_author_signature";
3578 $signature = "target_author_signature";
3580 $signed_text = $item["guid"].";".$target_type;
3582 $message = array("target_guid" => $item['guid'],
3583 "target_type" => $target_type,
3584 "sender_handle" => $itemaddr,
3585 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3587 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3589 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3593 * @brief Sends a mail
3595 * @param array $item The item that will be exported
3596 * @param array $owner The owner
3597 * @param array $contact Target of the communication
3599 * @return int The result of the transmission
3601 public static function send_mail($item, $owner, $contact) {
3603 $myaddr = self::my_handle($owner);
3605 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3606 intval($item["convid"]),
3607 intval($item["uid"])
3610 if (!dbm::is_result($r)) {
3611 logger("conversation not found.");
3617 "guid" => $cnv["guid"],
3618 "subject" => $cnv["subject"],
3619 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3620 "diaspora_handle" => $cnv["creator"],
3621 "participant_handles" => $cnv["recips"]
3624 $body = bb2diaspora($item["body"]);
3625 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3627 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3628 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3631 "guid" => $item["guid"],
3632 "parent_guid" => $cnv["guid"],
3633 "parent_author_signature" => $sig,
3634 "author_signature" => $sig,
3636 "created_at" => $created,
3637 "diaspora_handle" => $myaddr,
3638 "conversation_guid" => $cnv["guid"]
3641 if ($item["reply"]) {
3645 $message = array("guid" => $cnv["guid"],
3646 "subject" => $cnv["subject"],
3647 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3649 "diaspora_handle" => $cnv["creator"],
3650 "participant_handles" => $cnv["recips"]);
3652 $type = "conversation";
3655 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3659 * @brief Sends profile data
3661 * @param int $uid The user id
3663 public static function send_profile($uid, $recips = false) {
3669 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3670 AND `uid` = %d AND `rel` != %d",
3671 dbesc(NETWORK_DIASPORA),
3673 intval(CONTACT_IS_SHARING)
3678 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3680 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3681 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3682 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3691 $handle = $profile["addr"];
3692 $first = ((strpos($profile['name'],' ')
3693 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3694 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3695 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3696 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3697 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3698 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3700 if ($searchable === 'true') {
3701 $dob = '1000-00-00';
3703 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3704 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3706 $about = $profile['about'];
3707 $about = strip_tags(bbcode($about));
3709 $location = formatted_location($profile);
3711 if ($profile['pub_keywords']) {
3712 $kw = str_replace(',',' ',$profile['pub_keywords']);
3713 $kw = str_replace(' ',' ',$kw);
3714 $arr = explode(' ',$profile['pub_keywords']);
3716 for ($x = 0; $x < 5; $x ++) {
3718 $tags .= '#'. trim($arr[$x]) .' ';
3722 $tags = trim($tags);
3725 $message = array("diaspora_handle" => $handle,
3726 "first_name" => $first,
3727 "last_name" => $last,
3728 "image_url" => $large,
3729 "image_url_medium" => $medium,
3730 "image_url_small" => $small,
3732 "gender" => $profile['gender'],
3734 "location" => $location,
3735 "searchable" => $searchable,
3736 "tag_string" => $tags);
3738 foreach ($recips as $recip) {
3739 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3740 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3745 * @brief Stores the signature for likes that are created on our system
3747 * @param array $contact The contact array of the "like"
3748 * @param int $post_id The post id of the "like"
3750 * @return bool Success
3752 public static function store_like_signature($contact, $post_id) {
3754 // Is the contact the owner? Then fetch the private key
3755 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3756 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3760 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3761 if (!dbm::is_result($r)) {
3765 $contact["uprvkey"] = $r[0]['prvkey'];
3767 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3768 if (!dbm::is_result($r)) {
3772 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3776 $message = self::construct_like($r[0], $contact);
3777 $message["author_signature"] = self::signature($contact, $message);
3779 // We now store the signature more flexible to dynamically support new fields.
3780 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3781 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3782 intval($message_id),
3783 dbesc(json_encode($message))
3786 logger('Stored diaspora like signature');
3791 * @brief Stores the signature for comments that are created on our system
3793 * @param array $item The item array of the comment
3794 * @param array $contact The contact array of the item owner
3795 * @param string $uprvkey The private key of the sender
3796 * @param int $message_id The message id of the comment
3798 * @return bool Success
3800 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3802 if ($uprvkey == "") {
3803 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3807 $contact["uprvkey"] = $uprvkey;
3809 $message = self::construct_comment($item, $contact);
3810 $message["author_signature"] = self::signature($contact, $message);
3812 // We now store the signature more flexible to dynamically support new fields.
3813 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3814 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3815 intval($message_id),
3816 dbesc(json_encode($message))
3819 logger('Stored diaspora comment signature');