3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 use \Friendica\Core\Config;
13 require_once 'include/items.php';
14 require_once 'include/bb2diaspora.php';
15 require_once 'include/Scrape.php';
16 require_once 'include/Contact.php';
17 require_once 'include/Photo.php';
18 require_once 'include/socgraph.php';
19 require_once 'include/group.php';
20 require_once 'include/xml.php';
21 require_once 'include/datetime.php';
22 require_once 'include/queue_fn.php';
23 require_once 'include/cache.php';
24 require_once 'library/phpsec/Crypt/AES.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
193 * @param array $importer Array of the importer user
194 * @param string $xml urldecoded Diaspora salmon
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($importer, $xml) {
204 $basedom = parse_xml_string($xml);
206 if (!is_object($basedom))
209 $children = $basedom->children('https://joindiaspora.com/protocol');
211 if($children->header) {
213 $author_link = str_replace('acct:','',$children->header->author_id);
216 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
218 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
219 $ciphertext = base64_decode($encrypted_header->ciphertext);
221 $outer_key_bundle = '';
222 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
224 $j_outer_key_bundle = json_decode($outer_key_bundle);
226 $outer_iv = base64_decode($j_outer_key_bundle->iv);
227 $outer_key = base64_decode($j_outer_key_bundle->key);
229 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
231 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
232 $idom = parse_xml_string($decrypted,false);
234 $inner_iv = base64_decode($idom->iv);
235 $inner_aes_key = base64_decode($idom->aes_key);
237 $author_link = str_replace('acct:','',$idom->author_id);
240 $dom = $basedom->children(NAMESPACE_SALMON_ME);
242 // figure out where in the DOM tree our data is hiding
244 if($dom->provenance->data)
245 $base = $dom->provenance;
246 elseif($dom->env->data)
252 logger('unable to locate salmon data in xml');
253 http_status_exit(400);
257 // Stash the signature away for now. We have to find their key or it won't be good for anything.
258 $signature = base64url_decode($base->sig);
262 // strip whitespace so our data element will return to one big base64 blob
263 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
266 // stash away some other stuff for later
268 $type = $base->data[0]->attributes()->type[0];
269 $keyhash = $base->sig[0]->attributes()->keyhash[0];
270 $encoding = $base->encoding;
274 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
278 $data = base64url_decode($data);
282 $inner_decrypted = $data;
285 // Decode the encrypted blob
287 $inner_encrypted = base64_decode($data);
288 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
292 logger('Could not retrieve author URI.');
293 http_status_exit(400);
295 // Once we have the author URI, go to the web and try to find their public key
296 // (first this will look it up locally if it is in the fcontact cache)
297 // This will also convert diaspora public key from pkcs#1 to pkcs#8
299 logger('Fetching key for '.$author_link);
300 $key = self::key($author_link);
303 logger('Could not retrieve author key.');
304 http_status_exit(400);
307 $verify = rsa_verify($signed_data,$signature,$key);
310 logger('Message did not verify. Discarding.');
311 http_status_exit(400);
314 logger('Message verified.');
316 return array('message' => (string)$inner_decrypted,
317 'author' => unxmlify($author_link),
318 'key' => (string)$key);
323 * @brief Dispatches public messages and find the fitting receivers
325 * @param array $msg The post that will be dispatched
327 * @return int The message id of the generated message, "true" or "false" if there was an error
329 public static function dispatch_public($msg) {
331 $enabled = intval(get_config("system", "diaspora_enabled"));
333 logger("diaspora is disabled");
337 // Now distribute it to the followers
338 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
339 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
340 AND NOT `account_expired` AND NOT `account_removed`",
341 dbesc(NETWORK_DIASPORA),
342 dbesc($msg["author"])
345 if (dbm::is_result($r)) {
346 foreach ($r as $rr) {
347 logger("delivering to: ".$rr["username"]);
348 self::dispatch($rr,$msg);
351 $social_relay = (bool)Config::get('system', 'relay_subscribe', false);
353 // Use a dummy importer to import the data for the public copy
355 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
356 $message_id = self::dispatch($importer,$msg);
358 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
366 * @brief Dispatches the different message types to the different functions
368 * @param array $importer Array of the importer user
369 * @param array $msg The post that will be dispatched
371 * @return int The message id of the generated message, "true" or "false" if there was an error
373 public static function dispatch($importer, $msg) {
375 // The sender is the handle of the contact that sent the message.
376 // This will often be different with relayed messages (for example "like" and "comment")
377 $sender = $msg["author"];
379 if (!self::valid_posting($msg, $fields)) {
380 logger("Invalid posting");
384 $type = $fields->getName();
386 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
389 case "account_deletion":
390 return self::receive_account_deletion($importer, $fields);
393 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
396 return self::receive_contact_request($importer, $fields);
399 return self::receive_conversation($importer, $msg, $fields);
402 return self::receive_like($importer, $sender, $fields);
405 return self::receive_message($importer, $fields);
407 case "participation": // Not implemented
408 return self::receive_participation($importer, $fields);
410 case "photo": // Not implemented
411 return self::receive_photo($importer, $fields);
413 case "poll_participation": // Not implemented
414 return self::receive_poll_participation($importer, $fields);
417 return self::receive_profile($importer, $fields);
420 return self::receive_reshare($importer, $fields, $msg["message"]);
423 return self::receive_retraction($importer, $sender, $fields);
425 case "status_message":
426 return self::receive_status_message($importer, $fields, $msg["message"]);
429 logger("Unknown message type ".$type);
437 * @brief Checks if a posting is valid and fetches the data fields.
439 * This function does not only check the signature.
440 * It also does the conversion between the old and the new diaspora format.
442 * @param array $msg Array with the XML, the sender handle and the sender signature
443 * @param object $fields SimpleXML object that contains the posting when it is valid
445 * @return bool Is the posting valid?
447 private static function valid_posting($msg, &$fields) {
449 $data = parse_xml_string($msg["message"], false);
451 if (!is_object($data)) {
452 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
456 $first_child = $data->getName();
458 // Is this the new or the old version?
459 if ($data->getName() == "XML") {
461 foreach ($data->post->children() as $child)
468 $type = $element->getName();
471 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
473 // All retractions are handled identically from now on.
474 // In the new version there will only be "retraction".
475 if (in_array($type, array("signed_retraction", "relayable_retraction")))
476 $type = "retraction";
478 if ($type == "request")
481 $fields = new SimpleXMLElement("<".$type."/>");
485 foreach ($element->children() AS $fieldname => $entry) {
487 // Translation for the old XML structure
488 if ($fieldname == "diaspora_handle")
489 $fieldname = "author";
491 if ($fieldname == "participant_handles")
492 $fieldname = "participants";
494 if (in_array($type, array("like", "participation"))) {
495 if ($fieldname == "target_type")
496 $fieldname = "parent_type";
499 if ($fieldname == "sender_handle")
500 $fieldname = "author";
502 if ($fieldname == "recipient_handle")
503 $fieldname = "recipient";
505 if ($fieldname == "root_diaspora_id")
506 $fieldname = "root_author";
508 if ($type == "retraction") {
509 if ($fieldname == "post_guid")
510 $fieldname = "target_guid";
512 if ($fieldname == "type")
513 $fieldname = "target_type";
517 if (($fieldname == "author_signature") AND ($entry != ""))
518 $author_signature = base64_decode($entry);
519 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
520 $parent_author_signature = base64_decode($entry);
521 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
522 if ($signed_data != "") {
524 $signed_data_parent .= ";";
527 $signed_data .= $entry;
529 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
530 ($orig_type == "relayable_retraction"))
531 xml::copy($entry, $fields, $fieldname);
534 // This is something that shouldn't happen at all.
535 if (in_array($type, array("status_message", "reshare", "profile")))
536 if ($msg["author"] != $fields->author) {
537 logger("Message handle is not the same as envelope sender. Quitting this message.");
541 // Only some message types have signatures. So we quit here for the other types.
542 if (!in_array($type, array("comment", "message", "like")))
545 // No author_signature? This is a must, so we quit.
546 if (!isset($author_signature)) {
547 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
551 if (isset($parent_author_signature)) {
552 $key = self::key($msg["author"]);
554 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
555 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);
560 $key = self::key($fields->author);
562 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
563 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
570 * @brief Fetches the public key for a given handle
572 * @param string $handle The handle
574 * @return string The public key
576 private static function key($handle) {
577 $handle = strval($handle);
579 logger("Fetching diaspora key for: ".$handle);
581 $r = self::person_by_handle($handle);
589 * @brief Fetches data for a given handle
591 * @param string $handle The handle
593 * @return array the queried data
595 private static function person_by_handle($handle) {
597 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
598 dbesc(NETWORK_DIASPORA),
603 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
605 // update record occasionally so it doesn't get stale
606 $d = strtotime($person["updated"]." +00:00");
607 if ($d < strtotime("now - 14 days"))
610 if ($person["guid"] == "")
614 if (!$person OR $update) {
615 logger("create or refresh", LOGGER_DEBUG);
616 $r = probe_url($handle, PROBE_DIASPORA);
618 // Note that Friendica contacts will return a "Diaspora person"
619 // if Diaspora connectivity is enabled on their server
620 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
621 self::add_fcontact($r, $update);
629 * @brief Updates the fcontact table
631 * @param array $arr The fcontact data
632 * @param bool $update Update or insert?
634 * @return string The id of the fcontact entry
636 private static function add_fcontact($arr, $update = false) {
639 $r = q("UPDATE `fcontact` SET
653 WHERE `url` = '%s' AND `network` = '%s'",
655 dbesc($arr["photo"]),
656 dbesc($arr["request"]),
658 dbesc(strtolower($arr["addr"])),
660 dbesc($arr["batch"]),
661 dbesc($arr["notify"]),
663 dbesc($arr["confirm"]),
664 dbesc($arr["alias"]),
665 dbesc($arr["pubkey"]),
666 dbesc(datetime_convert()),
668 dbesc($arr["network"])
671 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
672 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
673 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
676 dbesc($arr["photo"]),
677 dbesc($arr["request"]),
681 dbesc($arr["batch"]),
682 dbesc($arr["notify"]),
684 dbesc($arr["confirm"]),
685 dbesc($arr["network"]),
686 dbesc($arr["alias"]),
687 dbesc($arr["pubkey"]),
688 dbesc(datetime_convert())
696 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
698 * @param int $contact_id The id in the contact table
699 * @param int $gcontact_id The id in the gcontact table
701 * @return string the handle
703 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
706 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
708 if ($gcontact_id != 0) {
709 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
710 intval($gcontact_id));
712 if (dbm::is_result($r)) {
713 return strtolower($r[0]["addr"]);
717 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
718 intval($contact_id));
720 if (dbm::is_result($r)) {
723 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
725 if ($contact['addr'] != "") {
726 $handle = $contact['addr'];
728 $baseurl_start = strpos($contact['url'],'://') + 3;
729 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
730 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
731 $handle = $contact['nick'].'@'.$baseurl;
735 return strtolower($handle);
739 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
742 * @param mixed $fcontact_guid Hexadecimal string guid
744 * @return string the contact url or null
746 public static function url_from_contact_guid($fcontact_guid) {
747 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
749 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
750 dbesc(NETWORK_DIASPORA),
751 dbesc($fcontact_guid)
754 if (dbm::is_result($r)) {
762 * @brief Get a contact id for a given handle
764 * @param int $uid The user id
765 * @param string $handle The handle in the format user@domain.tld
767 * @return The contact id
769 private static function contact_by_handle($uid, $handle) {
771 // First do a direct search on the contact table
772 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
777 if (dbm::is_result($r)) {
780 // We haven't found it?
781 // We use another function for it that will possibly create a contact entry
782 $cid = get_contact($handle, $uid);
785 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
787 if (dbm::is_result($r)) {
793 $handle_parts = explode("@", $handle);
794 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
795 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
800 if (dbm::is_result($r)) {
804 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
809 * @brief Check if posting is allowed for this contact
811 * @param array $importer Array of the importer user
812 * @param array $contact The contact that is checked
813 * @param bool $is_comment Is the check for a comment?
815 * @return bool is the contact allowed to post?
817 private static function post_allow($importer, $contact, $is_comment = false) {
819 // perhaps we were already sharing with this person. Now they're sharing with us.
820 // That makes us friends.
821 // Normally this should have handled by getting a request - but this could get lost
822 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
823 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
824 intval(CONTACT_IS_FRIEND),
825 intval($contact["id"]),
826 intval($importer["uid"])
828 $contact["rel"] = CONTACT_IS_FRIEND;
829 logger("defining user ".$contact["nick"]." as friend");
832 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
834 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
836 if($contact["rel"] == CONTACT_IS_FOLLOWER)
837 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
840 // Messages for the global users are always accepted
841 if ($importer["uid"] == 0)
848 * @brief Fetches the contact id for a handle and checks if posting is allowed
850 * @param array $importer Array of the importer user
851 * @param string $handle The checked handle in the format user@domain.tld
852 * @param bool $is_comment Is the check for a comment?
854 * @return array The contact data
856 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
857 $contact = self::contact_by_handle($importer["uid"], $handle);
859 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
863 if (!self::post_allow($importer, $contact, $is_comment)) {
864 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
871 * @brief Does the message already exists on the system?
873 * @param int $uid The user id
874 * @param string $guid The guid of the message
876 * @return int|bool message id if the message already was stored into the system - or false.
878 private static function message_exists($uid, $guid) {
879 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
884 if (dbm::is_result($r)) {
885 logger("message ".$guid." already exists for user ".$uid);
893 * @brief Checks for links to posts in a message
895 * @param array $item The item array
897 private static function fetch_guid($item) {
898 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
899 function ($match) use ($item){
900 return(self::fetch_guid_sub($match, $item));
905 * @brief Checks for relative /people/* links in an item body to match local
906 * contacts or prepends the remote host taken from the author link.
908 * @param string $body The item body to replace links from
909 * @param string $author_link The author link for missing local contact fallback
911 * @return the replaced string
913 public function replace_people_guid($body, $author_link) {
914 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
915 function ($match) use ($author_link) {
917 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
918 // 1 => '0123456789abcdef'
920 $handle = self::url_from_contact_guid($match[1]);
923 $return = '@[url='.$handle.']'.$match[2].'[/url]';
925 // No local match, restoring absolute remote URL from author scheme and host
926 $author_url = parse_url($author_link);
927 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
937 * @brief sub function of "fetch_guid" which checks for links in messages
939 * @param array $match array containing a link that has to be checked for a message link
940 * @param array $item The item array
942 private static function fetch_guid_sub($match, $item) {
943 if (!self::store_by_guid($match[1], $item["author-link"]))
944 self::store_by_guid($match[1], $item["owner-link"]);
948 * @brief Fetches an item with a given guid from a given server
950 * @param string $guid the message guid
951 * @param string $server The server address
952 * @param int $uid The user id of the user
954 * @return int the message id of the stored message or false
956 private static function store_by_guid($guid, $server, $uid = 0) {
957 $serverparts = parse_url($server);
958 $server = $serverparts["scheme"]."://".$serverparts["host"];
960 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
962 $msg = self::message($guid, $server);
967 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
969 // Now call the dispatcher
970 return self::dispatch_public($msg);
974 * @brief Fetches a message from a server
976 * @param string $guid message guid
977 * @param string $server The url of the server
978 * @param int $level Endless loop prevention
981 * 'message' => The message XML
982 * 'author' => The author handle
983 * 'key' => The public key of the author
985 private static function message($guid, $server, $level = 0) {
990 // This will work for new Diaspora servers and Friendica servers from 3.5
991 $source_url = $server."/fetch/post/".$guid;
992 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
994 $envelope = fetch_url($source_url);
996 logger("Envelope was fetched.", LOGGER_DEBUG);
997 $x = self::verify_magic_envelope($envelope);
999 logger("Envelope could not be verified.", LOGGER_DEBUG);
1001 logger("Envelope was verified.", LOGGER_DEBUG);
1005 // This will work for older Diaspora and Friendica servers
1007 $source_url = $server."/p/".$guid.".xml";
1008 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1010 $x = fetch_url($source_url);
1015 $source_xml = parse_xml_string($x, false);
1017 if (!is_object($source_xml))
1020 if ($source_xml->post->reshare) {
1021 // Reshare of a reshare - old Diaspora version
1022 logger("Message is a reshare", LOGGER_DEBUG);
1023 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1024 } elseif ($source_xml->getName() == "reshare") {
1025 // Reshare of a reshare - new Diaspora version
1026 logger("Message is a new reshare", LOGGER_DEBUG);
1027 return self::message($source_xml->root_guid, $server, ++$level);
1032 // Fetch the author - for the old and the new Diaspora version
1033 if ($source_xml->post->status_message->diaspora_handle)
1034 $author = (string)$source_xml->post->status_message->diaspora_handle;
1035 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1036 $author = (string)$source_xml->author;
1038 // If this isn't a "status_message" then quit
1040 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1044 $msg = array("message" => $x, "author" => $author);
1046 $msg["key"] = self::key($msg["author"]);
1052 * @brief Fetches the item record of a given guid
1054 * @param int $uid The user id
1055 * @param string $guid message guid
1056 * @param string $author The handle of the item
1057 * @param array $contact The contact of the item owner
1059 * @return array the item record
1061 private static function parent_item($uid, $guid, $author, $contact) {
1062 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1063 `author-name`, `author-link`, `author-avatar`,
1064 `owner-name`, `owner-link`, `owner-avatar`
1065 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1066 intval($uid), dbesc($guid));
1069 $result = self::store_by_guid($guid, $contact["url"], $uid);
1072 $person = self::person_by_handle($author);
1073 $result = self::store_by_guid($guid, $person["url"], $uid);
1077 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1079 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1080 `author-name`, `author-link`, `author-avatar`,
1081 `owner-name`, `owner-link`, `owner-avatar`
1082 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1083 intval($uid), dbesc($guid));
1088 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1091 logger("parent item found: parent: ".$guid." - user: ".$uid);
1097 * @brief returns contact details
1099 * @param array $contact The default contact if the person isn't found
1100 * @param array $person The record of the person
1101 * @param int $uid The user id
1104 * 'cid' => contact id
1105 * 'network' => network type
1107 private static function author_contact_by_url($contact, $person, $uid) {
1109 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1110 dbesc(normalise_link($person["url"])), intval($uid));
1113 $network = $r[0]["network"];
1115 // We are receiving content from a user that is about to be terminated
1116 // This means the user is vital, so we remove a possible termination date.
1117 unmark_for_death($contact);
1119 $cid = $contact["id"];
1120 $network = NETWORK_DIASPORA;
1123 return array("cid" => $cid, "network" => $network);
1127 * @brief Is the profile a hubzilla profile?
1129 * @param string $url The profile link
1131 * @return bool is it a hubzilla server?
1133 public static function is_redmatrix($url) {
1134 return(strstr($url, "/channel/"));
1138 * @brief Generate a post link with a given handle and message guid
1140 * @param string $addr The user handle
1141 * @param string $guid message guid
1143 * @return string the post link
1145 private static function plink($addr, $guid) {
1146 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1150 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1152 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1153 // So we try another way as well.
1154 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1156 $r[0]["network"] = $s[0]["network"];
1158 if ($r[0]["network"] == NETWORK_DFRN)
1159 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1161 if (self::is_redmatrix($r[0]["url"]))
1162 return $r[0]["url"]."/?f=&mid=".$guid;
1164 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1168 * @brief Processes an account deletion
1170 * @param array $importer Array of the importer user
1171 * @param object $data The message object
1173 * @return bool Success
1175 private static function receive_account_deletion($importer, $data) {
1177 /// @todo Account deletion should remove the contact from the global contacts as well
1179 $author = notags(unxmlify($data->author));
1181 $contact = self::contact_by_handle($importer["uid"], $author);
1183 logger("cannot find contact for author: ".$author);
1187 // We now remove the contact
1188 contact_remove($contact["id"]);
1193 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1195 * @param string $author Author handle
1196 * @param string $guid Message guid
1197 * @param boolean $onlyfound Only return uri when found in the database
1199 * @return string The constructed uri or the one from our database
1201 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1203 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1204 if (dbm::is_result($r)) {
1205 return $r[0]["uri"];
1206 } elseif (!$onlyfound) {
1207 return $author.":".$guid;
1214 * @brief Fetch the guid from our database with a given uri
1216 * @param string $author Author handle
1217 * @param string $uri Message uri
1219 * @return string The post guid
1221 private static function get_guid_from_uri($uri, $uid) {
1223 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1224 if (dbm::is_result($r)) {
1225 return $r[0]["guid"];
1232 * @brief Processes an incoming comment
1234 * @param array $importer Array of the importer user
1235 * @param string $sender The sender of the message
1236 * @param object $data The message object
1237 * @param string $xml The original XML of the message
1239 * @return int The message id of the generated comment or "false" if there was an error
1241 private static function receive_comment($importer, $sender, $data, $xml) {
1242 $guid = notags(unxmlify($data->guid));
1243 $parent_guid = notags(unxmlify($data->parent_guid));
1244 $text = unxmlify($data->text);
1245 $author = notags(unxmlify($data->author));
1247 if (isset($data->created_at)) {
1248 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1250 $created_at = datetime_convert();
1253 if (isset($data->thread_parent_guid)) {
1254 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1255 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1260 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1265 $message_id = self::message_exists($importer["uid"], $guid);
1270 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1271 if (!$parent_item) {
1275 $person = self::person_by_handle($author);
1276 if (!is_array($person)) {
1277 logger("unable to find author details");
1281 // Fetch the contact id - if we know this contact
1282 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1284 $datarray = array();
1286 $datarray["uid"] = $importer["uid"];
1287 $datarray["contact-id"] = $author_contact["cid"];
1288 $datarray["network"] = $author_contact["network"];
1290 $datarray["author-name"] = $person["name"];
1291 $datarray["author-link"] = $person["url"];
1292 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1294 $datarray["owner-name"] = $contact["name"];
1295 $datarray["owner-link"] = $contact["url"];
1296 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1298 $datarray["guid"] = $guid;
1299 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1301 $datarray["type"] = "remote-comment";
1302 $datarray["verb"] = ACTIVITY_POST;
1303 $datarray["gravity"] = GRAVITY_COMMENT;
1305 if ($thr_uri != "") {
1306 $datarray["parent-uri"] = $thr_uri;
1308 $datarray["parent-uri"] = $parent_item["uri"];
1311 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1312 $datarray["object"] = $xml;
1314 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1316 $body = diaspora2bb($text);
1318 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1320 self::fetch_guid($datarray);
1322 $message_id = item_store($datarray);
1325 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1328 // If we are the origin of the parent we store the original data and notify our followers
1329 if($message_id AND $parent_item["origin"]) {
1331 // Formerly we stored the signed text, the signature and the author in different fields.
1332 // We now store the raw data so that we are more flexible.
1333 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1334 intval($message_id),
1335 dbesc(json_encode($data))
1339 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1346 * @brief processes and stores private messages
1348 * @param array $importer Array of the importer user
1349 * @param array $contact The contact of the message
1350 * @param object $data The message object
1351 * @param array $msg Array of the processed message, author handle and key
1352 * @param object $mesg The private message
1353 * @param array $conversation The conversation record to which this message belongs
1355 * @return bool "true" if it was successful
1357 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1358 $guid = notags(unxmlify($data->guid));
1359 $subject = notags(unxmlify($data->subject));
1360 $author = notags(unxmlify($data->author));
1362 $msg_guid = notags(unxmlify($mesg->guid));
1363 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1364 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1365 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1366 $msg_text = unxmlify($mesg->text);
1367 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1369 // "diaspora_handle" is the element name from the old version
1370 // "author" is the element name from the new version
1371 if ($mesg->author) {
1372 $msg_author = notags(unxmlify($mesg->author));
1373 } elseif ($mesg->diaspora_handle) {
1374 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1379 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1381 if ($msg_conversation_guid != $guid) {
1382 logger("message conversation guid does not belong to the current conversation.");
1386 $body = diaspora2bb($msg_text);
1387 $message_uri = $msg_author.":".$msg_guid;
1389 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1391 $author_signature = base64_decode($msg_author_signature);
1393 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1397 $person = self::person_by_handle($msg_author);
1399 if (is_array($person) && x($person, "pubkey")) {
1400 $key = $person["pubkey"];
1402 logger("unable to find author details");
1407 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1408 logger("verification failed.");
1412 if ($msg_parent_author_signature) {
1413 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1415 $parent_author_signature = base64_decode($msg_parent_author_signature);
1419 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1420 logger("owner verification failed.");
1425 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1428 if (dbm::is_result($r)) {
1429 logger("duplicate message already delivered.", LOGGER_DEBUG);
1433 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1434 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1435 intval($importer["uid"]),
1437 intval($conversation["id"]),
1438 dbesc($person["name"]),
1439 dbesc($person["photo"]),
1440 dbesc($person["url"]),
1441 intval($contact["id"]),
1446 dbesc($message_uri),
1447 dbesc($author.":".$guid),
1448 dbesc($msg_created_at)
1451 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1452 dbesc(datetime_convert()),
1453 intval($conversation["id"])
1457 "type" => NOTIFY_MAIL,
1458 "notify_flags" => $importer["notify-flags"],
1459 "language" => $importer["language"],
1460 "to_name" => $importer["username"],
1461 "to_email" => $importer["email"],
1462 "uid" =>$importer["uid"],
1463 "item" => array("subject" => $subject, "body" => $body),
1464 "source_name" => $person["name"],
1465 "source_link" => $person["url"],
1466 "source_photo" => $person["thumb"],
1467 "verb" => ACTIVITY_POST,
1474 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1476 * @param array $importer Array of the importer user
1477 * @param array $msg Array of the processed message, author handle and key
1478 * @param object $data The message object
1480 * @return bool Success
1482 private static function receive_conversation($importer, $msg, $data) {
1483 $guid = notags(unxmlify($data->guid));
1484 $subject = notags(unxmlify($data->subject));
1485 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1486 $author = notags(unxmlify($data->author));
1487 $participants = notags(unxmlify($data->participants));
1489 $messages = $data->message;
1491 if (!count($messages)) {
1492 logger("empty conversation");
1496 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1500 $conversation = null;
1502 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1503 intval($importer["uid"]),
1507 $conversation = $c[0];
1509 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1510 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1511 intval($importer["uid"]),
1515 dbesc(datetime_convert()),
1517 dbesc($participants)
1520 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1521 intval($importer["uid"]),
1526 $conversation = $c[0];
1528 if (!$conversation) {
1529 logger("unable to create conversation.");
1533 foreach($messages as $mesg)
1534 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1540 * @brief Creates the body for a "like" message
1542 * @param array $contact The contact that send us the "like"
1543 * @param array $parent_item The item array of the parent item
1544 * @param string $guid message guid
1546 * @return string the body
1548 private static function construct_like_body($contact, $parent_item, $guid) {
1549 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1551 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1552 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1553 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1555 return sprintf($bodyverb, $ulink, $alink, $plink);
1559 * @brief Creates a XML object for a "like"
1561 * @param array $importer Array of the importer user
1562 * @param array $parent_item The item array of the parent item
1564 * @return string The XML
1566 private static function construct_like_object($importer, $parent_item) {
1567 $objtype = ACTIVITY_OBJ_NOTE;
1568 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1569 $parent_body = $parent_item["body"];
1571 $xmldata = array("object" => array("type" => $objtype,
1573 "id" => $parent_item["uri"],
1576 "content" => $parent_body));
1578 return xml::from_array($xmldata, $xml, true);
1582 * @brief Processes "like" messages
1584 * @param array $importer Array of the importer user
1585 * @param string $sender The sender of the message
1586 * @param object $data The message object
1588 * @return int The message id of the generated like or "false" if there was an error
1590 private static function receive_like($importer, $sender, $data) {
1591 $positive = notags(unxmlify($data->positive));
1592 $guid = notags(unxmlify($data->guid));
1593 $parent_type = notags(unxmlify($data->parent_type));
1594 $parent_guid = notags(unxmlify($data->parent_guid));
1595 $author = notags(unxmlify($data->author));
1597 // likes on comments aren't supported by Diaspora - only on posts
1598 // But maybe this will be supported in the future, so we will accept it.
1599 if (!in_array($parent_type, array("Post", "Comment")))
1602 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1606 $message_id = self::message_exists($importer["uid"], $guid);
1610 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1614 $person = self::person_by_handle($author);
1615 if (!is_array($person)) {
1616 logger("unable to find author details");
1620 // Fetch the contact id - if we know this contact
1621 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1623 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1624 // We would accept this anyhow.
1625 if ($positive == "true")
1626 $verb = ACTIVITY_LIKE;
1628 $verb = ACTIVITY_DISLIKE;
1630 $datarray = array();
1632 $datarray["uid"] = $importer["uid"];
1633 $datarray["contact-id"] = $author_contact["cid"];
1634 $datarray["network"] = $author_contact["network"];
1636 $datarray["author-name"] = $person["name"];
1637 $datarray["author-link"] = $person["url"];
1638 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1640 $datarray["owner-name"] = $contact["name"];
1641 $datarray["owner-link"] = $contact["url"];
1642 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1644 $datarray["guid"] = $guid;
1645 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1647 $datarray["type"] = "activity";
1648 $datarray["verb"] = $verb;
1649 $datarray["gravity"] = GRAVITY_LIKE;
1650 $datarray["parent-uri"] = $parent_item["uri"];
1652 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1653 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1655 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1657 $message_id = item_store($datarray);
1660 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1662 // If we are the origin of the parent we store the original data and notify our followers
1663 if($message_id AND $parent_item["origin"]) {
1665 // Formerly we stored the signed text, the signature and the author in different fields.
1666 // We now store the raw data so that we are more flexible.
1667 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1668 intval($message_id),
1669 dbesc(json_encode($data))
1673 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1680 * @brief Processes private messages
1682 * @param array $importer Array of the importer user
1683 * @param object $data The message object
1685 * @return bool Success?
1687 private static function receive_message($importer, $data) {
1688 $guid = notags(unxmlify($data->guid));
1689 $parent_guid = notags(unxmlify($data->parent_guid));
1690 $text = unxmlify($data->text);
1691 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1692 $author = notags(unxmlify($data->author));
1693 $conversation_guid = notags(unxmlify($data->conversation_guid));
1695 $contact = self::allowed_contact_by_handle($importer, $author, true);
1700 $conversation = null;
1702 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1703 intval($importer["uid"]),
1704 dbesc($conversation_guid)
1707 $conversation = $c[0];
1709 logger("conversation not available.");
1713 $message_uri = $author.":".$guid;
1715 $person = self::person_by_handle($author);
1717 logger("unable to find author details");
1721 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1722 dbesc($message_uri),
1723 intval($importer["uid"])
1725 if (dbm::is_result($r)) {
1726 logger("duplicate message already delivered.", LOGGER_DEBUG);
1730 $body = diaspora2bb($text);
1732 $body = self::replace_people_guid($body, $person["url"]);
1734 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1735 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1736 intval($importer["uid"]),
1738 intval($conversation["id"]),
1739 dbesc($person["name"]),
1740 dbesc($person["photo"]),
1741 dbesc($person["url"]),
1742 intval($contact["id"]),
1743 dbesc($conversation["subject"]),
1747 dbesc($message_uri),
1748 dbesc($author.":".$parent_guid),
1752 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1753 dbesc(datetime_convert()),
1754 intval($conversation["id"])
1761 * @brief Processes participations - unsupported by now
1763 * @param array $importer Array of the importer user
1764 * @param object $data The message object
1766 * @return bool always true
1768 private static function receive_participation($importer, $data) {
1769 // I'm not sure if we can fully support this message type
1774 * @brief Processes photos - unneeded
1776 * @param array $importer Array of the importer user
1777 * @param object $data The message object
1779 * @return bool always true
1781 private static function receive_photo($importer, $data) {
1782 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1787 * @brief Processes poll participations - unssupported
1789 * @param array $importer Array of the importer user
1790 * @param object $data The message object
1792 * @return bool always true
1794 private static function receive_poll_participation($importer, $data) {
1795 // We don't support polls by now
1800 * @brief Processes incoming profile updates
1802 * @param array $importer Array of the importer user
1803 * @param object $data The message object
1805 * @return bool Success
1807 private static function receive_profile($importer, $data) {
1808 $author = strtolower(notags(unxmlify($data->author)));
1810 $contact = self::contact_by_handle($importer["uid"], $author);
1814 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1815 $image_url = unxmlify($data->image_url);
1816 $birthday = unxmlify($data->birthday);
1817 $location = diaspora2bb(unxmlify($data->location));
1818 $about = diaspora2bb(unxmlify($data->bio));
1819 $gender = unxmlify($data->gender);
1820 $searchable = (unxmlify($data->searchable) == "true");
1821 $nsfw = (unxmlify($data->nsfw) == "true");
1822 $tags = unxmlify($data->tag_string);
1824 $tags = explode("#", $tags);
1826 $keywords = array();
1827 foreach ($tags as $tag) {
1828 $tag = trim(strtolower($tag));
1833 $keywords = implode(", ", $keywords);
1835 $handle_parts = explode("@", $author);
1836 $nick = $handle_parts[0];
1839 $name = $handle_parts[0];
1841 if( preg_match("|^https?://|", $image_url) === 0)
1842 $image_url = "http://".$handle_parts[1].$image_url;
1844 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1846 // Generic birthday. We don't know the timezone. The year is irrelevant.
1848 $birthday = str_replace("1000", "1901", $birthday);
1850 if ($birthday != "")
1851 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1853 // this is to prevent multiple birthday notifications in a single year
1854 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1856 if(substr($birthday,5) === substr($contact["bd"],5))
1857 $birthday = $contact["bd"];
1859 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1860 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1864 dbesc(datetime_convert()),
1870 intval($contact["id"]),
1871 intval($importer["uid"])
1874 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1875 "photo" => $image_url, "name" => $name, "location" => $location,
1876 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1877 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1878 "hide" => !$searchable, "nsfw" => $nsfw);
1880 $gcid = update_gcontact($gcontact);
1882 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1884 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1890 * @brief Processes incoming friend requests
1892 * @param array $importer Array of the importer user
1893 * @param array $contact The contact that send the request
1895 private static function receive_request_make_friend($importer, $contact) {
1899 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1900 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1901 intval(CONTACT_IS_FRIEND),
1902 intval($contact["id"]),
1903 intval($importer["uid"])
1906 // send notification
1908 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1909 intval($importer["uid"])
1912 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1914 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1915 intval($importer["uid"])
1918 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1920 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1923 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1924 $arr["uid"] = $importer["uid"];
1925 $arr["contact-id"] = $self[0]["id"];
1927 $arr["type"] = 'wall';
1928 $arr["gravity"] = 0;
1930 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1931 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1932 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1933 $arr["verb"] = ACTIVITY_FRIEND;
1934 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1936 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1937 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1938 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1939 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1941 $arr["object"] = self::construct_new_friend_object($contact);
1943 $arr["last-child"] = 1;
1945 $arr["allow_cid"] = $user[0]["allow_cid"];
1946 $arr["allow_gid"] = $user[0]["allow_gid"];
1947 $arr["deny_cid"] = $user[0]["deny_cid"];
1948 $arr["deny_gid"] = $user[0]["deny_gid"];
1950 $i = item_store($arr);
1952 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1958 * @brief Creates a XML object for a "new friend" message
1960 * @param array $contact Array of the contact
1962 * @return string The XML
1964 private static function construct_new_friend_object($contact) {
1965 $objtype = ACTIVITY_OBJ_PERSON;
1966 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1967 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1969 $xmldata = array("object" => array("type" => $objtype,
1970 "title" => $contact["name"],
1971 "id" => $contact["url"]."/".$contact["name"],
1974 return xml::from_array($xmldata, $xml, true);
1978 * @brief Processes incoming sharing notification
1980 * @param array $importer Array of the importer user
1981 * @param object $data The message object
1983 * @return bool Success
1985 private static function receive_contact_request($importer, $data) {
1986 $author = unxmlify($data->author);
1987 $recipient = unxmlify($data->recipient);
1989 if (!$author || !$recipient) {
1993 // the current protocol version doesn't know these fields
1994 // That means that we will assume their existance
1995 if (isset($data->following)) {
1996 $following = (unxmlify($data->following) == "true");
2001 if (isset($data->sharing)) {
2002 $sharing = (unxmlify($data->sharing) == "true");
2007 $contact = self::contact_by_handle($importer["uid"],$author);
2009 // perhaps we were already sharing with this person. Now they're sharing with us.
2010 // That makes us friends.
2012 if ($following AND $sharing) {
2013 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2014 self::receive_request_make_friend($importer, $contact);
2016 // refetch the contact array
2017 $contact = self::contact_by_handle($importer["uid"],$author);
2019 // If we are now friends, we are sending a share message.
2020 // Normally we needn't to do so, but the first message could have been vanished.
2021 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2022 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2024 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2025 $ret = self::send_share($u[0], $contact);
2029 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2030 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2035 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2036 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2038 } elseif (!$following AND !$sharing) {
2039 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2041 } elseif (!$following AND $sharing) {
2042 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2043 } elseif ($following AND $sharing) {
2044 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2045 } elseif ($following AND !$sharing) {
2046 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2049 $ret = self::person_by_handle($author);
2051 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2052 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2056 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2058 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2059 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2060 intval($importer["uid"]),
2061 dbesc($ret["network"]),
2062 dbesc($ret["addr"]),
2065 dbesc(normalise_link($ret["url"])),
2067 dbesc($ret["name"]),
2068 dbesc($ret["nick"]),
2069 dbesc($ret["photo"]),
2070 dbesc($ret["pubkey"]),
2071 dbesc($ret["notify"]),
2072 dbesc($ret["poll"]),
2077 // find the contact record we just created
2079 $contact_record = self::contact_by_handle($importer["uid"],$author);
2081 if (!$contact_record) {
2082 logger("unable to locate newly created contact record.");
2086 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2088 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2090 if(intval($def_gid))
2091 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2093 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2095 if($importer["page-flags"] == PAGE_NORMAL) {
2097 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2099 $hash = random_string().(string)time(); // Generate a confirm_key
2101 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2102 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2103 intval($importer["uid"]),
2104 intval($contact_record["id"]),
2107 dbesc(t("Sharing notification from Diaspora network")),
2109 dbesc(datetime_convert())
2113 // automatic friend approval
2115 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2117 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2119 // technically they are sharing with us (CONTACT_IS_SHARING),
2120 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2121 // we are going to change the relationship and make them a follower.
2123 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2124 $new_relation = CONTACT_IS_FRIEND;
2125 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2126 $new_relation = CONTACT_IS_SHARING;
2128 $new_relation = CONTACT_IS_FOLLOWER;
2130 $r = q("UPDATE `contact` SET `rel` = %d,
2138 intval($new_relation),
2139 dbesc(datetime_convert()),
2140 dbesc(datetime_convert()),
2141 intval($contact_record["id"])
2144 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2146 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2147 $ret = self::send_share($u[0], $contact_record);
2149 // Send the profile data, maybe it weren't transmitted before
2150 self::send_profile($importer["uid"], array($contact_record));
2158 * @brief Fetches a message with a given guid
2160 * @param string $guid message guid
2161 * @param string $orig_author handle of the original post
2162 * @param string $author handle of the sharer
2164 * @return array The fetched item
2166 private static function original_item($guid, $orig_author, $author) {
2168 // Do we already have this item?
2169 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2170 `author-name`, `author-link`, `author-avatar`
2171 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2174 if (dbm::is_result($r)) {
2175 logger("reshared message ".$guid." already exists on system.");
2177 // Maybe it is already a reshared item?
2178 // Then refetch the content, if it is a reshare from a reshare.
2179 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2180 if (self::is_reshare($r[0]["body"], true)) {
2182 } elseif (self::is_reshare($r[0]["body"], false)) {
2183 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2185 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2187 // Add OEmbed and other information to the body
2188 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2196 if (!dbm::is_result($r)) {
2197 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2198 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2199 $item_id = self::store_by_guid($guid, $server);
2202 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2203 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2204 $item_id = self::store_by_guid($guid, $server);
2208 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2209 `author-name`, `author-link`, `author-avatar`
2210 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2213 if (dbm::is_result($r)) {
2214 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2215 if (self::is_reshare($r[0]["body"], false)) {
2216 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2217 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2229 * @brief Processes a reshare message
2231 * @param array $importer Array of the importer user
2232 * @param object $data The message object
2233 * @param string $xml The original XML of the message
2235 * @return int the message id
2237 private static function receive_reshare($importer, $data, $xml) {
2238 $root_author = notags(unxmlify($data->root_author));
2239 $root_guid = notags(unxmlify($data->root_guid));
2240 $guid = notags(unxmlify($data->guid));
2241 $author = notags(unxmlify($data->author));
2242 $public = notags(unxmlify($data->public));
2243 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2245 $contact = self::allowed_contact_by_handle($importer, $author, false);
2250 $message_id = self::message_exists($importer["uid"], $guid);
2255 $original_item = self::original_item($root_guid, $root_author, $author);
2256 if (!$original_item) {
2260 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2262 $datarray = array();
2264 $datarray["uid"] = $importer["uid"];
2265 $datarray["contact-id"] = $contact["id"];
2266 $datarray["network"] = NETWORK_DIASPORA;
2268 $datarray["author-name"] = $contact["name"];
2269 $datarray["author-link"] = $contact["url"];
2270 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2272 $datarray["owner-name"] = $datarray["author-name"];
2273 $datarray["owner-link"] = $datarray["author-link"];
2274 $datarray["owner-avatar"] = $datarray["author-avatar"];
2276 $datarray["guid"] = $guid;
2277 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2279 $datarray["verb"] = ACTIVITY_POST;
2280 $datarray["gravity"] = GRAVITY_PARENT;
2282 $datarray["object"] = $xml;
2284 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2285 $original_item["guid"], $original_item["created"], $orig_url);
2286 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2288 $datarray["tag"] = $original_item["tag"];
2289 $datarray["app"] = $original_item["app"];
2291 $datarray["plink"] = self::plink($author, $guid);
2292 $datarray["private"] = (($public == "false") ? 1 : 0);
2293 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2295 $datarray["object-type"] = $original_item["object-type"];
2297 self::fetch_guid($datarray);
2298 $message_id = item_store($datarray);
2301 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2308 * @brief Processes retractions
2310 * @param array $importer Array of the importer user
2311 * @param array $contact The contact of the item owner
2312 * @param object $data The message object
2314 * @return bool success
2316 private static function item_retraction($importer, $contact, $data) {
2317 $target_type = notags(unxmlify($data->target_type));
2318 $target_guid = notags(unxmlify($data->target_guid));
2319 $author = notags(unxmlify($data->author));
2321 $person = self::person_by_handle($author);
2322 if (!is_array($person)) {
2323 logger("unable to find author detail for ".$author);
2327 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2328 dbesc($target_guid),
2329 intval($importer["uid"])
2335 // Check if the sender is the thread owner
2336 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2337 intval($r[0]["parent"]));
2339 // Only delete it if the parent author really fits
2340 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2341 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2345 // 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
2346 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2347 dbesc(datetime_convert()),
2348 dbesc(datetime_convert()),
2351 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2353 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2355 // Now check if the retraction needs to be relayed by us
2356 if ($p[0]["origin"]) {
2358 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2365 * @brief Receives retraction messages
2367 * @param array $importer Array of the importer user
2368 * @param string $sender The sender of the message
2369 * @param object $data The message object
2371 * @return bool Success
2373 private static function receive_retraction($importer, $sender, $data) {
2374 $target_type = notags(unxmlify($data->target_type));
2376 $contact = self::contact_by_handle($importer["uid"], $sender);
2378 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2382 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2384 switch ($target_type) {
2387 case "Post": // "Post" will be supported in a future version
2389 case "StatusMessage":
2390 return self::item_retraction($importer, $contact, $data);;
2394 /// @todo What should we do with an "unshare"?
2395 // Removing the contact isn't correct since we still can read the public items
2396 contact_remove($contact["id"]);
2400 logger("Unknown target type ".$target_type);
2407 * @brief Receives status messages
2409 * @param array $importer Array of the importer user
2410 * @param object $data The message object
2411 * @param string $xml The original XML of the message
2413 * @return int The message id of the newly created item
2415 private static function receive_status_message($importer, $data, $xml) {
2416 $raw_message = unxmlify($data->raw_message);
2417 $guid = notags(unxmlify($data->guid));
2418 $author = notags(unxmlify($data->author));
2419 $public = notags(unxmlify($data->public));
2420 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2421 $provider_display_name = notags(unxmlify($data->provider_display_name));
2423 /// @todo enable support for polls
2424 //if ($data->poll) {
2425 // foreach ($data->poll AS $poll)
2429 $contact = self::allowed_contact_by_handle($importer, $author, false);
2434 $message_id = self::message_exists($importer["uid"], $guid);
2440 if ($data->location) {
2441 foreach ($data->location->children() AS $fieldname => $data) {
2442 $address[$fieldname] = notags(unxmlify($data));
2446 $body = diaspora2bb($raw_message);
2448 $datarray = array();
2450 // Attach embedded pictures to the body
2452 foreach ($data->photo AS $photo) {
2453 $body = "[img]".unxmlify($photo->remote_photo_path).
2454 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2457 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2459 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2461 // Add OEmbed and other information to the body
2462 if (!self::is_redmatrix($contact["url"])) {
2463 $body = add_page_info_to_body($body, false, true);
2467 $datarray["uid"] = $importer["uid"];
2468 $datarray["contact-id"] = $contact["id"];
2469 $datarray["network"] = NETWORK_DIASPORA;
2471 $datarray["author-name"] = $contact["name"];
2472 $datarray["author-link"] = $contact["url"];
2473 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2475 $datarray["owner-name"] = $datarray["author-name"];
2476 $datarray["owner-link"] = $datarray["author-link"];
2477 $datarray["owner-avatar"] = $datarray["author-avatar"];
2479 $datarray["guid"] = $guid;
2480 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2482 $datarray["verb"] = ACTIVITY_POST;
2483 $datarray["gravity"] = GRAVITY_PARENT;
2485 $datarray["object"] = $xml;
2487 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2489 if ($provider_display_name != "") {
2490 $datarray["app"] = $provider_display_name;
2493 $datarray["plink"] = self::plink($author, $guid);
2494 $datarray["private"] = (($public == "false") ? 1 : 0);
2495 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2497 if (isset($address["address"])) {
2498 $datarray["location"] = $address["address"];
2501 if (isset($address["lat"]) AND isset($address["lng"])) {
2502 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2505 self::fetch_guid($datarray);
2506 $message_id = item_store($datarray);
2509 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2515 /* ************************************************************************************** *
2516 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2517 * ************************************************************************************** */
2520 * @brief returnes the handle of a contact
2522 * @param array $me contact array
2524 * @return string the handle in the format user@domain.tld
2526 private static function my_handle($contact) {
2527 if ($contact["addr"] != "") {
2528 return $contact["addr"];
2531 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2532 // So - just in case - we build the the address here.
2533 if ($contact["nickname"] != "") {
2534 $nick = $contact["nickname"];
2536 $nick = $contact["nick"];
2539 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2543 * @brief Creates the envelope for the "fetch" endpoint
2545 * @param string $msg The message that is to be transmitted
2546 * @param array $user The record of the sender
2548 * @return string The envelope
2551 public static function build_magic_envelope($msg, $user) {
2553 $b64url_data = base64url_encode($msg);
2554 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2556 $key_id = base64url_encode(self::my_handle($user));
2557 $type = "application/xml";
2558 $encoding = "base64url";
2559 $alg = "RSA-SHA256";
2560 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2561 $signature = rsa_sign($signable_data, $user["prvkey"]);
2562 $sig = base64url_encode($signature);
2564 $xmldata = array("me:env" => array("me:data" => $data,
2565 "@attributes" => array("type" => $type),
2566 "me:encoding" => $encoding,
2569 "@attributes2" => array("key_id" => $key_id)));
2571 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2573 return xml::from_array($xmldata, $xml, false, $namespaces);
2577 * @brief Creates the envelope for a public message
2579 * @param string $msg The message that is to be transmitted
2580 * @param array $user The record of the sender
2581 * @param array $contact Target of the communication
2582 * @param string $prvkey The private key of the sender
2583 * @param string $pubkey The public key of the receiver
2585 * @return string The envelope
2587 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2589 logger("Message: ".$msg, LOGGER_DATA);
2591 $handle = self::my_handle($user);
2593 $b64url_data = base64url_encode($msg);
2595 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2597 $type = "application/xml";
2598 $encoding = "base64url";
2599 $alg = "RSA-SHA256";
2601 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2603 $signature = rsa_sign($signable_data,$prvkey);
2604 $sig = base64url_encode($signature);
2606 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2607 "me:env" => array("me:encoding" => $encoding,
2610 "@attributes" => array("type" => $type),
2611 "me:sig" => $sig)));
2613 $namespaces = array("" => "https://joindiaspora.com/protocol",
2614 "me" => "http://salmon-protocol.org/ns/magic-env");
2616 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2618 logger("magic_env: ".$magic_env, LOGGER_DATA);
2623 * @brief Creates the envelope for a private message
2625 * @param string $msg The message that is to be transmitted
2626 * @param array $user The record of the sender
2627 * @param array $contact Target of the communication
2628 * @param string $prvkey The private key of the sender
2629 * @param string $pubkey The public key of the receiver
2631 * @return string The envelope
2633 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2635 logger("Message: ".$msg, LOGGER_DATA);
2637 // without a public key nothing will work
2640 logger("pubkey missing: contact id: ".$contact["id"]);
2644 $inner_aes_key = random_string(32);
2645 $b_inner_aes_key = base64_encode($inner_aes_key);
2646 $inner_iv = random_string(16);
2647 $b_inner_iv = base64_encode($inner_iv);
2649 $outer_aes_key = random_string(32);
2650 $b_outer_aes_key = base64_encode($outer_aes_key);
2651 $outer_iv = random_string(16);
2652 $b_outer_iv = base64_encode($outer_iv);
2654 $handle = self::my_handle($user);
2656 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2658 $b64_data = base64_encode($inner_encrypted);
2661 $b64url_data = base64url_encode($b64_data);
2662 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2664 $type = "application/xml";
2665 $encoding = "base64url";
2666 $alg = "RSA-SHA256";
2668 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2670 $signature = rsa_sign($signable_data,$prvkey);
2671 $sig = base64url_encode($signature);
2673 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2674 "aes_key" => $b_inner_aes_key,
2675 "author_id" => $handle));
2677 $decrypted_header = xml::from_array($xmldata, $xml, true);
2679 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2681 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2683 $encrypted_outer_key_bundle = "";
2684 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2686 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2688 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2690 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2691 "ciphertext" => base64_encode($ciphertext)));
2692 $cipher_json = base64_encode($encrypted_header_json_object);
2694 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2695 "me:env" => array("me:encoding" => $encoding,
2698 "@attributes" => array("type" => $type),
2699 "me:sig" => $sig)));
2701 $namespaces = array("" => "https://joindiaspora.com/protocol",
2702 "me" => "http://salmon-protocol.org/ns/magic-env");
2704 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2706 logger("magic_env: ".$magic_env, LOGGER_DATA);
2711 * @brief Create the envelope for a message
2713 * @param string $msg The message that is to be transmitted
2714 * @param array $user The record of the sender
2715 * @param array $contact Target of the communication
2716 * @param string $prvkey The private key of the sender
2717 * @param string $pubkey The public key of the receiver
2718 * @param bool $public Is the message public?
2720 * @return string The message that will be transmitted to other servers
2722 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2725 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2727 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2729 // The data that will be transmitted is double encoded via "urlencode", strange ...
2730 $slap = "xml=".urlencode(urlencode($magic_env));
2735 * @brief Creates a signature for a message
2737 * @param array $owner the array of the owner of the message
2738 * @param array $message The message that is to be signed
2740 * @return string The signature
2742 private static function signature($owner, $message) {
2744 unset($sigmsg["author_signature"]);
2745 unset($sigmsg["parent_author_signature"]);
2747 $signed_text = implode(";", $sigmsg);
2749 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2753 * @brief Transmit a message to a target server
2755 * @param array $owner the array of the item owner
2756 * @param array $contact Target of the communication
2757 * @param string $slap The message that is to be transmitted
2758 * @param bool $public_batch Is it a public post?
2759 * @param bool $queue_run Is the transmission called from the queue?
2760 * @param string $guid message guid
2762 * @return int Result of the transmission
2764 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2768 $enabled = intval(get_config("system", "diaspora_enabled"));
2772 $logid = random_string(4);
2773 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2775 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2779 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2781 if (!$queue_run && was_recently_delayed($contact["id"])) {
2784 if (!intval(get_config("system", "diaspora_test"))) {
2785 post_url($dest_url."/", $slap);
2786 $return_code = $a->get_curl_code();
2788 logger("test_mode");
2793 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2795 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2796 logger("queue message");
2798 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2799 intval($contact["id"]),
2800 dbesc(NETWORK_DIASPORA),
2802 intval($public_batch)
2805 logger("add_to_queue ignored - identical item already in queue");
2807 // queue message for redelivery
2808 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2810 // The message could not be delivered. We mark the contact as "dead"
2811 mark_for_death($contact);
2813 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2814 // We successfully delivered a message, the contact is alive
2815 unmark_for_death($contact);
2818 return(($return_code) ? $return_code : (-1));
2823 * @brief Build the post xml
2825 * @param string $type The message type
2826 * @param array $message The message data
2828 * @return string The post XML
2830 public static function build_post_xml($type, $message) {
2832 $data = array("XML" => array("post" => array($type => $message)));
2833 return xml::from_array($data, $xml);
2837 * @brief Builds and transmit messages
2839 * @param array $owner the array of the item owner
2840 * @param array $contact Target of the communication
2841 * @param string $type The message type
2842 * @param array $message The message data
2843 * @param bool $public_batch Is it a public post?
2844 * @param string $guid message guid
2845 * @param bool $spool Should the transmission be spooled or transmitted?
2847 * @return int Result of the transmission
2849 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2851 $msg = self::build_post_xml($type, $message);
2853 logger('message: '.$msg, LOGGER_DATA);
2854 logger('send guid '.$guid, LOGGER_DEBUG);
2856 // Fallback if the private key wasn't transmitted in the expected field
2857 if ($owner['uprvkey'] == "")
2858 $owner['uprvkey'] = $owner['prvkey'];
2860 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2863 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2866 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2868 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2870 return $return_code;
2874 * @brief Sends a "share" message
2876 * @param array $owner the array of the item owner
2877 * @param array $contact Target of the communication
2879 * @return int The result of the transmission
2881 public static function send_share($owner,$contact) {
2883 $message = array("sender_handle" => self::my_handle($owner),
2884 "recipient_handle" => $contact["addr"]);
2886 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2888 return self::build_and_transmit($owner, $contact, "request", $message);
2892 * @brief sends an "unshare"
2894 * @param array $owner the array of the item owner
2895 * @param array $contact Target of the communication
2897 * @return int The result of the transmission
2899 public static function send_unshare($owner,$contact) {
2901 $message = array("post_guid" => $owner["guid"],
2902 "diaspora_handle" => self::my_handle($owner),
2903 "type" => "Person");
2905 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2907 return self::build_and_transmit($owner, $contact, "retraction", $message);
2911 * @brief Checks a message body if it is a reshare
2913 * @param string $body The message body that is to be check
2914 * @param bool $complete Should it be a complete check or a simple check?
2916 * @return array|bool Reshare details or "false" if no reshare
2918 public static function is_reshare($body, $complete = true) {
2919 $body = trim($body);
2921 // Skip if it isn't a pure repeated messages
2922 // Does it start with a share?
2923 if ((strpos($body, "[share") > 0) AND $complete)
2926 // Does it end with a share?
2927 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2930 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2931 // Skip if there is no shared message in there
2932 if ($body == $attributes)
2935 // If we don't do the complete check we quit here
2940 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2941 if ($matches[1] != "")
2942 $guid = $matches[1];
2944 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2945 if ($matches[1] != "")
2946 $guid = $matches[1];
2949 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2950 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2953 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2954 $ret["root_guid"] = $guid;
2960 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2961 if ($matches[1] != "")
2962 $profile = $matches[1];
2964 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2965 if ($matches[1] != "")
2966 $profile = $matches[1];
2970 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2971 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2975 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2976 if ($matches[1] != "")
2977 $link = $matches[1];
2979 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2980 if ($matches[1] != "")
2981 $link = $matches[1];
2983 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2984 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2991 * @brief Create an event array
2993 * @param integer $event_id The id of the event
2995 * @return array with event data
2997 private static function build_event($event_id) {
2999 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3000 if (!dbm::is_result($r)) {
3006 $eventdata = array();
3008 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3009 if (!dbm::is_result($r)) {
3015 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3016 if (!dbm::is_result($r)) {
3022 $eventdata['author'] = self::my_handle($owner);
3024 if ($event['guid']) {
3025 $eventdata['guid'] = $event['guid'];
3028 $mask = 'Y-m-d\TH:i:s\Z';
3030 /// @todo - establish "all day" events in Friendica
3031 $eventdata["all_day"] = "false";
3033 if (!$event['adjust']) {
3034 $eventdata['timezone'] = $user['timezone'];
3036 if ($eventdata['timezone'] == "") {
3037 $eventdata['timezone'] = 'UTC';
3041 if ($event['start']) {
3042 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3044 if ($event['finish'] AND !$event['nofinish']) {
3045 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3047 if ($event['summary']) {
3048 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3050 if ($event['desc']) {
3051 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3053 if ($event['location']) {
3054 $location = array();
3055 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3056 $location["lat"] = 0;
3057 $location["lng"] = 0;
3058 $eventdata['location'] = $location;
3065 * @brief Create a post (status message or reshare)
3067 * @param array $item The item that will be exported
3068 * @param array $owner the array of the item owner
3071 * 'type' -> Message type ("status_message" or "reshare")
3072 * 'message' -> Array of XML elements of the status
3074 public static function build_status($item, $owner) {
3076 $cachekey = "diaspora:build_status:".$item['guid'];
3078 $result = Cache::get($cachekey);
3079 if (!is_null($result)) {
3083 $myaddr = self::my_handle($owner);
3085 $public = (($item["private"]) ? "false" : "true");
3087 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3089 // Detect a share element and do a reshare
3090 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3091 $message = array("root_diaspora_id" => $ret["root_handle"],
3092 "root_guid" => $ret["root_guid"],
3093 "guid" => $item["guid"],
3094 "diaspora_handle" => $myaddr,
3095 "public" => $public,
3096 "created_at" => $created,
3097 "provider_display_name" => $item["app"]);
3101 $title = $item["title"];
3102 $body = $item["body"];
3104 // convert to markdown
3105 $body = html_entity_decode(bb2diaspora($body));
3109 $body = "## ".html_entity_decode($title)."\n\n".$body;
3111 if ($item["attach"]) {
3112 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3114 $body .= "\n".t("Attachments:")."\n";
3115 foreach($matches as $mtch)
3116 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3120 $location = array();
3122 if ($item["location"] != "")
3123 $location["address"] = $item["location"];
3125 if ($item["coord"] != "") {
3126 $coord = explode(" ", $item["coord"]);
3127 $location["lat"] = $coord[0];
3128 $location["lng"] = $coord[1];
3131 $message = array("raw_message" => $body,
3132 "location" => $location,
3133 "guid" => $item["guid"],
3134 "diaspora_handle" => $myaddr,
3135 "public" => $public,
3136 "created_at" => $created,
3137 "provider_display_name" => $item["app"]);
3139 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3140 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3141 unset($message["location"]);
3144 if ($item['event-id'] > 0) {
3145 $event = self::build_event($item['event-id']);
3146 if (count($event)) {
3147 $message['event'] = $event;
3149 /// @todo Once Diaspora supports it, we will remove the body
3150 // $message['raw_message'] = '';
3154 $type = "status_message";
3157 $msg = array("type" => $type, "message" => $message);
3159 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3165 * @brief Sends a post
3167 * @param array $item The item that will be exported
3168 * @param array $owner the array of the item owner
3169 * @param array $contact Target of the communication
3170 * @param bool $public_batch Is it a public post?
3172 * @return int The result of the transmission
3174 public static function send_status($item, $owner, $contact, $public_batch = false) {
3176 $status = self::build_status($item, $owner);
3178 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3182 * @brief Creates a "like" object
3184 * @param array $item The item that will be exported
3185 * @param array $owner the array of the item owner
3187 * @return array The data for a "like"
3189 private static function construct_like($item, $owner) {
3191 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3192 dbesc($item["thr-parent"]));
3193 if (!dbm::is_result($p))
3198 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3199 if ($item['verb'] === ACTIVITY_LIKE) {
3201 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3202 $positive = "false";
3205 return(array("positive" => $positive,
3206 "guid" => $item["guid"],
3207 "target_type" => $target_type,
3208 "parent_guid" => $parent["guid"],
3209 "author_signature" => "",
3210 "diaspora_handle" => self::my_handle($owner)));
3214 * @brief Creates an "EventParticipation" object
3216 * @param array $item The item that will be exported
3217 * @param array $owner the array of the item owner
3219 * @return array The data for an "EventParticipation"
3221 private static function construct_attend($item, $owner) {
3223 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3224 dbesc($item["thr-parent"]));
3225 if (!dbm::is_result($p))
3230 switch ($item['verb']) {
3231 case ACTIVITY_ATTEND:
3232 $attend_answer = 'accepted';
3234 case ACTIVITY_ATTENDNO:
3235 $attend_answer = 'declined';
3237 case ACTIVITY_ATTENDMAYBE:
3238 $attend_answer = 'tentative';
3241 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3245 return(array("author" => self::my_handle($owner),
3246 "guid" => $item["guid"],
3247 "parent_guid" => $parent["guid"],
3248 "status" => $attend_answer,
3249 "author_signature" => ""));
3253 * @brief Creates the object for a comment
3255 * @param array $item The item that will be exported
3256 * @param array $owner the array of the item owner
3258 * @return array The data for a comment
3260 private static function construct_comment($item, $owner) {
3262 $cachekey = "diaspora:construct_comment:".$item['guid'];
3264 $result = Cache::get($cachekey);
3265 if (!is_null($result)) {
3269 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3270 intval($item["parent"]),
3271 intval($item["parent"])
3274 if (!dbm::is_result($p))
3279 $text = html_entity_decode(bb2diaspora($item["body"]));
3280 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3282 $comment = array("guid" => $item["guid"],
3283 "parent_guid" => $parent["guid"],
3284 "author_signature" => "",
3286 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3287 "diaspora_handle" => self::my_handle($owner));
3289 // Send the thread parent guid only if it is a threaded comment
3290 if ($item['thr-parent'] != $item['parent-uri']) {
3291 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3294 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3300 * @brief Send a like or a comment
3302 * @param array $item The item that will be exported
3303 * @param array $owner the array of the item owner
3304 * @param array $contact Target of the communication
3305 * @param bool $public_batch Is it a public post?
3307 * @return int The result of the transmission
3309 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3311 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3312 $message = self::construct_attend($item, $owner);
3313 $type = "event_participation";
3314 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3315 $message = self::construct_like($item, $owner);
3318 $message = self::construct_comment($item, $owner);
3325 $message["author_signature"] = self::signature($owner, $message);
3327 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3331 * @brief Creates a message from a signature record entry
3333 * @param array $item The item that will be exported
3334 * @param array $signature The entry of the "sign" record
3336 * @return string The message
3338 private static function message_from_signature($item, $signature) {
3340 // Split the signed text
3341 $signed_parts = explode(";", $signature['signed_text']);
3343 if ($item["deleted"])
3344 $message = array("parent_author_signature" => "",
3345 "target_guid" => $signed_parts[0],
3346 "target_type" => $signed_parts[1],
3347 "sender_handle" => $signature['signer'],
3348 "target_author_signature" => $signature['signature']);
3349 elseif ($item['verb'] === ACTIVITY_LIKE)
3350 $message = array("positive" => $signed_parts[0],
3351 "guid" => $signed_parts[1],
3352 "target_type" => $signed_parts[2],
3353 "parent_guid" => $signed_parts[3],
3354 "parent_author_signature" => "",
3355 "author_signature" => $signature['signature'],
3356 "diaspora_handle" => $signed_parts[4]);
3358 // Remove the comment guid
3359 $guid = array_shift($signed_parts);
3361 // Remove the parent guid
3362 $parent_guid = array_shift($signed_parts);
3364 // Remove the handle
3365 $handle = array_pop($signed_parts);
3367 // Glue the parts together
3368 $text = implode(";", $signed_parts);
3370 $message = array("guid" => $guid,
3371 "parent_guid" => $parent_guid,
3372 "parent_author_signature" => "",
3373 "author_signature" => $signature['signature'],
3374 "text" => implode(";", $signed_parts),
3375 "diaspora_handle" => $handle);
3381 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3383 * @param array $item The item that will be exported
3384 * @param array $owner the array of the item owner
3385 * @param array $contact Target of the communication
3386 * @param bool $public_batch Is it a public post?
3388 * @return int The result of the transmission
3390 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3392 if ($item["deleted"])
3393 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3394 elseif ($item['verb'] === ACTIVITY_LIKE)
3399 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3401 // fetch the original signature
3403 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3404 intval($item["id"]));
3407 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3413 // Old way - is used by the internal Friendica functions
3414 /// @todo Change all signatur storing functions to the new format
3415 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3416 $message = self::message_from_signature($item, $signature);
3418 $msg = json_decode($signature['signed_text'], true);
3421 if (is_array($msg)) {
3422 foreach ($msg AS $field => $data) {
3423 if (!$item["deleted"]) {
3424 if ($field == "author")
3425 $field = "diaspora_handle";
3426 if ($field == "parent_type")
3427 $field = "target_type";
3430 $message[$field] = $data;
3433 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3436 $message["parent_author_signature"] = self::signature($owner, $message);
3438 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3440 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3444 * @brief Sends a retraction (deletion) of a message, like or comment
3446 * @param array $item The item that will be exported
3447 * @param array $owner the array of the item owner
3448 * @param array $contact Target of the communication
3449 * @param bool $public_batch Is it a public post?
3450 * @param bool $relay Is the retraction transmitted from a relay?
3452 * @return int The result of the transmission
3454 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3456 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3458 // Check whether the retraction is for a top-level post or whether it's a relayable
3459 if ($item["uri"] !== $item["parent-uri"]) {
3460 $msg_type = "relayable_retraction";
3461 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3463 $msg_type = "signed_retraction";
3464 $target_type = "StatusMessage";
3467 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3468 $signature = "parent_author_signature";
3470 $signature = "target_author_signature";
3472 $signed_text = $item["guid"].";".$target_type;
3474 $message = array("target_guid" => $item['guid'],
3475 "target_type" => $target_type,
3476 "sender_handle" => $itemaddr,
3477 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3479 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3481 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3485 * @brief Sends a mail
3487 * @param array $item The item that will be exported
3488 * @param array $owner The owner
3489 * @param array $contact Target of the communication
3491 * @return int The result of the transmission
3493 public static function send_mail($item, $owner, $contact) {
3495 $myaddr = self::my_handle($owner);
3497 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3498 intval($item["convid"]),
3499 intval($item["uid"])
3502 if (!dbm::is_result($r)) {
3503 logger("conversation not found.");
3509 "guid" => $cnv["guid"],
3510 "subject" => $cnv["subject"],
3511 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3512 "diaspora_handle" => $cnv["creator"],
3513 "participant_handles" => $cnv["recips"]
3516 $body = bb2diaspora($item["body"]);
3517 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3519 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3520 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3523 "guid" => $item["guid"],
3524 "parent_guid" => $cnv["guid"],
3525 "parent_author_signature" => $sig,
3526 "author_signature" => $sig,
3528 "created_at" => $created,
3529 "diaspora_handle" => $myaddr,
3530 "conversation_guid" => $cnv["guid"]
3533 if ($item["reply"]) {
3537 $message = array("guid" => $cnv["guid"],
3538 "subject" => $cnv["subject"],
3539 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3541 "diaspora_handle" => $cnv["creator"],
3542 "participant_handles" => $cnv["recips"]);
3544 $type = "conversation";
3547 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3551 * @brief Sends profile data
3553 * @param int $uid The user id
3555 public static function send_profile($uid, $recips = false) {
3561 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3562 AND `uid` = %d AND `rel` != %d",
3563 dbesc(NETWORK_DIASPORA),
3565 intval(CONTACT_IS_SHARING)
3570 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3572 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3573 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3574 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3583 $handle = $profile["addr"];
3584 $first = ((strpos($profile['name'],' ')
3585 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3586 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3587 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3588 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3589 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3590 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3592 if ($searchable === 'true') {
3593 $dob = '1000-00-00';
3595 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3596 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3598 $about = $profile['about'];
3599 $about = strip_tags(bbcode($about));
3601 $location = formatted_location($profile);
3603 if ($profile['pub_keywords']) {
3604 $kw = str_replace(',',' ',$profile['pub_keywords']);
3605 $kw = str_replace(' ',' ',$kw);
3606 $arr = explode(' ',$profile['pub_keywords']);
3608 for($x = 0; $x < 5; $x ++) {
3610 $tags .= '#'. trim($arr[$x]) .' ';
3614 $tags = trim($tags);
3617 $message = array("diaspora_handle" => $handle,
3618 "first_name" => $first,
3619 "last_name" => $last,
3620 "image_url" => $large,
3621 "image_url_medium" => $medium,
3622 "image_url_small" => $small,
3624 "gender" => $profile['gender'],
3626 "location" => $location,
3627 "searchable" => $searchable,
3628 "tag_string" => $tags);
3630 foreach($recips as $recip) {
3631 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3632 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3637 * @brief Stores the signature for likes that are created on our system
3639 * @param array $contact The contact array of the "like"
3640 * @param int $post_id The post id of the "like"
3642 * @return bool Success
3644 public static function store_like_signature($contact, $post_id) {
3646 // Is the contact the owner? Then fetch the private key
3647 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3648 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3652 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3656 $contact["uprvkey"] = $r[0]['prvkey'];
3658 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3662 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3665 $message = self::construct_like($r[0], $contact);
3666 $message["author_signature"] = self::signature($contact, $message);
3668 // We now store the signature more flexible to dynamically support new fields.
3669 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3670 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3671 intval($message_id),
3672 dbesc(json_encode($message))
3675 logger('Stored diaspora like signature');
3680 * @brief Stores the signature for comments that are created on our system
3682 * @param array $item The item array of the comment
3683 * @param array $contact The contact array of the item owner
3684 * @param string $uprvkey The private key of the sender
3685 * @param int $message_id The message id of the comment
3687 * @return bool Success
3689 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3691 if ($uprvkey == "") {
3692 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3696 $contact["uprvkey"] = $uprvkey;
3698 $message = self::construct_comment($item, $contact);
3699 $message["author_signature"] = self::signature($contact, $message);
3701 // We now store the signature more flexible to dynamically support new fields.
3702 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3703 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3704 intval($message_id),
3705 dbesc(json_encode($message))
3708 logger('Stored diaspora comment signature');