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';
26 * @brief This class contain functions to create and send Diaspora XML files
32 * @brief Return a list of relay servers
34 * This is an experimental Diaspora feature.
36 * @return array of relay servers
38 public static function relay_list() {
40 $serverdata = get_config("system", "relay_server");
41 if ($serverdata == "")
46 $servers = explode(",", $serverdata);
48 foreach ($servers AS $server) {
49 $server = trim($server);
50 $addr = "relay@".str_replace("http://", "", normalise_link($server));
51 $batch = $server."/receive/public";
53 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
54 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
57 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
58 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
63 dbesc(normalise_link($server)),
65 dbesc(NETWORK_DIASPORA),
66 intval(CONTACT_IS_FOLLOWER),
67 dbesc(datetime_convert()),
68 dbesc(datetime_convert()),
69 dbesc(datetime_convert())
72 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
74 $relay[] = $relais[0];
76 $relay[] = $relais[0];
83 * @brief repairs a signature that was double encoded
85 * The function is unused at the moment. It was copied from the old implementation.
87 * @param string $signature The signature
88 * @param string $handle The handle of the signature owner
89 * @param integer $level This value is only set inside this function to avoid endless loops
91 * @return string the repaired signature
93 private static function repair_signature($signature, $handle = "", $level = 1) {
98 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
99 $signature = base64_decode($signature);
100 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
102 // Do a recursive call to be able to fix even multiple levels
104 $signature = self::repair_signature($signature, $handle, ++$level);
111 * @brief verify the envelope and return the verified data
113 * @param string $envelope The magic envelope
115 * @return string verified data
117 private static function verify_magic_envelope($envelope) {
119 $basedom = parse_xml_string($envelope, false);
121 if (!is_object($basedom)) {
122 logger("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 logger("XML has no children");
135 $data = base64url_decode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = base64url_decode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = base64url_decode($key_id);
147 $b64url_data = base64url_encode($data);
148 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
150 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
152 $key = self::key($handle);
154 $verify = rsa_verify($signable_data, $sig, $key);
156 logger('Message did not verify. Discarding.');
164 * @brief encrypts data via AES
166 * @param string $key The AES key
167 * @param string $iv The IV (is used for CBC encoding)
168 * @param string $data The data that is to be encrypted
170 * @return string encrypted data
172 private static function aes_encrypt($key, $iv, $data) {
173 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
177 * @brief decrypts data via AES
179 * @param string $key The AES key
180 * @param string $iv The IV (is used for CBC encoding)
181 * @param string $encrypted The encrypted data
183 * @return string decrypted data
185 private static function aes_decrypt($key, $iv, $encrypted) {
186 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
190 * @brief: Decodes incoming Diaspora message
192 * @param array $importer Array of the importer user
193 * @param string $xml urldecoded Diaspora salmon
196 * 'message' -> decoded Diaspora XML message
197 * 'author' -> author diaspora handle
198 * 'key' -> author public key (converted to pkcs#8)
200 public static function decode($importer, $xml) {
203 $basedom = parse_xml_string($xml);
205 if (!is_object($basedom))
208 $children = $basedom->children('https://joindiaspora.com/protocol');
210 if ($children->header) {
212 $author_link = str_replace('acct:','',$children->header->author_id);
215 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
217 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
218 $ciphertext = base64_decode($encrypted_header->ciphertext);
220 $outer_key_bundle = '';
221 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
223 $j_outer_key_bundle = json_decode($outer_key_bundle);
225 $outer_iv = base64_decode($j_outer_key_bundle->iv);
226 $outer_key = base64_decode($j_outer_key_bundle->key);
228 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
230 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
231 $idom = parse_xml_string($decrypted,false);
233 $inner_iv = base64_decode($idom->iv);
234 $inner_aes_key = base64_decode($idom->aes_key);
236 $author_link = str_replace('acct:','',$idom->author_id);
239 $dom = $basedom->children(NAMESPACE_SALMON_ME);
241 // figure out where in the DOM tree our data is hiding
243 if ($dom->provenance->data)
244 $base = $dom->provenance;
245 elseif ($dom->env->data)
251 logger('unable to locate salmon data in xml');
252 http_status_exit(400);
256 // Stash the signature away for now. We have to find their key or it won't be good for anything.
257 $signature = base64url_decode($base->sig);
261 // strip whitespace so our data element will return to one big base64 blob
262 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
265 // stash away some other stuff for later
267 $type = $base->data[0]->attributes()->type[0];
268 $keyhash = $base->sig[0]->attributes()->keyhash[0];
269 $encoding = $base->encoding;
273 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
277 $data = base64url_decode($data);
281 $inner_decrypted = $data;
284 // Decode the encrypted blob
286 $inner_encrypted = base64_decode($data);
287 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
291 logger('Could not retrieve author URI.');
292 http_status_exit(400);
294 // Once we have the author URI, go to the web and try to find their public key
295 // (first this will look it up locally if it is in the fcontact cache)
296 // This will also convert diaspora public key from pkcs#1 to pkcs#8
298 logger('Fetching key for '.$author_link);
299 $key = self::key($author_link);
302 logger('Could not retrieve author key.');
303 http_status_exit(400);
306 $verify = rsa_verify($signed_data,$signature,$key);
309 logger('Message did not verify. Discarding.');
310 http_status_exit(400);
313 logger('Message verified.');
315 return array('message' => (string)$inner_decrypted,
316 'author' => unxmlify($author_link),
317 'key' => (string)$key);
322 * @brief Dispatches public messages and find the fitting receivers
324 * @param array $msg The post that will be dispatched
326 * @return int The message id of the generated message, "true" or "false" if there was an error
328 public static function dispatch_public($msg) {
330 $enabled = intval(get_config("system", "diaspora_enabled"));
332 logger("diaspora is disabled");
336 if (!($postdata = self::valid_posting($msg))) {
337 logger("Invalid posting");
341 $fields = $postdata['fields'];
343 // Is it a an action (comment, like, ...) for our own post?
344 if (isset($fields->parent_guid) AND !$postdata["relayed"]) {
345 $guid = notags(unxmlify($fields->parent_guid));
346 $importer = self::importer_for_guid($guid);
347 if (is_array($importer)) {
348 logger("delivering to origin: ".$importer["name"]);
349 $message_id = self::dispatch($importer, $msg, $fields);
354 // Now distribute it to the followers
355 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
356 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
357 AND NOT `account_expired` AND NOT `account_removed`",
358 dbesc(NETWORK_DIASPORA),
359 dbesc($msg["author"])
362 if (dbm::is_result($r)) {
363 foreach ($r as $rr) {
364 logger("delivering to: ".$rr["username"]);
365 self::dispatch($rr, $msg, $fields);
367 } elseif (!Config::get('system', 'relay_subscribe', false)) {
368 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
370 // Use a dummy importer to import the data for the public copy
371 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
372 $message_id = self::dispatch($importer, $msg, $fields);
379 * @brief Dispatches the different message types to the different functions
381 * @param array $importer Array of the importer user
382 * @param array $msg The post that will be dispatched
384 * @return int The message id of the generated message, "true" or "false" if there was an error
386 public static function dispatch($importer, $msg, $fields = null) {
388 // The sender is the handle of the contact that sent the message.
389 // This will often be different with relayed messages (for example "like" and "comment")
390 $sender = $msg["author"];
392 // This is only needed for private postings since this is already done for public ones before
393 if (is_null($fields)) {
394 if (!($postdata = self::valid_posting($msg))) {
395 logger("Invalid posting");
398 $fields = $postdata['fields'];
401 $type = $fields->getName();
403 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
406 case "account_deletion":
407 return self::receive_account_deletion($importer, $fields);
410 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
413 return self::receive_contact_request($importer, $fields);
416 return self::receive_conversation($importer, $msg, $fields);
419 return self::receive_like($importer, $sender, $fields);
422 return self::receive_message($importer, $fields);
424 case "participation": // Not implemented
425 return self::receive_participation($importer, $fields);
427 case "photo": // Not implemented
428 return self::receive_photo($importer, $fields);
430 case "poll_participation": // Not implemented
431 return self::receive_poll_participation($importer, $fields);
434 return self::receive_profile($importer, $fields);
437 return self::receive_reshare($importer, $fields, $msg["message"]);
440 return self::receive_retraction($importer, $sender, $fields);
442 case "status_message":
443 return self::receive_status_message($importer, $fields, $msg["message"]);
446 logger("Unknown message type ".$type);
454 * @brief Checks if a posting is valid and fetches the data fields.
456 * This function does not only check the signature.
457 * It also does the conversion between the old and the new diaspora format.
459 * @param array $msg Array with the XML, the sender handle and the sender signature
460 * @param object $fields SimpleXML object that contains the posting when it is valid
462 * @return bool Is the posting valid?
464 private static function valid_posting($msg) {
466 $data = parse_xml_string($msg["message"], false);
468 if (!is_object($data)) {
469 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
473 $first_child = $data->getName();
475 // Is this the new or the old version?
476 if ($data->getName() == "XML") {
478 foreach ($data->post->children() as $child)
485 $type = $element->getName();
488 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
490 // All retractions are handled identically from now on.
491 // In the new version there will only be "retraction".
492 if (in_array($type, array("signed_retraction", "relayable_retraction")))
493 $type = "retraction";
495 if ($type == "request")
498 $fields = new SimpleXMLElement("<".$type."/>");
502 foreach ($element->children() AS $fieldname => $entry) {
504 // Translation for the old XML structure
505 if ($fieldname == "diaspora_handle")
506 $fieldname = "author";
508 if ($fieldname == "participant_handles")
509 $fieldname = "participants";
511 if (in_array($type, array("like", "participation"))) {
512 if ($fieldname == "target_type")
513 $fieldname = "parent_type";
516 if ($fieldname == "sender_handle")
517 $fieldname = "author";
519 if ($fieldname == "recipient_handle")
520 $fieldname = "recipient";
522 if ($fieldname == "root_diaspora_id")
523 $fieldname = "root_author";
525 if ($type == "retraction") {
526 if ($fieldname == "post_guid")
527 $fieldname = "target_guid";
529 if ($fieldname == "type")
530 $fieldname = "target_type";
534 if (($fieldname == "author_signature") AND ($entry != ""))
535 $author_signature = base64_decode($entry);
536 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
537 $parent_author_signature = base64_decode($entry);
538 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
539 if ($signed_data != "") {
541 $signed_data_parent .= ";";
544 $signed_data .= $entry;
546 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
547 ($orig_type == "relayable_retraction"))
548 xml::copy($entry, $fields, $fieldname);
551 // This is something that shouldn't happen at all.
552 if (in_array($type, array("status_message", "reshare", "profile")))
553 if ($msg["author"] != $fields->author) {
554 logger("Message handle is not the same as envelope sender. Quitting this message.");
558 // Only some message types have signatures. So we quit here for the other types.
559 if (!in_array($type, array("comment", "message", "like")))
560 return array("fields" => $fields, "relayed" => false);
562 // No author_signature? This is a must, so we quit.
563 if (!isset($author_signature)) {
564 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
568 if (isset($parent_author_signature)) {
571 $key = self::key($msg["author"]);
573 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
574 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);
581 $key = self::key($fields->author);
583 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
584 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
587 return array("fields" => $fields, "relayed" => $relayed);
591 * @brief Fetches the public key for a given handle
593 * @param string $handle The handle
595 * @return string The public key
597 private static function key($handle) {
598 $handle = strval($handle);
600 logger("Fetching diaspora key for: ".$handle);
602 $r = self::person_by_handle($handle);
610 * @brief Fetches data for a given handle
612 * @param string $handle The handle
614 * @return array the queried data
616 private static function person_by_handle($handle) {
618 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
619 dbesc(NETWORK_DIASPORA),
624 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
626 // update record occasionally so it doesn't get stale
627 $d = strtotime($person["updated"]." +00:00");
628 if ($d < strtotime("now - 14 days"))
631 if ($person["guid"] == "")
635 if (!$person OR $update) {
636 logger("create or refresh", LOGGER_DEBUG);
637 $r = probe_url($handle, PROBE_DIASPORA);
639 // Note that Friendica contacts will return a "Diaspora person"
640 // if Diaspora connectivity is enabled on their server
641 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
642 self::add_fcontact($r, $update);
650 * @brief Updates the fcontact table
652 * @param array $arr The fcontact data
653 * @param bool $update Update or insert?
655 * @return string The id of the fcontact entry
657 private static function add_fcontact($arr, $update = false) {
660 $r = q("UPDATE `fcontact` SET
674 WHERE `url` = '%s' AND `network` = '%s'",
676 dbesc($arr["photo"]),
677 dbesc($arr["request"]),
679 dbesc(strtolower($arr["addr"])),
681 dbesc($arr["batch"]),
682 dbesc($arr["notify"]),
684 dbesc($arr["confirm"]),
685 dbesc($arr["alias"]),
686 dbesc($arr["pubkey"]),
687 dbesc(datetime_convert()),
689 dbesc($arr["network"])
692 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
693 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
694 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
697 dbesc($arr["photo"]),
698 dbesc($arr["request"]),
702 dbesc($arr["batch"]),
703 dbesc($arr["notify"]),
705 dbesc($arr["confirm"]),
706 dbesc($arr["network"]),
707 dbesc($arr["alias"]),
708 dbesc($arr["pubkey"]),
709 dbesc(datetime_convert())
717 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
719 * @param int $contact_id The id in the contact table
720 * @param int $gcontact_id The id in the gcontact table
722 * @return string the handle
724 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
727 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
729 if ($gcontact_id != 0) {
730 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
731 intval($gcontact_id));
733 if (dbm::is_result($r)) {
734 return strtolower($r[0]["addr"]);
738 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
739 intval($contact_id));
741 if (dbm::is_result($r)) {
744 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
746 if ($contact['addr'] != "") {
747 $handle = $contact['addr'];
749 $baseurl_start = strpos($contact['url'],'://') + 3;
750 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
751 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
752 $handle = $contact['nick'].'@'.$baseurl;
756 return strtolower($handle);
760 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
763 * @param mixed $fcontact_guid Hexadecimal string guid
765 * @return string the contact url or null
767 public static function url_from_contact_guid($fcontact_guid) {
768 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
770 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
771 dbesc(NETWORK_DIASPORA),
772 dbesc($fcontact_guid)
775 if (dbm::is_result($r)) {
783 * @brief Get a contact id for a given handle
785 * @param int $uid The user id
786 * @param string $handle The handle in the format user@domain.tld
788 * @return The contact id
790 private static function contact_by_handle($uid, $handle) {
792 // First do a direct search on the contact table
793 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
798 if (dbm::is_result($r)) {
801 // We haven't found it?
802 // We use another function for it that will possibly create a contact entry
803 $cid = get_contact($handle, $uid);
806 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
808 if (dbm::is_result($r)) {
814 $handle_parts = explode("@", $handle);
815 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
816 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
821 if (dbm::is_result($r)) {
825 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
830 * @brief Check if posting is allowed for this contact
832 * @param array $importer Array of the importer user
833 * @param array $contact The contact that is checked
834 * @param bool $is_comment Is the check for a comment?
836 * @return bool is the contact allowed to post?
838 private static function post_allow($importer, $contact, $is_comment = false) {
840 // perhaps we were already sharing with this person. Now they're sharing with us.
841 // That makes us friends.
842 // Normally this should have handled by getting a request - but this could get lost
843 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
844 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
845 intval(CONTACT_IS_FRIEND),
846 intval($contact["id"]),
847 intval($importer["uid"])
849 $contact["rel"] = CONTACT_IS_FRIEND;
850 logger("defining user ".$contact["nick"]." as friend");
853 // We don't seem to like that person
854 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
856 // We are following this person? Then it is okay
857 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
859 // Is it a post to a community? That's good
860 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
863 // Messages for the global users and comments are always accepted
864 if (($importer["uid"] == 0) || $is_comment) {
872 * @brief Fetches the contact id for a handle and checks if posting is allowed
874 * @param array $importer Array of the importer user
875 * @param string $handle The checked handle in the format user@domain.tld
876 * @param bool $is_comment Is the check for a comment?
878 * @return array The contact data
880 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
881 $contact = self::contact_by_handle($importer["uid"], $handle);
883 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
884 // If a contact isn't found, we accept it anyway if it is a comment
892 if (!self::post_allow($importer, $contact, $is_comment)) {
893 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
900 * @brief Does the message already exists on the system?
902 * @param int $uid The user id
903 * @param string $guid The guid of the message
905 * @return int|bool message id if the message already was stored into the system - or false.
907 private static function message_exists($uid, $guid) {
908 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
913 if (dbm::is_result($r)) {
914 logger("message ".$guid." already exists for user ".$uid);
922 * @brief Checks for links to posts in a message
924 * @param array $item The item array
926 private static function fetch_guid($item) {
927 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
928 function ($match) use ($item){
929 return(self::fetch_guid_sub($match, $item));
934 * @brief Checks for relative /people/* links in an item body to match local
935 * contacts or prepends the remote host taken from the author link.
937 * @param string $body The item body to replace links from
938 * @param string $author_link The author link for missing local contact fallback
940 * @return the replaced string
942 public function replace_people_guid($body, $author_link) {
943 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
944 function ($match) use ($author_link) {
946 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
947 // 1 => '0123456789abcdef'
949 $handle = self::url_from_contact_guid($match[1]);
952 $return = '@[url='.$handle.']'.$match[2].'[/url]';
954 // No local match, restoring absolute remote URL from author scheme and host
955 $author_url = parse_url($author_link);
956 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
966 * @brief sub function of "fetch_guid" which checks for links in messages
968 * @param array $match array containing a link that has to be checked for a message link
969 * @param array $item The item array
971 private static function fetch_guid_sub($match, $item) {
972 if (!self::store_by_guid($match[1], $item["author-link"]))
973 self::store_by_guid($match[1], $item["owner-link"]);
977 * @brief Fetches an item with a given guid from a given server
979 * @param string $guid the message guid
980 * @param string $server The server address
981 * @param int $uid The user id of the user
983 * @return int the message id of the stored message or false
985 private static function store_by_guid($guid, $server, $uid = 0) {
986 $serverparts = parse_url($server);
987 $server = $serverparts["scheme"]."://".$serverparts["host"];
989 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
991 $msg = self::message($guid, $server);
996 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
998 // Now call the dispatcher
999 return self::dispatch_public($msg);
1003 * @brief Fetches a message from a server
1005 * @param string $guid message guid
1006 * @param string $server The url of the server
1007 * @param int $level Endless loop prevention
1010 * 'message' => The message XML
1011 * 'author' => The author handle
1012 * 'key' => The public key of the author
1014 private static function message($guid, $server, $level = 0) {
1019 // This will work for new Diaspora servers and Friendica servers from 3.5
1020 $source_url = $server."/fetch/post/".$guid;
1021 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1023 $envelope = fetch_url($source_url);
1025 logger("Envelope was fetched.", LOGGER_DEBUG);
1026 $x = self::verify_magic_envelope($envelope);
1028 logger("Envelope could not be verified.", LOGGER_DEBUG);
1030 logger("Envelope was verified.", LOGGER_DEBUG);
1034 // This will work for older Diaspora and Friendica servers
1036 $source_url = $server."/p/".$guid.".xml";
1037 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1039 $x = fetch_url($source_url);
1044 $source_xml = parse_xml_string($x, false);
1046 if (!is_object($source_xml))
1049 if ($source_xml->post->reshare) {
1050 // Reshare of a reshare - old Diaspora version
1051 logger("Message is a reshare", LOGGER_DEBUG);
1052 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1053 } elseif ($source_xml->getName() == "reshare") {
1054 // Reshare of a reshare - new Diaspora version
1055 logger("Message is a new reshare", LOGGER_DEBUG);
1056 return self::message($source_xml->root_guid, $server, ++$level);
1061 // Fetch the author - for the old and the new Diaspora version
1062 if ($source_xml->post->status_message->diaspora_handle)
1063 $author = (string)$source_xml->post->status_message->diaspora_handle;
1064 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1065 $author = (string)$source_xml->author;
1067 // If this isn't a "status_message" then quit
1069 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1073 $msg = array("message" => $x, "author" => $author);
1075 $msg["key"] = self::key($msg["author"]);
1081 * @brief Fetches the item record of a given guid
1083 * @param int $uid The user id
1084 * @param string $guid message guid
1085 * @param string $author The handle of the item
1086 * @param array $contact The contact of the item owner
1088 * @return array the item record
1090 private static function parent_item($uid, $guid, $author, $contact) {
1091 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1092 `author-name`, `author-link`, `author-avatar`,
1093 `owner-name`, `owner-link`, `owner-avatar`
1094 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1095 intval($uid), dbesc($guid));
1098 $result = self::store_by_guid($guid, $contact["url"], $uid);
1101 $person = self::person_by_handle($author);
1102 $result = self::store_by_guid($guid, $person["url"], $uid);
1106 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1108 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1109 `author-name`, `author-link`, `author-avatar`,
1110 `owner-name`, `owner-link`, `owner-avatar`
1111 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1112 intval($uid), dbesc($guid));
1117 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1120 logger("parent item found: parent: ".$guid." - user: ".$uid);
1126 * @brief returns contact details
1128 * @param array $contact The default contact if the person isn't found
1129 * @param array $person The record of the person
1130 * @param int $uid The user id
1133 * 'cid' => contact id
1134 * 'network' => network type
1136 private static function author_contact_by_url($contact, $person, $uid) {
1138 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1139 dbesc(normalise_link($person["url"])), intval($uid));
1142 $network = $r[0]["network"];
1144 // We are receiving content from a user that possibly is about to be terminated
1145 // This means the user is vital, so we remove a possible termination date.
1146 unmark_for_death($r[0]);
1148 $cid = $contact["id"];
1149 $network = NETWORK_DIASPORA;
1152 return array("cid" => $cid, "network" => $network);
1156 * @brief Is the profile a hubzilla profile?
1158 * @param string $url The profile link
1160 * @return bool is it a hubzilla server?
1162 public static function is_redmatrix($url) {
1163 return(strstr($url, "/channel/"));
1167 * @brief Generate a post link with a given handle and message guid
1169 * @param string $addr The user handle
1170 * @param string $guid message guid
1172 * @return string the post link
1174 private static function plink($addr, $guid) {
1175 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1179 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1181 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1182 // So we try another way as well.
1183 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1185 $r[0]["network"] = $s[0]["network"];
1187 if ($r[0]["network"] == NETWORK_DFRN)
1188 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1190 if (self::is_redmatrix($r[0]["url"]))
1191 return $r[0]["url"]."/?f=&mid=".$guid;
1193 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1197 * @brief Processes an account deletion
1199 * @param array $importer Array of the importer user
1200 * @param object $data The message object
1202 * @return bool Success
1204 private static function receive_account_deletion($importer, $data) {
1206 /// @todo Account deletion should remove the contact from the global contacts as well
1208 $author = notags(unxmlify($data->author));
1210 $contact = self::contact_by_handle($importer["uid"], $author);
1212 logger("cannot find contact for author: ".$author);
1216 // We now remove the contact
1217 contact_remove($contact["id"]);
1222 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1224 * @param string $author Author handle
1225 * @param string $guid Message guid
1226 * @param boolean $onlyfound Only return uri when found in the database
1228 * @return string The constructed uri or the one from our database
1230 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1232 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1233 if (dbm::is_result($r)) {
1234 return $r[0]["uri"];
1235 } elseif (!$onlyfound) {
1236 return $author.":".$guid;
1243 * @brief Fetch the guid from our database with a given uri
1245 * @param string $author Author handle
1246 * @param string $uri Message uri
1248 * @return string The post guid
1250 private static function get_guid_from_uri($uri, $uid) {
1252 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1253 if (dbm::is_result($r)) {
1254 return $r[0]["guid"];
1261 * @brief Find the best importer for a comment, like, ...
1263 * @param string $guid The guid of the item
1265 * @return array|boolean the origin owner of that post - or false
1267 private static function importer_for_guid($guid) {
1268 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1270 if (dbm::is_result($item)) {
1271 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1272 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1273 if (dbm::is_result($contact)) {
1281 * @brief Processes an incoming comment
1283 * @param array $importer Array of the importer user
1284 * @param string $sender The sender of the message
1285 * @param object $data The message object
1286 * @param string $xml The original XML of the message
1288 * @return int The message id of the generated comment or "false" if there was an error
1290 private static function receive_comment($importer, $sender, $data, $xml) {
1291 $guid = notags(unxmlify($data->guid));
1292 $parent_guid = notags(unxmlify($data->parent_guid));
1293 $text = unxmlify($data->text);
1294 $author = notags(unxmlify($data->author));
1296 if (isset($data->created_at)) {
1297 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1299 $created_at = datetime_convert();
1302 if (isset($data->thread_parent_guid)) {
1303 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1304 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1309 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1314 $message_id = self::message_exists($importer["uid"], $guid);
1319 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1320 if (!$parent_item) {
1324 $person = self::person_by_handle($author);
1325 if (!is_array($person)) {
1326 logger("unable to find author details");
1330 // Fetch the contact id - if we know this contact
1331 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1333 $datarray = array();
1335 $datarray["uid"] = $importer["uid"];
1336 $datarray["contact-id"] = $author_contact["cid"];
1337 $datarray["network"] = $author_contact["network"];
1339 $datarray["author-name"] = $person["name"];
1340 $datarray["author-link"] = $person["url"];
1341 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1343 $datarray["owner-name"] = $contact["name"];
1344 $datarray["owner-link"] = $contact["url"];
1345 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1347 $datarray["guid"] = $guid;
1348 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1350 $datarray["type"] = "remote-comment";
1351 $datarray["verb"] = ACTIVITY_POST;
1352 $datarray["gravity"] = GRAVITY_COMMENT;
1354 if ($thr_uri != "") {
1355 $datarray["parent-uri"] = $thr_uri;
1357 $datarray["parent-uri"] = $parent_item["uri"];
1360 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1362 $datarray["protocol"] = PROTOCOL_DIASPORA;
1363 $datarray["source"] = $xml;
1365 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1367 $body = diaspora2bb($text);
1369 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1371 self::fetch_guid($datarray);
1373 $message_id = item_store($datarray);
1376 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1379 // If we are the origin of the parent we store the original data and notify our followers
1380 if ($message_id AND $parent_item["origin"]) {
1382 // Formerly we stored the signed text, the signature and the author in different fields.
1383 // We now store the raw data so that we are more flexible.
1384 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1385 intval($message_id),
1386 dbesc(json_encode($data))
1390 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1397 * @brief processes and stores private messages
1399 * @param array $importer Array of the importer user
1400 * @param array $contact The contact of the message
1401 * @param object $data The message object
1402 * @param array $msg Array of the processed message, author handle and key
1403 * @param object $mesg The private message
1404 * @param array $conversation The conversation record to which this message belongs
1406 * @return bool "true" if it was successful
1408 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1409 $guid = notags(unxmlify($data->guid));
1410 $subject = notags(unxmlify($data->subject));
1411 $author = notags(unxmlify($data->author));
1413 $msg_guid = notags(unxmlify($mesg->guid));
1414 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1415 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1416 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1417 $msg_text = unxmlify($mesg->text);
1418 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1420 // "diaspora_handle" is the element name from the old version
1421 // "author" is the element name from the new version
1422 if ($mesg->author) {
1423 $msg_author = notags(unxmlify($mesg->author));
1424 } elseif ($mesg->diaspora_handle) {
1425 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1430 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1432 if ($msg_conversation_guid != $guid) {
1433 logger("message conversation guid does not belong to the current conversation.");
1437 $body = diaspora2bb($msg_text);
1438 $message_uri = $msg_author.":".$msg_guid;
1440 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1442 $author_signature = base64_decode($msg_author_signature);
1444 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1448 $person = self::person_by_handle($msg_author);
1450 if (is_array($person) && x($person, "pubkey")) {
1451 $key = $person["pubkey"];
1453 logger("unable to find author details");
1458 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1459 logger("verification failed.");
1463 if ($msg_parent_author_signature) {
1464 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1466 $parent_author_signature = base64_decode($msg_parent_author_signature);
1470 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1471 logger("owner verification failed.");
1476 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1479 if (dbm::is_result($r)) {
1480 logger("duplicate message already delivered.", LOGGER_DEBUG);
1484 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1485 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1486 intval($importer["uid"]),
1488 intval($conversation["id"]),
1489 dbesc($person["name"]),
1490 dbesc($person["photo"]),
1491 dbesc($person["url"]),
1492 intval($contact["id"]),
1497 dbesc($message_uri),
1498 dbesc($author.":".$guid),
1499 dbesc($msg_created_at)
1502 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1503 dbesc(datetime_convert()),
1504 intval($conversation["id"])
1508 "type" => NOTIFY_MAIL,
1509 "notify_flags" => $importer["notify-flags"],
1510 "language" => $importer["language"],
1511 "to_name" => $importer["username"],
1512 "to_email" => $importer["email"],
1513 "uid" =>$importer["uid"],
1514 "item" => array("subject" => $subject, "body" => $body),
1515 "source_name" => $person["name"],
1516 "source_link" => $person["url"],
1517 "source_photo" => $person["thumb"],
1518 "verb" => ACTIVITY_POST,
1525 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1527 * @param array $importer Array of the importer user
1528 * @param array $msg Array of the processed message, author handle and key
1529 * @param object $data The message object
1531 * @return bool Success
1533 private static function receive_conversation($importer, $msg, $data) {
1534 $guid = notags(unxmlify($data->guid));
1535 $subject = notags(unxmlify($data->subject));
1536 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1537 $author = notags(unxmlify($data->author));
1538 $participants = notags(unxmlify($data->participants));
1540 $messages = $data->message;
1542 if (!count($messages)) {
1543 logger("empty conversation");
1547 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1551 $conversation = null;
1553 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1554 intval($importer["uid"]),
1558 $conversation = $c[0];
1560 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1561 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1562 intval($importer["uid"]),
1566 dbesc(datetime_convert()),
1568 dbesc($participants)
1571 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1572 intval($importer["uid"]),
1577 $conversation = $c[0];
1579 if (!$conversation) {
1580 logger("unable to create conversation.");
1584 foreach ($messages as $mesg)
1585 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1591 * @brief Creates the body for a "like" message
1593 * @param array $contact The contact that send us the "like"
1594 * @param array $parent_item The item array of the parent item
1595 * @param string $guid message guid
1597 * @return string the body
1599 private static function construct_like_body($contact, $parent_item, $guid) {
1600 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1602 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1603 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1604 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1606 return sprintf($bodyverb, $ulink, $alink, $plink);
1610 * @brief Creates a XML object for a "like"
1612 * @param array $importer Array of the importer user
1613 * @param array $parent_item The item array of the parent item
1615 * @return string The XML
1617 private static function construct_like_object($importer, $parent_item) {
1618 $objtype = ACTIVITY_OBJ_NOTE;
1619 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1620 $parent_body = $parent_item["body"];
1622 $xmldata = array("object" => array("type" => $objtype,
1624 "id" => $parent_item["uri"],
1627 "content" => $parent_body));
1629 return xml::from_array($xmldata, $xml, true);
1633 * @brief Processes "like" messages
1635 * @param array $importer Array of the importer user
1636 * @param string $sender The sender of the message
1637 * @param object $data The message object
1639 * @return int The message id of the generated like or "false" if there was an error
1641 private static function receive_like($importer, $sender, $data) {
1642 $positive = notags(unxmlify($data->positive));
1643 $guid = notags(unxmlify($data->guid));
1644 $parent_type = notags(unxmlify($data->parent_type));
1645 $parent_guid = notags(unxmlify($data->parent_guid));
1646 $author = notags(unxmlify($data->author));
1648 // likes on comments aren't supported by Diaspora - only on posts
1649 // But maybe this will be supported in the future, so we will accept it.
1650 if (!in_array($parent_type, array("Post", "Comment")))
1653 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1657 $message_id = self::message_exists($importer["uid"], $guid);
1661 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1665 $person = self::person_by_handle($author);
1666 if (!is_array($person)) {
1667 logger("unable to find author details");
1671 // Fetch the contact id - if we know this contact
1672 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1674 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1675 // We would accept this anyhow.
1676 if ($positive == "true")
1677 $verb = ACTIVITY_LIKE;
1679 $verb = ACTIVITY_DISLIKE;
1681 $datarray = array();
1683 $datarray["protocol"] = PROTOCOL_DIASPORA;
1685 $datarray["uid"] = $importer["uid"];
1686 $datarray["contact-id"] = $author_contact["cid"];
1687 $datarray["network"] = $author_contact["network"];
1689 $datarray["author-name"] = $person["name"];
1690 $datarray["author-link"] = $person["url"];
1691 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1693 $datarray["owner-name"] = $contact["name"];
1694 $datarray["owner-link"] = $contact["url"];
1695 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1697 $datarray["guid"] = $guid;
1698 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1700 $datarray["type"] = "activity";
1701 $datarray["verb"] = $verb;
1702 $datarray["gravity"] = GRAVITY_LIKE;
1703 $datarray["parent-uri"] = $parent_item["uri"];
1705 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1706 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1708 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1710 $message_id = item_store($datarray);
1713 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1715 // If we are the origin of the parent we store the original data and notify our followers
1716 if ($message_id AND $parent_item["origin"]) {
1718 // Formerly we stored the signed text, the signature and the author in different fields.
1719 // We now store the raw data so that we are more flexible.
1720 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1721 intval($message_id),
1722 dbesc(json_encode($data))
1726 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1733 * @brief Processes private messages
1735 * @param array $importer Array of the importer user
1736 * @param object $data The message object
1738 * @return bool Success?
1740 private static function receive_message($importer, $data) {
1741 $guid = notags(unxmlify($data->guid));
1742 $parent_guid = notags(unxmlify($data->parent_guid));
1743 $text = unxmlify($data->text);
1744 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1745 $author = notags(unxmlify($data->author));
1746 $conversation_guid = notags(unxmlify($data->conversation_guid));
1748 $contact = self::allowed_contact_by_handle($importer, $author, true);
1753 $conversation = null;
1755 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1756 intval($importer["uid"]),
1757 dbesc($conversation_guid)
1760 $conversation = $c[0];
1762 logger("conversation not available.");
1766 $message_uri = $author.":".$guid;
1768 $person = self::person_by_handle($author);
1770 logger("unable to find author details");
1774 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1775 dbesc($message_uri),
1776 intval($importer["uid"])
1778 if (dbm::is_result($r)) {
1779 logger("duplicate message already delivered.", LOGGER_DEBUG);
1783 $body = diaspora2bb($text);
1785 $body = self::replace_people_guid($body, $person["url"]);
1787 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1788 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1789 intval($importer["uid"]),
1791 intval($conversation["id"]),
1792 dbesc($person["name"]),
1793 dbesc($person["photo"]),
1794 dbesc($person["url"]),
1795 intval($contact["id"]),
1796 dbesc($conversation["subject"]),
1800 dbesc($message_uri),
1801 dbesc($author.":".$parent_guid),
1805 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1806 dbesc(datetime_convert()),
1807 intval($conversation["id"])
1814 * @brief Processes participations - unsupported by now
1816 * @param array $importer Array of the importer user
1817 * @param object $data The message object
1819 * @return bool always true
1821 private static function receive_participation($importer, $data) {
1822 // I'm not sure if we can fully support this message type
1827 * @brief Processes photos - unneeded
1829 * @param array $importer Array of the importer user
1830 * @param object $data The message object
1832 * @return bool always true
1834 private static function receive_photo($importer, $data) {
1835 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1840 * @brief Processes poll participations - unssupported
1842 * @param array $importer Array of the importer user
1843 * @param object $data The message object
1845 * @return bool always true
1847 private static function receive_poll_participation($importer, $data) {
1848 // We don't support polls by now
1853 * @brief Processes incoming profile updates
1855 * @param array $importer Array of the importer user
1856 * @param object $data The message object
1858 * @return bool Success
1860 private static function receive_profile($importer, $data) {
1861 $author = strtolower(notags(unxmlify($data->author)));
1863 $contact = self::contact_by_handle($importer["uid"], $author);
1867 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1868 $image_url = unxmlify($data->image_url);
1869 $birthday = unxmlify($data->birthday);
1870 $location = diaspora2bb(unxmlify($data->location));
1871 $about = diaspora2bb(unxmlify($data->bio));
1872 $gender = unxmlify($data->gender);
1873 $searchable = (unxmlify($data->searchable) == "true");
1874 $nsfw = (unxmlify($data->nsfw) == "true");
1875 $tags = unxmlify($data->tag_string);
1877 $tags = explode("#", $tags);
1879 $keywords = array();
1880 foreach ($tags as $tag) {
1881 $tag = trim(strtolower($tag));
1886 $keywords = implode(", ", $keywords);
1888 $handle_parts = explode("@", $author);
1889 $nick = $handle_parts[0];
1892 $name = $handle_parts[0];
1894 if ( preg_match("|^https?://|", $image_url) === 0)
1895 $image_url = "http://".$handle_parts[1].$image_url;
1897 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1899 // Generic birthday. We don't know the timezone. The year is irrelevant.
1901 $birthday = str_replace("1000", "1901", $birthday);
1903 if ($birthday != "")
1904 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1906 // this is to prevent multiple birthday notifications in a single year
1907 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1909 if (substr($birthday,5) === substr($contact["bd"],5))
1910 $birthday = $contact["bd"];
1912 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1913 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1917 dbesc(datetime_convert()),
1923 intval($contact["id"]),
1924 intval($importer["uid"])
1927 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1928 "photo" => $image_url, "name" => $name, "location" => $location,
1929 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1930 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1931 "hide" => !$searchable, "nsfw" => $nsfw);
1933 $gcid = update_gcontact($gcontact);
1935 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1937 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1943 * @brief Processes incoming friend requests
1945 * @param array $importer Array of the importer user
1946 * @param array $contact The contact that send the request
1948 private static function receive_request_make_friend($importer, $contact) {
1952 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1953 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1954 intval(CONTACT_IS_FRIEND),
1955 intval($contact["id"]),
1956 intval($importer["uid"])
1959 // send notification
1961 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1962 intval($importer["uid"])
1965 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1967 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1968 intval($importer["uid"])
1971 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1973 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1976 $arr["protocol"] = PROTOCOL_DIASPORA;
1977 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1978 $arr["uid"] = $importer["uid"];
1979 $arr["contact-id"] = $self[0]["id"];
1981 $arr["type"] = 'wall';
1982 $arr["gravity"] = 0;
1984 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1985 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1986 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1987 $arr["verb"] = ACTIVITY_FRIEND;
1988 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1990 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1991 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1992 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1993 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1995 $arr["object"] = self::construct_new_friend_object($contact);
1997 $arr["last-child"] = 1;
1999 $arr["allow_cid"] = $user[0]["allow_cid"];
2000 $arr["allow_gid"] = $user[0]["allow_gid"];
2001 $arr["deny_cid"] = $user[0]["deny_cid"];
2002 $arr["deny_gid"] = $user[0]["deny_gid"];
2004 $i = item_store($arr);
2006 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2012 * @brief Creates a XML object for a "new friend" message
2014 * @param array $contact Array of the contact
2016 * @return string The XML
2018 private static function construct_new_friend_object($contact) {
2019 $objtype = ACTIVITY_OBJ_PERSON;
2020 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2021 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2023 $xmldata = array("object" => array("type" => $objtype,
2024 "title" => $contact["name"],
2025 "id" => $contact["url"]."/".$contact["name"],
2028 return xml::from_array($xmldata, $xml, true);
2032 * @brief Processes incoming sharing notification
2034 * @param array $importer Array of the importer user
2035 * @param object $data The message object
2037 * @return bool Success
2039 private static function receive_contact_request($importer, $data) {
2040 $author = unxmlify($data->author);
2041 $recipient = unxmlify($data->recipient);
2043 if (!$author || !$recipient) {
2047 // the current protocol version doesn't know these fields
2048 // That means that we will assume their existance
2049 if (isset($data->following)) {
2050 $following = (unxmlify($data->following) == "true");
2055 if (isset($data->sharing)) {
2056 $sharing = (unxmlify($data->sharing) == "true");
2061 $contact = self::contact_by_handle($importer["uid"],$author);
2063 // perhaps we were already sharing with this person. Now they're sharing with us.
2064 // That makes us friends.
2066 if ($following AND $sharing) {
2067 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2068 self::receive_request_make_friend($importer, $contact);
2070 // refetch the contact array
2071 $contact = self::contact_by_handle($importer["uid"],$author);
2073 // If we are now friends, we are sending a share message.
2074 // Normally we needn't to do so, but the first message could have been vanished.
2075 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2076 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2078 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2079 $ret = self::send_share($u[0], $contact);
2083 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2084 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2089 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2090 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2092 } elseif (!$following AND !$sharing) {
2093 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2095 } elseif (!$following AND $sharing) {
2096 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2097 } elseif ($following AND $sharing) {
2098 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2099 } elseif ($following AND !$sharing) {
2100 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2103 $ret = self::person_by_handle($author);
2105 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2106 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2110 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2112 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2113 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2114 intval($importer["uid"]),
2115 dbesc($ret["network"]),
2116 dbesc($ret["addr"]),
2119 dbesc(normalise_link($ret["url"])),
2121 dbesc($ret["name"]),
2122 dbesc($ret["nick"]),
2123 dbesc($ret["photo"]),
2124 dbesc($ret["pubkey"]),
2125 dbesc($ret["notify"]),
2126 dbesc($ret["poll"]),
2131 // find the contact record we just created
2133 $contact_record = self::contact_by_handle($importer["uid"],$author);
2135 if (!$contact_record) {
2136 logger("unable to locate newly created contact record.");
2140 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2142 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2144 if (intval($def_gid))
2145 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2147 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2149 if ($importer["page-flags"] == PAGE_NORMAL) {
2151 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2153 $hash = random_string().(string)time(); // Generate a confirm_key
2155 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2156 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2157 intval($importer["uid"]),
2158 intval($contact_record["id"]),
2161 dbesc(t("Sharing notification from Diaspora network")),
2163 dbesc(datetime_convert())
2167 // automatic friend approval
2169 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2171 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2173 // technically they are sharing with us (CONTACT_IS_SHARING),
2174 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2175 // we are going to change the relationship and make them a follower.
2177 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2178 $new_relation = CONTACT_IS_FRIEND;
2179 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2180 $new_relation = CONTACT_IS_SHARING;
2182 $new_relation = CONTACT_IS_FOLLOWER;
2184 $r = q("UPDATE `contact` SET `rel` = %d,
2192 intval($new_relation),
2193 dbesc(datetime_convert()),
2194 dbesc(datetime_convert()),
2195 intval($contact_record["id"])
2198 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2200 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2201 $ret = self::send_share($u[0], $contact_record);
2203 // Send the profile data, maybe it weren't transmitted before
2204 self::send_profile($importer["uid"], array($contact_record));
2212 * @brief Fetches a message with a given guid
2214 * @param string $guid message guid
2215 * @param string $orig_author handle of the original post
2216 * @param string $author handle of the sharer
2218 * @return array The fetched item
2220 private static function original_item($guid, $orig_author, $author) {
2222 // Do we already have this item?
2223 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2224 `author-name`, `author-link`, `author-avatar`
2225 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2228 if (dbm::is_result($r)) {
2229 logger("reshared message ".$guid." already exists on system.");
2231 // Maybe it is already a reshared item?
2232 // Then refetch the content, if it is a reshare from a reshare.
2233 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2234 if (self::is_reshare($r[0]["body"], true)) {
2236 } elseif (self::is_reshare($r[0]["body"], false)) {
2237 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2239 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2241 // Add OEmbed and other information to the body
2242 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2250 if (!dbm::is_result($r)) {
2251 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2252 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2253 $item_id = self::store_by_guid($guid, $server);
2256 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2257 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2258 $item_id = self::store_by_guid($guid, $server);
2262 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2263 `author-name`, `author-link`, `author-avatar`
2264 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2267 if (dbm::is_result($r)) {
2268 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2269 if (self::is_reshare($r[0]["body"], false)) {
2270 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2271 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2283 * @brief Processes a reshare message
2285 * @param array $importer Array of the importer user
2286 * @param object $data The message object
2287 * @param string $xml The original XML of the message
2289 * @return int the message id
2291 private static function receive_reshare($importer, $data, $xml) {
2292 $root_author = notags(unxmlify($data->root_author));
2293 $root_guid = notags(unxmlify($data->root_guid));
2294 $guid = notags(unxmlify($data->guid));
2295 $author = notags(unxmlify($data->author));
2296 $public = notags(unxmlify($data->public));
2297 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2299 $contact = self::allowed_contact_by_handle($importer, $author, false);
2304 $message_id = self::message_exists($importer["uid"], $guid);
2309 $original_item = self::original_item($root_guid, $root_author, $author);
2310 if (!$original_item) {
2314 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2316 $datarray = array();
2318 $datarray["uid"] = $importer["uid"];
2319 $datarray["contact-id"] = $contact["id"];
2320 $datarray["network"] = NETWORK_DIASPORA;
2322 $datarray["author-name"] = $contact["name"];
2323 $datarray["author-link"] = $contact["url"];
2324 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2326 $datarray["owner-name"] = $datarray["author-name"];
2327 $datarray["owner-link"] = $datarray["author-link"];
2328 $datarray["owner-avatar"] = $datarray["author-avatar"];
2330 $datarray["guid"] = $guid;
2331 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2333 $datarray["verb"] = ACTIVITY_POST;
2334 $datarray["gravity"] = GRAVITY_PARENT;
2336 $datarray["protocol"] = PROTOCOL_DIASPORA;
2337 $datarray["source"] = $xml;
2339 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2340 $original_item["guid"], $original_item["created"], $orig_url);
2341 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2343 $datarray["tag"] = $original_item["tag"];
2344 $datarray["app"] = $original_item["app"];
2346 $datarray["plink"] = self::plink($author, $guid);
2347 $datarray["private"] = (($public == "false") ? 1 : 0);
2348 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2350 $datarray["object-type"] = $original_item["object-type"];
2352 self::fetch_guid($datarray);
2353 $message_id = item_store($datarray);
2356 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2363 * @brief Processes retractions
2365 * @param array $importer Array of the importer user
2366 * @param array $contact The contact of the item owner
2367 * @param object $data The message object
2369 * @return bool success
2371 private static function item_retraction($importer, $contact, $data) {
2372 $target_type = notags(unxmlify($data->target_type));
2373 $target_guid = notags(unxmlify($data->target_guid));
2374 $author = notags(unxmlify($data->author));
2376 $person = self::person_by_handle($author);
2377 if (!is_array($person)) {
2378 logger("unable to find author detail for ".$author);
2382 if (!isset($contact["url"])) {
2383 $contact["url"] = $person["url"];
2386 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2387 dbesc($target_guid),
2388 intval($importer["uid"])
2391 logger("Target guid ".$target_guid." was not found for user ".$importer["uid"]);
2395 // Check if the sender is the thread owner
2396 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2397 intval($r[0]["parent"]));
2399 // Only delete it if the parent author really fits
2400 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2401 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2405 // 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
2406 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2407 dbesc(datetime_convert()),
2408 dbesc(datetime_convert()),
2411 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2413 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2415 // Now check if the retraction needs to be relayed by us
2416 if ($p[0]["origin"]) {
2418 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2425 * @brief Receives retraction messages
2427 * @param array $importer Array of the importer user
2428 * @param string $sender The sender of the message
2429 * @param object $data The message object
2431 * @return bool Success
2433 private static function receive_retraction($importer, $sender, $data) {
2434 $target_type = notags(unxmlify($data->target_type));
2436 $contact = self::contact_by_handle($importer["uid"], $sender);
2437 if (!$contact AND (in_array($target_type, array("Contact", "Person")))) {
2438 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2442 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2444 switch ($target_type) {
2447 case "Post": // "Post" will be supported in a future version
2449 case "StatusMessage":
2450 return self::item_retraction($importer, $contact, $data);
2454 /// @todo What should we do with an "unshare"?
2455 // Removing the contact isn't correct since we still can read the public items
2456 contact_remove($contact["id"]);
2460 logger("Unknown target type ".$target_type);
2467 * @brief Receives status messages
2469 * @param array $importer Array of the importer user
2470 * @param object $data The message object
2471 * @param string $xml The original XML of the message
2473 * @return int The message id of the newly created item
2475 private static function receive_status_message($importer, $data, $xml) {
2476 $raw_message = unxmlify($data->raw_message);
2477 $guid = notags(unxmlify($data->guid));
2478 $author = notags(unxmlify($data->author));
2479 $public = notags(unxmlify($data->public));
2480 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2481 $provider_display_name = notags(unxmlify($data->provider_display_name));
2483 /// @todo enable support for polls
2484 //if ($data->poll) {
2485 // foreach ($data->poll AS $poll)
2489 $contact = self::allowed_contact_by_handle($importer, $author, false);
2494 $message_id = self::message_exists($importer["uid"], $guid);
2500 if ($data->location) {
2501 foreach ($data->location->children() AS $fieldname => $data) {
2502 $address[$fieldname] = notags(unxmlify($data));
2506 $body = diaspora2bb($raw_message);
2508 $datarray = array();
2510 // Attach embedded pictures to the body
2512 foreach ($data->photo AS $photo) {
2513 $body = "[img]".unxmlify($photo->remote_photo_path).
2514 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2517 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2519 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2521 // Add OEmbed and other information to the body
2522 if (!self::is_redmatrix($contact["url"])) {
2523 $body = add_page_info_to_body($body, false, true);
2527 $datarray["uid"] = $importer["uid"];
2528 $datarray["contact-id"] = $contact["id"];
2529 $datarray["network"] = NETWORK_DIASPORA;
2531 $datarray["author-name"] = $contact["name"];
2532 $datarray["author-link"] = $contact["url"];
2533 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2535 $datarray["owner-name"] = $datarray["author-name"];
2536 $datarray["owner-link"] = $datarray["author-link"];
2537 $datarray["owner-avatar"] = $datarray["author-avatar"];
2539 $datarray["guid"] = $guid;
2540 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2542 $datarray["verb"] = ACTIVITY_POST;
2543 $datarray["gravity"] = GRAVITY_PARENT;
2545 $datarray["protocol"] = PROTOCOL_DIASPORA;
2546 $datarray["source"] = $xml;
2548 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2550 if ($provider_display_name != "") {
2551 $datarray["app"] = $provider_display_name;
2554 $datarray["plink"] = self::plink($author, $guid);
2555 $datarray["private"] = (($public == "false") ? 1 : 0);
2556 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2558 if (isset($address["address"])) {
2559 $datarray["location"] = $address["address"];
2562 if (isset($address["lat"]) AND isset($address["lng"])) {
2563 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2566 self::fetch_guid($datarray);
2567 $message_id = item_store($datarray);
2570 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2576 /* ************************************************************************************** *
2577 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2578 * ************************************************************************************** */
2581 * @brief returnes the handle of a contact
2583 * @param array $me contact array
2585 * @return string the handle in the format user@domain.tld
2587 private static function my_handle($contact) {
2588 if ($contact["addr"] != "") {
2589 return $contact["addr"];
2592 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2593 // So - just in case - we build the the address here.
2594 if ($contact["nickname"] != "") {
2595 $nick = $contact["nickname"];
2597 $nick = $contact["nick"];
2600 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2604 * @brief Creates the envelope for the "fetch" endpoint
2606 * @param string $msg The message that is to be transmitted
2607 * @param array $user The record of the sender
2609 * @return string The envelope
2612 public static function build_magic_envelope($msg, $user) {
2614 $b64url_data = base64url_encode($msg);
2615 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2617 $key_id = base64url_encode(self::my_handle($user));
2618 $type = "application/xml";
2619 $encoding = "base64url";
2620 $alg = "RSA-SHA256";
2621 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2622 $signature = rsa_sign($signable_data, $user["prvkey"]);
2623 $sig = base64url_encode($signature);
2625 $xmldata = array("me:env" => array("me:data" => $data,
2626 "@attributes" => array("type" => $type),
2627 "me:encoding" => $encoding,
2630 "@attributes2" => array("key_id" => $key_id)));
2632 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2634 return xml::from_array($xmldata, $xml, false, $namespaces);
2638 * @brief Creates the envelope for a public message
2640 * @param string $msg The message that is to be transmitted
2641 * @param array $user The record of the sender
2642 * @param array $contact Target of the communication
2643 * @param string $prvkey The private key of the sender
2644 * @param string $pubkey The public key of the receiver
2646 * @return string The envelope
2648 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2650 logger("Message: ".$msg, LOGGER_DATA);
2652 $handle = self::my_handle($user);
2654 $b64url_data = base64url_encode($msg);
2656 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2658 $type = "application/xml";
2659 $encoding = "base64url";
2660 $alg = "RSA-SHA256";
2662 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2664 $signature = rsa_sign($signable_data,$prvkey);
2665 $sig = base64url_encode($signature);
2667 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2668 "me:env" => array("me:encoding" => $encoding,
2671 "@attributes" => array("type" => $type),
2672 "me:sig" => $sig)));
2674 $namespaces = array("" => "https://joindiaspora.com/protocol",
2675 "me" => "http://salmon-protocol.org/ns/magic-env");
2677 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2679 logger("magic_env: ".$magic_env, LOGGER_DATA);
2684 * @brief Creates the envelope for a private message
2686 * @param string $msg The message that is to be transmitted
2687 * @param array $user The record of the sender
2688 * @param array $contact Target of the communication
2689 * @param string $prvkey The private key of the sender
2690 * @param string $pubkey The public key of the receiver
2692 * @return string The envelope
2694 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2696 logger("Message: ".$msg, LOGGER_DATA);
2698 // without a public key nothing will work
2701 logger("pubkey missing: contact id: ".$contact["id"]);
2705 $inner_aes_key = openssl_random_pseudo_bytes(32);
2706 $b_inner_aes_key = base64_encode($inner_aes_key);
2707 $inner_iv = openssl_random_pseudo_bytes(16);
2708 $b_inner_iv = base64_encode($inner_iv);
2710 $outer_aes_key = openssl_random_pseudo_bytes(32);
2711 $b_outer_aes_key = base64_encode($outer_aes_key);
2712 $outer_iv = openssl_random_pseudo_bytes(16);
2713 $b_outer_iv = base64_encode($outer_iv);
2715 $handle = self::my_handle($user);
2717 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2719 $b64_data = base64_encode($inner_encrypted);
2722 $b64url_data = base64url_encode($b64_data);
2723 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2725 $type = "application/xml";
2726 $encoding = "base64url";
2727 $alg = "RSA-SHA256";
2729 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2731 $signature = rsa_sign($signable_data,$prvkey);
2732 $sig = base64url_encode($signature);
2734 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2735 "aes_key" => $b_inner_aes_key,
2736 "author_id" => $handle));
2738 $decrypted_header = xml::from_array($xmldata, $xml, true);
2740 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2742 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2744 $encrypted_outer_key_bundle = "";
2745 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2747 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2749 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2751 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2752 "ciphertext" => base64_encode($ciphertext)));
2753 $cipher_json = base64_encode($encrypted_header_json_object);
2755 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2756 "me:env" => array("me:encoding" => $encoding,
2759 "@attributes" => array("type" => $type),
2760 "me:sig" => $sig)));
2762 $namespaces = array("" => "https://joindiaspora.com/protocol",
2763 "me" => "http://salmon-protocol.org/ns/magic-env");
2765 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2767 logger("magic_env: ".$magic_env, LOGGER_DATA);
2772 * @brief Create the envelope for a message
2774 * @param string $msg The message that is to be transmitted
2775 * @param array $user The record of the sender
2776 * @param array $contact Target of the communication
2777 * @param string $prvkey The private key of the sender
2778 * @param string $pubkey The public key of the receiver
2779 * @param bool $public Is the message public?
2781 * @return string The message that will be transmitted to other servers
2783 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2786 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2788 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2790 // The data that will be transmitted is double encoded via "urlencode", strange ...
2791 $slap = "xml=".urlencode(urlencode($magic_env));
2796 * @brief Creates a signature for a message
2798 * @param array $owner the array of the owner of the message
2799 * @param array $message The message that is to be signed
2801 * @return string The signature
2803 private static function signature($owner, $message) {
2805 unset($sigmsg["author_signature"]);
2806 unset($sigmsg["parent_author_signature"]);
2808 $signed_text = implode(";", $sigmsg);
2810 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2814 * @brief Transmit a message to a target server
2816 * @param array $owner the array of the item owner
2817 * @param array $contact Target of the communication
2818 * @param string $slap The message that is to be transmitted
2819 * @param bool $public_batch Is it a public post?
2820 * @param bool $queue_run Is the transmission called from the queue?
2821 * @param string $guid message guid
2823 * @return int Result of the transmission
2825 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2829 $enabled = intval(get_config("system", "diaspora_enabled"));
2833 $logid = random_string(4);
2834 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2836 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2840 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2842 if (!$queue_run && was_recently_delayed($contact["id"])) {
2845 if (!intval(get_config("system", "diaspora_test"))) {
2846 post_url($dest_url."/", $slap);
2847 $return_code = $a->get_curl_code();
2849 logger("test_mode");
2854 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2856 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2857 logger("queue message");
2859 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2860 intval($contact["id"]),
2861 dbesc(NETWORK_DIASPORA),
2863 intval($public_batch)
2866 logger("add_to_queue ignored - identical item already in queue");
2868 // queue message for redelivery
2869 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2871 // The message could not be delivered. We mark the contact as "dead"
2872 mark_for_death($contact);
2874 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2875 // We successfully delivered a message, the contact is alive
2876 unmark_for_death($contact);
2879 return(($return_code) ? $return_code : (-1));
2884 * @brief Build the post xml
2886 * @param string $type The message type
2887 * @param array $message The message data
2889 * @return string The post XML
2891 public static function build_post_xml($type, $message) {
2893 $data = array("XML" => array("post" => array($type => $message)));
2894 return xml::from_array($data, $xml);
2898 * @brief Builds and transmit messages
2900 * @param array $owner the array of the item owner
2901 * @param array $contact Target of the communication
2902 * @param string $type The message type
2903 * @param array $message The message data
2904 * @param bool $public_batch Is it a public post?
2905 * @param string $guid message guid
2906 * @param bool $spool Should the transmission be spooled or transmitted?
2908 * @return int Result of the transmission
2910 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2912 $msg = self::build_post_xml($type, $message);
2914 logger('message: '.$msg, LOGGER_DATA);
2915 logger('send guid '.$guid, LOGGER_DEBUG);
2917 // Fallback if the private key wasn't transmitted in the expected field
2918 if ($owner['uprvkey'] == "")
2919 $owner['uprvkey'] = $owner['prvkey'];
2921 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2924 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2927 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2929 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2931 return $return_code;
2935 * @brief Sends a "share" message
2937 * @param array $owner the array of the item owner
2938 * @param array $contact Target of the communication
2940 * @return int The result of the transmission
2942 public static function send_share($owner,$contact) {
2944 $message = array("sender_handle" => self::my_handle($owner),
2945 "recipient_handle" => $contact["addr"]);
2947 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2949 return self::build_and_transmit($owner, $contact, "request", $message);
2953 * @brief sends an "unshare"
2955 * @param array $owner the array of the item owner
2956 * @param array $contact Target of the communication
2958 * @return int The result of the transmission
2960 public static function send_unshare($owner,$contact) {
2962 $message = array("post_guid" => $owner["guid"],
2963 "diaspora_handle" => self::my_handle($owner),
2964 "type" => "Person");
2966 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2968 return self::build_and_transmit($owner, $contact, "retraction", $message);
2972 * @brief Checks a message body if it is a reshare
2974 * @param string $body The message body that is to be check
2975 * @param bool $complete Should it be a complete check or a simple check?
2977 * @return array|bool Reshare details or "false" if no reshare
2979 public static function is_reshare($body, $complete = true) {
2980 $body = trim($body);
2982 // Skip if it isn't a pure repeated messages
2983 // Does it start with a share?
2984 if ((strpos($body, "[share") > 0) AND $complete)
2987 // Does it end with a share?
2988 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2991 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2992 // Skip if there is no shared message in there
2993 if ($body == $attributes)
2996 // If we don't do the complete check we quit here
3001 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3002 if ($matches[1] != "")
3003 $guid = $matches[1];
3005 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3006 if ($matches[1] != "")
3007 $guid = $matches[1];
3010 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3011 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3014 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3015 $ret["root_guid"] = $guid;
3021 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3022 if ($matches[1] != "")
3023 $profile = $matches[1];
3025 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3026 if ($matches[1] != "")
3027 $profile = $matches[1];
3031 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3032 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3036 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3037 if ($matches[1] != "")
3038 $link = $matches[1];
3040 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3041 if ($matches[1] != "")
3042 $link = $matches[1];
3044 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3045 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3052 * @brief Create an event array
3054 * @param integer $event_id The id of the event
3056 * @return array with event data
3058 private static function build_event($event_id) {
3060 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3061 if (!dbm::is_result($r)) {
3067 $eventdata = array();
3069 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3070 if (!dbm::is_result($r)) {
3076 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3077 if (!dbm::is_result($r)) {
3083 $eventdata['author'] = self::my_handle($owner);
3085 if ($event['guid']) {
3086 $eventdata['guid'] = $event['guid'];
3089 $mask = 'Y-m-d\TH:i:s\Z';
3091 /// @todo - establish "all day" events in Friendica
3092 $eventdata["all_day"] = "false";
3094 if (!$event['adjust']) {
3095 $eventdata['timezone'] = $user['timezone'];
3097 if ($eventdata['timezone'] == "") {
3098 $eventdata['timezone'] = 'UTC';
3102 if ($event['start']) {
3103 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3105 if ($event['finish'] AND !$event['nofinish']) {
3106 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3108 if ($event['summary']) {
3109 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3111 if ($event['desc']) {
3112 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3114 if ($event['location']) {
3115 $location = array();
3116 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3117 $location["lat"] = 0;
3118 $location["lng"] = 0;
3119 $eventdata['location'] = $location;
3126 * @brief Create a post (status message or reshare)
3128 * @param array $item The item that will be exported
3129 * @param array $owner the array of the item owner
3132 * 'type' -> Message type ("status_message" or "reshare")
3133 * 'message' -> Array of XML elements of the status
3135 public static function build_status($item, $owner) {
3137 $cachekey = "diaspora:build_status:".$item['guid'];
3139 $result = Cache::get($cachekey);
3140 if (!is_null($result)) {
3144 $myaddr = self::my_handle($owner);
3146 $public = (($item["private"]) ? "false" : "true");
3148 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3150 // Detect a share element and do a reshare
3151 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3152 $message = array("root_diaspora_id" => $ret["root_handle"],
3153 "root_guid" => $ret["root_guid"],
3154 "guid" => $item["guid"],
3155 "diaspora_handle" => $myaddr,
3156 "public" => $public,
3157 "created_at" => $created,
3158 "provider_display_name" => $item["app"]);
3162 $title = $item["title"];
3163 $body = $item["body"];
3165 // convert to markdown
3166 $body = html_entity_decode(bb2diaspora($body));
3170 $body = "## ".html_entity_decode($title)."\n\n".$body;
3172 if ($item["attach"]) {
3173 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3175 $body .= "\n".t("Attachments:")."\n";
3176 foreach ($matches as $mtch)
3177 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3181 $location = array();
3183 if ($item["location"] != "")
3184 $location["address"] = $item["location"];
3186 if ($item["coord"] != "") {
3187 $coord = explode(" ", $item["coord"]);
3188 $location["lat"] = $coord[0];
3189 $location["lng"] = $coord[1];
3192 $message = array("raw_message" => $body,
3193 "location" => $location,
3194 "guid" => $item["guid"],
3195 "diaspora_handle" => $myaddr,
3196 "public" => $public,
3197 "created_at" => $created,
3198 "provider_display_name" => $item["app"]);
3200 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3201 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3202 unset($message["location"]);
3205 if ($item['event-id'] > 0) {
3206 $event = self::build_event($item['event-id']);
3207 if (count($event)) {
3208 $message['event'] = $event;
3210 /// @todo Once Diaspora supports it, we will remove the body
3211 // $message['raw_message'] = '';
3215 $type = "status_message";
3218 $msg = array("type" => $type, "message" => $message);
3220 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3226 * @brief Sends a post
3228 * @param array $item The item that will be exported
3229 * @param array $owner the array of the item owner
3230 * @param array $contact Target of the communication
3231 * @param bool $public_batch Is it a public post?
3233 * @return int The result of the transmission
3235 public static function send_status($item, $owner, $contact, $public_batch = false) {
3237 $status = self::build_status($item, $owner);
3239 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3243 * @brief Creates a "like" object
3245 * @param array $item The item that will be exported
3246 * @param array $owner the array of the item owner
3248 * @return array The data for a "like"
3250 private static function construct_like($item, $owner) {
3252 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3253 dbesc($item["thr-parent"]));
3254 if (!dbm::is_result($p))
3259 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3260 if ($item['verb'] === ACTIVITY_LIKE) {
3262 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3263 $positive = "false";
3266 return(array("positive" => $positive,
3267 "guid" => $item["guid"],
3268 "target_type" => $target_type,
3269 "parent_guid" => $parent["guid"],
3270 "author_signature" => "",
3271 "diaspora_handle" => self::my_handle($owner)));
3275 * @brief Creates an "EventParticipation" object
3277 * @param array $item The item that will be exported
3278 * @param array $owner the array of the item owner
3280 * @return array The data for an "EventParticipation"
3282 private static function construct_attend($item, $owner) {
3284 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3285 dbesc($item["thr-parent"]));
3286 if (!dbm::is_result($p))
3291 switch ($item['verb']) {
3292 case ACTIVITY_ATTEND:
3293 $attend_answer = 'accepted';
3295 case ACTIVITY_ATTENDNO:
3296 $attend_answer = 'declined';
3298 case ACTIVITY_ATTENDMAYBE:
3299 $attend_answer = 'tentative';
3302 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3306 return(array("author" => self::my_handle($owner),
3307 "guid" => $item["guid"],
3308 "parent_guid" => $parent["guid"],
3309 "status" => $attend_answer,
3310 "author_signature" => ""));
3314 * @brief Creates the object for a comment
3316 * @param array $item The item that will be exported
3317 * @param array $owner the array of the item owner
3319 * @return array The data for a comment
3321 private static function construct_comment($item, $owner) {
3323 $cachekey = "diaspora:construct_comment:".$item['guid'];
3325 $result = Cache::get($cachekey);
3326 if (!is_null($result)) {
3330 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3331 intval($item["parent"]),
3332 intval($item["parent"])
3335 if (!dbm::is_result($p))
3340 $text = html_entity_decode(bb2diaspora($item["body"]));
3341 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3343 $comment = array("guid" => $item["guid"],
3344 "parent_guid" => $parent["guid"],
3345 "author_signature" => "",
3347 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3348 "diaspora_handle" => self::my_handle($owner));
3350 // Send the thread parent guid only if it is a threaded comment
3351 if ($item['thr-parent'] != $item['parent-uri']) {
3352 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3355 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3361 * @brief Send a like or a comment
3363 * @param array $item The item that will be exported
3364 * @param array $owner the array of the item owner
3365 * @param array $contact Target of the communication
3366 * @param bool $public_batch Is it a public post?
3368 * @return int The result of the transmission
3370 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3372 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3373 $message = self::construct_attend($item, $owner);
3374 $type = "event_participation";
3375 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3376 $message = self::construct_like($item, $owner);
3379 $message = self::construct_comment($item, $owner);
3386 $message["author_signature"] = self::signature($owner, $message);
3388 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3392 * @brief Creates a message from a signature record entry
3394 * @param array $item The item that will be exported
3395 * @param array $signature The entry of the "sign" record
3397 * @return string The message
3399 private static function message_from_signature($item, $signature) {
3401 // Split the signed text
3402 $signed_parts = explode(";", $signature['signed_text']);
3404 if ($item["deleted"])
3405 $message = array("parent_author_signature" => "",
3406 "target_guid" => $signed_parts[0],
3407 "target_type" => $signed_parts[1],
3408 "sender_handle" => $signature['signer'],
3409 "target_author_signature" => $signature['signature']);
3410 elseif ($item['verb'] === ACTIVITY_LIKE)
3411 $message = array("positive" => $signed_parts[0],
3412 "guid" => $signed_parts[1],
3413 "target_type" => $signed_parts[2],
3414 "parent_guid" => $signed_parts[3],
3415 "parent_author_signature" => "",
3416 "author_signature" => $signature['signature'],
3417 "diaspora_handle" => $signed_parts[4]);
3419 // Remove the comment guid
3420 $guid = array_shift($signed_parts);
3422 // Remove the parent guid
3423 $parent_guid = array_shift($signed_parts);
3425 // Remove the handle
3426 $handle = array_pop($signed_parts);
3428 // Glue the parts together
3429 $text = implode(";", $signed_parts);
3431 $message = array("guid" => $guid,
3432 "parent_guid" => $parent_guid,
3433 "parent_author_signature" => "",
3434 "author_signature" => $signature['signature'],
3435 "text" => implode(";", $signed_parts),
3436 "diaspora_handle" => $handle);
3442 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3444 * @param array $item The item that will be exported
3445 * @param array $owner the array of the item owner
3446 * @param array $contact Target of the communication
3447 * @param bool $public_batch Is it a public post?
3449 * @return int The result of the transmission
3451 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3453 if ($item["deleted"])
3454 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3455 elseif ($item['verb'] === ACTIVITY_LIKE)
3460 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3462 // fetch the original signature
3464 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3465 intval($item["id"]));
3468 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3474 // Old way - is used by the internal Friendica functions
3475 /// @todo Change all signatur storing functions to the new format
3476 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3477 $message = self::message_from_signature($item, $signature);
3479 $msg = json_decode($signature['signed_text'], true);
3482 if (is_array($msg)) {
3483 foreach ($msg AS $field => $data) {
3484 if (!$item["deleted"]) {
3485 if ($field == "author")
3486 $field = "diaspora_handle";
3487 if ($field == "parent_type")
3488 $field = "target_type";
3491 $message[$field] = $data;
3494 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3497 $message["parent_author_signature"] = self::signature($owner, $message);
3499 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3501 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3505 * @brief Sends a retraction (deletion) of a message, like or comment
3507 * @param array $item The item that will be exported
3508 * @param array $owner the array of the item owner
3509 * @param array $contact Target of the communication
3510 * @param bool $public_batch Is it a public post?
3511 * @param bool $relay Is the retraction transmitted from a relay?
3513 * @return int The result of the transmission
3515 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3517 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3519 // Check whether the retraction is for a top-level post or whether it's a relayable
3520 if ($item["uri"] !== $item["parent-uri"]) {
3521 $msg_type = "relayable_retraction";
3522 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3524 $msg_type = "signed_retraction";
3525 $target_type = "StatusMessage";
3528 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3529 $signature = "parent_author_signature";
3531 $signature = "target_author_signature";
3533 $signed_text = $item["guid"].";".$target_type;
3535 $message = array("target_guid" => $item['guid'],
3536 "target_type" => $target_type,
3537 "sender_handle" => $itemaddr,
3538 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3540 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3542 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3546 * @brief Sends a mail
3548 * @param array $item The item that will be exported
3549 * @param array $owner The owner
3550 * @param array $contact Target of the communication
3552 * @return int The result of the transmission
3554 public static function send_mail($item, $owner, $contact) {
3556 $myaddr = self::my_handle($owner);
3558 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3559 intval($item["convid"]),
3560 intval($item["uid"])
3563 if (!dbm::is_result($r)) {
3564 logger("conversation not found.");
3570 "guid" => $cnv["guid"],
3571 "subject" => $cnv["subject"],
3572 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3573 "diaspora_handle" => $cnv["creator"],
3574 "participant_handles" => $cnv["recips"]
3577 $body = bb2diaspora($item["body"]);
3578 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3580 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3581 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3584 "guid" => $item["guid"],
3585 "parent_guid" => $cnv["guid"],
3586 "parent_author_signature" => $sig,
3587 "author_signature" => $sig,
3589 "created_at" => $created,
3590 "diaspora_handle" => $myaddr,
3591 "conversation_guid" => $cnv["guid"]
3594 if ($item["reply"]) {
3598 $message = array("guid" => $cnv["guid"],
3599 "subject" => $cnv["subject"],
3600 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3602 "diaspora_handle" => $cnv["creator"],
3603 "participant_handles" => $cnv["recips"]);
3605 $type = "conversation";
3608 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3612 * @brief Sends profile data
3614 * @param int $uid The user id
3616 public static function send_profile($uid, $recips = false) {
3622 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3623 AND `uid` = %d AND `rel` != %d",
3624 dbesc(NETWORK_DIASPORA),
3626 intval(CONTACT_IS_SHARING)
3631 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3633 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3634 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3635 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3644 $handle = $profile["addr"];
3645 $first = ((strpos($profile['name'],' ')
3646 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3647 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3648 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3649 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3650 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3651 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3653 if ($searchable === 'true') {
3654 $dob = '1000-00-00';
3656 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3657 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3659 $about = $profile['about'];
3660 $about = strip_tags(bbcode($about));
3662 $location = formatted_location($profile);
3664 if ($profile['pub_keywords']) {
3665 $kw = str_replace(',',' ',$profile['pub_keywords']);
3666 $kw = str_replace(' ',' ',$kw);
3667 $arr = explode(' ',$profile['pub_keywords']);
3669 for ($x = 0; $x < 5; $x ++) {
3671 $tags .= '#'. trim($arr[$x]) .' ';
3675 $tags = trim($tags);
3678 $message = array("diaspora_handle" => $handle,
3679 "first_name" => $first,
3680 "last_name" => $last,
3681 "image_url" => $large,
3682 "image_url_medium" => $medium,
3683 "image_url_small" => $small,
3685 "gender" => $profile['gender'],
3687 "location" => $location,
3688 "searchable" => $searchable,
3689 "tag_string" => $tags);
3691 foreach ($recips as $recip) {
3692 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3693 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3698 * @brief Stores the signature for likes that are created on our system
3700 * @param array $contact The contact array of the "like"
3701 * @param int $post_id The post id of the "like"
3703 * @return bool Success
3705 public static function store_like_signature($contact, $post_id) {
3707 // Is the contact the owner? Then fetch the private key
3708 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3709 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3713 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3714 if (!dbm::is_result($r)) {
3718 $contact["uprvkey"] = $r[0]['prvkey'];
3720 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3721 if (!dbm::is_result($r)) {
3725 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3729 $message = self::construct_like($r[0], $contact);
3730 $message["author_signature"] = self::signature($contact, $message);
3732 // We now store the signature more flexible to dynamically support new fields.
3733 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3734 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3735 intval($message_id),
3736 dbesc(json_encode($message))
3739 logger('Stored diaspora like signature');
3744 * @brief Stores the signature for comments that are created on our system
3746 * @param array $item The item array of the comment
3747 * @param array $contact The contact array of the item owner
3748 * @param string $uprvkey The private key of the sender
3749 * @param int $message_id The message id of the comment
3751 * @return bool Success
3753 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3755 if ($uprvkey == "") {
3756 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3760 $contact["uprvkey"] = $uprvkey;
3762 $message = self::construct_comment($item, $contact);
3763 $message["author_signature"] = self::signature($contact, $message);
3765 // We now store the signature more flexible to dynamically support new fields.
3766 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3767 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3768 intval($message_id),
3769 dbesc(json_encode($message))
3772 logger('Stored diaspora comment signature');