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 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "valid_posting" and interpret only the new protocol.
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
15 require_once 'include/items.php';
16 require_once 'include/bb2diaspora.php';
17 require_once 'include/probe.php';
18 require_once 'include/Contact.php';
19 require_once 'include/Photo.php';
20 require_once 'include/socgraph.php';
21 require_once 'include/group.php';
22 require_once 'include/xml.php';
23 require_once 'include/datetime.php';
24 require_once 'include/queue_fn.php';
25 require_once 'include/cache.php';
28 * @brief This class contain functions to create and send Diaspora XML files
34 * @brief Return a list of relay servers
36 * This is an experimental Diaspora feature.
38 * @return array of relay servers
40 public static function relay_list() {
42 $serverdata = get_config("system", "relay_server");
43 if ($serverdata == "")
48 $servers = explode(",", $serverdata);
50 foreach ($servers AS $server) {
51 $server = trim($server);
52 $addr = "relay@".str_replace("http://", "", normalise_link($server));
53 $batch = $server."/receive/public";
55 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
56 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
59 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
60 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
65 dbesc(normalise_link($server)),
67 dbesc(NETWORK_DIASPORA),
68 intval(CONTACT_IS_FOLLOWER),
69 dbesc(datetime_convert()),
70 dbesc(datetime_convert()),
71 dbesc(datetime_convert())
74 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
76 $relay[] = $relais[0];
78 $relay[] = $relais[0];
85 * @brief repairs a signature that was double encoded
87 * The function is unused at the moment. It was copied from the old implementation.
89 * @param string $signature The signature
90 * @param string $handle The handle of the signature owner
91 * @param integer $level This value is only set inside this function to avoid endless loops
93 * @return string the repaired signature
95 private static function repair_signature($signature, $handle = "", $level = 1) {
100 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
101 $signature = base64_decode($signature);
102 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
104 // Do a recursive call to be able to fix even multiple levels
106 $signature = self::repair_signature($signature, $handle, ++$level);
113 * @brief verify the envelope and return the verified data
115 * @param string $envelope The magic envelope
117 * @return string verified data
119 private static function verify_magic_envelope($envelope) {
121 $basedom = parse_xml_string($envelope, false);
123 if (!is_object($basedom)) {
124 logger("Envelope is no XML file");
128 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
130 if (sizeof($children) == 0) {
131 logger("XML has no children");
137 $data = base64url_decode($children->data);
138 $type = $children->data->attributes()->type[0];
140 $encoding = $children->encoding;
142 $alg = $children->alg;
144 $sig = base64url_decode($children->sig);
145 $key_id = $children->sig->attributes()->key_id[0];
147 $handle = base64url_decode($key_id);
149 $b64url_data = base64url_encode($data);
150 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
152 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
154 $key = self::key($handle);
156 $verify = rsa_verify($signable_data, $sig, $key);
158 logger('Message did not verify. Discarding.');
166 * @brief encrypts data via AES
168 * @param string $key The AES key
169 * @param string $iv The IV (is used for CBC encoding)
170 * @param string $data The data that is to be encrypted
172 * @return string encrypted data
174 private static function aes_encrypt($key, $iv, $data) {
175 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
179 * @brief decrypts data via AES
181 * @param string $key The AES key
182 * @param string $iv The IV (is used for CBC encoding)
183 * @param string $encrypted The encrypted data
185 * @return string decrypted data
187 private static function aes_decrypt($key, $iv, $encrypted) {
188 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
192 * @brief: Decodes incoming Diaspora message in the new format
194 * @param array $importer Array of the importer user
195 * @param string $raw raw post message
198 * 'message' -> decoded Diaspora XML message
199 * 'author' -> author diaspora handle
200 * 'key' -> author public key (converted to pkcs#8)
202 public static function decode_raw($importer, $raw) {
203 $data = json_decode($raw);
205 // Is it a private post? Then decrypt the outer Salmon
206 if (is_object($data)) {
207 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
208 $ciphertext = base64_decode($data->encrypted_magic_envelope);
210 $outer_key_bundle = '';
211 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
212 $j_outer_key_bundle = json_decode($outer_key_bundle);
214 if (!is_object($j_outer_key_bundle)) {
215 logger('Outer Salmon did not verify. Discarding.');
216 http_status_exit(400);
219 $outer_iv = base64_decode($j_outer_key_bundle->iv);
220 $outer_key = base64_decode($j_outer_key_bundle->key);
222 $xml = diaspora::aes_decrypt($outer_key, $outer_iv, $ciphertext);
227 $basedom = parse_xml_string($xml);
229 if (!is_object($basedom)) {
230 logger('Received data does not seem to be an XML. Discarding.');
231 http_status_exit(400);
234 $base = $basedom->children(NAMESPACE_SALMON_ME);
236 // Not sure if this cleaning is needed
237 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
239 // Build the signed data
240 $type = $base->data[0]->attributes()->type[0];
241 $encoding = $base->encoding;
243 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
245 // This is the signature
246 $signature = base64url_decode($base->sig);
248 // Get the senders' public key
249 $key_id = $base->sig[0]->attributes()->key_id[0];
250 $author_addr = base64_decode($key_id);
251 $key = diaspora::key($author_addr);
253 $verify = rsa_verify($signed_data, $signature, $key);
255 logger('Message did not verify. Discarding.');
256 http_status_exit(400);
259 return array('message' => (string)base64url_decode($base->data),
260 'author' => unxmlify($author_addr),
261 'key' => (string)$key);
265 * @brief: Decodes incoming Diaspora message in the deprecated format
267 * @param array $importer Array of the importer user
268 * @param string $xml urldecoded Diaspora salmon
271 * 'message' -> decoded Diaspora XML message
272 * 'author' -> author diaspora handle
273 * 'key' -> author public key (converted to pkcs#8)
275 public static function decode($importer, $xml) {
278 $basedom = parse_xml_string($xml);
280 if (!is_object($basedom)) {
281 logger("XML is not parseable.");
284 $children = $basedom->children('https://joindiaspora.com/protocol');
286 if ($children->header) {
288 $author_link = str_replace('acct:','',$children->header->author_id);
291 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
293 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
294 $ciphertext = base64_decode($encrypted_header->ciphertext);
296 $outer_key_bundle = '';
297 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
299 $j_outer_key_bundle = json_decode($outer_key_bundle);
301 $outer_iv = base64_decode($j_outer_key_bundle->iv);
302 $outer_key = base64_decode($j_outer_key_bundle->key);
304 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
306 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
307 $idom = parse_xml_string($decrypted,false);
309 $inner_iv = base64_decode($idom->iv);
310 $inner_aes_key = base64_decode($idom->aes_key);
312 $author_link = str_replace('acct:','',$idom->author_id);
315 $dom = $basedom->children(NAMESPACE_SALMON_ME);
317 // figure out where in the DOM tree our data is hiding
319 if ($dom->provenance->data)
320 $base = $dom->provenance;
321 elseif ($dom->env->data)
327 logger('unable to locate salmon data in xml');
328 http_status_exit(400);
332 // Stash the signature away for now. We have to find their key or it won't be good for anything.
333 $signature = base64url_decode($base->sig);
337 // strip whitespace so our data element will return to one big base64 blob
338 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
341 // stash away some other stuff for later
343 $type = $base->data[0]->attributes()->type[0];
344 $keyhash = $base->sig[0]->attributes()->keyhash[0];
345 $encoding = $base->encoding;
349 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
353 $data = base64url_decode($data);
357 $inner_decrypted = $data;
360 // Decode the encrypted blob
362 $inner_encrypted = base64_decode($data);
363 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
367 logger('Could not retrieve author URI.');
368 http_status_exit(400);
370 // Once we have the author URI, go to the web and try to find their public key
371 // (first this will look it up locally if it is in the fcontact cache)
372 // This will also convert diaspora public key from pkcs#1 to pkcs#8
374 logger('Fetching key for '.$author_link);
375 $key = self::key($author_link);
378 logger('Could not retrieve author key.');
379 http_status_exit(400);
382 $verify = rsa_verify($signed_data,$signature,$key);
385 logger('Message did not verify. Discarding.');
386 http_status_exit(400);
389 logger('Message verified.');
391 return array('message' => (string)$inner_decrypted,
392 'author' => unxmlify($author_link),
393 'key' => (string)$key);
398 * @brief Dispatches public messages and find the fitting receivers
400 * @param array $msg The post that will be dispatched
402 * @return int The message id of the generated message, "true" or "false" if there was an error
404 public static function dispatch_public($msg) {
406 $enabled = intval(get_config("system", "diaspora_enabled"));
408 logger("diaspora is disabled");
412 if (!($postdata = self::valid_posting($msg))) {
413 logger("Invalid posting");
417 $fields = $postdata['fields'];
419 // Is it a an action (comment, like, ...) for our own post?
420 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
421 $guid = notags(unxmlify($fields->parent_guid));
422 $importer = self::importer_for_guid($guid);
423 if (is_array($importer)) {
424 logger("delivering to origin: ".$importer["name"]);
425 $message_id = self::dispatch($importer, $msg, $fields);
430 // Now distribute it to the followers
431 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
432 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
433 AND NOT `account_expired` AND NOT `account_removed`",
434 dbesc(NETWORK_DIASPORA),
435 dbesc($msg["author"])
438 if (dbm::is_result($r)) {
439 foreach ($r as $rr) {
440 logger("delivering to: ".$rr["username"]);
441 self::dispatch($rr, $msg, $fields);
443 } elseif (!Config::get('system', 'relay_subscribe', false)) {
444 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
446 // Use a dummy importer to import the data for the public copy
447 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
448 $message_id = self::dispatch($importer, $msg, $fields);
455 * @brief Dispatches the different message types to the different functions
457 * @param array $importer Array of the importer user
458 * @param array $msg The post that will be dispatched
459 * @param object $fields SimpleXML object that contains the message
461 * @return int The message id of the generated message, "true" or "false" if there was an error
463 public static function dispatch($importer, $msg, $fields = null) {
465 // The sender is the handle of the contact that sent the message.
466 // This will often be different with relayed messages (for example "like" and "comment")
467 $sender = $msg["author"];
469 // This is only needed for private postings since this is already done for public ones before
470 if (is_null($fields)) {
471 if (!($postdata = self::valid_posting($msg))) {
472 logger("Invalid posting");
475 $fields = $postdata['fields'];
478 $type = $fields->getName();
480 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
483 case "account_deletion":
484 return self::receive_account_deletion($importer, $fields);
487 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
490 return self::receive_contact_request($importer, $fields);
493 return self::receive_conversation($importer, $msg, $fields);
496 return self::receive_like($importer, $sender, $fields);
499 return self::receive_message($importer, $fields);
501 case "participation": // Not implemented
502 return self::receive_participation($importer, $fields);
504 case "photo": // Not implemented
505 return self::receive_photo($importer, $fields);
507 case "poll_participation": // Not implemented
508 return self::receive_poll_participation($importer, $fields);
511 return self::receive_profile($importer, $fields);
514 return self::receive_reshare($importer, $fields, $msg["message"]);
517 return self::receive_retraction($importer, $sender, $fields);
519 case "status_message":
520 return self::receive_status_message($importer, $fields, $msg["message"]);
523 logger("Unknown message type ".$type);
531 * @brief Checks if a posting is valid and fetches the data fields.
533 * This function does not only check the signature.
534 * It also does the conversion between the old and the new diaspora format.
536 * @param array $msg Array with the XML, the sender handle and the sender signature
538 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
540 private static function valid_posting($msg) {
542 $data = parse_xml_string($msg["message"], false);
544 if (!is_object($data)) {
545 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
549 $first_child = $data->getName();
551 // Is this the new or the old version?
552 if ($data->getName() == "XML") {
554 foreach ($data->post->children() as $child)
561 $type = $element->getName();
564 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
566 // All retractions are handled identically from now on.
567 // In the new version there will only be "retraction".
568 if (in_array($type, array("signed_retraction", "relayable_retraction")))
569 $type = "retraction";
571 if ($type == "request")
574 $fields = new SimpleXMLElement("<".$type."/>");
578 foreach ($element->children() AS $fieldname => $entry) {
580 // Translation for the old XML structure
581 if ($fieldname == "diaspora_handle") {
582 $fieldname = "author";
584 if ($fieldname == "participant_handles") {
585 $fieldname = "participants";
587 if (in_array($type, array("like", "participation"))) {
588 if ($fieldname == "target_type") {
589 $fieldname = "parent_type";
592 if ($fieldname == "sender_handle") {
593 $fieldname = "author";
595 if ($fieldname == "recipient_handle") {
596 $fieldname = "recipient";
598 if ($fieldname == "root_diaspora_id") {
599 $fieldname = "root_author";
601 if ($type == "status_message") {
602 if ($fieldname == "raw_message") {
606 if ($type == "retraction") {
607 if ($fieldname == "post_guid") {
608 $fieldname = "target_guid";
610 if ($fieldname == "type") {
611 $fieldname = "target_type";
616 if (($fieldname == "author_signature") && ($entry != ""))
617 $author_signature = base64_decode($entry);
618 elseif (($fieldname == "parent_author_signature") && ($entry != ""))
619 $parent_author_signature = base64_decode($entry);
620 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
621 if ($signed_data != "") {
623 $signed_data_parent .= ";";
626 $signed_data .= $entry;
628 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) ||
629 ($orig_type == "relayable_retraction"))
630 xml::copy($entry, $fields, $fieldname);
633 // This is something that shouldn't happen at all.
634 if (in_array($type, array("status_message", "reshare", "profile")))
635 if ($msg["author"] != $fields->author) {
636 logger("Message handle is not the same as envelope sender. Quitting this message.");
640 // Only some message types have signatures. So we quit here for the other types.
641 if (!in_array($type, array("comment", "like"))) {
642 return array("fields" => $fields, "relayed" => false);
644 // No author_signature? This is a must, so we quit.
645 if (!isset($author_signature)) {
646 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
650 if (isset($parent_author_signature)) {
653 $key = self::key($msg["author"]);
655 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
656 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);
663 $key = self::key($fields->author);
665 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
666 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
669 return array("fields" => $fields, "relayed" => $relayed);
674 * @brief Fetches the public key for a given handle
676 * @param string $handle The handle
678 * @return string The public key
680 private static function key($handle) {
681 $handle = strval($handle);
683 logger("Fetching diaspora key for: ".$handle);
685 $r = self::person_by_handle($handle);
693 * @brief Fetches data for a given handle
695 * @param string $handle The handle
697 * @return array the queried data
699 public static function person_by_handle($handle) {
701 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
702 dbesc(NETWORK_DIASPORA),
707 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
709 // update record occasionally so it doesn't get stale
710 $d = strtotime($person["updated"]." +00:00");
711 if ($d < strtotime("now - 14 days"))
714 if ($person["guid"] == "")
718 if (!$person || $update) {
719 logger("create or refresh", LOGGER_DEBUG);
720 $r = probe_url($handle, PROBE_DIASPORA);
722 // Note that Friendica contacts will return a "Diaspora person"
723 // if Diaspora connectivity is enabled on their server
724 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
725 self::add_fcontact($r, $update);
733 * @brief Updates the fcontact table
735 * @param array $arr The fcontact data
736 * @param bool $update Update or insert?
738 * @return string The id of the fcontact entry
740 private static function add_fcontact($arr, $update = false) {
743 $r = q("UPDATE `fcontact` SET
757 WHERE `url` = '%s' AND `network` = '%s'",
759 dbesc($arr["photo"]),
760 dbesc($arr["request"]),
762 dbesc(strtolower($arr["addr"])),
764 dbesc($arr["batch"]),
765 dbesc($arr["notify"]),
767 dbesc($arr["confirm"]),
768 dbesc($arr["alias"]),
769 dbesc($arr["pubkey"]),
770 dbesc(datetime_convert()),
772 dbesc($arr["network"])
775 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
776 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
777 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
780 dbesc($arr["photo"]),
781 dbesc($arr["request"]),
785 dbesc($arr["batch"]),
786 dbesc($arr["notify"]),
788 dbesc($arr["confirm"]),
789 dbesc($arr["network"]),
790 dbesc($arr["alias"]),
791 dbesc($arr["pubkey"]),
792 dbesc(datetime_convert())
800 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
802 * @param int $contact_id The id in the contact table
803 * @param int $gcontact_id The id in the gcontact table
805 * @return string the handle
807 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
810 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
812 if ($gcontact_id != 0) {
813 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
814 intval($gcontact_id));
816 if (dbm::is_result($r)) {
817 return strtolower($r[0]["addr"]);
821 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
822 intval($contact_id));
824 if (dbm::is_result($r)) {
827 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
829 if ($contact['addr'] != "") {
830 $handle = $contact['addr'];
832 $baseurl_start = strpos($contact['url'],'://') + 3;
833 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
834 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
835 $handle = $contact['nick'].'@'.$baseurl;
839 return strtolower($handle);
843 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
846 * @param mixed $fcontact_guid Hexadecimal string guid
848 * @return string the contact url or null
850 public static function url_from_contact_guid($fcontact_guid) {
851 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
853 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
854 dbesc(NETWORK_DIASPORA),
855 dbesc($fcontact_guid)
858 if (dbm::is_result($r)) {
866 * @brief Get a contact id for a given handle
868 * @param int $uid The user id
869 * @param string $handle The handle in the format user@domain.tld
871 * @return The contact id
873 private static function contact_by_handle($uid, $handle) {
875 // First do a direct search on the contact table
876 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
881 if (dbm::is_result($r)) {
885 * We haven't found it?
886 * We use another function for it that will possibly create a contact entry.
888 $cid = get_contact($handle, $uid);
891 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
892 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
894 if (dbm::is_result($r)) {
900 $handle_parts = explode("@", $handle);
901 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
902 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
907 if (dbm::is_result($r)) {
911 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
916 * @brief Check if posting is allowed for this contact
918 * @param array $importer Array of the importer user
919 * @param array $contact The contact that is checked
920 * @param bool $is_comment Is the check for a comment?
922 * @return bool is the contact allowed to post?
924 private static function post_allow($importer, $contact, $is_comment = false) {
927 * Perhaps we were already sharing with this person. Now they're sharing with us.
928 * That makes us friends.
929 * Normally this should have handled by getting a request - but this could get lost
931 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
932 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
933 array('id' => $contact["id"], 'uid' => $contact["uid"]));
935 $contact["rel"] = CONTACT_IS_FRIEND;
936 logger("defining user ".$contact["nick"]." as friend");
939 // We don't seem to like that person
940 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
941 // Maybe blocked, don't accept.
943 // We are following this person?
944 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
945 // Yes, then it is fine.
947 // Is it a post to a community?
948 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
951 // Is the message a global user or a comment?
952 } elseif (($importer["uid"] == 0) || $is_comment) {
953 // Messages for the global users and comments are always accepted
961 * @brief Fetches the contact id for a handle and checks if posting is allowed
963 * @param array $importer Array of the importer user
964 * @param string $handle The checked handle in the format user@domain.tld
965 * @param bool $is_comment Is the check for a comment?
967 * @return array The contact data
969 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
970 $contact = self::contact_by_handle($importer["uid"], $handle);
972 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
973 // If a contact isn't found, we accept it anyway if it is a comment
981 if (!self::post_allow($importer, $contact, $is_comment)) {
982 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
989 * @brief Does the message already exists on the system?
991 * @param int $uid The user id
992 * @param string $guid The guid of the message
994 * @return int|bool message id if the message already was stored into the system - or false.
996 private static function message_exists($uid, $guid) {
997 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1002 if (dbm::is_result($r)) {
1003 logger("message ".$guid." already exists for user ".$uid);
1011 * @brief Checks for links to posts in a message
1013 * @param array $item The item array
1015 private static function fetch_guid($item) {
1016 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1017 preg_replace_callback($expression,
1018 function ($match) use ($item) {
1019 return self::fetch_guid_sub($match, $item);
1022 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1023 function ($match) use ($item) {
1024 return self::fetch_guid_sub($match, $item);
1029 * @brief Checks for relative /people/* links in an item body to match local
1030 * contacts or prepends the remote host taken from the author link.
1032 * @param string $body The item body to replace links from
1033 * @param string $author_link The author link for missing local contact fallback
1035 * @return the replaced string
1037 public static function replace_people_guid($body, $author_link) {
1038 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1039 function ($match) use ($author_link) {
1041 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1042 // 1 => '0123456789abcdef'
1044 $handle = self::url_from_contact_guid($match[1]);
1047 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1049 // No local match, restoring absolute remote URL from author scheme and host
1050 $author_url = parse_url($author_link);
1051 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1061 * @brief sub function of "fetch_guid" which checks for links in messages
1063 * @param array $match array containing a link that has to be checked for a message link
1064 * @param array $item The item array
1066 private static function fetch_guid_sub($match, $item) {
1067 if (!self::store_by_guid($match[1], $item["author-link"]))
1068 self::store_by_guid($match[1], $item["owner-link"]);
1072 * @brief Fetches an item with a given guid from a given server
1074 * @param string $guid the message guid
1075 * @param string $server The server address
1076 * @param int $uid The user id of the user
1078 * @return int the message id of the stored message or false
1080 private static function store_by_guid($guid, $server, $uid = 0) {
1081 $serverparts = parse_url($server);
1082 $server = $serverparts["scheme"]."://".$serverparts["host"];
1084 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1086 $msg = self::message($guid, $server);
1091 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1093 // Now call the dispatcher
1094 return self::dispatch_public($msg);
1098 * @brief Fetches a message from a server
1100 * @param string $guid message guid
1101 * @param string $server The url of the server
1102 * @param int $level Endless loop prevention
1105 * 'message' => The message XML
1106 * 'author' => The author handle
1107 * 'key' => The public key of the author
1109 private static function message($guid, $server, $level = 0) {
1114 // This will work for new Diaspora servers and Friendica servers from 3.5
1115 $source_url = $server."/fetch/post/".$guid;
1116 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1118 $envelope = fetch_url($source_url);
1120 logger("Envelope was fetched.", LOGGER_DEBUG);
1121 $x = self::verify_magic_envelope($envelope);
1123 logger("Envelope could not be verified.", LOGGER_DEBUG);
1125 logger("Envelope was verified.", LOGGER_DEBUG);
1129 // This will work for older Diaspora and Friendica servers
1131 $source_url = $server."/p/".$guid.".xml";
1132 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1134 $x = fetch_url($source_url);
1139 $source_xml = parse_xml_string($x, false);
1141 if (!is_object($source_xml))
1144 if ($source_xml->post->reshare) {
1145 // Reshare of a reshare - old Diaspora version
1146 logger("Message is a reshare", LOGGER_DEBUG);
1147 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1148 } elseif ($source_xml->getName() == "reshare") {
1149 // Reshare of a reshare - new Diaspora version
1150 logger("Message is a new reshare", LOGGER_DEBUG);
1151 return self::message($source_xml->root_guid, $server, ++$level);
1156 // Fetch the author - for the old and the new Diaspora version
1157 if ($source_xml->post->status_message->diaspora_handle)
1158 $author = (string)$source_xml->post->status_message->diaspora_handle;
1159 elseif ($source_xml->author && ($source_xml->getName() == "status_message"))
1160 $author = (string)$source_xml->author;
1162 // If this isn't a "status_message" then quit
1164 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1168 $msg = array("message" => $x, "author" => $author);
1170 $msg["key"] = self::key($msg["author"]);
1176 * @brief Fetches the item record of a given guid
1178 * @param int $uid The user id
1179 * @param string $guid message guid
1180 * @param string $author The handle of the item
1181 * @param array $contact The contact of the item owner
1183 * @return array the item record
1185 private static function parent_item($uid, $guid, $author, $contact) {
1186 $r = q("SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1187 `author-name`, `author-link`, `author-avatar`,
1188 `owner-name`, `owner-link`, `owner-avatar`
1189 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1190 intval($uid), dbesc($guid));
1193 $result = self::store_by_guid($guid, $contact["url"], $uid);
1196 $person = self::person_by_handle($author);
1197 $result = self::store_by_guid($guid, $person["url"], $uid);
1201 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1203 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1204 `author-name`, `author-link`, `author-avatar`,
1205 `owner-name`, `owner-link`, `owner-avatar`
1206 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1207 intval($uid), dbesc($guid));
1212 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1215 logger("parent item found: parent: ".$guid." - user: ".$uid);
1221 * @brief returns contact details
1223 * @param array $contact The default contact if the person isn't found
1224 * @param array $person The record of the person
1225 * @param int $uid The user id
1228 * 'cid' => contact id
1229 * 'network' => network type
1231 private static function author_contact_by_url($contact, $person, $uid) {
1233 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1234 dbesc(normalise_link($person["url"])), intval($uid));
1237 $network = $r[0]["network"];
1239 // We are receiving content from a user that possibly is about to be terminated
1240 // This means the user is vital, so we remove a possible termination date.
1241 unmark_for_death($r[0]);
1243 $cid = $contact["id"];
1244 $network = NETWORK_DIASPORA;
1247 return array("cid" => $cid, "network" => $network);
1251 * @brief Is the profile a hubzilla profile?
1253 * @param string $url The profile link
1255 * @return bool is it a hubzilla server?
1257 public static function is_redmatrix($url) {
1258 return(strstr($url, "/channel/"));
1262 * @brief Generate a post link with a given handle and message guid
1264 * @param string $addr The user handle
1265 * @param string $guid message guid
1267 * @return string the post link
1269 private static function plink($addr, $guid, $parent_guid = '') {
1270 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1273 if (!dbm::is_result($r)) {
1274 if ($parent_guid != '') {
1275 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$parent_guid."#".$guid;
1277 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$guid;
1281 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1282 // So we try another way as well.
1283 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1284 if (dbm::is_result($s)) {
1285 $r[0]["network"] = $s[0]["network"];
1288 if ($r[0]["network"] == NETWORK_DFRN) {
1289 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1292 if (self::is_redmatrix($r[0]["url"])) {
1293 return $r[0]["url"]."/?f=&mid=".$guid;
1296 if ($parent_guid != '') {
1297 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$parent_guid."#".$guid;
1299 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1304 * @brief Processes an account deletion
1306 * @param array $importer Array of the importer user
1307 * @param object $data The message object
1309 * @return bool Success
1311 private static function receive_account_deletion($importer, $data) {
1313 /// @todo Account deletion should remove the contact from the global contacts as well
1315 $author = notags(unxmlify($data->author));
1317 $contact = self::contact_by_handle($importer["uid"], $author);
1319 logger("cannot find contact for author: ".$author);
1323 // We now remove the contact
1324 contact_remove($contact["id"]);
1329 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1331 * @param string $author Author handle
1332 * @param string $guid Message guid
1333 * @param boolean $onlyfound Only return uri when found in the database
1335 * @return string The constructed uri or the one from our database
1337 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1339 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1340 if (dbm::is_result($r)) {
1341 return $r[0]["uri"];
1342 } elseif (!$onlyfound) {
1343 return $author.":".$guid;
1350 * @brief Fetch the guid from our database with a given uri
1352 * @param string $author Author handle
1353 * @param string $uri Message uri
1355 * @return string The post guid
1357 private static function get_guid_from_uri($uri, $uid) {
1359 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1360 if (dbm::is_result($r)) {
1361 return $r[0]["guid"];
1368 * @brief Find the best importer for a comment, like, ...
1370 * @param string $guid The guid of the item
1372 * @return array|boolean the origin owner of that post - or false
1374 private static function importer_for_guid($guid) {
1375 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1377 if (dbm::is_result($item)) {
1378 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1379 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1380 if (dbm::is_result($contact)) {
1388 * @brief Processes an incoming comment
1390 * @param array $importer Array of the importer user
1391 * @param string $sender The sender of the message
1392 * @param object $data The message object
1393 * @param string $xml The original XML of the message
1395 * @return int The message id of the generated comment or "false" if there was an error
1397 private static function receive_comment($importer, $sender, $data, $xml) {
1398 $author = notags(unxmlify($data->author));
1399 $guid = notags(unxmlify($data->guid));
1400 $parent_guid = notags(unxmlify($data->parent_guid));
1401 $text = unxmlify($data->text);
1403 if (isset($data->created_at)) {
1404 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1406 $created_at = datetime_convert();
1409 if (isset($data->thread_parent_guid)) {
1410 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1411 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1416 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1421 $message_id = self::message_exists($importer["uid"], $guid);
1426 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1427 if (!$parent_item) {
1431 $person = self::person_by_handle($author);
1432 if (!is_array($person)) {
1433 logger("unable to find author details");
1437 // Fetch the contact id - if we know this contact
1438 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1440 $datarray = array();
1442 $datarray["uid"] = $importer["uid"];
1443 $datarray["contact-id"] = $author_contact["cid"];
1444 $datarray["network"] = $author_contact["network"];
1446 $datarray["author-name"] = $person["name"];
1447 $datarray["author-link"] = $person["url"];
1448 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1450 $datarray["owner-name"] = $contact["name"];
1451 $datarray["owner-link"] = $contact["url"];
1452 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1454 $datarray["guid"] = $guid;
1455 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1457 $datarray["type"] = "remote-comment";
1458 $datarray["verb"] = ACTIVITY_POST;
1459 $datarray["gravity"] = GRAVITY_COMMENT;
1461 if ($thr_uri != "") {
1462 $datarray["parent-uri"] = $thr_uri;
1464 $datarray["parent-uri"] = $parent_item["uri"];
1467 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1469 $datarray["protocol"] = PROTOCOL_DIASPORA;
1470 $datarray["source"] = $xml;
1472 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1474 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1476 $body = diaspora2bb($text);
1478 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1480 self::fetch_guid($datarray);
1482 $message_id = item_store($datarray);
1484 if ($message_id <= 0) {
1489 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1492 // If we are the origin of the parent we store the original data and notify our followers
1493 if ($message_id && $parent_item["origin"]) {
1495 // Formerly we stored the signed text, the signature and the author in different fields.
1496 // We now store the raw data so that we are more flexible.
1497 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1500 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1507 * @brief processes and stores private messages
1509 * @param array $importer Array of the importer user
1510 * @param array $contact The contact of the message
1511 * @param object $data The message object
1512 * @param array $msg Array of the processed message, author handle and key
1513 * @param object $mesg The private message
1514 * @param array $conversation The conversation record to which this message belongs
1516 * @return bool "true" if it was successful
1518 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1519 $author = notags(unxmlify($data->author));
1520 $guid = notags(unxmlify($data->guid));
1521 $subject = notags(unxmlify($data->subject));
1523 // "diaspora_handle" is the element name from the old version
1524 // "author" is the element name from the new version
1525 if ($mesg->author) {
1526 $msg_author = notags(unxmlify($mesg->author));
1527 } elseif ($mesg->diaspora_handle) {
1528 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1533 $msg_guid = notags(unxmlify($mesg->guid));
1534 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1535 $msg_text = unxmlify($mesg->text);
1536 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1538 if ($msg_conversation_guid != $guid) {
1539 logger("message conversation guid does not belong to the current conversation.");
1543 $body = diaspora2bb($msg_text);
1544 $message_uri = $msg_author.":".$msg_guid;
1546 $person = self::person_by_handle($msg_author);
1550 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1552 intval($importer["uid"])
1554 if (dbm::is_result($r)) {
1555 logger("duplicate message already delivered.", LOGGER_DEBUG);
1559 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1560 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1561 intval($importer["uid"]),
1563 intval($conversation["id"]),
1564 dbesc($person["name"]),
1565 dbesc($person["photo"]),
1566 dbesc($person["url"]),
1567 intval($contact["id"]),
1572 dbesc($message_uri),
1573 dbesc($author.":".$guid),
1574 dbesc($msg_created_at)
1579 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1582 "type" => NOTIFY_MAIL,
1583 "notify_flags" => $importer["notify-flags"],
1584 "language" => $importer["language"],
1585 "to_name" => $importer["username"],
1586 "to_email" => $importer["email"],
1587 "uid" =>$importer["uid"],
1588 "item" => array("subject" => $subject, "body" => $body),
1589 "source_name" => $person["name"],
1590 "source_link" => $person["url"],
1591 "source_photo" => $person["thumb"],
1592 "verb" => ACTIVITY_POST,
1599 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1601 * @param array $importer Array of the importer user
1602 * @param array $msg Array of the processed message, author handle and key
1603 * @param object $data The message object
1605 * @return bool Success
1607 private static function receive_conversation($importer, $msg, $data) {
1608 $author = notags(unxmlify($data->author));
1609 $guid = notags(unxmlify($data->guid));
1610 $subject = notags(unxmlify($data->subject));
1611 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1612 $participants = notags(unxmlify($data->participants));
1614 $messages = $data->message;
1616 if (!count($messages)) {
1617 logger("empty conversation");
1621 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1625 $conversation = null;
1627 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1628 intval($importer["uid"]),
1632 $conversation = $c[0];
1634 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1635 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1636 intval($importer["uid"]),
1640 dbesc(datetime_convert()),
1642 dbesc($participants)
1645 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1646 intval($importer["uid"]),
1651 $conversation = $c[0];
1653 if (!$conversation) {
1654 logger("unable to create conversation.");
1658 foreach ($messages as $mesg)
1659 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1665 * @brief Creates the body for a "like" message
1667 * @param array $contact The contact that send us the "like"
1668 * @param array $parent_item The item array of the parent item
1669 * @param string $guid message guid
1671 * @return string the body
1673 private static function construct_like_body($contact, $parent_item, $guid) {
1674 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1676 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1677 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1678 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1680 return sprintf($bodyverb, $ulink, $alink, $plink);
1684 * @brief Creates a XML object for a "like"
1686 * @param array $importer Array of the importer user
1687 * @param array $parent_item The item array of the parent item
1689 * @return string The XML
1691 private static function construct_like_object($importer, $parent_item) {
1692 $objtype = ACTIVITY_OBJ_NOTE;
1693 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1694 $parent_body = $parent_item["body"];
1696 $xmldata = array("object" => array("type" => $objtype,
1698 "id" => $parent_item["uri"],
1701 "content" => $parent_body));
1703 return xml::from_array($xmldata, $xml, true);
1707 * @brief Processes "like" messages
1709 * @param array $importer Array of the importer user
1710 * @param string $sender The sender of the message
1711 * @param object $data The message object
1713 * @return int The message id of the generated like or "false" if there was an error
1715 private static function receive_like($importer, $sender, $data) {
1716 $author = notags(unxmlify($data->author));
1717 $guid = notags(unxmlify($data->guid));
1718 $parent_guid = notags(unxmlify($data->parent_guid));
1719 $parent_type = notags(unxmlify($data->parent_type));
1720 $positive = notags(unxmlify($data->positive));
1722 // likes on comments aren't supported by Diaspora - only on posts
1723 // But maybe this will be supported in the future, so we will accept it.
1724 if (!in_array($parent_type, array("Post", "Comment")))
1727 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1731 $message_id = self::message_exists($importer["uid"], $guid);
1735 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1739 $person = self::person_by_handle($author);
1740 if (!is_array($person)) {
1741 logger("unable to find author details");
1745 // Fetch the contact id - if we know this contact
1746 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1748 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1749 // We would accept this anyhow.
1750 if ($positive == "true")
1751 $verb = ACTIVITY_LIKE;
1753 $verb = ACTIVITY_DISLIKE;
1755 $datarray = array();
1757 $datarray["protocol"] = PROTOCOL_DIASPORA;
1759 $datarray["uid"] = $importer["uid"];
1760 $datarray["contact-id"] = $author_contact["cid"];
1761 $datarray["network"] = $author_contact["network"];
1763 $datarray["author-name"] = $person["name"];
1764 $datarray["author-link"] = $person["url"];
1765 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1767 $datarray["owner-name"] = $contact["name"];
1768 $datarray["owner-link"] = $contact["url"];
1769 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1771 $datarray["guid"] = $guid;
1772 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1774 $datarray["type"] = "activity";
1775 $datarray["verb"] = $verb;
1776 $datarray["gravity"] = GRAVITY_LIKE;
1777 $datarray["parent-uri"] = $parent_item["uri"];
1779 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1780 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1782 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1784 $message_id = item_store($datarray);
1786 if ($message_id <= 0) {
1791 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1794 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1795 if ($parent_item["id"] != $parent_item["parent"]) {
1796 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
1797 $origin = $toplevel["origin"];
1799 $origin = $parent_item["origin"];
1802 // If we are the origin of the parent we store the original data and notify our followers
1803 if ($message_id && $origin) {
1805 // Formerly we stored the signed text, the signature and the author in different fields.
1806 // We now store the raw data so that we are more flexible.
1807 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1810 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1817 * @brief Processes private messages
1819 * @param array $importer Array of the importer user
1820 * @param object $data The message object
1822 * @return bool Success?
1824 private static function receive_message($importer, $data) {
1825 $author = notags(unxmlify($data->author));
1826 $guid = notags(unxmlify($data->guid));
1827 $conversation_guid = notags(unxmlify($data->conversation_guid));
1828 $text = unxmlify($data->text);
1829 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1831 $contact = self::allowed_contact_by_handle($importer, $author, true);
1836 $conversation = null;
1838 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1839 intval($importer["uid"]),
1840 dbesc($conversation_guid)
1843 $conversation = $c[0];
1845 logger("conversation not available.");
1849 $message_uri = $author.":".$guid;
1851 $person = self::person_by_handle($author);
1853 logger("unable to find author details");
1857 $body = diaspora2bb($text);
1859 $body = self::replace_people_guid($body, $person["url"]);
1863 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1865 intval($importer["uid"])
1867 if (dbm::is_result($r)) {
1868 logger("duplicate message already delivered.", LOGGER_DEBUG);
1872 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1873 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1874 intval($importer["uid"]),
1876 intval($conversation["id"]),
1877 dbesc($person["name"]),
1878 dbesc($person["photo"]),
1879 dbesc($person["url"]),
1880 intval($contact["id"]),
1881 dbesc($conversation["subject"]),
1885 dbesc($message_uri),
1886 dbesc($author.":".$conversation["guid"]),
1892 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1897 * @brief Processes participations - unsupported by now
1899 * @param array $importer Array of the importer user
1900 * @param object $data The message object
1902 * @return bool always true
1904 private static function receive_participation($importer, $data) {
1905 // I'm not sure if we can fully support this message type
1910 * @brief Processes photos - unneeded
1912 * @param array $importer Array of the importer user
1913 * @param object $data The message object
1915 * @return bool always true
1917 private static function receive_photo($importer, $data) {
1918 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1923 * @brief Processes poll participations - unssupported
1925 * @param array $importer Array of the importer user
1926 * @param object $data The message object
1928 * @return bool always true
1930 private static function receive_poll_participation($importer, $data) {
1931 // We don't support polls by now
1936 * @brief Processes incoming profile updates
1938 * @param array $importer Array of the importer user
1939 * @param object $data The message object
1941 * @return bool Success
1943 private static function receive_profile($importer, $data) {
1944 $author = strtolower(notags(unxmlify($data->author)));
1946 $contact = self::contact_by_handle($importer["uid"], $author);
1950 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1951 $image_url = unxmlify($data->image_url);
1952 $birthday = unxmlify($data->birthday);
1953 $gender = unxmlify($data->gender);
1954 $about = diaspora2bb(unxmlify($data->bio));
1955 $location = diaspora2bb(unxmlify($data->location));
1956 $searchable = (unxmlify($data->searchable) == "true");
1957 $nsfw = (unxmlify($data->nsfw) == "true");
1958 $tags = unxmlify($data->tag_string);
1960 $tags = explode("#", $tags);
1962 $keywords = array();
1963 foreach ($tags as $tag) {
1964 $tag = trim(strtolower($tag));
1969 $keywords = implode(", ", $keywords);
1971 $handle_parts = explode("@", $author);
1972 $nick = $handle_parts[0];
1975 $name = $handle_parts[0];
1977 if ( preg_match("|^https?://|", $image_url) === 0)
1978 $image_url = "http://".$handle_parts[1].$image_url;
1980 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1982 // Generic birthday. We don't know the timezone. The year is irrelevant.
1984 $birthday = str_replace("1000", "1901", $birthday);
1986 if ($birthday != "")
1987 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1989 // this is to prevent multiple birthday notifications in a single year
1990 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1992 if (substr($birthday,5) === substr($contact["bd"],5))
1993 $birthday = $contact["bd"];
1995 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1996 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2000 dbesc(datetime_convert()),
2006 intval($contact["id"]),
2007 intval($importer["uid"])
2010 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2011 "photo" => $image_url, "name" => $name, "location" => $location,
2012 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2013 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2014 "hide" => !$searchable, "nsfw" => $nsfw);
2016 $gcid = update_gcontact($gcontact);
2018 link_gcontact($gcid, $importer["uid"], $contact["id"]);
2020 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2026 * @brief Processes incoming friend requests
2028 * @param array $importer Array of the importer user
2029 * @param array $contact The contact that send the request
2031 private static function receive_request_make_friend($importer, $contact) {
2035 if ($contact["rel"] == CONTACT_IS_SHARING) {
2036 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2037 array('id' => $contact["id"], 'uid' => $importer["uid"]));
2039 // send notification
2041 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2042 intval($importer["uid"])
2045 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
2047 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2048 intval($importer["uid"])
2051 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2053 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2056 $arr["protocol"] = PROTOCOL_DIASPORA;
2057 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2058 $arr["uid"] = $importer["uid"];
2059 $arr["contact-id"] = $self[0]["id"];
2061 $arr["type"] = 'wall';
2062 $arr["gravity"] = 0;
2064 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2065 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2066 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2067 $arr["verb"] = ACTIVITY_FRIEND;
2068 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2070 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2071 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2072 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2073 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2075 $arr["object"] = self::construct_new_friend_object($contact);
2077 $arr["last-child"] = 1;
2079 $arr["allow_cid"] = $user[0]["allow_cid"];
2080 $arr["allow_gid"] = $user[0]["allow_gid"];
2081 $arr["deny_cid"] = $user[0]["deny_cid"];
2082 $arr["deny_gid"] = $user[0]["deny_gid"];
2084 $i = item_store($arr);
2086 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2092 * @brief Creates a XML object for a "new friend" message
2094 * @param array $contact Array of the contact
2096 * @return string The XML
2098 private static function construct_new_friend_object($contact) {
2099 $objtype = ACTIVITY_OBJ_PERSON;
2100 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2101 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2103 $xmldata = array("object" => array("type" => $objtype,
2104 "title" => $contact["name"],
2105 "id" => $contact["url"]."/".$contact["name"],
2108 return xml::from_array($xmldata, $xml, true);
2112 * @brief Processes incoming sharing notification
2114 * @param array $importer Array of the importer user
2115 * @param object $data The message object
2117 * @return bool Success
2119 private static function receive_contact_request($importer, $data) {
2120 $author = unxmlify($data->author);
2121 $recipient = unxmlify($data->recipient);
2123 if (!$author || !$recipient) {
2127 // the current protocol version doesn't know these fields
2128 // That means that we will assume their existance
2129 if (isset($data->following)) {
2130 $following = (unxmlify($data->following) == "true");
2135 if (isset($data->sharing)) {
2136 $sharing = (unxmlify($data->sharing) == "true");
2141 $contact = self::contact_by_handle($importer["uid"],$author);
2143 // perhaps we were already sharing with this person. Now they're sharing with us.
2144 // That makes us friends.
2147 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2148 self::receive_request_make_friend($importer, $contact);
2150 // refetch the contact array
2151 $contact = self::contact_by_handle($importer["uid"],$author);
2153 // If we are now friends, we are sending a share message.
2154 // Normally we needn't to do so, but the first message could have been vanished.
2155 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2156 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2158 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2159 $ret = self::send_share($u[0], $contact);
2164 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2165 lose_follower($importer, $contact);
2170 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2171 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2173 } elseif (!$following && !$sharing) {
2174 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2176 } elseif (!$following && $sharing) {
2177 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2178 } elseif ($following && $sharing) {
2179 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2180 } elseif ($following && !$sharing) {
2181 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2184 $ret = self::person_by_handle($author);
2186 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2187 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2191 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2193 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2194 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2195 intval($importer["uid"]),
2196 dbesc($ret["network"]),
2197 dbesc($ret["addr"]),
2200 dbesc(normalise_link($ret["url"])),
2202 dbesc($ret["name"]),
2203 dbesc($ret["nick"]),
2204 dbesc($ret["photo"]),
2205 dbesc($ret["pubkey"]),
2206 dbesc($ret["notify"]),
2207 dbesc($ret["poll"]),
2212 // find the contact record we just created
2214 $contact_record = self::contact_by_handle($importer["uid"],$author);
2216 if (!$contact_record) {
2217 logger("unable to locate newly created contact record.");
2221 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2223 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2225 if (intval($def_gid))
2226 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2228 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2230 if ($importer["page-flags"] == PAGE_NORMAL) {
2232 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2234 $hash = random_string().(string)time(); // Generate a confirm_key
2236 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2237 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2238 intval($importer["uid"]),
2239 intval($contact_record["id"]),
2242 dbesc(t("Sharing notification from Diaspora network")),
2244 dbesc(datetime_convert())
2248 // automatic friend approval
2250 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2252 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2254 // technically they are sharing with us (CONTACT_IS_SHARING),
2255 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2256 // we are going to change the relationship and make them a follower.
2258 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following)
2259 $new_relation = CONTACT_IS_FRIEND;
2260 elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing)
2261 $new_relation = CONTACT_IS_SHARING;
2263 $new_relation = CONTACT_IS_FOLLOWER;
2265 $r = q("UPDATE `contact` SET `rel` = %d,
2273 intval($new_relation),
2274 dbesc(datetime_convert()),
2275 dbesc(datetime_convert()),
2276 intval($contact_record["id"])
2279 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2281 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2282 $ret = self::send_share($u[0], $contact_record);
2284 // Send the profile data, maybe it weren't transmitted before
2285 self::send_profile($importer["uid"], array($contact_record));
2293 * @brief Fetches a message with a given guid
2295 * @param string $guid message guid
2296 * @param string $orig_author handle of the original post
2297 * @param string $author handle of the sharer
2299 * @return array The fetched item
2301 private static function original_item($guid, $orig_author, $author) {
2303 // Do we already have this item?
2304 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2305 `author-name`, `author-link`, `author-avatar`
2306 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2309 if (dbm::is_result($r)) {
2310 logger("reshared message ".$guid." already exists on system.");
2312 // Maybe it is already a reshared item?
2313 // Then refetch the content, if it is a reshare from a reshare.
2314 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2315 if (self::is_reshare($r[0]["body"], true)) {
2317 } elseif (self::is_reshare($r[0]["body"], false)) {
2318 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2320 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2322 // Add OEmbed and other information to the body
2323 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2331 if (!dbm::is_result($r)) {
2332 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2333 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2334 $item_id = self::store_by_guid($guid, $server);
2337 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2338 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2339 $item_id = self::store_by_guid($guid, $server);
2343 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2344 `author-name`, `author-link`, `author-avatar`
2345 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2348 if (dbm::is_result($r)) {
2349 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2350 if (self::is_reshare($r[0]["body"], false)) {
2351 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2352 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2364 * @brief Processes a reshare message
2366 * @param array $importer Array of the importer user
2367 * @param object $data The message object
2368 * @param string $xml The original XML of the message
2370 * @return int the message id
2372 private static function receive_reshare($importer, $data, $xml) {
2373 $author = notags(unxmlify($data->author));
2374 $guid = notags(unxmlify($data->guid));
2375 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2376 $root_author = notags(unxmlify($data->root_author));
2377 $root_guid = notags(unxmlify($data->root_guid));
2378 /// @todo handle unprocessed property "provider_display_name"
2379 $public = notags(unxmlify($data->public));
2381 $contact = self::allowed_contact_by_handle($importer, $author, false);
2386 $message_id = self::message_exists($importer["uid"], $guid);
2391 $original_item = self::original_item($root_guid, $root_author, $author);
2392 if (!$original_item) {
2396 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2398 $datarray = array();
2400 $datarray["uid"] = $importer["uid"];
2401 $datarray["contact-id"] = $contact["id"];
2402 $datarray["network"] = NETWORK_DIASPORA;
2404 $datarray["author-name"] = $contact["name"];
2405 $datarray["author-link"] = $contact["url"];
2406 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2408 $datarray["owner-name"] = $datarray["author-name"];
2409 $datarray["owner-link"] = $datarray["author-link"];
2410 $datarray["owner-avatar"] = $datarray["author-avatar"];
2412 $datarray["guid"] = $guid;
2413 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2415 $datarray["verb"] = ACTIVITY_POST;
2416 $datarray["gravity"] = GRAVITY_PARENT;
2418 $datarray["protocol"] = PROTOCOL_DIASPORA;
2419 $datarray["source"] = $xml;
2421 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2422 $original_item["guid"], $original_item["created"], $orig_url);
2423 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2425 $datarray["tag"] = $original_item["tag"];
2426 $datarray["app"] = $original_item["app"];
2428 $datarray["plink"] = self::plink($author, $guid);
2429 $datarray["private"] = (($public == "false") ? 1 : 0);
2430 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2432 $datarray["object-type"] = $original_item["object-type"];
2434 self::fetch_guid($datarray);
2435 $message_id = item_store($datarray);
2438 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2446 * @brief Processes retractions
2448 * @param array $importer Array of the importer user
2449 * @param array $contact The contact of the item owner
2450 * @param object $data The message object
2452 * @return bool success
2454 private static function item_retraction($importer, $contact, $data) {
2455 $author = notags(unxmlify($data->author));
2456 $target_guid = notags(unxmlify($data->target_guid));
2457 $target_type = notags(unxmlify($data->target_type));
2459 $person = self::person_by_handle($author);
2460 if (!is_array($person)) {
2461 logger("unable to find author detail for ".$author);
2465 if (!isset($contact["url"])) {
2466 $contact["url"] = $person["url"];
2469 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2470 dbesc($target_guid),
2471 intval($importer["uid"])
2474 logger("Target guid ".$target_guid." was not found for user ".$importer["uid"]);
2478 // Check if the sender is the thread owner
2479 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2480 intval($r[0]["parent"]));
2482 // Only delete it if the parent author really fits
2483 if (!link_compare($p[0]["author-link"], $contact["url"]) && !link_compare($r[0]["author-link"], $contact["url"])) {
2484 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2488 // 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
2489 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
2490 'edited' => datetime_convert(), 'changed' => datetime_convert()),
2491 array('id' => $r[0]["id"]));
2493 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2495 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2497 // Now check if the retraction needs to be relayed by us
2498 if ($p[0]["origin"]) {
2500 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2507 * @brief Receives retraction messages
2509 * @param array $importer Array of the importer user
2510 * @param string $sender The sender of the message
2511 * @param object $data The message object
2513 * @return bool Success
2515 private static function receive_retraction($importer, $sender, $data) {
2516 $target_type = notags(unxmlify($data->target_type));
2518 $contact = self::contact_by_handle($importer["uid"], $sender);
2519 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2520 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2524 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2526 switch ($target_type) {
2531 case "StatusMessage":
2532 return self::item_retraction($importer, $contact, $data);
2536 /// @todo What should we do with an "unshare"?
2537 // Removing the contact isn't correct since we still can read the public items
2538 contact_remove($contact["id"]);
2542 logger("Unknown target type ".$target_type);
2549 * @brief Receives status messages
2551 * @param array $importer Array of the importer user
2552 * @param object $data The message object
2553 * @param string $xml The original XML of the message
2555 * @return int The message id of the newly created item
2557 private static function receive_status_message($importer, $data, $xml) {
2558 $author = notags(unxmlify($data->author));
2559 $guid = notags(unxmlify($data->guid));
2560 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2561 $public = notags(unxmlify($data->public));
2562 $text = unxmlify($data->text);
2563 $provider_display_name = notags(unxmlify($data->provider_display_name));
2565 $contact = self::allowed_contact_by_handle($importer, $author, false);
2570 $message_id = self::message_exists($importer["uid"], $guid);
2576 if ($data->location) {
2577 foreach ($data->location->children() AS $fieldname => $data) {
2578 $address[$fieldname] = notags(unxmlify($data));
2582 $body = diaspora2bb($text);
2584 $datarray = array();
2586 // Attach embedded pictures to the body
2588 foreach ($data->photo AS $photo) {
2589 $body = "[img]".unxmlify($photo->remote_photo_path).
2590 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2593 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2595 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2597 // Add OEmbed and other information to the body
2598 if (!self::is_redmatrix($contact["url"])) {
2599 $body = add_page_info_to_body($body, false, true);
2603 /// @todo enable support for polls
2604 //if ($data->poll) {
2605 // foreach ($data->poll AS $poll)
2610 /// @todo enable support for events
2612 $datarray["uid"] = $importer["uid"];
2613 $datarray["contact-id"] = $contact["id"];
2614 $datarray["network"] = NETWORK_DIASPORA;
2616 $datarray["author-name"] = $contact["name"];
2617 $datarray["author-link"] = $contact["url"];
2618 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2620 $datarray["owner-name"] = $datarray["author-name"];
2621 $datarray["owner-link"] = $datarray["author-link"];
2622 $datarray["owner-avatar"] = $datarray["author-avatar"];
2624 $datarray["guid"] = $guid;
2625 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2627 $datarray["verb"] = ACTIVITY_POST;
2628 $datarray["gravity"] = GRAVITY_PARENT;
2630 $datarray["protocol"] = PROTOCOL_DIASPORA;
2631 $datarray["source"] = $xml;
2633 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2635 if ($provider_display_name != "") {
2636 $datarray["app"] = $provider_display_name;
2639 $datarray["plink"] = self::plink($author, $guid);
2640 $datarray["private"] = (($public == "false") ? 1 : 0);
2641 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2643 if (isset($address["address"])) {
2644 $datarray["location"] = $address["address"];
2647 if (isset($address["lat"]) && isset($address["lng"])) {
2648 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2651 self::fetch_guid($datarray);
2652 $message_id = item_store($datarray);
2655 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2662 /* ************************************************************************************** *
2663 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2664 * ************************************************************************************** */
2667 * @brief returnes the handle of a contact
2669 * @param array $me contact array
2671 * @return string the handle in the format user@domain.tld
2673 private static function my_handle($contact) {
2674 if ($contact["addr"] != "") {
2675 return $contact["addr"];
2678 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2679 // So - just in case - we build the the address here.
2680 if ($contact["nickname"] != "") {
2681 $nick = $contact["nickname"];
2683 $nick = $contact["nick"];
2686 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(),"://") + 3);
2691 * @brief Creates the data for a private message in the new format
2693 * @param string $msg The message that is to be transmitted
2694 * @param array $user The record of the sender
2695 * @param array $contact Target of the communication
2696 * @param string $prvkey The private key of the sender
2697 * @param string $pubkey The public key of the receiver
2699 * @return string The encrypted data
2701 public static function encode_private_data($msg, $user, $contact, $prvkey, $pubkey) {
2703 logger("Message: ".$msg, LOGGER_DATA);
2705 // without a public key nothing will work
2707 logger("pubkey missing: contact id: ".$contact["id"]);
2711 $aes_key = openssl_random_pseudo_bytes(32);
2712 $b_aes_key = base64_encode($aes_key);
2713 $iv = openssl_random_pseudo_bytes(16);
2714 $b_iv = base64_encode($iv);
2716 $ciphertext = self::aes_encrypt($aes_key, $iv, $msg);
2718 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2720 $encrypted_key_bundle = "";
2721 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2723 $json_object = json_encode(array("aes_key" => base64_encode($encrypted_key_bundle),
2724 "encrypted_magic_envelope" => base64_encode($ciphertext)));
2726 return $json_object;
2730 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2732 * @param string $msg The message that is to be transmitted
2733 * @param array $user The record of the sender
2735 * @return string The envelope
2737 public static function build_magic_envelope($msg, $user) {
2739 $b64url_data = base64url_encode($msg);
2740 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2742 $key_id = base64url_encode(self::my_handle($user));
2743 $type = "application/xml";
2744 $encoding = "base64url";
2745 $alg = "RSA-SHA256";
2746 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2748 // Fallback if the private key wasn't transmitted in the expected field
2749 if ($user['uprvkey'] == "")
2750 $user['uprvkey'] = $user['prvkey'];
2752 $signature = rsa_sign($signable_data, $user["uprvkey"]);
2753 $sig = base64url_encode($signature);
2755 $xmldata = array("me:env" => array("me:data" => $data,
2756 "@attributes" => array("type" => $type),
2757 "me:encoding" => $encoding,
2760 "@attributes2" => array("key_id" => $key_id)));
2762 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2764 return xml::from_array($xmldata, $xml, false, $namespaces);
2768 * @brief Create the envelope for a message
2770 * @param string $msg The message that is to be transmitted
2771 * @param array $user The record of the sender
2772 * @param array $contact Target of the communication
2773 * @param string $prvkey The private key of the sender
2774 * @param string $pubkey The public key of the receiver
2775 * @param bool $public Is the message public?
2777 * @return string The message that will be transmitted to other servers
2779 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2781 // The message is put into an envelope with the sender's signature
2782 $envelope = self::build_magic_envelope($msg, $user);
2784 // Private messages are put into a second envelope, encrypted with the receivers public key
2786 $envelope = self::encode_private_data($envelope, $user, $contact, $prvkey, $pubkey);
2793 * @brief Creates a signature for a message
2795 * @param array $owner the array of the owner of the message
2796 * @param array $message The message that is to be signed
2798 * @return string The signature
2800 private static function signature($owner, $message) {
2802 unset($sigmsg["author_signature"]);
2803 unset($sigmsg["parent_author_signature"]);
2805 $signed_text = implode(";", $sigmsg);
2807 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2811 * @brief Transmit a message to a target server
2813 * @param array $owner the array of the item owner
2814 * @param array $contact Target of the communication
2815 * @param string $envelope The message that is to be transmitted
2816 * @param bool $public_batch Is it a public post?
2817 * @param bool $queue_run Is the transmission called from the queue?
2818 * @param string $guid message guid
2820 * @return int Result of the transmission
2822 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run=false, $guid = "") {
2826 $enabled = intval(get_config("system", "diaspora_enabled"));
2830 $logid = random_string(4);
2831 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2833 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2837 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2839 if (!$queue_run && was_recently_delayed($contact["id"])) {
2842 if (!intval(get_config("system", "diaspora_test"))) {
2843 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
2845 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
2846 $return_code = $a->get_curl_code();
2848 logger("test_mode");
2853 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2855 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2856 logger("queue message");
2858 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2859 intval($contact["id"]),
2860 dbesc(NETWORK_DIASPORA),
2862 intval($public_batch)
2865 logger("add_to_queue ignored - identical item already in queue");
2867 // queue message for redelivery
2868 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
2870 // The message could not be delivered. We mark the contact as "dead"
2871 mark_for_death($contact);
2873 } elseif (($return_code >= 200) && ($return_code <= 299)) {
2874 // We successfully delivered a message, the contact is alive
2875 unmark_for_death($contact);
2878 return(($return_code) ? $return_code : (-1));
2883 * @brief Build the post xml
2885 * @param string $type The message type
2886 * @param array $message The message data
2888 * @return string The post XML
2890 public static function build_post_xml($type, $message) {
2892 $data = array($type => $message);
2894 return xml::from_array($data, $xml);
2898 * @brief Builds and transmit messages
2900 * @param array $owner the array of the item owner
2901 * @param array $contact Target of the communication
2902 * @param string $type The message type
2903 * @param array $message The message data
2904 * @param bool $public_batch Is it a public post?
2905 * @param string $guid message guid
2906 * @param bool $spool Should the transmission be spooled or transmitted?
2908 * @return int Result of the transmission
2910 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2912 $msg = self::build_post_xml($type, $message);
2914 logger('message: '.$msg, LOGGER_DATA);
2915 logger('send guid '.$guid, LOGGER_DEBUG);
2917 // Fallback if the private key wasn't transmitted in the expected field
2918 if ($owner['uprvkey'] == "")
2919 $owner['uprvkey'] = $owner['prvkey'];
2921 $envelope = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2924 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
2927 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
2929 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2931 return $return_code;
2935 * @brief Sends a "share" message
2937 * @param array $owner the array of the item owner
2938 * @param array $contact Target of the communication
2940 * @return int The result of the transmission
2942 public static function send_share($owner, $contact) {
2945 * @todo support the different possible combinations of "following" and "sharing"
2946 * Currently, Diaspora only interprets the "sharing" field
2948 * Before switching this code productive, we have to check all "send_share" calls if "rel" is set correctly
2952 switch ($contact["rel"]) {
2953 case CONTACT_IS_FRIEND:
2956 case CONTACT_IS_SHARING:
2959 case CONTACT_IS_FOLLOWER:
2965 $message = array("author" => self::my_handle($owner),
2966 "recipient" => $contact["addr"],
2967 "following" => "true",
2968 "sharing" => "true");
2970 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2972 return self::build_and_transmit($owner, $contact, "contact", $message);
2976 * @brief sends an "unshare"
2978 * @param array $owner the array of the item owner
2979 * @param array $contact Target of the communication
2981 * @return int The result of the transmission
2983 public static function send_unshare($owner, $contact) {
2985 $message = array("author" => self::my_handle($owner),
2986 "recipient" => $contact["addr"],
2987 "following" => "false",
2988 "sharing" => "false");
2990 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2992 return self::build_and_transmit($owner, $contact, "contact", $message);
2996 * @brief Checks a message body if it is a reshare
2998 * @param string $body The message body that is to be check
2999 * @param bool $complete Should it be a complete check or a simple check?
3001 * @return array|bool Reshare details or "false" if no reshare
3003 public static function is_reshare($body, $complete = true) {
3004 $body = trim($body);
3006 // Skip if it isn't a pure repeated messages
3007 // Does it start with a share?
3008 if ((strpos($body, "[share") > 0) && $complete)
3011 // Does it end with a share?
3012 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3015 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3016 // Skip if there is no shared message in there
3017 if ($body == $attributes)
3020 // If we don't do the complete check we quit here
3025 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3026 if ($matches[1] != "")
3027 $guid = $matches[1];
3029 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3030 if ($matches[1] != "")
3031 $guid = $matches[1];
3034 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3035 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3038 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3039 $ret["root_guid"] = $guid;
3045 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3046 if ($matches[1] != "")
3047 $profile = $matches[1];
3049 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3050 if ($matches[1] != "")
3051 $profile = $matches[1];
3055 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3056 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == ""))
3060 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3061 if ($matches[1] != "")
3062 $link = $matches[1];
3064 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3065 if ($matches[1] != "")
3066 $link = $matches[1];
3068 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3069 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == ""))
3076 * @brief Create an event array
3078 * @param integer $event_id The id of the event
3080 * @return array with event data
3082 private static function build_event($event_id) {
3084 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3085 if (!dbm::is_result($r)) {
3091 $eventdata = array();
3093 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3094 if (!dbm::is_result($r)) {
3100 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3101 if (!dbm::is_result($r)) {
3107 $eventdata['author'] = self::my_handle($owner);
3109 if ($event['guid']) {
3110 $eventdata['guid'] = $event['guid'];
3113 $mask = 'Y-m-d\TH:i:s\Z';
3115 /// @todo - establish "all day" events in Friendica
3116 $eventdata["all_day"] = "false";
3118 if (!$event['adjust']) {
3119 $eventdata['timezone'] = $user['timezone'];
3121 if ($eventdata['timezone'] == "") {
3122 $eventdata['timezone'] = 'UTC';
3126 if ($event['start']) {
3127 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3129 if ($event['finish'] && !$event['nofinish']) {
3130 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3132 if ($event['summary']) {
3133 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3135 if ($event['desc']) {
3136 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3138 if ($event['location']) {
3139 $location = array();
3140 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3141 $location["lat"] = 0;
3142 $location["lng"] = 0;
3143 $eventdata['location'] = $location;
3150 * @brief Create a post (status message or reshare)
3152 * @param array $item The item that will be exported
3153 * @param array $owner the array of the item owner
3156 * 'type' -> Message type ("status_message" or "reshare")
3157 * 'message' -> Array of XML elements of the status
3159 public static function build_status($item, $owner) {
3161 $cachekey = "diaspora:build_status:".$item['guid'];
3163 $result = Cache::get($cachekey);
3164 if (!is_null($result)) {
3168 $myaddr = self::my_handle($owner);
3170 $public = (($item["private"]) ? "false" : "true");
3172 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3174 // Detect a share element and do a reshare
3175 if (!$item['private'] && ($ret = self::is_reshare($item["body"]))) {
3176 $message = array("author" => $myaddr,
3177 "guid" => $item["guid"],
3178 "created_at" => $created,
3179 "root_author" => $ret["root_handle"],
3180 "root_guid" => $ret["root_guid"],
3181 "provider_display_name" => $item["app"],
3182 "public" => $public);
3186 $title = $item["title"];
3187 $body = $item["body"];
3189 // convert to markdown
3190 $body = html_entity_decode(bb2diaspora($body));
3194 $body = "## ".html_entity_decode($title)."\n\n".$body;
3196 if ($item["attach"]) {
3197 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3199 $body .= "\n".t("Attachments:")."\n";
3200 foreach ($matches as $mtch)
3201 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3205 $location = array();
3207 if ($item["location"] != "")
3208 $location["address"] = $item["location"];
3210 if ($item["coord"] != "") {
3211 $coord = explode(" ", $item["coord"]);
3212 $location["lat"] = $coord[0];
3213 $location["lng"] = $coord[1];
3216 $message = array("author" => $myaddr,
3217 "guid" => $item["guid"],
3218 "created_at" => $created,
3219 "public" => $public,
3221 "provider_display_name" => $item["app"],
3222 "location" => $location);
3224 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3225 if (!isset($location["lat"]) || !isset($location["lng"])) {
3226 unset($message["location"]);
3229 if ($item['event-id'] > 0) {
3230 $event = self::build_event($item['event-id']);
3231 if (count($event)) {
3232 $message['event'] = $event;
3234 /// @todo Once Diaspora supports it, we will remove the body
3235 // $message['text'] = '';
3239 $type = "status_message";
3242 $msg = array("type" => $type, "message" => $message);
3244 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3250 * @brief Sends a post
3252 * @param array $item The item that will be exported
3253 * @param array $owner the array of the item owner
3254 * @param array $contact Target of the communication
3255 * @param bool $public_batch Is it a public post?
3257 * @return int The result of the transmission
3259 public static function send_status($item, $owner, $contact, $public_batch = false) {
3261 $status = self::build_status($item, $owner);
3263 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3267 * @brief Creates a "like" object
3269 * @param array $item The item that will be exported
3270 * @param array $owner the array of the item owner
3272 * @return array The data for a "like"
3274 private static function construct_like($item, $owner) {
3276 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3277 dbesc($item["thr-parent"]));
3278 if (!dbm::is_result($p))
3283 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3284 if ($item['verb'] === ACTIVITY_LIKE) {
3286 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3287 $positive = "false";
3290 return(array("author" => self::my_handle($owner),
3291 "guid" => $item["guid"],
3292 "parent_guid" => $parent["guid"],
3293 "parent_type" => $target_type,
3294 "positive" => $positive,
3295 "author_signature" => ""));
3299 * @brief Creates an "EventParticipation" object
3301 * @param array $item The item that will be exported
3302 * @param array $owner the array of the item owner
3304 * @return array The data for an "EventParticipation"
3306 private static function construct_attend($item, $owner) {
3308 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3309 dbesc($item["thr-parent"]));
3310 if (!dbm::is_result($p))
3315 switch ($item['verb']) {
3316 case ACTIVITY_ATTEND:
3317 $attend_answer = 'accepted';
3319 case ACTIVITY_ATTENDNO:
3320 $attend_answer = 'declined';
3322 case ACTIVITY_ATTENDMAYBE:
3323 $attend_answer = 'tentative';
3326 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3330 return(array("author" => self::my_handle($owner),
3331 "guid" => $item["guid"],
3332 "parent_guid" => $parent["guid"],
3333 "status" => $attend_answer,
3334 "author_signature" => ""));
3338 * @brief Creates the object for a comment
3340 * @param array $item The item that will be exported
3341 * @param array $owner the array of the item owner
3343 * @return array The data for a comment
3345 private static function construct_comment($item, $owner) {
3347 $cachekey = "diaspora:construct_comment:".$item['guid'];
3349 $result = Cache::get($cachekey);
3350 if (!is_null($result)) {
3354 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3355 intval($item["parent"]),
3356 intval($item["parent"])
3359 if (!dbm::is_result($p))
3364 $text = html_entity_decode(bb2diaspora($item["body"]));
3365 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3367 $comment = array("author" => self::my_handle($owner),
3368 "guid" => $item["guid"],
3369 "created_at" => $created,
3370 "parent_guid" => $parent["guid"],
3372 "author_signature" => "");
3374 // Send the thread parent guid only if it is a threaded comment
3375 if ($item['thr-parent'] != $item['parent-uri']) {
3376 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3379 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3385 * @brief Send a like or a comment
3387 * @param array $item The item that will be exported
3388 * @param array $owner the array of the item owner
3389 * @param array $contact Target of the communication
3390 * @param bool $public_batch Is it a public post?
3392 * @return int The result of the transmission
3394 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3396 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3397 $message = self::construct_attend($item, $owner);
3398 $type = "event_participation";
3399 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3400 $message = self::construct_like($item, $owner);
3403 $message = self::construct_comment($item, $owner);
3410 $message["author_signature"] = self::signature($owner, $message);
3412 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3416 * @brief Creates a message from a signature record entry
3418 * @param array $item The item that will be exported
3419 * @param array $signature The entry of the "sign" record
3421 * @return string The message
3423 private static function message_from_signature($item, $signature) {
3425 // Split the signed text
3426 $signed_parts = explode(";", $signature['signed_text']);
3428 if ($item["deleted"])
3429 $message = array("author" => $signature['signer'],
3430 "target_guid" => $signed_parts[0],
3431 "target_type" => $signed_parts[1]);
3432 elseif ($item['verb'] === ACTIVITY_LIKE)
3433 $message = array("author" => $signed_parts[4],
3434 "guid" => $signed_parts[1],
3435 "parent_guid" => $signed_parts[3],
3436 "parent_type" => $signed_parts[2],
3437 "positive" => $signed_parts[0],
3438 "author_signature" => $signature['signature'],
3439 "parent_author_signature" => "");
3441 // Remove the comment guid
3442 $guid = array_shift($signed_parts);
3444 // Remove the parent guid
3445 $parent_guid = array_shift($signed_parts);
3447 // Remove the handle
3448 $handle = array_pop($signed_parts);
3450 // Glue the parts together
3451 $text = implode(";", $signed_parts);
3453 $message = array("author" => $handle,
3455 "parent_guid" => $parent_guid,
3456 "text" => implode(";", $signed_parts),
3457 "author_signature" => $signature['signature'],
3458 "parent_author_signature" => "");
3464 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3466 * @param array $item The item that will be exported
3467 * @param array $owner the array of the item owner
3468 * @param array $contact Target of the communication
3469 * @param bool $public_batch Is it a public post?
3471 * @return int The result of the transmission
3473 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3475 if ($item["deleted"])
3476 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3477 elseif ($item['verb'] === ACTIVITY_LIKE)
3482 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3484 // fetch the original signature
3486 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3487 intval($item["id"]));
3490 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3496 // Old way - is used by the internal Friendica functions
3497 /// @todo Change all signatur storing functions to the new format
3498 if ($signature['signed_text'] && $signature['signature'] && $signature['signer'])
3499 $message = self::message_from_signature($item, $signature);
3501 $msg = json_decode($signature['signed_text'], true);
3504 if (is_array($msg)) {
3505 foreach ($msg AS $field => $data) {
3506 if (!$item["deleted"]) {
3507 if ($field == "diaspora_handle") {
3510 if ($field == "target_type") {
3511 $field = "parent_type";
3515 $message[$field] = $data;
3518 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3521 $message["parent_author_signature"] = self::signature($owner, $message);
3523 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3525 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3529 * @brief Sends a retraction (deletion) of a message, like or comment
3531 * @param array $item The item that will be exported
3532 * @param array $owner the array of the item owner
3533 * @param array $contact Target of the communication
3534 * @param bool $public_batch Is it a public post?
3535 * @param bool $relay Is the retraction transmitted from a relay?
3537 * @return int The result of the transmission
3539 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3541 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3543 $msg_type = "retraction";
3545 if ($item['id'] == $item['parent']) {
3546 $target_type = "Post";
3547 } elseif ($item["verb"] == ACTIVITY_LIKE) {
3548 $target_type = "Like";
3550 $target_type = "Comment";
3553 $message = array("author" => $itemaddr,
3554 "target_guid" => $item['guid'],
3555 "target_type" => $target_type);
3557 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3559 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3563 * @brief Sends a mail
3565 * @param array $item The item that will be exported
3566 * @param array $owner The owner
3567 * @param array $contact Target of the communication
3569 * @return int The result of the transmission
3571 public static function send_mail($item, $owner, $contact) {
3573 $myaddr = self::my_handle($owner);
3575 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3576 intval($item["convid"]),
3577 intval($item["uid"])
3580 if (!dbm::is_result($r)) {
3581 logger("conversation not found.");
3587 "author" => $cnv["creator"],
3588 "guid" => $cnv["guid"],
3589 "subject" => $cnv["subject"],
3590 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3591 "participants" => $cnv["recips"]
3594 $body = bb2diaspora($item["body"]);
3595 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3598 "author" => $myaddr,
3599 "guid" => $item["guid"],
3600 "conversation_guid" => $cnv["guid"],
3602 "created_at" => $created,
3605 if ($item["reply"]) {
3610 "author" => $cnv["creator"],
3611 "guid" => $cnv["guid"],
3612 "subject" => $cnv["subject"],
3613 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3614 "participants" => $cnv["recips"],
3617 $type = "conversation";
3620 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3624 * @brief Sends profile data
3626 * @param int $uid The user id
3628 public static function send_profile($uid, $recips = false) {
3634 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3635 AND `uid` = %d AND `rel` != %d",
3636 dbesc(NETWORK_DIASPORA),
3638 intval(CONTACT_IS_SHARING)
3643 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3645 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3646 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3647 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3656 $handle = $profile["addr"];
3657 $first = ((strpos($profile['name'],' ')
3658 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3659 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3660 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3661 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3662 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3663 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3665 if ($searchable === 'true') {
3666 $dob = '1000-00-00';
3668 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3669 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3671 $about = $profile['about'];
3672 $about = strip_tags(bbcode($about));
3674 $location = formatted_location($profile);
3676 if ($profile['pub_keywords']) {
3677 $kw = str_replace(',',' ',$profile['pub_keywords']);
3678 $kw = str_replace(' ',' ',$kw);
3679 $arr = explode(' ',$profile['pub_keywords']);
3681 for ($x = 0; $x < 5; $x ++) {
3683 $tags .= '#'. trim($arr[$x]) .' ';
3687 $tags = trim($tags);
3690 $message = array("author" => $handle,
3691 "first_name" => $first,
3692 "last_name" => $last,
3693 "image_url" => $large,
3694 "image_url_medium" => $medium,
3695 "image_url_small" => $small,
3697 "gender" => $profile['gender'],
3699 "location" => $location,
3700 "searchable" => $searchable,
3702 "tag_string" => $tags);
3704 foreach ($recips as $recip) {
3705 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3706 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3711 * @brief Stores the signature for likes that are created on our system
3713 * @param array $contact The contact array of the "like"
3714 * @param int $post_id The post id of the "like"
3716 * @return bool Success
3718 public static function store_like_signature($contact, $post_id) {
3720 // Is the contact the owner? Then fetch the private key
3721 if (!$contact['self'] || ($contact['uid'] == 0)) {
3722 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3726 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3727 if (!dbm::is_result($r)) {
3731 $contact["uprvkey"] = $r[0]['prvkey'];
3733 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3734 if (!dbm::is_result($r)) {
3738 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3742 $message = self::construct_like($r[0], $contact);
3743 $message["author_signature"] = self::signature($contact, $message);
3746 * Now store the signature more flexible to dynamically support new fields.
3747 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3749 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
3751 logger('Stored diaspora like signature');
3756 * @brief Stores the signature for comments that are created on our system
3758 * @param array $item The item array of the comment
3759 * @param array $contact The contact array of the item owner
3760 * @param string $uprvkey The private key of the sender
3761 * @param int $message_id The message id of the comment
3763 * @return bool Success
3765 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3767 if ($uprvkey == "") {
3768 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3772 $contact["uprvkey"] = $uprvkey;
3774 $message = self::construct_comment($item, $contact);
3775 $message["author_signature"] = self::signature($contact, $message);
3778 * Now store the signature more flexible to dynamically support new fields.
3779 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3781 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
3783 logger('Stored diaspora comment signature');