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 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2383 dbesc($target_guid),
2384 intval($importer["uid"])
2390 // Check if the sender is the thread owner
2391 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2392 intval($r[0]["parent"]));
2394 // Only delete it if the parent author really fits
2395 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2396 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2400 // 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
2401 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2402 dbesc(datetime_convert()),
2403 dbesc(datetime_convert()),
2406 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2408 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2410 // Now check if the retraction needs to be relayed by us
2411 if ($p[0]["origin"]) {
2413 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2420 * @brief Receives retraction messages
2422 * @param array $importer Array of the importer user
2423 * @param string $sender The sender of the message
2424 * @param object $data The message object
2426 * @return bool Success
2428 private static function receive_retraction($importer, $sender, $data) {
2429 $target_type = notags(unxmlify($data->target_type));
2431 $contact = self::contact_by_handle($importer["uid"], $sender);
2433 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2437 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2439 switch ($target_type) {
2442 case "Post": // "Post" will be supported in a future version
2444 case "StatusMessage":
2445 return self::item_retraction($importer, $contact, $data);;
2449 /// @todo What should we do with an "unshare"?
2450 // Removing the contact isn't correct since we still can read the public items
2451 contact_remove($contact["id"]);
2455 logger("Unknown target type ".$target_type);
2462 * @brief Receives status messages
2464 * @param array $importer Array of the importer user
2465 * @param object $data The message object
2466 * @param string $xml The original XML of the message
2468 * @return int The message id of the newly created item
2470 private static function receive_status_message($importer, $data, $xml) {
2471 $raw_message = unxmlify($data->raw_message);
2472 $guid = notags(unxmlify($data->guid));
2473 $author = notags(unxmlify($data->author));
2474 $public = notags(unxmlify($data->public));
2475 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2476 $provider_display_name = notags(unxmlify($data->provider_display_name));
2478 /// @todo enable support for polls
2479 //if ($data->poll) {
2480 // foreach ($data->poll AS $poll)
2484 $contact = self::allowed_contact_by_handle($importer, $author, false);
2489 $message_id = self::message_exists($importer["uid"], $guid);
2495 if ($data->location) {
2496 foreach ($data->location->children() AS $fieldname => $data) {
2497 $address[$fieldname] = notags(unxmlify($data));
2501 $body = diaspora2bb($raw_message);
2503 $datarray = array();
2505 // Attach embedded pictures to the body
2507 foreach ($data->photo AS $photo) {
2508 $body = "[img]".unxmlify($photo->remote_photo_path).
2509 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2512 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2514 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2516 // Add OEmbed and other information to the body
2517 if (!self::is_redmatrix($contact["url"])) {
2518 $body = add_page_info_to_body($body, false, true);
2522 $datarray["uid"] = $importer["uid"];
2523 $datarray["contact-id"] = $contact["id"];
2524 $datarray["network"] = NETWORK_DIASPORA;
2526 $datarray["author-name"] = $contact["name"];
2527 $datarray["author-link"] = $contact["url"];
2528 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2530 $datarray["owner-name"] = $datarray["author-name"];
2531 $datarray["owner-link"] = $datarray["author-link"];
2532 $datarray["owner-avatar"] = $datarray["author-avatar"];
2534 $datarray["guid"] = $guid;
2535 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2537 $datarray["verb"] = ACTIVITY_POST;
2538 $datarray["gravity"] = GRAVITY_PARENT;
2540 $datarray["protocol"] = PROTOCOL_DIASPORA;
2541 $datarray["source"] = $xml;
2543 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2545 if ($provider_display_name != "") {
2546 $datarray["app"] = $provider_display_name;
2549 $datarray["plink"] = self::plink($author, $guid);
2550 $datarray["private"] = (($public == "false") ? 1 : 0);
2551 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2553 if (isset($address["address"])) {
2554 $datarray["location"] = $address["address"];
2557 if (isset($address["lat"]) AND isset($address["lng"])) {
2558 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2561 self::fetch_guid($datarray);
2562 $message_id = item_store($datarray);
2565 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2571 /* ************************************************************************************** *
2572 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2573 * ************************************************************************************** */
2576 * @brief returnes the handle of a contact
2578 * @param array $me contact array
2580 * @return string the handle in the format user@domain.tld
2582 private static function my_handle($contact) {
2583 if ($contact["addr"] != "") {
2584 return $contact["addr"];
2587 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2588 // So - just in case - we build the the address here.
2589 if ($contact["nickname"] != "") {
2590 $nick = $contact["nickname"];
2592 $nick = $contact["nick"];
2595 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2599 * @brief Creates the envelope for the "fetch" endpoint
2601 * @param string $msg The message that is to be transmitted
2602 * @param array $user The record of the sender
2604 * @return string The envelope
2607 public static function build_magic_envelope($msg, $user) {
2609 $b64url_data = base64url_encode($msg);
2610 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2612 $key_id = base64url_encode(self::my_handle($user));
2613 $type = "application/xml";
2614 $encoding = "base64url";
2615 $alg = "RSA-SHA256";
2616 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2617 $signature = rsa_sign($signable_data, $user["prvkey"]);
2618 $sig = base64url_encode($signature);
2620 $xmldata = array("me:env" => array("me:data" => $data,
2621 "@attributes" => array("type" => $type),
2622 "me:encoding" => $encoding,
2625 "@attributes2" => array("key_id" => $key_id)));
2627 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2629 return xml::from_array($xmldata, $xml, false, $namespaces);
2633 * @brief Creates the envelope for a public message
2635 * @param string $msg The message that is to be transmitted
2636 * @param array $user The record of the sender
2637 * @param array $contact Target of the communication
2638 * @param string $prvkey The private key of the sender
2639 * @param string $pubkey The public key of the receiver
2641 * @return string The envelope
2643 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2645 logger("Message: ".$msg, LOGGER_DATA);
2647 $handle = self::my_handle($user);
2649 $b64url_data = base64url_encode($msg);
2651 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2653 $type = "application/xml";
2654 $encoding = "base64url";
2655 $alg = "RSA-SHA256";
2657 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2659 $signature = rsa_sign($signable_data,$prvkey);
2660 $sig = base64url_encode($signature);
2662 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2663 "me:env" => array("me:encoding" => $encoding,
2666 "@attributes" => array("type" => $type),
2667 "me:sig" => $sig)));
2669 $namespaces = array("" => "https://joindiaspora.com/protocol",
2670 "me" => "http://salmon-protocol.org/ns/magic-env");
2672 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2674 logger("magic_env: ".$magic_env, LOGGER_DATA);
2679 * @brief Creates the envelope for a private message
2681 * @param string $msg The message that is to be transmitted
2682 * @param array $user The record of the sender
2683 * @param array $contact Target of the communication
2684 * @param string $prvkey The private key of the sender
2685 * @param string $pubkey The public key of the receiver
2687 * @return string The envelope
2689 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2691 logger("Message: ".$msg, LOGGER_DATA);
2693 // without a public key nothing will work
2696 logger("pubkey missing: contact id: ".$contact["id"]);
2700 $inner_aes_key = openssl_random_pseudo_bytes(32);
2701 $b_inner_aes_key = base64_encode($inner_aes_key);
2702 $inner_iv = openssl_random_pseudo_bytes(16);
2703 $b_inner_iv = base64_encode($inner_iv);
2705 $outer_aes_key = openssl_random_pseudo_bytes(32);
2706 $b_outer_aes_key = base64_encode($outer_aes_key);
2707 $outer_iv = openssl_random_pseudo_bytes(16);
2708 $b_outer_iv = base64_encode($outer_iv);
2710 $handle = self::my_handle($user);
2712 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2714 $b64_data = base64_encode($inner_encrypted);
2717 $b64url_data = base64url_encode($b64_data);
2718 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2720 $type = "application/xml";
2721 $encoding = "base64url";
2722 $alg = "RSA-SHA256";
2724 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2726 $signature = rsa_sign($signable_data,$prvkey);
2727 $sig = base64url_encode($signature);
2729 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2730 "aes_key" => $b_inner_aes_key,
2731 "author_id" => $handle));
2733 $decrypted_header = xml::from_array($xmldata, $xml, true);
2735 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2737 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2739 $encrypted_outer_key_bundle = "";
2740 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2742 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2744 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2746 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2747 "ciphertext" => base64_encode($ciphertext)));
2748 $cipher_json = base64_encode($encrypted_header_json_object);
2750 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2751 "me:env" => array("me:encoding" => $encoding,
2754 "@attributes" => array("type" => $type),
2755 "me:sig" => $sig)));
2757 $namespaces = array("" => "https://joindiaspora.com/protocol",
2758 "me" => "http://salmon-protocol.org/ns/magic-env");
2760 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2762 logger("magic_env: ".$magic_env, LOGGER_DATA);
2767 * @brief Create the envelope for a message
2769 * @param string $msg The message that is to be transmitted
2770 * @param array $user The record of the sender
2771 * @param array $contact Target of the communication
2772 * @param string $prvkey The private key of the sender
2773 * @param string $pubkey The public key of the receiver
2774 * @param bool $public Is the message public?
2776 * @return string The message that will be transmitted to other servers
2778 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2781 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2783 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2785 // The data that will be transmitted is double encoded via "urlencode", strange ...
2786 $slap = "xml=".urlencode(urlencode($magic_env));
2791 * @brief Creates a signature for a message
2793 * @param array $owner the array of the owner of the message
2794 * @param array $message The message that is to be signed
2796 * @return string The signature
2798 private static function signature($owner, $message) {
2800 unset($sigmsg["author_signature"]);
2801 unset($sigmsg["parent_author_signature"]);
2803 $signed_text = implode(";", $sigmsg);
2805 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2809 * @brief Transmit a message to a target server
2811 * @param array $owner the array of the item owner
2812 * @param array $contact Target of the communication
2813 * @param string $slap The message that is to be transmitted
2814 * @param bool $public_batch Is it a public post?
2815 * @param bool $queue_run Is the transmission called from the queue?
2816 * @param string $guid message guid
2818 * @return int Result of the transmission
2820 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2824 $enabled = intval(get_config("system", "diaspora_enabled"));
2828 $logid = random_string(4);
2829 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2831 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2835 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2837 if (!$queue_run && was_recently_delayed($contact["id"])) {
2840 if (!intval(get_config("system", "diaspora_test"))) {
2841 post_url($dest_url."/", $slap);
2842 $return_code = $a->get_curl_code();
2844 logger("test_mode");
2849 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2851 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2852 logger("queue message");
2854 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2855 intval($contact["id"]),
2856 dbesc(NETWORK_DIASPORA),
2858 intval($public_batch)
2861 logger("add_to_queue ignored - identical item already in queue");
2863 // queue message for redelivery
2864 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2866 // The message could not be delivered. We mark the contact as "dead"
2867 mark_for_death($contact);
2869 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2870 // We successfully delivered a message, the contact is alive
2871 unmark_for_death($contact);
2874 return(($return_code) ? $return_code : (-1));
2879 * @brief Build the post xml
2881 * @param string $type The message type
2882 * @param array $message The message data
2884 * @return string The post XML
2886 public static function build_post_xml($type, $message) {
2888 $data = array("XML" => array("post" => array($type => $message)));
2889 return xml::from_array($data, $xml);
2893 * @brief Builds and transmit messages
2895 * @param array $owner the array of the item owner
2896 * @param array $contact Target of the communication
2897 * @param string $type The message type
2898 * @param array $message The message data
2899 * @param bool $public_batch Is it a public post?
2900 * @param string $guid message guid
2901 * @param bool $spool Should the transmission be spooled or transmitted?
2903 * @return int Result of the transmission
2905 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2907 $msg = self::build_post_xml($type, $message);
2909 logger('message: '.$msg, LOGGER_DATA);
2910 logger('send guid '.$guid, LOGGER_DEBUG);
2912 // Fallback if the private key wasn't transmitted in the expected field
2913 if ($owner['uprvkey'] == "")
2914 $owner['uprvkey'] = $owner['prvkey'];
2916 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2919 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2922 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2924 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2926 return $return_code;
2930 * @brief Sends a "share" message
2932 * @param array $owner the array of the item owner
2933 * @param array $contact Target of the communication
2935 * @return int The result of the transmission
2937 public static function send_share($owner,$contact) {
2939 $message = array("sender_handle" => self::my_handle($owner),
2940 "recipient_handle" => $contact["addr"]);
2942 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2944 return self::build_and_transmit($owner, $contact, "request", $message);
2948 * @brief sends an "unshare"
2950 * @param array $owner the array of the item owner
2951 * @param array $contact Target of the communication
2953 * @return int The result of the transmission
2955 public static function send_unshare($owner,$contact) {
2957 $message = array("post_guid" => $owner["guid"],
2958 "diaspora_handle" => self::my_handle($owner),
2959 "type" => "Person");
2961 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2963 return self::build_and_transmit($owner, $contact, "retraction", $message);
2967 * @brief Checks a message body if it is a reshare
2969 * @param string $body The message body that is to be check
2970 * @param bool $complete Should it be a complete check or a simple check?
2972 * @return array|bool Reshare details or "false" if no reshare
2974 public static function is_reshare($body, $complete = true) {
2975 $body = trim($body);
2977 // Skip if it isn't a pure repeated messages
2978 // Does it start with a share?
2979 if ((strpos($body, "[share") > 0) AND $complete)
2982 // Does it end with a share?
2983 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2986 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2987 // Skip if there is no shared message in there
2988 if ($body == $attributes)
2991 // If we don't do the complete check we quit here
2996 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2997 if ($matches[1] != "")
2998 $guid = $matches[1];
3000 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3001 if ($matches[1] != "")
3002 $guid = $matches[1];
3005 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3006 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3009 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3010 $ret["root_guid"] = $guid;
3016 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3017 if ($matches[1] != "")
3018 $profile = $matches[1];
3020 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3021 if ($matches[1] != "")
3022 $profile = $matches[1];
3026 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3027 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3031 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3032 if ($matches[1] != "")
3033 $link = $matches[1];
3035 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3036 if ($matches[1] != "")
3037 $link = $matches[1];
3039 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3040 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3047 * @brief Create an event array
3049 * @param integer $event_id The id of the event
3051 * @return array with event data
3053 private static function build_event($event_id) {
3055 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3056 if (!dbm::is_result($r)) {
3062 $eventdata = array();
3064 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3065 if (!dbm::is_result($r)) {
3071 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3072 if (!dbm::is_result($r)) {
3078 $eventdata['author'] = self::my_handle($owner);
3080 if ($event['guid']) {
3081 $eventdata['guid'] = $event['guid'];
3084 $mask = 'Y-m-d\TH:i:s\Z';
3086 /// @todo - establish "all day" events in Friendica
3087 $eventdata["all_day"] = "false";
3089 if (!$event['adjust']) {
3090 $eventdata['timezone'] = $user['timezone'];
3092 if ($eventdata['timezone'] == "") {
3093 $eventdata['timezone'] = 'UTC';
3097 if ($event['start']) {
3098 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3100 if ($event['finish'] AND !$event['nofinish']) {
3101 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3103 if ($event['summary']) {
3104 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3106 if ($event['desc']) {
3107 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3109 if ($event['location']) {
3110 $location = array();
3111 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3112 $location["lat"] = 0;
3113 $location["lng"] = 0;
3114 $eventdata['location'] = $location;
3121 * @brief Create a post (status message or reshare)
3123 * @param array $item The item that will be exported
3124 * @param array $owner the array of the item owner
3127 * 'type' -> Message type ("status_message" or "reshare")
3128 * 'message' -> Array of XML elements of the status
3130 public static function build_status($item, $owner) {
3132 $cachekey = "diaspora:build_status:".$item['guid'];
3134 $result = Cache::get($cachekey);
3135 if (!is_null($result)) {
3139 $myaddr = self::my_handle($owner);
3141 $public = (($item["private"]) ? "false" : "true");
3143 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3145 // Detect a share element and do a reshare
3146 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3147 $message = array("root_diaspora_id" => $ret["root_handle"],
3148 "root_guid" => $ret["root_guid"],
3149 "guid" => $item["guid"],
3150 "diaspora_handle" => $myaddr,
3151 "public" => $public,
3152 "created_at" => $created,
3153 "provider_display_name" => $item["app"]);
3157 $title = $item["title"];
3158 $body = $item["body"];
3160 // convert to markdown
3161 $body = html_entity_decode(bb2diaspora($body));
3165 $body = "## ".html_entity_decode($title)."\n\n".$body;
3167 if ($item["attach"]) {
3168 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3170 $body .= "\n".t("Attachments:")."\n";
3171 foreach ($matches as $mtch)
3172 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3176 $location = array();
3178 if ($item["location"] != "")
3179 $location["address"] = $item["location"];
3181 if ($item["coord"] != "") {
3182 $coord = explode(" ", $item["coord"]);
3183 $location["lat"] = $coord[0];
3184 $location["lng"] = $coord[1];
3187 $message = array("raw_message" => $body,
3188 "location" => $location,
3189 "guid" => $item["guid"],
3190 "diaspora_handle" => $myaddr,
3191 "public" => $public,
3192 "created_at" => $created,
3193 "provider_display_name" => $item["app"]);
3195 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3196 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3197 unset($message["location"]);
3200 if ($item['event-id'] > 0) {
3201 $event = self::build_event($item['event-id']);
3202 if (count($event)) {
3203 $message['event'] = $event;
3205 /// @todo Once Diaspora supports it, we will remove the body
3206 // $message['raw_message'] = '';
3210 $type = "status_message";
3213 $msg = array("type" => $type, "message" => $message);
3215 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3221 * @brief Sends a post
3223 * @param array $item The item that will be exported
3224 * @param array $owner the array of the item owner
3225 * @param array $contact Target of the communication
3226 * @param bool $public_batch Is it a public post?
3228 * @return int The result of the transmission
3230 public static function send_status($item, $owner, $contact, $public_batch = false) {
3232 $status = self::build_status($item, $owner);
3234 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3238 * @brief Creates a "like" object
3240 * @param array $item The item that will be exported
3241 * @param array $owner the array of the item owner
3243 * @return array The data for a "like"
3245 private static function construct_like($item, $owner) {
3247 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3248 dbesc($item["thr-parent"]));
3249 if (!dbm::is_result($p))
3254 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3255 if ($item['verb'] === ACTIVITY_LIKE) {
3257 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3258 $positive = "false";
3261 return(array("positive" => $positive,
3262 "guid" => $item["guid"],
3263 "target_type" => $target_type,
3264 "parent_guid" => $parent["guid"],
3265 "author_signature" => "",
3266 "diaspora_handle" => self::my_handle($owner)));
3270 * @brief Creates an "EventParticipation" object
3272 * @param array $item The item that will be exported
3273 * @param array $owner the array of the item owner
3275 * @return array The data for an "EventParticipation"
3277 private static function construct_attend($item, $owner) {
3279 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3280 dbesc($item["thr-parent"]));
3281 if (!dbm::is_result($p))
3286 switch ($item['verb']) {
3287 case ACTIVITY_ATTEND:
3288 $attend_answer = 'accepted';
3290 case ACTIVITY_ATTENDNO:
3291 $attend_answer = 'declined';
3293 case ACTIVITY_ATTENDMAYBE:
3294 $attend_answer = 'tentative';
3297 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3301 return(array("author" => self::my_handle($owner),
3302 "guid" => $item["guid"],
3303 "parent_guid" => $parent["guid"],
3304 "status" => $attend_answer,
3305 "author_signature" => ""));
3309 * @brief Creates the object for a comment
3311 * @param array $item The item that will be exported
3312 * @param array $owner the array of the item owner
3314 * @return array The data for a comment
3316 private static function construct_comment($item, $owner) {
3318 $cachekey = "diaspora:construct_comment:".$item['guid'];
3320 $result = Cache::get($cachekey);
3321 if (!is_null($result)) {
3325 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3326 intval($item["parent"]),
3327 intval($item["parent"])
3330 if (!dbm::is_result($p))
3335 $text = html_entity_decode(bb2diaspora($item["body"]));
3336 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3338 $comment = array("guid" => $item["guid"],
3339 "parent_guid" => $parent["guid"],
3340 "author_signature" => "",
3342 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3343 "diaspora_handle" => self::my_handle($owner));
3345 // Send the thread parent guid only if it is a threaded comment
3346 if ($item['thr-parent'] != $item['parent-uri']) {
3347 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3350 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3356 * @brief Send a like or a comment
3358 * @param array $item The item that will be exported
3359 * @param array $owner the array of the item owner
3360 * @param array $contact Target of the communication
3361 * @param bool $public_batch Is it a public post?
3363 * @return int The result of the transmission
3365 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3367 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3368 $message = self::construct_attend($item, $owner);
3369 $type = "event_participation";
3370 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3371 $message = self::construct_like($item, $owner);
3374 $message = self::construct_comment($item, $owner);
3381 $message["author_signature"] = self::signature($owner, $message);
3383 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3387 * @brief Creates a message from a signature record entry
3389 * @param array $item The item that will be exported
3390 * @param array $signature The entry of the "sign" record
3392 * @return string The message
3394 private static function message_from_signature($item, $signature) {
3396 // Split the signed text
3397 $signed_parts = explode(";", $signature['signed_text']);
3399 if ($item["deleted"])
3400 $message = array("parent_author_signature" => "",
3401 "target_guid" => $signed_parts[0],
3402 "target_type" => $signed_parts[1],
3403 "sender_handle" => $signature['signer'],
3404 "target_author_signature" => $signature['signature']);
3405 elseif ($item['verb'] === ACTIVITY_LIKE)
3406 $message = array("positive" => $signed_parts[0],
3407 "guid" => $signed_parts[1],
3408 "target_type" => $signed_parts[2],
3409 "parent_guid" => $signed_parts[3],
3410 "parent_author_signature" => "",
3411 "author_signature" => $signature['signature'],
3412 "diaspora_handle" => $signed_parts[4]);
3414 // Remove the comment guid
3415 $guid = array_shift($signed_parts);
3417 // Remove the parent guid
3418 $parent_guid = array_shift($signed_parts);
3420 // Remove the handle
3421 $handle = array_pop($signed_parts);
3423 // Glue the parts together
3424 $text = implode(";", $signed_parts);
3426 $message = array("guid" => $guid,
3427 "parent_guid" => $parent_guid,
3428 "parent_author_signature" => "",
3429 "author_signature" => $signature['signature'],
3430 "text" => implode(";", $signed_parts),
3431 "diaspora_handle" => $handle);
3437 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3439 * @param array $item The item that will be exported
3440 * @param array $owner the array of the item owner
3441 * @param array $contact Target of the communication
3442 * @param bool $public_batch Is it a public post?
3444 * @return int The result of the transmission
3446 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3448 if ($item["deleted"])
3449 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3450 elseif ($item['verb'] === ACTIVITY_LIKE)
3455 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3457 // fetch the original signature
3459 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3460 intval($item["id"]));
3463 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3469 // Old way - is used by the internal Friendica functions
3470 /// @todo Change all signatur storing functions to the new format
3471 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3472 $message = self::message_from_signature($item, $signature);
3474 $msg = json_decode($signature['signed_text'], true);
3477 if (is_array($msg)) {
3478 foreach ($msg AS $field => $data) {
3479 if (!$item["deleted"]) {
3480 if ($field == "author")
3481 $field = "diaspora_handle";
3482 if ($field == "parent_type")
3483 $field = "target_type";
3486 $message[$field] = $data;
3489 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3492 $message["parent_author_signature"] = self::signature($owner, $message);
3494 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3496 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3500 * @brief Sends a retraction (deletion) of a message, like or comment
3502 * @param array $item The item that will be exported
3503 * @param array $owner the array of the item owner
3504 * @param array $contact Target of the communication
3505 * @param bool $public_batch Is it a public post?
3506 * @param bool $relay Is the retraction transmitted from a relay?
3508 * @return int The result of the transmission
3510 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3512 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3514 // Check whether the retraction is for a top-level post or whether it's a relayable
3515 if ($item["uri"] !== $item["parent-uri"]) {
3516 $msg_type = "relayable_retraction";
3517 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3519 $msg_type = "signed_retraction";
3520 $target_type = "StatusMessage";
3523 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3524 $signature = "parent_author_signature";
3526 $signature = "target_author_signature";
3528 $signed_text = $item["guid"].";".$target_type;
3530 $message = array("target_guid" => $item['guid'],
3531 "target_type" => $target_type,
3532 "sender_handle" => $itemaddr,
3533 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3535 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3537 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3541 * @brief Sends a mail
3543 * @param array $item The item that will be exported
3544 * @param array $owner The owner
3545 * @param array $contact Target of the communication
3547 * @return int The result of the transmission
3549 public static function send_mail($item, $owner, $contact) {
3551 $myaddr = self::my_handle($owner);
3553 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3554 intval($item["convid"]),
3555 intval($item["uid"])
3558 if (!dbm::is_result($r)) {
3559 logger("conversation not found.");
3565 "guid" => $cnv["guid"],
3566 "subject" => $cnv["subject"],
3567 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3568 "diaspora_handle" => $cnv["creator"],
3569 "participant_handles" => $cnv["recips"]
3572 $body = bb2diaspora($item["body"]);
3573 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3575 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3576 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3579 "guid" => $item["guid"],
3580 "parent_guid" => $cnv["guid"],
3581 "parent_author_signature" => $sig,
3582 "author_signature" => $sig,
3584 "created_at" => $created,
3585 "diaspora_handle" => $myaddr,
3586 "conversation_guid" => $cnv["guid"]
3589 if ($item["reply"]) {
3593 $message = array("guid" => $cnv["guid"],
3594 "subject" => $cnv["subject"],
3595 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3597 "diaspora_handle" => $cnv["creator"],
3598 "participant_handles" => $cnv["recips"]);
3600 $type = "conversation";
3603 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3607 * @brief Sends profile data
3609 * @param int $uid The user id
3611 public static function send_profile($uid, $recips = false) {
3617 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3618 AND `uid` = %d AND `rel` != %d",
3619 dbesc(NETWORK_DIASPORA),
3621 intval(CONTACT_IS_SHARING)
3626 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3628 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3629 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3630 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3639 $handle = $profile["addr"];
3640 $first = ((strpos($profile['name'],' ')
3641 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3642 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3643 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3644 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3645 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3646 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3648 if ($searchable === 'true') {
3649 $dob = '1000-00-00';
3651 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3652 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3654 $about = $profile['about'];
3655 $about = strip_tags(bbcode($about));
3657 $location = formatted_location($profile);
3659 if ($profile['pub_keywords']) {
3660 $kw = str_replace(',',' ',$profile['pub_keywords']);
3661 $kw = str_replace(' ',' ',$kw);
3662 $arr = explode(' ',$profile['pub_keywords']);
3664 for ($x = 0; $x < 5; $x ++) {
3666 $tags .= '#'. trim($arr[$x]) .' ';
3670 $tags = trim($tags);
3673 $message = array("diaspora_handle" => $handle,
3674 "first_name" => $first,
3675 "last_name" => $last,
3676 "image_url" => $large,
3677 "image_url_medium" => $medium,
3678 "image_url_small" => $small,
3680 "gender" => $profile['gender'],
3682 "location" => $location,
3683 "searchable" => $searchable,
3684 "tag_string" => $tags);
3686 foreach ($recips as $recip) {
3687 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3688 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3693 * @brief Stores the signature for likes that are created on our system
3695 * @param array $contact The contact array of the "like"
3696 * @param int $post_id The post id of the "like"
3698 * @return bool Success
3700 public static function store_like_signature($contact, $post_id) {
3702 // Is the contact the owner? Then fetch the private key
3703 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3704 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3708 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3709 if (!dbm::is_result($r)) {
3713 $contact["uprvkey"] = $r[0]['prvkey'];
3715 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3716 if (!dbm::is_result($r)) {
3720 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3724 $message = self::construct_like($r[0], $contact);
3725 $message["author_signature"] = self::signature($contact, $message);
3727 // We now store the signature more flexible to dynamically support new fields.
3728 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3729 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3730 intval($message_id),
3731 dbesc(json_encode($message))
3734 logger('Stored diaspora like signature');
3739 * @brief Stores the signature for comments that are created on our system
3741 * @param array $item The item array of the comment
3742 * @param array $contact The contact array of the item owner
3743 * @param string $uprvkey The private key of the sender
3744 * @param int $message_id The message id of the comment
3746 * @return bool Success
3748 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3750 if ($uprvkey == "") {
3751 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3755 $contact["uprvkey"] = $uprvkey;
3757 $message = self::construct_comment($item, $contact);
3758 $message["author_signature"] = self::signature($contact, $message);
3760 // We now store the signature more flexible to dynamically support new fields.
3761 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3762 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3763 intval($message_id),
3764 dbesc(json_encode($message))
3767 logger('Stored diaspora comment signature');