2 namespace Friendica\Protocol;
5 * @file include/diaspora.php
6 * @brief The implementation of the diaspora protocol
8 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
9 * This implementation here interprets the old and the new protocol and sends the new one.
10 * In the future we will remove most stuff from "valid_posting" and interpret only the new protocol.
14 use Friendica\Core\System;
15 use Friendica\Core\Config;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Worker;
18 use Friendica\Database\Dbm;
19 use Friendica\Network\Probe;
23 require_once 'include/items.php';
24 require_once 'include/bb2diaspora.php';
25 require_once 'include/Contact.php';
26 require_once 'include/Photo.php';
27 require_once 'include/socgraph.php';
28 require_once 'include/group.php';
29 require_once 'include/xml.php';
30 require_once 'include/datetime.php';
31 require_once 'include/queue_fn.php';
32 require_once 'include/cache.php';
35 * @brief This class contain functions to create and send Diaspora XML files
41 * @brief Return a list of relay servers
43 * This is an experimental Diaspora feature.
45 * @return array of relay servers
47 public static function relay_list() {
49 $serverdata = Config::get("system", "relay_server");
50 if ($serverdata == "")
55 $servers = explode(",", $serverdata);
57 foreach ($servers AS $server) {
58 $server = trim($server);
59 $addr = "relay@".str_replace("http://", "", normalise_link($server));
60 $batch = $server."/receive/public";
62 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
63 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
66 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
67 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
72 dbesc(normalise_link($server)),
74 dbesc(NETWORK_DIASPORA),
75 intval(CONTACT_IS_FOLLOWER),
76 dbesc(datetime_convert()),
77 dbesc(datetime_convert()),
78 dbesc(datetime_convert())
81 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
83 $relay[] = $relais[0];
85 $relay[] = $relais[0];
92 * @brief repairs a signature that was double encoded
94 * The function is unused at the moment. It was copied from the old implementation.
96 * @param string $signature The signature
97 * @param string $handle The handle of the signature owner
98 * @param integer $level This value is only set inside this function to avoid endless loops
100 * @return string the repaired signature
102 private static function repair_signature($signature, $handle = "", $level = 1) {
104 if ($signature == "")
107 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
108 $signature = base64_decode($signature);
109 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
111 // Do a recursive call to be able to fix even multiple levels
113 $signature = self::repair_signature($signature, $handle, ++$level);
120 * @brief verify the envelope and return the verified data
122 * @param string $envelope The magic envelope
124 * @return string verified data
126 private static function verify_magic_envelope($envelope) {
128 $basedom = parse_xml_string($envelope);
130 if (!is_object($basedom)) {
131 logger("Envelope is no XML file");
135 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
137 if (sizeof($children) == 0) {
138 logger("XML has no children");
144 $data = base64url_decode($children->data);
145 $type = $children->data->attributes()->type[0];
147 $encoding = $children->encoding;
149 $alg = $children->alg;
151 $sig = base64url_decode($children->sig);
152 $key_id = $children->sig->attributes()->key_id[0];
154 $handle = base64url_decode($key_id);
156 $b64url_data = base64url_encode($data);
157 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
159 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
161 $key = self::key($handle);
163 $verify = rsa_verify($signable_data, $sig, $key);
165 logger('Message did not verify. Discarding.');
173 * @brief encrypts data via AES
175 * @param string $key The AES key
176 * @param string $iv The IV (is used for CBC encoding)
177 * @param string $data The data that is to be encrypted
179 * @return string encrypted data
181 private static function aes_encrypt($key, $iv, $data) {
182 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
186 * @brief decrypts data via AES
188 * @param string $key The AES key
189 * @param string $iv The IV (is used for CBC encoding)
190 * @param string $encrypted The encrypted data
192 * @return string decrypted data
194 private static function aes_decrypt($key, $iv, $encrypted) {
195 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
199 * @brief: Decodes incoming Diaspora message in the new format
201 * @param array $importer Array of the importer user
202 * @param string $raw raw post message
205 * 'message' -> decoded Diaspora XML message
206 * 'author' -> author diaspora handle
207 * 'key' -> author public key (converted to pkcs#8)
209 public static function decode_raw($importer, $raw) {
210 $data = json_decode($raw);
212 // Is it a private post? Then decrypt the outer Salmon
213 if (is_object($data)) {
214 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
215 $ciphertext = base64_decode($data->encrypted_magic_envelope);
217 $outer_key_bundle = '';
218 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
219 $j_outer_key_bundle = json_decode($outer_key_bundle);
221 if (!is_object($j_outer_key_bundle)) {
222 logger('Outer Salmon did not verify. Discarding.');
223 http_status_exit(400);
226 $outer_iv = base64_decode($j_outer_key_bundle->iv);
227 $outer_key = base64_decode($j_outer_key_bundle->key);
229 $xml = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
234 $basedom = parse_xml_string($xml);
236 if (!is_object($basedom)) {
237 logger('Received data does not seem to be an XML. Discarding. '.$xml);
238 http_status_exit(400);
241 $base = $basedom->children(NAMESPACE_SALMON_ME);
243 // Not sure if this cleaning is needed
244 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
246 // Build the signed data
247 $type = $base->data[0]->attributes()->type[0];
248 $encoding = $base->encoding;
250 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
252 // This is the signature
253 $signature = base64url_decode($base->sig);
255 // Get the senders' public key
256 $key_id = $base->sig[0]->attributes()->key_id[0];
257 $author_addr = base64_decode($key_id);
258 $key = self::key($author_addr);
260 $verify = rsa_verify($signed_data, $signature, $key);
262 logger('Message did not verify. Discarding.');
263 http_status_exit(400);
266 return array('message' => (string)base64url_decode($base->data),
267 'author' => unxmlify($author_addr),
268 'key' => (string)$key);
272 * @brief: Decodes incoming Diaspora message in the deprecated format
274 * @param array $importer Array of the importer user
275 * @param string $xml urldecoded Diaspora salmon
278 * 'message' -> decoded Diaspora XML message
279 * 'author' -> author diaspora handle
280 * 'key' -> author public key (converted to pkcs#8)
282 public static function decode($importer, $xml) {
285 $basedom = parse_xml_string($xml);
287 if (!is_object($basedom)) {
288 logger("XML is not parseable.");
291 $children = $basedom->children('https://joindiaspora.com/protocol');
293 if ($children->header) {
295 $author_link = str_replace('acct:','',$children->header->author_id);
297 // This happens with posts from a relais
299 logger("This is no private post in the old format", LOGGER_DEBUG);
303 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
305 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
306 $ciphertext = base64_decode($encrypted_header->ciphertext);
308 $outer_key_bundle = '';
309 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
311 $j_outer_key_bundle = json_decode($outer_key_bundle);
313 $outer_iv = base64_decode($j_outer_key_bundle->iv);
314 $outer_key = base64_decode($j_outer_key_bundle->key);
316 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
318 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
319 $idom = parse_xml_string($decrypted);
321 $inner_iv = base64_decode($idom->iv);
322 $inner_aes_key = base64_decode($idom->aes_key);
324 $author_link = str_replace('acct:','',$idom->author_id);
327 $dom = $basedom->children(NAMESPACE_SALMON_ME);
329 // figure out where in the DOM tree our data is hiding
331 if ($dom->provenance->data)
332 $base = $dom->provenance;
333 elseif ($dom->env->data)
339 logger('unable to locate salmon data in xml');
340 http_status_exit(400);
344 // Stash the signature away for now. We have to find their key or it won't be good for anything.
345 $signature = base64url_decode($base->sig);
349 // strip whitespace so our data element will return to one big base64 blob
350 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
353 // stash away some other stuff for later
355 $type = $base->data[0]->attributes()->type[0];
356 $keyhash = $base->sig[0]->attributes()->keyhash[0];
357 $encoding = $base->encoding;
361 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
365 $data = base64url_decode($data);
369 $inner_decrypted = $data;
372 // Decode the encrypted blob
374 $inner_encrypted = base64_decode($data);
375 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
379 logger('Could not retrieve author URI.');
380 http_status_exit(400);
382 // Once we have the author URI, go to the web and try to find their public key
383 // (first this will look it up locally if it is in the fcontact cache)
384 // This will also convert diaspora public key from pkcs#1 to pkcs#8
386 logger('Fetching key for '.$author_link);
387 $key = self::key($author_link);
390 logger('Could not retrieve author key.');
391 http_status_exit(400);
394 $verify = rsa_verify($signed_data,$signature,$key);
397 logger('Message did not verify. Discarding.');
398 http_status_exit(400);
401 logger('Message verified.');
403 return array('message' => (string)$inner_decrypted,
404 'author' => unxmlify($author_link),
405 'key' => (string)$key);
410 * @brief Dispatches public messages and find the fitting receivers
412 * @param array $msg The post that will be dispatched
414 * @return int The message id of the generated message, "true" or "false" if there was an error
416 public static function dispatch_public($msg) {
418 $enabled = intval(Config::get("system", "diaspora_enabled"));
420 logger("diaspora is disabled");
424 if (!($postdata = self::valid_posting($msg))) {
425 logger("Invalid posting");
429 $fields = $postdata['fields'];
431 // Is it a an action (comment, like, ...) for our own post?
432 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
433 $guid = notags(unxmlify($fields->parent_guid));
434 $importer = self::importer_for_guid($guid);
435 if (is_array($importer)) {
436 logger("delivering to origin: ".$importer["name"]);
437 $message_id = self::dispatch($importer, $msg, $fields);
442 // Process item retractions. This has to be done separated from the other stuff,
443 // since retractions for comments could come even from non followers.
444 if (!empty($fields) && in_array($fields->getName(), array('retraction'))) {
445 $target = notags(unxmlify($fields->target_type));
446 if (in_array($target, array("Comment", "Like", "Post", "Reshare", "StatusMessage"))) {
447 logger('processing retraction for '.$target, LOGGER_DEBUG);
448 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
449 $message_id = self::dispatch($importer, $msg, $fields);
454 // Now distribute it to the followers
455 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
456 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
457 AND NOT `account_expired` AND NOT `account_removed`",
458 dbesc(NETWORK_DIASPORA),
459 dbesc($msg["author"])
462 if (Dbm::is_result($r)) {
463 foreach ($r as $rr) {
464 logger("delivering to: ".$rr["username"]);
465 self::dispatch($rr, $msg, $fields);
467 } elseif (!Config::get('system', 'relay_subscribe', false)) {
468 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
470 // Use a dummy importer to import the data for the public copy
471 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
472 $message_id = self::dispatch($importer, $msg, $fields);
479 * @brief Dispatches the different message types to the different functions
481 * @param array $importer Array of the importer user
482 * @param array $msg The post that will be dispatched
483 * @param object $fields SimpleXML object that contains the message
485 * @return int The message id of the generated message, "true" or "false" if there was an error
487 public static function dispatch($importer, $msg, $fields = null) {
489 // The sender is the handle of the contact that sent the message.
490 // This will often be different with relayed messages (for example "like" and "comment")
491 $sender = $msg["author"];
493 // This is only needed for private postings since this is already done for public ones before
494 if (is_null($fields)) {
495 if (!($postdata = self::valid_posting($msg))) {
496 logger("Invalid posting");
499 $fields = $postdata['fields'];
502 $type = $fields->getName();
504 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
507 case "account_migration":
508 return self::receiveAccountMigration($importer, $fields);
510 case "account_deletion":
511 return self::receive_account_deletion($importer, $fields);
514 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
517 return self::receive_contact_request($importer, $fields);
520 return self::receive_conversation($importer, $msg, $fields);
523 return self::receive_like($importer, $sender, $fields);
526 return self::receive_message($importer, $fields);
528 case "participation": // Not implemented
529 return self::receive_participation($importer, $fields);
531 case "photo": // Not implemented
532 return self::receive_photo($importer, $fields);
534 case "poll_participation": // Not implemented
535 return self::receive_poll_participation($importer, $fields);
538 return self::receive_profile($importer, $fields);
541 return self::receive_reshare($importer, $fields, $msg["message"]);
544 return self::receive_retraction($importer, $sender, $fields);
546 case "status_message":
547 return self::receive_status_message($importer, $fields, $msg["message"]);
550 logger("Unknown message type ".$type);
558 * @brief Checks if a posting is valid and fetches the data fields.
560 * This function does not only check the signature.
561 * It also does the conversion between the old and the new diaspora format.
563 * @param array $msg Array with the XML, the sender handle and the sender signature
565 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
567 private static function valid_posting($msg) {
569 $data = parse_xml_string($msg["message"]);
571 if (!is_object($data)) {
572 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
576 $first_child = $data->getName();
578 // Is this the new or the old version?
579 if ($data->getName() == "XML") {
581 foreach ($data->post->children() as $child)
588 $type = $element->getName();
591 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
593 // All retractions are handled identically from now on.
594 // In the new version there will only be "retraction".
595 if (in_array($type, array("signed_retraction", "relayable_retraction")))
596 $type = "retraction";
598 if ($type == "request")
601 $fields = new SimpleXMLElement("<".$type."/>");
605 foreach ($element->children() AS $fieldname => $entry) {
607 // Translation for the old XML structure
608 if ($fieldname == "diaspora_handle") {
609 $fieldname = "author";
611 if ($fieldname == "participant_handles") {
612 $fieldname = "participants";
614 if (in_array($type, array("like", "participation"))) {
615 if ($fieldname == "target_type") {
616 $fieldname = "parent_type";
619 if ($fieldname == "sender_handle") {
620 $fieldname = "author";
622 if ($fieldname == "recipient_handle") {
623 $fieldname = "recipient";
625 if ($fieldname == "root_diaspora_id") {
626 $fieldname = "root_author";
628 if ($type == "status_message") {
629 if ($fieldname == "raw_message") {
633 if ($type == "retraction") {
634 if ($fieldname == "post_guid") {
635 $fieldname = "target_guid";
637 if ($fieldname == "type") {
638 $fieldname = "target_type";
643 if (($fieldname == "author_signature") && ($entry != ""))
644 $author_signature = base64_decode($entry);
645 elseif (($fieldname == "parent_author_signature") && ($entry != ""))
646 $parent_author_signature = base64_decode($entry);
647 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
648 if ($signed_data != "") {
650 $signed_data_parent .= ";";
653 $signed_data .= $entry;
655 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) ||
656 ($orig_type == "relayable_retraction"))
657 xml::copy($entry, $fields, $fieldname);
660 // This is something that shouldn't happen at all.
661 if (in_array($type, array("status_message", "reshare", "profile")))
662 if ($msg["author"] != $fields->author) {
663 logger("Message handle is not the same as envelope sender. Quitting this message.");
667 // Only some message types have signatures. So we quit here for the other types.
668 if (!in_array($type, array("comment", "like"))) {
669 return array("fields" => $fields, "relayed" => false);
671 // No author_signature? This is a must, so we quit.
672 if (!isset($author_signature)) {
673 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
677 if (isset($parent_author_signature)) {
680 $key = self::key($msg["author"]);
682 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
683 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);
690 $key = self::key($fields->author);
692 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
693 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
696 return array("fields" => $fields, "relayed" => $relayed);
701 * @brief Fetches the public key for a given handle
703 * @param string $handle The handle
705 * @return string The public key
707 private static function key($handle) {
708 $handle = strval($handle);
710 logger("Fetching diaspora key for: ".$handle);
712 $r = self::person_by_handle($handle);
720 * @brief Fetches data for a given handle
722 * @param string $handle The handle
724 * @return array the queried data
726 public static function person_by_handle($handle) {
728 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
729 dbesc(NETWORK_DIASPORA),
734 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
736 // update record occasionally so it doesn't get stale
737 $d = strtotime($person["updated"]." +00:00");
738 if ($d < strtotime("now - 14 days"))
741 if ($person["guid"] == "")
745 if (!$person || $update) {
746 logger("create or refresh", LOGGER_DEBUG);
747 $r = Probe::uri($handle, NETWORK_DIASPORA);
749 // Note that Friendica contacts will return a "Diaspora person"
750 // if Diaspora connectivity is enabled on their server
751 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
752 self::add_fcontact($r, $update);
760 * @brief Updates the fcontact table
762 * @param array $arr The fcontact data
763 * @param bool $update Update or insert?
765 * @return string The id of the fcontact entry
767 private static function add_fcontact($arr, $update = false) {
770 $r = q("UPDATE `fcontact` SET
784 WHERE `url` = '%s' AND `network` = '%s'",
786 dbesc($arr["photo"]),
787 dbesc($arr["request"]),
789 dbesc(strtolower($arr["addr"])),
791 dbesc($arr["batch"]),
792 dbesc($arr["notify"]),
794 dbesc($arr["confirm"]),
795 dbesc($arr["alias"]),
796 dbesc($arr["pubkey"]),
797 dbesc(datetime_convert()),
799 dbesc($arr["network"])
802 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
803 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
804 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
807 dbesc($arr["photo"]),
808 dbesc($arr["request"]),
812 dbesc($arr["batch"]),
813 dbesc($arr["notify"]),
815 dbesc($arr["confirm"]),
816 dbesc($arr["network"]),
817 dbesc($arr["alias"]),
818 dbesc($arr["pubkey"]),
819 dbesc(datetime_convert())
827 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
829 * @param int $contact_id The id in the contact table
830 * @param int $gcontact_id The id in the gcontact table
832 * @return string the handle
834 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
837 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
839 if ($gcontact_id != 0) {
840 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
841 intval($gcontact_id));
843 if (Dbm::is_result($r)) {
844 return strtolower($r[0]["addr"]);
848 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
849 intval($contact_id));
851 if (Dbm::is_result($r)) {
854 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
856 if ($contact['addr'] != "") {
857 $handle = $contact['addr'];
859 $baseurl_start = strpos($contact['url'],'://') + 3;
860 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
861 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
862 $handle = $contact['nick'].'@'.$baseurl;
866 return strtolower($handle);
870 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
873 * @param mixed $fcontact_guid Hexadecimal string guid
875 * @return string the contact url or null
877 public static function url_from_contact_guid($fcontact_guid) {
878 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
880 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
881 dbesc(NETWORK_DIASPORA),
882 dbesc($fcontact_guid)
885 if (Dbm::is_result($r)) {
893 * @brief Get a contact id for a given handle
895 * @param int $uid The user id
896 * @param string $handle The handle in the format user@domain.tld
898 * @return The contact id
900 private static function contact_by_handle($uid, $handle) {
902 // First do a direct search on the contact table
903 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
908 if (Dbm::is_result($r)) {
912 * We haven't found it?
913 * We use another function for it that will possibly create a contact entry.
915 $cid = get_contact($handle, $uid);
918 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
919 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
921 if (Dbm::is_result($r)) {
927 $handle_parts = explode("@", $handle);
928 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
929 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
934 if (Dbm::is_result($r)) {
938 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
943 * @brief Check if posting is allowed for this contact
945 * @param array $importer Array of the importer user
946 * @param array $contact The contact that is checked
947 * @param bool $is_comment Is the check for a comment?
949 * @return bool is the contact allowed to post?
951 private static function post_allow($importer, $contact, $is_comment = false) {
954 * Perhaps we were already sharing with this person. Now they're sharing with us.
955 * That makes us friends.
956 * Normally this should have handled by getting a request - but this could get lost
958 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
959 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
960 array('id' => $contact["id"], 'uid' => $contact["uid"]));
962 $contact["rel"] = CONTACT_IS_FRIEND;
963 logger("defining user ".$contact["nick"]." as friend");
966 // We don't seem to like that person
967 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
968 // Maybe blocked, don't accept.
970 // We are following this person?
971 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
972 // Yes, then it is fine.
974 // Is it a post to a community?
975 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
978 // Is the message a global user or a comment?
979 } elseif (($importer["uid"] == 0) || $is_comment) {
980 // Messages for the global users and comments are always accepted
988 * @brief Fetches the contact id for a handle and checks if posting is allowed
990 * @param array $importer Array of the importer user
991 * @param string $handle The checked handle in the format user@domain.tld
992 * @param bool $is_comment Is the check for a comment?
994 * @return array The contact data
996 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
997 $contact = self::contact_by_handle($importer["uid"], $handle);
999 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1000 // If a contact isn't found, we accept it anyway if it is a comment
1008 if (!self::post_allow($importer, $contact, $is_comment)) {
1009 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1016 * @brief Does the message already exists on the system?
1018 * @param int $uid The user id
1019 * @param string $guid The guid of the message
1021 * @return int|bool message id if the message already was stored into the system - or false.
1023 private static function message_exists($uid, $guid) {
1024 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1029 if (Dbm::is_result($r)) {
1030 logger("message ".$guid." already exists for user ".$uid);
1038 * @brief Checks for links to posts in a message
1040 * @param array $item The item array
1042 private static function fetch_guid($item) {
1043 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1044 preg_replace_callback($expression,
1045 function ($match) use ($item) {
1046 return self::fetch_guid_sub($match, $item);
1049 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1050 function ($match) use ($item) {
1051 return self::fetch_guid_sub($match, $item);
1056 * @brief Checks for relative /people/* links in an item body to match local
1057 * contacts or prepends the remote host taken from the author link.
1059 * @param string $body The item body to replace links from
1060 * @param string $author_link The author link for missing local contact fallback
1062 * @return the replaced string
1064 public static function replace_people_guid($body, $author_link) {
1065 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1066 function ($match) use ($author_link) {
1068 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1069 // 1 => '0123456789abcdef'
1071 $handle = self::url_from_contact_guid($match[1]);
1074 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1076 // No local match, restoring absolute remote URL from author scheme and host
1077 $author_url = parse_url($author_link);
1078 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1088 * @brief sub function of "fetch_guid" which checks for links in messages
1090 * @param array $match array containing a link that has to be checked for a message link
1091 * @param array $item The item array
1093 private static function fetch_guid_sub($match, $item) {
1094 if (!self::store_by_guid($match[1], $item["author-link"]))
1095 self::store_by_guid($match[1], $item["owner-link"]);
1099 * @brief Fetches an item with a given guid from a given server
1101 * @param string $guid the message guid
1102 * @param string $server The server address
1103 * @param int $uid The user id of the user
1105 * @return int the message id of the stored message or false
1107 private static function store_by_guid($guid, $server, $uid = 0) {
1108 $serverparts = parse_url($server);
1109 $server = $serverparts["scheme"]."://".$serverparts["host"];
1111 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1113 $msg = self::message($guid, $server);
1118 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1120 // Now call the dispatcher
1121 return self::dispatch_public($msg);
1125 * @brief Fetches a message from a server
1127 * @param string $guid message guid
1128 * @param string $server The url of the server
1129 * @param int $level Endless loop prevention
1132 * 'message' => The message XML
1133 * 'author' => The author handle
1134 * 'key' => The public key of the author
1136 private static function message($guid, $server, $level = 0) {
1141 // This will work for new Diaspora servers and Friendica servers from 3.5
1142 $source_url = $server."/fetch/post/".urlencode($guid);
1144 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1146 $envelope = fetch_url($source_url);
1148 logger("Envelope was fetched.", LOGGER_DEBUG);
1149 $x = self::verify_magic_envelope($envelope);
1151 logger("Envelope could not be verified.", LOGGER_DEBUG);
1153 logger("Envelope was verified.", LOGGER_DEBUG);
1157 // This will work for older Diaspora and Friendica servers
1159 $source_url = $server."/p/".urlencode($guid).".xml";
1160 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1162 $x = fetch_url($source_url);
1167 $source_xml = parse_xml_string($x);
1169 if (!is_object($source_xml))
1172 if ($source_xml->post->reshare) {
1173 // Reshare of a reshare - old Diaspora version
1174 logger("Message is a reshare", LOGGER_DEBUG);
1175 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1176 } elseif ($source_xml->getName() == "reshare") {
1177 // Reshare of a reshare - new Diaspora version
1178 logger("Message is a new reshare", LOGGER_DEBUG);
1179 return self::message($source_xml->root_guid, $server, ++$level);
1184 // Fetch the author - for the old and the new Diaspora version
1185 if ($source_xml->post->status_message->diaspora_handle)
1186 $author = (string)$source_xml->post->status_message->diaspora_handle;
1187 elseif ($source_xml->author && ($source_xml->getName() == "status_message"))
1188 $author = (string)$source_xml->author;
1190 // If this isn't a "status_message" then quit
1192 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1196 $msg = array("message" => $x, "author" => $author);
1198 $msg["key"] = self::key($msg["author"]);
1204 * @brief Fetches the item record of a given guid
1206 * @param int $uid The user id
1207 * @param string $guid message guid
1208 * @param string $author The handle of the item
1209 * @param array $contact The contact of the item owner
1211 * @return array the item record
1213 private static function parent_item($uid, $guid, $author, $contact) {
1214 $r = q("SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1215 `author-name`, `author-link`, `author-avatar`,
1216 `owner-name`, `owner-link`, `owner-avatar`
1217 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1218 intval($uid), dbesc($guid));
1221 $result = self::store_by_guid($guid, $contact["url"], $uid);
1224 $person = self::person_by_handle($author);
1225 $result = self::store_by_guid($guid, $person["url"], $uid);
1229 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1231 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1232 `author-name`, `author-link`, `author-avatar`,
1233 `owner-name`, `owner-link`, `owner-avatar`
1234 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1235 intval($uid), dbesc($guid));
1240 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1243 logger("parent item found: parent: ".$guid." - user: ".$uid);
1249 * @brief returns contact details
1251 * @param array $contact The default contact if the person isn't found
1252 * @param array $person The record of the person
1253 * @param int $uid The user id
1256 * 'cid' => contact id
1257 * 'network' => network type
1259 private static function author_contact_by_url($contact, $person, $uid) {
1261 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1262 dbesc(normalise_link($person["url"])), intval($uid));
1265 $network = $r[0]["network"];
1267 // We are receiving content from a user that possibly is about to be terminated
1268 // This means the user is vital, so we remove a possible termination date.
1269 unmark_for_death($r[0]);
1271 $cid = $contact["id"];
1272 $network = NETWORK_DIASPORA;
1275 return array("cid" => $cid, "network" => $network);
1279 * @brief Is the profile a hubzilla profile?
1281 * @param string $url The profile link
1283 * @return bool is it a hubzilla server?
1285 public static function is_redmatrix($url) {
1286 return(strstr($url, "/channel/"));
1290 * @brief Generate a post link with a given handle and message guid
1292 * @param string $addr The user handle
1293 * @param string $guid message guid
1295 * @return string the post link
1297 private static function plink($addr, $guid, $parent_guid = '') {
1298 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1301 if (!Dbm::is_result($r)) {
1302 if ($parent_guid != '') {
1303 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$parent_guid."#".$guid;
1305 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$guid;
1309 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1310 // So we try another way as well.
1311 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1312 if (Dbm::is_result($s)) {
1313 $r[0]["network"] = $s[0]["network"];
1316 if ($r[0]["network"] == NETWORK_DFRN) {
1317 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1320 if (self::is_redmatrix($r[0]["url"])) {
1321 return $r[0]["url"]."/?f=&mid=".$guid;
1324 if ($parent_guid != '') {
1325 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$parent_guid."#".$guid;
1327 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1332 * @brief Receives account migration
1334 * @param array $importer Array of the importer user
1335 * @param object $data The message object
1337 * @return bool Success
1339 private static function receiveAccountMigration($importer, $data) {
1340 $old_handle = notags(unxmlify($data->author));
1341 $new_handle = notags(unxmlify($data->profile->author));
1342 $signature = notags(unxmlify($data->signature));
1344 $contact = self::contact_by_handle($importer["uid"], $old_handle);
1346 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1350 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1353 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1354 $key = self::key($old_handle);
1355 if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
1356 logger('No valid signature for migration.');
1360 // Update the profile
1361 self::receive_profile($importer, $data->profile);
1363 // change the technical stuff in contact and gcontact
1364 $data = Probe::uri($new_handle);
1365 if ($data['network'] == NETWORK_PHANTOM) {
1366 logger('Account for '.$new_handle." couldn't be probed.");
1370 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1371 'name' => $data['name'], 'nick' => $data['nick'],
1372 'addr' => $data['addr'], 'batch' => $data['batch'],
1373 'notify' => $data['notify'], 'poll' => $data['poll'],
1374 'network' => $data['network']);
1376 dba::update('contact', $fields, array('addr' => $old_handle));
1378 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1379 'name' => $data['name'], 'nick' => $data['nick'],
1380 'addr' => $data['addr'], 'connect' => $data['addr'],
1381 'notify' => $data['notify'], 'photo' => $data['photo'],
1382 'server_url' => $data['baseurl'], 'network' => $data['network']);
1384 dba::update('gcontact', $fields, array('addr' => $old_handle));
1386 logger('Contacts are updated.');
1389 /// @todo This is an extreme performance killer
1391 'owner-link' => array($contact["url"], $data["url"]),
1392 'author-link' => array($contact["url"], $data["url"]),
1394 foreach ($fields as $n=>$f) {
1395 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1397 intval($importer["uid"]));
1399 if (Dbm::is_result($r)) {
1400 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1403 intval($importer["uid"]));
1411 logger('Items are updated.');
1417 * @brief Processes an account deletion
1419 * @param array $importer Array of the importer user
1420 * @param object $data The message object
1422 * @return bool Success
1424 private static function receive_account_deletion($importer, $data) {
1426 /// @todo Account deletion should remove the contact from the global contacts as well
1428 $author = notags(unxmlify($data->author));
1430 $contact = self::contact_by_handle($importer["uid"], $author);
1432 logger("cannot find contact for author: ".$author);
1436 // We now remove the contact
1437 contact_remove($contact["id"]);
1442 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1444 * @param string $author Author handle
1445 * @param string $guid Message guid
1446 * @param boolean $onlyfound Only return uri when found in the database
1448 * @return string The constructed uri or the one from our database
1450 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1452 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1453 if (Dbm::is_result($r)) {
1454 return $r[0]["uri"];
1455 } elseif (!$onlyfound) {
1456 return $author.":".$guid;
1463 * @brief Fetch the guid from our database with a given uri
1465 * @param string $author Author handle
1466 * @param string $uri Message uri
1468 * @return string The post guid
1470 private static function get_guid_from_uri($uri, $uid) {
1472 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1473 if (Dbm::is_result($r)) {
1474 return $r[0]["guid"];
1481 * @brief Find the best importer for a comment, like, ...
1483 * @param string $guid The guid of the item
1485 * @return array|boolean the origin owner of that post - or false
1487 private static function importer_for_guid($guid) {
1488 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1490 if (Dbm::is_result($item)) {
1491 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1492 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1493 if (Dbm::is_result($contact)) {
1501 * @brief Processes an incoming comment
1503 * @param array $importer Array of the importer user
1504 * @param string $sender The sender of the message
1505 * @param object $data The message object
1506 * @param string $xml The original XML of the message
1508 * @return int The message id of the generated comment or "false" if there was an error
1510 private static function receive_comment($importer, $sender, $data, $xml) {
1511 $author = notags(unxmlify($data->author));
1512 $guid = notags(unxmlify($data->guid));
1513 $parent_guid = notags(unxmlify($data->parent_guid));
1514 $text = unxmlify($data->text);
1516 if (isset($data->created_at)) {
1517 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1519 $created_at = datetime_convert();
1522 if (isset($data->thread_parent_guid)) {
1523 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1524 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1529 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1534 $message_id = self::message_exists($importer["uid"], $guid);
1539 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1540 if (!$parent_item) {
1544 $person = self::person_by_handle($author);
1545 if (!is_array($person)) {
1546 logger("unable to find author details");
1550 // Fetch the contact id - if we know this contact
1551 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1553 $datarray = array();
1555 $datarray["uid"] = $importer["uid"];
1556 $datarray["contact-id"] = $author_contact["cid"];
1557 $datarray["network"] = $author_contact["network"];
1559 $datarray["author-name"] = $person["name"];
1560 $datarray["author-link"] = $person["url"];
1561 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1563 $datarray["owner-name"] = $contact["name"];
1564 $datarray["owner-link"] = $contact["url"];
1565 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1567 $datarray["guid"] = $guid;
1568 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1570 $datarray["type"] = "remote-comment";
1571 $datarray["verb"] = ACTIVITY_POST;
1572 $datarray["gravity"] = GRAVITY_COMMENT;
1574 if ($thr_uri != "") {
1575 $datarray["parent-uri"] = $thr_uri;
1577 $datarray["parent-uri"] = $parent_item["uri"];
1580 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1582 $datarray["protocol"] = PROTOCOL_DIASPORA;
1583 $datarray["source"] = $xml;
1585 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1587 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1589 $body = diaspora2bb($text);
1591 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1593 self::fetch_guid($datarray);
1595 $message_id = item_store($datarray);
1597 if ($message_id <= 0) {
1602 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1605 // If we are the origin of the parent we store the original data and notify our followers
1606 if ($message_id && $parent_item["origin"]) {
1608 // Formerly we stored the signed text, the signature and the author in different fields.
1609 // We now store the raw data so that we are more flexible.
1610 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1613 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $message_id);
1620 * @brief processes and stores private messages
1622 * @param array $importer Array of the importer user
1623 * @param array $contact The contact of the message
1624 * @param object $data The message object
1625 * @param array $msg Array of the processed message, author handle and key
1626 * @param object $mesg The private message
1627 * @param array $conversation The conversation record to which this message belongs
1629 * @return bool "true" if it was successful
1631 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1632 $author = notags(unxmlify($data->author));
1633 $guid = notags(unxmlify($data->guid));
1634 $subject = notags(unxmlify($data->subject));
1636 // "diaspora_handle" is the element name from the old version
1637 // "author" is the element name from the new version
1638 if ($mesg->author) {
1639 $msg_author = notags(unxmlify($mesg->author));
1640 } elseif ($mesg->diaspora_handle) {
1641 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1646 $msg_guid = notags(unxmlify($mesg->guid));
1647 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1648 $msg_text = unxmlify($mesg->text);
1649 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1651 if ($msg_conversation_guid != $guid) {
1652 logger("message conversation guid does not belong to the current conversation.");
1656 $body = diaspora2bb($msg_text);
1657 $message_uri = $msg_author.":".$msg_guid;
1659 $person = self::person_by_handle($msg_author);
1663 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1665 intval($importer["uid"])
1667 if (Dbm::is_result($r)) {
1668 logger("duplicate message already delivered.", LOGGER_DEBUG);
1672 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1673 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1674 intval($importer["uid"]),
1676 intval($conversation["id"]),
1677 dbesc($person["name"]),
1678 dbesc($person["photo"]),
1679 dbesc($person["url"]),
1680 intval($contact["id"]),
1685 dbesc($message_uri),
1686 dbesc($author.":".$guid),
1687 dbesc($msg_created_at)
1692 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1695 "type" => NOTIFY_MAIL,
1696 "notify_flags" => $importer["notify-flags"],
1697 "language" => $importer["language"],
1698 "to_name" => $importer["username"],
1699 "to_email" => $importer["email"],
1700 "uid" =>$importer["uid"],
1701 "item" => array("subject" => $subject, "body" => $body),
1702 "source_name" => $person["name"],
1703 "source_link" => $person["url"],
1704 "source_photo" => $person["thumb"],
1705 "verb" => ACTIVITY_POST,
1712 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1714 * @param array $importer Array of the importer user
1715 * @param array $msg Array of the processed message, author handle and key
1716 * @param object $data The message object
1718 * @return bool Success
1720 private static function receive_conversation($importer, $msg, $data) {
1721 $author = notags(unxmlify($data->author));
1722 $guid = notags(unxmlify($data->guid));
1723 $subject = notags(unxmlify($data->subject));
1724 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1725 $participants = notags(unxmlify($data->participants));
1727 $messages = $data->message;
1729 if (!count($messages)) {
1730 logger("empty conversation");
1734 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1738 $conversation = null;
1740 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1741 intval($importer["uid"]),
1745 $conversation = $c[0];
1747 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1748 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1749 intval($importer["uid"]),
1753 dbesc(datetime_convert()),
1755 dbesc($participants)
1758 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1759 intval($importer["uid"]),
1764 $conversation = $c[0];
1766 if (!$conversation) {
1767 logger("unable to create conversation.");
1771 foreach ($messages as $mesg)
1772 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1778 * @brief Creates the body for a "like" message
1780 * @param array $contact The contact that send us the "like"
1781 * @param array $parent_item The item array of the parent item
1782 * @param string $guid message guid
1784 * @return string the body
1786 private static function construct_like_body($contact, $parent_item, $guid) {
1787 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1789 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1790 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1791 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1793 return sprintf($bodyverb, $ulink, $alink, $plink);
1797 * @brief Creates a XML object for a "like"
1799 * @param array $importer Array of the importer user
1800 * @param array $parent_item The item array of the parent item
1802 * @return string The XML
1804 private static function construct_like_object($importer, $parent_item) {
1805 $objtype = ACTIVITY_OBJ_NOTE;
1806 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1807 $parent_body = $parent_item["body"];
1809 $xmldata = array("object" => array("type" => $objtype,
1811 "id" => $parent_item["uri"],
1814 "content" => $parent_body));
1816 return xml::from_array($xmldata, $xml, true);
1820 * @brief Processes "like" messages
1822 * @param array $importer Array of the importer user
1823 * @param string $sender The sender of the message
1824 * @param object $data The message object
1826 * @return int The message id of the generated like or "false" if there was an error
1828 private static function receive_like($importer, $sender, $data) {
1829 $author = notags(unxmlify($data->author));
1830 $guid = notags(unxmlify($data->guid));
1831 $parent_guid = notags(unxmlify($data->parent_guid));
1832 $parent_type = notags(unxmlify($data->parent_type));
1833 $positive = notags(unxmlify($data->positive));
1835 // likes on comments aren't supported by Diaspora - only on posts
1836 // But maybe this will be supported in the future, so we will accept it.
1837 if (!in_array($parent_type, array("Post", "Comment")))
1840 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1844 $message_id = self::message_exists($importer["uid"], $guid);
1848 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1852 $person = self::person_by_handle($author);
1853 if (!is_array($person)) {
1854 logger("unable to find author details");
1858 // Fetch the contact id - if we know this contact
1859 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1861 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1862 // We would accept this anyhow.
1863 if ($positive == "true")
1864 $verb = ACTIVITY_LIKE;
1866 $verb = ACTIVITY_DISLIKE;
1868 $datarray = array();
1870 $datarray["protocol"] = PROTOCOL_DIASPORA;
1872 $datarray["uid"] = $importer["uid"];
1873 $datarray["contact-id"] = $author_contact["cid"];
1874 $datarray["network"] = $author_contact["network"];
1876 $datarray["author-name"] = $person["name"];
1877 $datarray["author-link"] = $person["url"];
1878 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1880 $datarray["owner-name"] = $contact["name"];
1881 $datarray["owner-link"] = $contact["url"];
1882 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1884 $datarray["guid"] = $guid;
1885 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1887 $datarray["type"] = "activity";
1888 $datarray["verb"] = $verb;
1889 $datarray["gravity"] = GRAVITY_LIKE;
1890 $datarray["parent-uri"] = $parent_item["uri"];
1892 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1893 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1895 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1897 $message_id = item_store($datarray);
1899 if ($message_id <= 0) {
1904 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1907 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1908 if ($parent_item["id"] != $parent_item["parent"]) {
1909 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
1910 $origin = $toplevel["origin"];
1912 $origin = $parent_item["origin"];
1915 // If we are the origin of the parent we store the original data and notify our followers
1916 if ($message_id && $origin) {
1918 // Formerly we stored the signed text, the signature and the author in different fields.
1919 // We now store the raw data so that we are more flexible.
1920 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1923 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $message_id);
1930 * @brief Processes private messages
1932 * @param array $importer Array of the importer user
1933 * @param object $data The message object
1935 * @return bool Success?
1937 private static function receive_message($importer, $data) {
1938 $author = notags(unxmlify($data->author));
1939 $guid = notags(unxmlify($data->guid));
1940 $conversation_guid = notags(unxmlify($data->conversation_guid));
1941 $text = unxmlify($data->text);
1942 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1944 $contact = self::allowed_contact_by_handle($importer, $author, true);
1949 $conversation = null;
1951 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1952 intval($importer["uid"]),
1953 dbesc($conversation_guid)
1956 $conversation = $c[0];
1958 logger("conversation not available.");
1962 $message_uri = $author.":".$guid;
1964 $person = self::person_by_handle($author);
1966 logger("unable to find author details");
1970 $body = diaspora2bb($text);
1972 $body = self::replace_people_guid($body, $person["url"]);
1976 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1978 intval($importer["uid"])
1980 if (Dbm::is_result($r)) {
1981 logger("duplicate message already delivered.", LOGGER_DEBUG);
1985 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1986 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1987 intval($importer["uid"]),
1989 intval($conversation["id"]),
1990 dbesc($person["name"]),
1991 dbesc($person["photo"]),
1992 dbesc($person["url"]),
1993 intval($contact["id"]),
1994 dbesc($conversation["subject"]),
1998 dbesc($message_uri),
1999 dbesc($author.":".$conversation["guid"]),
2005 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
2010 * @brief Processes participations - unsupported by now
2012 * @param array $importer Array of the importer user
2013 * @param object $data The message object
2015 * @return bool always true
2017 private static function receive_participation($importer, $data) {
2018 // I'm not sure if we can fully support this message type
2023 * @brief Processes photos - unneeded
2025 * @param array $importer Array of the importer user
2026 * @param object $data The message object
2028 * @return bool always true
2030 private static function receive_photo($importer, $data) {
2031 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
2036 * @brief Processes poll participations - unssupported
2038 * @param array $importer Array of the importer user
2039 * @param object $data The message object
2041 * @return bool always true
2043 private static function receive_poll_participation($importer, $data) {
2044 // We don't support polls by now
2049 * @brief Processes incoming profile updates
2051 * @param array $importer Array of the importer user
2052 * @param object $data The message object
2054 * @return bool Success
2056 private static function receive_profile($importer, $data) {
2057 $author = strtolower(notags(unxmlify($data->author)));
2059 $contact = self::contact_by_handle($importer["uid"], $author);
2063 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2064 $image_url = unxmlify($data->image_url);
2065 $birthday = unxmlify($data->birthday);
2066 $gender = unxmlify($data->gender);
2067 $about = diaspora2bb(unxmlify($data->bio));
2068 $location = diaspora2bb(unxmlify($data->location));
2069 $searchable = (unxmlify($data->searchable) == "true");
2070 $nsfw = (unxmlify($data->nsfw) == "true");
2071 $tags = unxmlify($data->tag_string);
2073 $tags = explode("#", $tags);
2075 $keywords = array();
2076 foreach ($tags as $tag) {
2077 $tag = trim(strtolower($tag));
2082 $keywords = implode(", ", $keywords);
2084 $handle_parts = explode("@", $author);
2085 $nick = $handle_parts[0];
2088 $name = $handle_parts[0];
2090 if ( preg_match("|^https?://|", $image_url) === 0)
2091 $image_url = "http://".$handle_parts[1].$image_url;
2093 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
2095 // Generic birthday. We don't know the timezone. The year is irrelevant.
2097 $birthday = str_replace("1000", "1901", $birthday);
2099 if ($birthday != "")
2100 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2102 // this is to prevent multiple birthday notifications in a single year
2103 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2105 if (substr($birthday,5) === substr($contact["bd"],5))
2106 $birthday = $contact["bd"];
2108 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2109 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2113 dbesc(datetime_convert()),
2119 intval($contact["id"]),
2120 intval($importer["uid"])
2123 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2124 "photo" => $image_url, "name" => $name, "location" => $location,
2125 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2126 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2127 "hide" => !$searchable, "nsfw" => $nsfw);
2129 $gcid = update_gcontact($gcontact);
2131 link_gcontact($gcid, $importer["uid"], $contact["id"]);
2133 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2139 * @brief Processes incoming friend requests
2141 * @param array $importer Array of the importer user
2142 * @param array $contact The contact that send the request
2144 private static function receive_request_make_friend($importer, $contact) {
2148 if ($contact["rel"] == CONTACT_IS_SHARING) {
2149 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2150 array('id' => $contact["id"], 'uid' => $importer["uid"]));
2152 // send notification
2154 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2155 intval($importer["uid"])
2158 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2160 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2161 intval($importer["uid"])
2164 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2166 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2169 $arr["protocol"] = PROTOCOL_DIASPORA;
2170 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2171 $arr["uid"] = $importer["uid"];
2172 $arr["contact-id"] = $self[0]["id"];
2174 $arr["type"] = 'wall';
2175 $arr["gravity"] = 0;
2177 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2178 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2179 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2180 $arr["verb"] = ACTIVITY_FRIEND;
2181 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2183 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2184 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2185 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2186 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2188 $arr["object"] = self::construct_new_friend_object($contact);
2190 $arr["last-child"] = 1;
2192 $arr["allow_cid"] = $user[0]["allow_cid"];
2193 $arr["allow_gid"] = $user[0]["allow_gid"];
2194 $arr["deny_cid"] = $user[0]["deny_cid"];
2195 $arr["deny_gid"] = $user[0]["deny_gid"];
2197 $i = item_store($arr);
2199 Worker::add(PRIORITY_HIGH, "notifier", "activity", $i);
2205 * @brief Creates a XML object for a "new friend" message
2207 * @param array $contact Array of the contact
2209 * @return string The XML
2211 private static function construct_new_friend_object($contact) {
2212 $objtype = ACTIVITY_OBJ_PERSON;
2213 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2214 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2216 $xmldata = array("object" => array("type" => $objtype,
2217 "title" => $contact["name"],
2218 "id" => $contact["url"]."/".$contact["name"],
2221 return xml::from_array($xmldata, $xml, true);
2225 * @brief Processes incoming sharing notification
2227 * @param array $importer Array of the importer user
2228 * @param object $data The message object
2230 * @return bool Success
2232 private static function receive_contact_request($importer, $data) {
2233 $author = unxmlify($data->author);
2234 $recipient = unxmlify($data->recipient);
2236 if (!$author || !$recipient) {
2240 // the current protocol version doesn't know these fields
2241 // That means that we will assume their existance
2242 if (isset($data->following)) {
2243 $following = (unxmlify($data->following) == "true");
2248 if (isset($data->sharing)) {
2249 $sharing = (unxmlify($data->sharing) == "true");
2254 $contact = self::contact_by_handle($importer["uid"],$author);
2256 // perhaps we were already sharing with this person. Now they're sharing with us.
2257 // That makes us friends.
2260 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2261 self::receive_request_make_friend($importer, $contact);
2263 // refetch the contact array
2264 $contact = self::contact_by_handle($importer["uid"],$author);
2266 // If we are now friends, we are sending a share message.
2267 // Normally we needn't to do so, but the first message could have been vanished.
2268 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2269 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2271 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2272 $ret = self::send_share($u[0], $contact);
2277 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2278 lose_follower($importer, $contact);
2283 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2284 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2286 } elseif (!$following && !$sharing) {
2287 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2289 } elseif (!$following && $sharing) {
2290 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2291 } elseif ($following && $sharing) {
2292 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2293 } elseif ($following && !$sharing) {
2294 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2297 $ret = self::person_by_handle($author);
2299 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2300 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2304 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2306 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2307 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2308 intval($importer["uid"]),
2309 dbesc($ret["network"]),
2310 dbesc($ret["addr"]),
2313 dbesc(normalise_link($ret["url"])),
2315 dbesc($ret["name"]),
2316 dbesc($ret["nick"]),
2317 dbesc($ret["photo"]),
2318 dbesc($ret["pubkey"]),
2319 dbesc($ret["notify"]),
2320 dbesc($ret["poll"]),
2325 // find the contact record we just created
2327 $contact_record = self::contact_by_handle($importer["uid"],$author);
2329 if (!$contact_record) {
2330 logger("unable to locate newly created contact record.");
2334 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2336 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2338 if (intval($def_gid))
2339 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2341 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2343 if ($importer["page-flags"] == PAGE_NORMAL) {
2345 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2347 $hash = random_string().(string)time(); // Generate a confirm_key
2349 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2350 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2351 intval($importer["uid"]),
2352 intval($contact_record["id"]),
2355 dbesc(t("Sharing notification from Diaspora network")),
2357 dbesc(datetime_convert())
2361 // automatic friend approval
2363 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2365 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2367 // technically they are sharing with us (CONTACT_IS_SHARING),
2368 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2369 // we are going to change the relationship and make them a follower.
2371 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following)
2372 $new_relation = CONTACT_IS_FRIEND;
2373 elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing)
2374 $new_relation = CONTACT_IS_SHARING;
2376 $new_relation = CONTACT_IS_FOLLOWER;
2378 $r = q("UPDATE `contact` SET `rel` = %d,
2386 intval($new_relation),
2387 dbesc(datetime_convert()),
2388 dbesc(datetime_convert()),
2389 intval($contact_record["id"])
2392 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2394 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2395 $ret = self::send_share($u[0], $contact_record);
2397 // Send the profile data, maybe it weren't transmitted before
2398 self::send_profile($importer["uid"], array($contact_record));
2406 * @brief Fetches a message with a given guid
2408 * @param string $guid message guid
2409 * @param string $orig_author handle of the original post
2410 * @param string $author handle of the sharer
2412 * @return array The fetched item
2414 private static function original_item($guid, $orig_author, $author) {
2416 // Do we already have this item?
2417 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2418 `author-name`, `author-link`, `author-avatar`
2419 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2422 if (Dbm::is_result($r)) {
2423 logger("reshared message ".$guid." already exists on system.");
2425 // Maybe it is already a reshared item?
2426 // Then refetch the content, if it is a reshare from a reshare.
2427 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2428 if (self::is_reshare($r[0]["body"], true)) {
2430 } elseif (self::is_reshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2431 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2433 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2435 // Add OEmbed and other information to the body
2436 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2444 if (!Dbm::is_result($r)) {
2445 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2446 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2447 $item_id = self::store_by_guid($guid, $server);
2450 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2451 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2452 $item_id = self::store_by_guid($guid, $server);
2456 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2457 `author-name`, `author-link`, `author-avatar`
2458 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2461 if (Dbm::is_result($r)) {
2462 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2463 if (self::is_reshare($r[0]["body"], false)) {
2464 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2465 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2477 * @brief Processes a reshare message
2479 * @param array $importer Array of the importer user
2480 * @param object $data The message object
2481 * @param string $xml The original XML of the message
2483 * @return int the message id
2485 private static function receive_reshare($importer, $data, $xml) {
2486 $author = notags(unxmlify($data->author));
2487 $guid = notags(unxmlify($data->guid));
2488 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2489 $root_author = notags(unxmlify($data->root_author));
2490 $root_guid = notags(unxmlify($data->root_guid));
2491 /// @todo handle unprocessed property "provider_display_name"
2492 $public = notags(unxmlify($data->public));
2494 $contact = self::allowed_contact_by_handle($importer, $author, false);
2499 $message_id = self::message_exists($importer["uid"], $guid);
2504 $original_item = self::original_item($root_guid, $root_author, $author);
2505 if (!$original_item) {
2509 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2511 $datarray = array();
2513 $datarray["uid"] = $importer["uid"];
2514 $datarray["contact-id"] = $contact["id"];
2515 $datarray["network"] = NETWORK_DIASPORA;
2517 $datarray["author-name"] = $contact["name"];
2518 $datarray["author-link"] = $contact["url"];
2519 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2521 $datarray["owner-name"] = $datarray["author-name"];
2522 $datarray["owner-link"] = $datarray["author-link"];
2523 $datarray["owner-avatar"] = $datarray["author-avatar"];
2525 $datarray["guid"] = $guid;
2526 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2528 $datarray["verb"] = ACTIVITY_POST;
2529 $datarray["gravity"] = GRAVITY_PARENT;
2531 $datarray["protocol"] = PROTOCOL_DIASPORA;
2532 $datarray["source"] = $xml;
2534 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2535 $original_item["guid"], $original_item["created"], $orig_url);
2536 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2538 $datarray["tag"] = $original_item["tag"];
2539 $datarray["app"] = $original_item["app"];
2541 $datarray["plink"] = self::plink($author, $guid);
2542 $datarray["private"] = (($public == "false") ? 1 : 0);
2543 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2545 $datarray["object-type"] = $original_item["object-type"];
2547 self::fetch_guid($datarray);
2548 $message_id = item_store($datarray);
2551 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2559 * @brief Processes retractions
2561 * @param array $importer Array of the importer user
2562 * @param array $contact The contact of the item owner
2563 * @param object $data The message object
2565 * @return bool success
2567 private static function item_retraction($importer, $contact, $data) {
2568 $author = notags(unxmlify($data->author));
2569 $target_guid = notags(unxmlify($data->target_guid));
2570 $target_type = notags(unxmlify($data->target_type));
2572 $person = self::person_by_handle($author);
2573 if (!is_array($person)) {
2574 logger("unable to find author detail for ".$author);
2578 if (empty($contact["url"])) {
2579 $contact["url"] = $person["url"];
2582 // Fetch items that are about to be deleted
2583 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2585 // When we receive a public retraction, we delete every item that we find.
2586 if ($importer['uid'] == 0) {
2587 $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2589 $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2591 $r = dba::select('item', $fields, $condition);
2592 if (!Dbm::is_result($r)) {
2593 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2597 while ($item = dba::fetch($r)) {
2598 // Fetch the parent item
2599 $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2601 // Only delete it if the parent author really fits
2602 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2603 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2607 // 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
2608 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
2609 'edited' => datetime_convert(), 'changed' => datetime_convert()),
2610 array('id' => $item["id"]));
2612 // Delete the thread - if it is a starting post and not a comment
2613 if ($target_type != 'Comment') {
2614 delete_thread($item["id"], $item["parent-uri"]);
2617 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2619 // Now check if the retraction needs to be relayed by us
2620 if ($parent["origin"]) {
2622 Worker::add(PRIORITY_HIGH, "notifier", "drop", $item["id"]);
2630 * @brief Receives retraction messages
2632 * @param array $importer Array of the importer user
2633 * @param string $sender The sender of the message
2634 * @param object $data The message object
2636 * @return bool Success
2638 private static function receive_retraction($importer, $sender, $data) {
2639 $target_type = notags(unxmlify($data->target_type));
2641 $contact = self::contact_by_handle($importer["uid"], $sender);
2642 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2643 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2647 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2649 switch ($target_type) {
2654 case "StatusMessage":
2655 return self::item_retraction($importer, $contact, $data);
2659 /// @todo What should we do with an "unshare"?
2660 // Removing the contact isn't correct since we still can read the public items
2661 contact_remove($contact["id"]);
2665 logger("Unknown target type ".$target_type);
2672 * @brief Receives status messages
2674 * @param array $importer Array of the importer user
2675 * @param object $data The message object
2676 * @param string $xml The original XML of the message
2678 * @return int The message id of the newly created item
2680 private static function receive_status_message($importer, $data, $xml) {
2681 $author = notags(unxmlify($data->author));
2682 $guid = notags(unxmlify($data->guid));
2683 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2684 $public = notags(unxmlify($data->public));
2685 $text = unxmlify($data->text);
2686 $provider_display_name = notags(unxmlify($data->provider_display_name));
2688 $contact = self::allowed_contact_by_handle($importer, $author, false);
2693 $message_id = self::message_exists($importer["uid"], $guid);
2699 if ($data->location) {
2700 foreach ($data->location->children() AS $fieldname => $data) {
2701 $address[$fieldname] = notags(unxmlify($data));
2705 $body = diaspora2bb($text);
2707 $datarray = array();
2709 // Attach embedded pictures to the body
2711 foreach ($data->photo AS $photo) {
2712 $body = "[img]".unxmlify($photo->remote_photo_path).
2713 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2716 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2718 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2720 // Add OEmbed and other information to the body
2721 if (!self::is_redmatrix($contact["url"])) {
2722 $body = add_page_info_to_body($body, false, true);
2726 /// @todo enable support for polls
2727 //if ($data->poll) {
2728 // foreach ($data->poll AS $poll)
2733 /// @todo enable support for events
2735 $datarray["uid"] = $importer["uid"];
2736 $datarray["contact-id"] = $contact["id"];
2737 $datarray["network"] = NETWORK_DIASPORA;
2739 $datarray["author-name"] = $contact["name"];
2740 $datarray["author-link"] = $contact["url"];
2741 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2743 $datarray["owner-name"] = $datarray["author-name"];
2744 $datarray["owner-link"] = $datarray["author-link"];
2745 $datarray["owner-avatar"] = $datarray["author-avatar"];
2747 $datarray["guid"] = $guid;
2748 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2750 $datarray["verb"] = ACTIVITY_POST;
2751 $datarray["gravity"] = GRAVITY_PARENT;
2753 $datarray["protocol"] = PROTOCOL_DIASPORA;
2754 $datarray["source"] = $xml;
2756 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2758 if ($provider_display_name != "") {
2759 $datarray["app"] = $provider_display_name;
2762 $datarray["plink"] = self::plink($author, $guid);
2763 $datarray["private"] = (($public == "false") ? 1 : 0);
2764 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2766 if (isset($address["address"])) {
2767 $datarray["location"] = $address["address"];
2770 if (isset($address["lat"]) && isset($address["lng"])) {
2771 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2774 self::fetch_guid($datarray);
2775 $message_id = item_store($datarray);
2778 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2785 /* ************************************************************************************** *
2786 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2787 * ************************************************************************************** */
2790 * @brief returnes the handle of a contact
2792 * @param array $me contact array
2794 * @return string the handle in the format user@domain.tld
2796 private static function my_handle($contact) {
2797 if ($contact["addr"] != "") {
2798 return $contact["addr"];
2801 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2802 // So - just in case - we build the the address here.
2803 if ($contact["nickname"] != "") {
2804 $nick = $contact["nickname"];
2806 $nick = $contact["nick"];
2809 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(),"://") + 3);
2814 * @brief Creates the data for a private message in the new format
2816 * @param string $msg The message that is to be transmitted
2817 * @param array $user The record of the sender
2818 * @param array $contact Target of the communication
2819 * @param string $prvkey The private key of the sender
2820 * @param string $pubkey The public key of the receiver
2822 * @return string The encrypted data
2824 public static function encode_private_data($msg, $user, $contact, $prvkey, $pubkey) {
2826 logger("Message: ".$msg, LOGGER_DATA);
2828 // without a public key nothing will work
2830 logger("pubkey missing: contact id: ".$contact["id"]);
2834 $aes_key = openssl_random_pseudo_bytes(32);
2835 $b_aes_key = base64_encode($aes_key);
2836 $iv = openssl_random_pseudo_bytes(16);
2837 $b_iv = base64_encode($iv);
2839 $ciphertext = self::aes_encrypt($aes_key, $iv, $msg);
2841 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2843 $encrypted_key_bundle = "";
2844 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2846 $json_object = json_encode(array("aes_key" => base64_encode($encrypted_key_bundle),
2847 "encrypted_magic_envelope" => base64_encode($ciphertext)));
2849 return $json_object;
2853 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2855 * @param string $msg The message that is to be transmitted
2856 * @param array $user The record of the sender
2858 * @return string The envelope
2860 public static function build_magic_envelope($msg, $user) {
2862 $b64url_data = base64url_encode($msg);
2863 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2865 $key_id = base64url_encode(self::my_handle($user));
2866 $type = "application/xml";
2867 $encoding = "base64url";
2868 $alg = "RSA-SHA256";
2869 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2871 // Fallback if the private key wasn't transmitted in the expected field
2872 if ($user['uprvkey'] == "")
2873 $user['uprvkey'] = $user['prvkey'];
2875 $signature = rsa_sign($signable_data, $user["uprvkey"]);
2876 $sig = base64url_encode($signature);
2878 $xmldata = array("me:env" => array("me:data" => $data,
2879 "@attributes" => array("type" => $type),
2880 "me:encoding" => $encoding,
2883 "@attributes2" => array("key_id" => $key_id)));
2885 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2887 return xml::from_array($xmldata, $xml, false, $namespaces);
2891 * @brief Create the envelope for a message
2893 * @param string $msg The message that is to be transmitted
2894 * @param array $user The record of the sender
2895 * @param array $contact Target of the communication
2896 * @param string $prvkey The private key of the sender
2897 * @param string $pubkey The public key of the receiver
2898 * @param bool $public Is the message public?
2900 * @return string The message that will be transmitted to other servers
2902 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2904 // The message is put into an envelope with the sender's signature
2905 $envelope = self::build_magic_envelope($msg, $user);
2907 // Private messages are put into a second envelope, encrypted with the receivers public key
2909 $envelope = self::encode_private_data($envelope, $user, $contact, $prvkey, $pubkey);
2916 * @brief Creates a signature for a message
2918 * @param array $owner the array of the owner of the message
2919 * @param array $message The message that is to be signed
2921 * @return string The signature
2923 private static function signature($owner, $message) {
2925 unset($sigmsg["author_signature"]);
2926 unset($sigmsg["parent_author_signature"]);
2928 $signed_text = implode(";", $sigmsg);
2930 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2934 * @brief Transmit a message to a target server
2936 * @param array $owner the array of the item owner
2937 * @param array $contact Target of the communication
2938 * @param string $envelope The message that is to be transmitted
2939 * @param bool $public_batch Is it a public post?
2940 * @param bool $queue_run Is the transmission called from the queue?
2941 * @param string $guid message guid
2943 * @return int Result of the transmission
2945 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run=false, $guid = "") {
2949 $enabled = intval(Config::get("system", "diaspora_enabled"));
2953 $logid = random_string(4);
2954 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2956 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2960 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2962 if (!$queue_run && was_recently_delayed($contact["id"])) {
2965 if (!intval(Config::get("system", "diaspora_test"))) {
2966 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
2968 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
2969 $return_code = $a->get_curl_code();
2971 logger("test_mode");
2976 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2978 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2979 logger("queue message");
2981 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2982 intval($contact["id"]),
2983 dbesc(NETWORK_DIASPORA),
2985 intval($public_batch)
2988 logger("add_to_queue ignored - identical item already in queue");
2990 // queue message for redelivery
2991 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
2993 // The message could not be delivered. We mark the contact as "dead"
2994 mark_for_death($contact);
2996 } elseif (($return_code >= 200) && ($return_code <= 299)) {
2997 // We successfully delivered a message, the contact is alive
2998 unmark_for_death($contact);
3001 return(($return_code) ? $return_code : (-1));
3006 * @brief Build the post xml
3008 * @param string $type The message type
3009 * @param array $message The message data
3011 * @return string The post XML
3013 public static function build_post_xml($type, $message) {
3015 $data = array($type => $message);
3017 return xml::from_array($data, $xml);
3021 * @brief Builds and transmit messages
3023 * @param array $owner the array of the item owner
3024 * @param array $contact Target of the communication
3025 * @param string $type The message type
3026 * @param array $message The message data
3027 * @param bool $public_batch Is it a public post?
3028 * @param string $guid message guid
3029 * @param bool $spool Should the transmission be spooled or transmitted?
3031 * @return int Result of the transmission
3033 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
3035 $msg = self::build_post_xml($type, $message);
3037 logger('message: '.$msg, LOGGER_DATA);
3038 logger('send guid '.$guid, LOGGER_DEBUG);
3040 // Fallback if the private key wasn't transmitted in the expected field
3041 if ($owner['uprvkey'] == "")
3042 $owner['uprvkey'] = $owner['prvkey'];
3044 $envelope = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3047 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3050 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3052 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3054 return $return_code;
3058 * @brief sends an account migration
3060 * @param array $owner the array of the item owner
3061 * @param array $contact Target of the communication
3062 * @param int $uid User ID
3064 * @return int The result of the transmission
3066 public static function sendAccountMigration($owner, $contact, $uid) {
3068 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3069 $profile = self::createProfileData($uid);
3071 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3072 $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3074 $message = array("author" => $old_handle,
3075 "profile" => $profile,
3076 "signature" => $signature);
3078 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3080 return self::build_and_transmit($owner, $contact, "account_migration", $message);
3084 * @brief Sends a "share" message
3086 * @param array $owner the array of the item owner
3087 * @param array $contact Target of the communication
3089 * @return int The result of the transmission
3091 public static function send_share($owner, $contact) {
3094 * @todo support the different possible combinations of "following" and "sharing"
3095 * Currently, Diaspora only interprets the "sharing" field
3097 * Before switching this code productive, we have to check all "send_share" calls if "rel" is set correctly
3101 switch ($contact["rel"]) {
3102 case CONTACT_IS_FRIEND:
3105 case CONTACT_IS_SHARING:
3108 case CONTACT_IS_FOLLOWER:
3114 $message = array("author" => self::my_handle($owner),
3115 "recipient" => $contact["addr"],
3116 "following" => "true",
3117 "sharing" => "true");
3119 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3121 return self::build_and_transmit($owner, $contact, "contact", $message);
3125 * @brief sends an "unshare"
3127 * @param array $owner the array of the item owner
3128 * @param array $contact Target of the communication
3130 * @return int The result of the transmission
3132 public static function send_unshare($owner, $contact) {
3134 $message = array("author" => self::my_handle($owner),
3135 "recipient" => $contact["addr"],
3136 "following" => "false",
3137 "sharing" => "false");
3139 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3141 return self::build_and_transmit($owner, $contact, "contact", $message);
3145 * @brief Checks a message body if it is a reshare
3147 * @param string $body The message body that is to be check
3148 * @param bool $complete Should it be a complete check or a simple check?
3150 * @return array|bool Reshare details or "false" if no reshare
3152 public static function is_reshare($body, $complete = true) {
3153 $body = trim($body);
3155 // Skip if it isn't a pure repeated messages
3156 // Does it start with a share?
3157 if ((strpos($body, "[share") > 0) && $complete)
3160 // Does it end with a share?
3161 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3164 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3165 // Skip if there is no shared message in there
3166 if ($body == $attributes)
3169 // If we don't do the complete check we quit here
3174 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3175 if ($matches[1] != "")
3176 $guid = $matches[1];
3178 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3179 if ($matches[1] != "")
3180 $guid = $matches[1];
3183 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3184 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3187 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3188 $ret["root_guid"] = $guid;
3194 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3195 if ($matches[1] != "")
3196 $profile = $matches[1];
3198 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3199 if ($matches[1] != "")
3200 $profile = $matches[1];
3204 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3205 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == ""))
3209 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3210 if ($matches[1] != "")
3211 $link = $matches[1];
3213 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3214 if ($matches[1] != "")
3215 $link = $matches[1];
3217 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3218 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == ""))
3225 * @brief Create an event array
3227 * @param integer $event_id The id of the event
3229 * @return array with event data
3231 private static function build_event($event_id) {
3233 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3234 if (!Dbm::is_result($r)) {
3240 $eventdata = array();
3242 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3243 if (!Dbm::is_result($r)) {
3249 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3250 if (!Dbm::is_result($r)) {
3256 $eventdata['author'] = self::my_handle($owner);
3258 if ($event['guid']) {
3259 $eventdata['guid'] = $event['guid'];
3262 $mask = 'Y-m-d\TH:i:s\Z';
3264 /// @todo - establish "all day" events in Friendica
3265 $eventdata["all_day"] = "false";
3267 if (!$event['adjust']) {
3268 $eventdata['timezone'] = $user['timezone'];
3270 if ($eventdata['timezone'] == "") {
3271 $eventdata['timezone'] = 'UTC';
3275 if ($event['start']) {
3276 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3278 if ($event['finish'] && !$event['nofinish']) {
3279 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3281 if ($event['summary']) {
3282 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3284 if ($event['desc']) {
3285 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3287 if ($event['location']) {
3288 $location = array();
3289 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3290 $location["lat"] = 0;
3291 $location["lng"] = 0;
3292 $eventdata['location'] = $location;
3299 * @brief Create a post (status message or reshare)
3301 * @param array $item The item that will be exported
3302 * @param array $owner the array of the item owner
3305 * 'type' -> Message type ("status_message" or "reshare")
3306 * 'message' -> Array of XML elements of the status
3308 public static function build_status($item, $owner) {
3310 $cachekey = "diaspora:build_status:".$item['guid'];
3312 $result = Cache::get($cachekey);
3313 if (!is_null($result)) {
3317 $myaddr = self::my_handle($owner);
3319 $public = (($item["private"]) ? "false" : "true");
3321 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3323 // Detect a share element and do a reshare
3324 if (!$item['private'] && ($ret = self::is_reshare($item["body"]))) {
3325 $message = array("author" => $myaddr,
3326 "guid" => $item["guid"],
3327 "created_at" => $created,
3328 "root_author" => $ret["root_handle"],
3329 "root_guid" => $ret["root_guid"],
3330 "provider_display_name" => $item["app"],
3331 "public" => $public);
3335 $title = $item["title"];
3336 $body = $item["body"];
3338 // convert to markdown
3339 $body = html_entity_decode(bb2diaspora($body));
3343 $body = "## ".html_entity_decode($title)."\n\n".$body;
3345 if ($item["attach"]) {
3346 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3348 $body .= "\n".t("Attachments:")."\n";
3349 foreach ($matches as $mtch)
3350 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3354 $location = array();
3356 if ($item["location"] != "")
3357 $location["address"] = $item["location"];
3359 if ($item["coord"] != "") {
3360 $coord = explode(" ", $item["coord"]);
3361 $location["lat"] = $coord[0];
3362 $location["lng"] = $coord[1];
3365 $message = array("author" => $myaddr,
3366 "guid" => $item["guid"],
3367 "created_at" => $created,
3368 "public" => $public,
3370 "provider_display_name" => $item["app"],
3371 "location" => $location);
3373 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3374 if (!isset($location["lat"]) || !isset($location["lng"])) {
3375 unset($message["location"]);
3378 if ($item['event-id'] > 0) {
3379 $event = self::build_event($item['event-id']);
3380 if (count($event)) {
3381 $message['event'] = $event;
3383 /// @todo Once Diaspora supports it, we will remove the body
3384 // $message['text'] = '';
3388 $type = "status_message";
3391 $msg = array("type" => $type, "message" => $message);
3393 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3399 * @brief Sends a post
3401 * @param array $item The item that will be exported
3402 * @param array $owner the array of the item owner
3403 * @param array $contact Target of the communication
3404 * @param bool $public_batch Is it a public post?
3406 * @return int The result of the transmission
3408 public static function send_status($item, $owner, $contact, $public_batch = false) {
3410 $status = self::build_status($item, $owner);
3412 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3416 * @brief Creates a "like" object
3418 * @param array $item The item that will be exported
3419 * @param array $owner the array of the item owner
3421 * @return array The data for a "like"
3423 private static function construct_like($item, $owner) {
3425 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3426 dbesc($item["thr-parent"]));
3427 if (!Dbm::is_result($p))
3432 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3433 if ($item['verb'] === ACTIVITY_LIKE) {
3435 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3436 $positive = "false";
3439 return(array("author" => self::my_handle($owner),
3440 "guid" => $item["guid"],
3441 "parent_guid" => $parent["guid"],
3442 "parent_type" => $target_type,
3443 "positive" => $positive,
3444 "author_signature" => ""));
3448 * @brief Creates an "EventParticipation" object
3450 * @param array $item The item that will be exported
3451 * @param array $owner the array of the item owner
3453 * @return array The data for an "EventParticipation"
3455 private static function construct_attend($item, $owner) {
3457 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3458 dbesc($item["thr-parent"]));
3459 if (!Dbm::is_result($p))
3464 switch ($item['verb']) {
3465 case ACTIVITY_ATTEND:
3466 $attend_answer = 'accepted';
3468 case ACTIVITY_ATTENDNO:
3469 $attend_answer = 'declined';
3471 case ACTIVITY_ATTENDMAYBE:
3472 $attend_answer = 'tentative';
3475 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3479 return(array("author" => self::my_handle($owner),
3480 "guid" => $item["guid"],
3481 "parent_guid" => $parent["guid"],
3482 "status" => $attend_answer,
3483 "author_signature" => ""));
3487 * @brief Creates the object for a comment
3489 * @param array $item The item that will be exported
3490 * @param array $owner the array of the item owner
3492 * @return array The data for a comment
3494 private static function construct_comment($item, $owner) {
3496 $cachekey = "diaspora:construct_comment:".$item['guid'];
3498 $result = Cache::get($cachekey);
3499 if (!is_null($result)) {
3503 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3504 intval($item["parent"]),
3505 intval($item["parent"])
3508 if (!Dbm::is_result($p))
3513 $text = html_entity_decode(bb2diaspora($item["body"]));
3514 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3516 $comment = array("author" => self::my_handle($owner),
3517 "guid" => $item["guid"],
3518 "created_at" => $created,
3519 "parent_guid" => $parent["guid"],
3521 "author_signature" => "");
3523 // Send the thread parent guid only if it is a threaded comment
3524 if ($item['thr-parent'] != $item['parent-uri']) {
3525 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3528 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3534 * @brief Send a like or a comment
3536 * @param array $item The item that will be exported
3537 * @param array $owner the array of the item owner
3538 * @param array $contact Target of the communication
3539 * @param bool $public_batch Is it a public post?
3541 * @return int The result of the transmission
3543 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3545 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3546 $message = self::construct_attend($item, $owner);
3547 $type = "event_participation";
3548 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3549 $message = self::construct_like($item, $owner);
3552 $message = self::construct_comment($item, $owner);
3559 $message["author_signature"] = self::signature($owner, $message);
3561 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3565 * @brief Creates a message from a signature record entry
3567 * @param array $item The item that will be exported
3568 * @param array $signature The entry of the "sign" record
3570 * @return string The message
3572 private static function message_from_signature($item, $signature) {
3574 // Split the signed text
3575 $signed_parts = explode(";", $signature['signed_text']);
3577 if ($item["deleted"]) {
3578 $message = array("author" => $signature['signer'],
3579 "target_guid" => $signed_parts[0],
3580 "target_type" => $signed_parts[1]);
3581 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3582 $message = array("author" => $signed_parts[4],
3583 "guid" => $signed_parts[1],
3584 "parent_guid" => $signed_parts[3],
3585 "parent_type" => $signed_parts[2],
3586 "positive" => $signed_parts[0],
3587 "author_signature" => $signature['signature'],
3588 "parent_author_signature" => "");
3590 // Remove the comment guid
3591 $guid = array_shift($signed_parts);
3593 // Remove the parent guid
3594 $parent_guid = array_shift($signed_parts);
3596 // Remove the handle
3597 $handle = array_pop($signed_parts);
3599 // Glue the parts together
3600 $text = implode(";", $signed_parts);
3602 $message = array("author" => $handle,
3604 "parent_guid" => $parent_guid,
3605 "text" => implode(";", $signed_parts),
3606 "author_signature" => $signature['signature'],
3607 "parent_author_signature" => "");
3613 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3615 * @param array $item The item that will be exported
3616 * @param array $owner the array of the item owner
3617 * @param array $contact Target of the communication
3618 * @param bool $public_batch Is it a public post?
3620 * @return int The result of the transmission
3622 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3624 if ($item["deleted"]) {
3625 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3626 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3632 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3634 // fetch the original signature
3636 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3637 intval($item["id"]));
3640 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3646 // Old way - is used by the internal Friendica functions
3647 /// @todo Change all signatur storing functions to the new format
3648 if ($signature['signed_text'] && $signature['signature'] && $signature['signer'])
3649 $message = self::message_from_signature($item, $signature);
3651 $msg = json_decode($signature['signed_text'], true);
3654 if (is_array($msg)) {
3655 foreach ($msg AS $field => $data) {
3656 if (!$item["deleted"]) {
3657 if ($field == "diaspora_handle") {
3660 if ($field == "target_type") {
3661 $field = "parent_type";
3665 $message[$field] = $data;
3668 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3671 $message["parent_author_signature"] = self::signature($owner, $message);
3673 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3675 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3679 * @brief Sends a retraction (deletion) of a message, like or comment
3681 * @param array $item The item that will be exported
3682 * @param array $owner the array of the item owner
3683 * @param array $contact Target of the communication
3684 * @param bool $public_batch Is it a public post?
3685 * @param bool $relay Is the retraction transmitted from a relay?
3687 * @return int The result of the transmission
3689 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3691 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3693 $msg_type = "retraction";
3695 if ($item['id'] == $item['parent']) {
3696 $target_type = "Post";
3697 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3698 $target_type = "Like";
3700 $target_type = "Comment";
3703 $message = array("author" => $itemaddr,
3704 "target_guid" => $item['guid'],
3705 "target_type" => $target_type);
3707 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3709 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3713 * @brief Sends a mail
3715 * @param array $item The item that will be exported
3716 * @param array $owner The owner
3717 * @param array $contact Target of the communication
3719 * @return int The result of the transmission
3721 public static function send_mail($item, $owner, $contact) {
3723 $myaddr = self::my_handle($owner);
3725 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3726 intval($item["convid"]),
3727 intval($item["uid"])
3730 if (!Dbm::is_result($r)) {
3731 logger("conversation not found.");
3737 "author" => $cnv["creator"],
3738 "guid" => $cnv["guid"],
3739 "subject" => $cnv["subject"],
3740 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3741 "participants" => $cnv["recips"]
3744 $body = bb2diaspora($item["body"]);
3745 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3748 "author" => $myaddr,
3749 "guid" => $item["guid"],
3750 "conversation_guid" => $cnv["guid"],
3752 "created_at" => $created,
3755 if ($item["reply"]) {
3760 "author" => $cnv["creator"],
3761 "guid" => $cnv["guid"],
3762 "subject" => $cnv["subject"],
3763 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3764 "participants" => $cnv["recips"],
3767 $type = "conversation";
3770 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3774 * @brief Create profile data
3776 * @param int $uid The user id
3778 * @return array The profile data
3780 private static function createProfileData($uid) {
3781 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3783 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3784 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3785 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3795 $handle = $profile["addr"];
3796 $first = ((strpos($profile['name'],' ')
3797 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3798 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3799 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3800 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3801 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3802 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3804 if ($searchable === 'true') {
3805 $dob = '1000-00-00';
3807 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3808 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3810 $about = $profile['about'];
3811 $about = strip_tags(bbcode($about));
3813 $location = formatted_location($profile);
3815 if ($profile['pub_keywords']) {
3816 $kw = str_replace(',',' ',$profile['pub_keywords']);
3817 $kw = str_replace(' ',' ',$kw);
3818 $arr = explode(' ',$profile['pub_keywords']);
3820 for ($x = 0; $x < 5; $x ++) {
3822 $tags .= '#'. trim($arr[$x]) .' ';
3826 $tags = trim($tags);
3829 return array("author" => $handle,
3830 "first_name" => $first,
3831 "last_name" => $last,
3832 "image_url" => $large,
3833 "image_url_medium" => $medium,
3834 "image_url_small" => $small,
3836 "gender" => $profile['gender'],
3838 "location" => $location,
3839 "searchable" => $searchable,
3841 "tag_string" => $tags);
3845 * @brief Sends profile data
3847 * @param int $uid The user id
3849 public static function send_profile($uid, $recips = false) {
3855 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3856 AND `uid` = %d AND `rel` != %d",
3857 dbesc(NETWORK_DIASPORA),
3859 intval(CONTACT_IS_SHARING)
3864 $message = self::createProfileData($uid);
3866 foreach ($recips as $recip) {
3867 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3868 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3873 * @brief Stores the signature for likes that are created on our system
3875 * @param array $contact The contact array of the "like"
3876 * @param int $post_id The post id of the "like"
3878 * @return bool Success
3880 public static function store_like_signature($contact, $post_id) {
3882 // Is the contact the owner? Then fetch the private key
3883 if (!$contact['self'] || ($contact['uid'] == 0)) {
3884 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3888 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3889 if (!Dbm::is_result($r)) {
3893 $contact["uprvkey"] = $r[0]['prvkey'];
3895 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3896 if (!Dbm::is_result($r)) {
3900 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3904 $message = self::construct_like($r[0], $contact);
3905 $message["author_signature"] = self::signature($contact, $message);
3908 * Now store the signature more flexible to dynamically support new fields.
3909 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3911 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
3913 logger('Stored diaspora like signature');
3918 * @brief Stores the signature for comments that are created on our system
3920 * @param array $item The item array of the comment
3921 * @param array $contact The contact array of the item owner
3922 * @param string $uprvkey The private key of the sender
3923 * @param int $message_id The message id of the comment
3925 * @return bool Success
3927 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3929 if ($uprvkey == "") {
3930 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3934 $contact["uprvkey"] = $uprvkey;
3936 $message = self::construct_comment($item, $contact);
3937 $message["author_signature"] = self::signature($contact, $message);
3940 * Now store the signature more flexible to dynamically support new fields.
3941 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3943 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
3945 logger('Stored diaspora comment signature');