3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "valid_posting" and interpret only the new protocol.
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Worker;
16 use Friendica\Network\Probe;
18 require_once 'include/items.php';
19 require_once 'include/bb2diaspora.php';
20 require_once 'include/probe.php';
21 require_once 'include/Contact.php';
22 require_once 'include/Photo.php';
23 require_once 'include/socgraph.php';
24 require_once 'include/group.php';
25 require_once 'include/xml.php';
26 require_once 'include/datetime.php';
27 require_once 'include/queue_fn.php';
28 require_once 'include/cache.php';
31 * @brief This class contain functions to create and send Diaspora XML files
37 * @brief Return a list of relay servers
39 * This is an experimental Diaspora feature.
41 * @return array of relay servers
43 public static function relay_list() {
45 $serverdata = Config::get("system", "relay_server");
46 if ($serverdata == "")
51 $servers = explode(",", $serverdata);
53 foreach ($servers AS $server) {
54 $server = trim($server);
55 $addr = "relay@".str_replace("http://", "", normalise_link($server));
56 $batch = $server."/receive/public";
58 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
59 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
62 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
63 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
68 dbesc(normalise_link($server)),
70 dbesc(NETWORK_DIASPORA),
71 intval(CONTACT_IS_FOLLOWER),
72 dbesc(datetime_convert()),
73 dbesc(datetime_convert()),
74 dbesc(datetime_convert())
77 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
79 $relay[] = $relais[0];
81 $relay[] = $relais[0];
88 * @brief repairs a signature that was double encoded
90 * The function is unused at the moment. It was copied from the old implementation.
92 * @param string $signature The signature
93 * @param string $handle The handle of the signature owner
94 * @param integer $level This value is only set inside this function to avoid endless loops
96 * @return string the repaired signature
98 private static function repair_signature($signature, $handle = "", $level = 1) {
100 if ($signature == "")
103 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
104 $signature = base64_decode($signature);
105 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
107 // Do a recursive call to be able to fix even multiple levels
109 $signature = self::repair_signature($signature, $handle, ++$level);
116 * @brief verify the envelope and return the verified data
118 * @param string $envelope The magic envelope
120 * @return string verified data
122 private static function verify_magic_envelope($envelope) {
124 $basedom = parse_xml_string($envelope);
126 if (!is_object($basedom)) {
127 logger("Envelope is no XML file");
131 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
133 if (sizeof($children) == 0) {
134 logger("XML has no children");
140 $data = base64url_decode($children->data);
141 $type = $children->data->attributes()->type[0];
143 $encoding = $children->encoding;
145 $alg = $children->alg;
147 $sig = base64url_decode($children->sig);
148 $key_id = $children->sig->attributes()->key_id[0];
150 $handle = base64url_decode($key_id);
152 $b64url_data = base64url_encode($data);
153 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
155 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
157 $key = self::key($handle);
159 $verify = rsa_verify($signable_data, $sig, $key);
161 logger('Message did not verify. Discarding.');
169 * @brief encrypts data via AES
171 * @param string $key The AES key
172 * @param string $iv The IV (is used for CBC encoding)
173 * @param string $data The data that is to be encrypted
175 * @return string encrypted data
177 private static function aes_encrypt($key, $iv, $data) {
178 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
182 * @brief decrypts data via AES
184 * @param string $key The AES key
185 * @param string $iv The IV (is used for CBC encoding)
186 * @param string $encrypted The encrypted data
188 * @return string decrypted data
190 private static function aes_decrypt($key, $iv, $encrypted) {
191 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
195 * @brief: Decodes incoming Diaspora message in the new format
197 * @param array $importer Array of the importer user
198 * @param string $raw raw post message
201 * 'message' -> decoded Diaspora XML message
202 * 'author' -> author diaspora handle
203 * 'key' -> author public key (converted to pkcs#8)
205 public static function decode_raw($importer, $raw) {
206 $data = json_decode($raw);
208 // Is it a private post? Then decrypt the outer Salmon
209 if (is_object($data)) {
210 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
211 $ciphertext = base64_decode($data->encrypted_magic_envelope);
213 $outer_key_bundle = '';
214 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
215 $j_outer_key_bundle = json_decode($outer_key_bundle);
217 if (!is_object($j_outer_key_bundle)) {
218 logger('Outer Salmon did not verify. Discarding.');
219 http_status_exit(400);
222 $outer_iv = base64_decode($j_outer_key_bundle->iv);
223 $outer_key = base64_decode($j_outer_key_bundle->key);
225 $xml = diaspora::aes_decrypt($outer_key, $outer_iv, $ciphertext);
230 $basedom = parse_xml_string($xml);
232 if (!is_object($basedom)) {
233 logger('Received data does not seem to be an XML. Discarding. '.$xml);
234 http_status_exit(400);
237 $base = $basedom->children(NAMESPACE_SALMON_ME);
239 // Not sure if this cleaning is needed
240 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
242 // Build the signed data
243 $type = $base->data[0]->attributes()->type[0];
244 $encoding = $base->encoding;
246 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
248 // This is the signature
249 $signature = base64url_decode($base->sig);
251 // Get the senders' public key
252 $key_id = $base->sig[0]->attributes()->key_id[0];
253 $author_addr = base64_decode($key_id);
254 $key = diaspora::key($author_addr);
256 $verify = rsa_verify($signed_data, $signature, $key);
258 logger('Message did not verify. Discarding.');
259 http_status_exit(400);
262 return array('message' => (string)base64url_decode($base->data),
263 'author' => unxmlify($author_addr),
264 'key' => (string)$key);
268 * @brief: Decodes incoming Diaspora message in the deprecated format
270 * @param array $importer Array of the importer user
271 * @param string $xml urldecoded Diaspora salmon
274 * 'message' -> decoded Diaspora XML message
275 * 'author' -> author diaspora handle
276 * 'key' -> author public key (converted to pkcs#8)
278 public static function decode($importer, $xml) {
281 $basedom = parse_xml_string($xml);
283 if (!is_object($basedom)) {
284 logger("XML is not parseable.");
287 $children = $basedom->children('https://joindiaspora.com/protocol');
289 if ($children->header) {
291 $author_link = str_replace('acct:','',$children->header->author_id);
293 // This happens with posts from a relais
295 logger("This is no private post in the old format", LOGGER_DEBUG);
299 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
301 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
302 $ciphertext = base64_decode($encrypted_header->ciphertext);
304 $outer_key_bundle = '';
305 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
307 $j_outer_key_bundle = json_decode($outer_key_bundle);
309 $outer_iv = base64_decode($j_outer_key_bundle->iv);
310 $outer_key = base64_decode($j_outer_key_bundle->key);
312 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
314 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
315 $idom = parse_xml_string($decrypted);
317 $inner_iv = base64_decode($idom->iv);
318 $inner_aes_key = base64_decode($idom->aes_key);
320 $author_link = str_replace('acct:','',$idom->author_id);
323 $dom = $basedom->children(NAMESPACE_SALMON_ME);
325 // figure out where in the DOM tree our data is hiding
327 if ($dom->provenance->data)
328 $base = $dom->provenance;
329 elseif ($dom->env->data)
335 logger('unable to locate salmon data in xml');
336 http_status_exit(400);
340 // Stash the signature away for now. We have to find their key or it won't be good for anything.
341 $signature = base64url_decode($base->sig);
345 // strip whitespace so our data element will return to one big base64 blob
346 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
349 // stash away some other stuff for later
351 $type = $base->data[0]->attributes()->type[0];
352 $keyhash = $base->sig[0]->attributes()->keyhash[0];
353 $encoding = $base->encoding;
357 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
361 $data = base64url_decode($data);
365 $inner_decrypted = $data;
368 // Decode the encrypted blob
370 $inner_encrypted = base64_decode($data);
371 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
375 logger('Could not retrieve author URI.');
376 http_status_exit(400);
378 // Once we have the author URI, go to the web and try to find their public key
379 // (first this will look it up locally if it is in the fcontact cache)
380 // This will also convert diaspora public key from pkcs#1 to pkcs#8
382 logger('Fetching key for '.$author_link);
383 $key = self::key($author_link);
386 logger('Could not retrieve author key.');
387 http_status_exit(400);
390 $verify = rsa_verify($signed_data,$signature,$key);
393 logger('Message did not verify. Discarding.');
394 http_status_exit(400);
397 logger('Message verified.');
399 return array('message' => (string)$inner_decrypted,
400 'author' => unxmlify($author_link),
401 'key' => (string)$key);
406 * @brief Dispatches public messages and find the fitting receivers
408 * @param array $msg The post that will be dispatched
410 * @return int The message id of the generated message, "true" or "false" if there was an error
412 public static function dispatch_public($msg) {
414 $enabled = intval(Config::get("system", "diaspora_enabled"));
416 logger("diaspora is disabled");
420 if (!($postdata = self::valid_posting($msg))) {
421 logger("Invalid posting");
425 $fields = $postdata['fields'];
427 // Is it a an action (comment, like, ...) for our own post?
428 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
429 $guid = notags(unxmlify($fields->parent_guid));
430 $importer = self::importer_for_guid($guid);
431 if (is_array($importer)) {
432 logger("delivering to origin: ".$importer["name"]);
433 $message_id = self::dispatch($importer, $msg, $fields);
438 // Process item retractions. This has to be done separated from the other stuff,
439 // since retractions for comments could come even from non followers.
440 if (!empty($fields) && in_array($fields->getName(), array('retraction'))) {
441 $target = notags(unxmlify($fields->target_type));
442 if (in_array($target, array("Comment", "Like", "Post", "Reshare", "StatusMessage"))) {
443 logger('processing retraction for '.$target, LOGGER_DEBUG);
444 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
445 $message_id = self::dispatch($importer, $msg, $fields);
450 // Now distribute it to the followers
451 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
452 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
453 AND NOT `account_expired` AND NOT `account_removed`",
454 dbesc(NETWORK_DIASPORA),
455 dbesc($msg["author"])
458 if (dbm::is_result($r)) {
459 foreach ($r as $rr) {
460 logger("delivering to: ".$rr["username"]);
461 self::dispatch($rr, $msg, $fields);
463 } elseif (!Config::get('system', 'relay_subscribe', false)) {
464 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
466 // Use a dummy importer to import the data for the public copy
467 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
468 $message_id = self::dispatch($importer, $msg, $fields);
475 * @brief Dispatches the different message types to the different functions
477 * @param array $importer Array of the importer user
478 * @param array $msg The post that will be dispatched
479 * @param object $fields SimpleXML object that contains the message
481 * @return int The message id of the generated message, "true" or "false" if there was an error
483 public static function dispatch($importer, $msg, $fields = null) {
485 // The sender is the handle of the contact that sent the message.
486 // This will often be different with relayed messages (for example "like" and "comment")
487 $sender = $msg["author"];
489 // This is only needed for private postings since this is already done for public ones before
490 if (is_null($fields)) {
491 if (!($postdata = self::valid_posting($msg))) {
492 logger("Invalid posting");
495 $fields = $postdata['fields'];
498 $type = $fields->getName();
500 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
503 case "account_migration":
504 return self::receiveAccountMigration($importer, $fields);
506 case "account_deletion":
507 return self::receive_account_deletion($importer, $fields);
510 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
513 return self::receive_contact_request($importer, $fields);
516 return self::receive_conversation($importer, $msg, $fields);
519 return self::receive_like($importer, $sender, $fields);
522 return self::receive_message($importer, $fields);
524 case "participation": // Not implemented
525 return self::receive_participation($importer, $fields);
527 case "photo": // Not implemented
528 return self::receive_photo($importer, $fields);
530 case "poll_participation": // Not implemented
531 return self::receive_poll_participation($importer, $fields);
534 return self::receive_profile($importer, $fields);
537 return self::receive_reshare($importer, $fields, $msg["message"]);
540 return self::receive_retraction($importer, $sender, $fields);
542 case "status_message":
543 return self::receive_status_message($importer, $fields, $msg["message"]);
546 logger("Unknown message type ".$type);
554 * @brief Checks if a posting is valid and fetches the data fields.
556 * This function does not only check the signature.
557 * It also does the conversion between the old and the new diaspora format.
559 * @param array $msg Array with the XML, the sender handle and the sender signature
561 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
563 private static function valid_posting($msg) {
565 $data = parse_xml_string($msg["message"]);
567 if (!is_object($data)) {
568 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
572 $first_child = $data->getName();
574 // Is this the new or the old version?
575 if ($data->getName() == "XML") {
577 foreach ($data->post->children() as $child)
584 $type = $element->getName();
587 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
589 // All retractions are handled identically from now on.
590 // In the new version there will only be "retraction".
591 if (in_array($type, array("signed_retraction", "relayable_retraction")))
592 $type = "retraction";
594 if ($type == "request")
597 $fields = new SimpleXMLElement("<".$type."/>");
601 foreach ($element->children() AS $fieldname => $entry) {
603 // Translation for the old XML structure
604 if ($fieldname == "diaspora_handle") {
605 $fieldname = "author";
607 if ($fieldname == "participant_handles") {
608 $fieldname = "participants";
610 if (in_array($type, array("like", "participation"))) {
611 if ($fieldname == "target_type") {
612 $fieldname = "parent_type";
615 if ($fieldname == "sender_handle") {
616 $fieldname = "author";
618 if ($fieldname == "recipient_handle") {
619 $fieldname = "recipient";
621 if ($fieldname == "root_diaspora_id") {
622 $fieldname = "root_author";
624 if ($type == "status_message") {
625 if ($fieldname == "raw_message") {
629 if ($type == "retraction") {
630 if ($fieldname == "post_guid") {
631 $fieldname = "target_guid";
633 if ($fieldname == "type") {
634 $fieldname = "target_type";
639 if (($fieldname == "author_signature") && ($entry != ""))
640 $author_signature = base64_decode($entry);
641 elseif (($fieldname == "parent_author_signature") && ($entry != ""))
642 $parent_author_signature = base64_decode($entry);
643 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
644 if ($signed_data != "") {
646 $signed_data_parent .= ";";
649 $signed_data .= $entry;
651 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) ||
652 ($orig_type == "relayable_retraction"))
653 xml::copy($entry, $fields, $fieldname);
656 // This is something that shouldn't happen at all.
657 if (in_array($type, array("status_message", "reshare", "profile")))
658 if ($msg["author"] != $fields->author) {
659 logger("Message handle is not the same as envelope sender. Quitting this message.");
663 // Only some message types have signatures. So we quit here for the other types.
664 if (!in_array($type, array("comment", "like"))) {
665 return array("fields" => $fields, "relayed" => false);
667 // No author_signature? This is a must, so we quit.
668 if (!isset($author_signature)) {
669 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
673 if (isset($parent_author_signature)) {
676 $key = self::key($msg["author"]);
678 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
679 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);
686 $key = self::key($fields->author);
688 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
689 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
692 return array("fields" => $fields, "relayed" => $relayed);
697 * @brief Fetches the public key for a given handle
699 * @param string $handle The handle
701 * @return string The public key
703 private static function key($handle) {
704 $handle = strval($handle);
706 logger("Fetching diaspora key for: ".$handle);
708 $r = self::person_by_handle($handle);
716 * @brief Fetches data for a given handle
718 * @param string $handle The handle
720 * @return array the queried data
722 public static function person_by_handle($handle) {
724 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
725 dbesc(NETWORK_DIASPORA),
730 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
732 // update record occasionally so it doesn't get stale
733 $d = strtotime($person["updated"]." +00:00");
734 if ($d < strtotime("now - 14 days"))
737 if ($person["guid"] == "")
741 if (!$person || $update) {
742 logger("create or refresh", LOGGER_DEBUG);
743 $r = Probe::uri($handle, NETWORK_DIASPORA);
745 // Note that Friendica contacts will return a "Diaspora person"
746 // if Diaspora connectivity is enabled on their server
747 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
748 self::add_fcontact($r, $update);
756 * @brief Updates the fcontact table
758 * @param array $arr The fcontact data
759 * @param bool $update Update or insert?
761 * @return string The id of the fcontact entry
763 private static function add_fcontact($arr, $update = false) {
766 $r = q("UPDATE `fcontact` SET
780 WHERE `url` = '%s' AND `network` = '%s'",
782 dbesc($arr["photo"]),
783 dbesc($arr["request"]),
785 dbesc(strtolower($arr["addr"])),
787 dbesc($arr["batch"]),
788 dbesc($arr["notify"]),
790 dbesc($arr["confirm"]),
791 dbesc($arr["alias"]),
792 dbesc($arr["pubkey"]),
793 dbesc(datetime_convert()),
795 dbesc($arr["network"])
798 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
799 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
800 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
803 dbesc($arr["photo"]),
804 dbesc($arr["request"]),
808 dbesc($arr["batch"]),
809 dbesc($arr["notify"]),
811 dbesc($arr["confirm"]),
812 dbesc($arr["network"]),
813 dbesc($arr["alias"]),
814 dbesc($arr["pubkey"]),
815 dbesc(datetime_convert())
823 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
825 * @param int $contact_id The id in the contact table
826 * @param int $gcontact_id The id in the gcontact table
828 * @return string the handle
830 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
833 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
835 if ($gcontact_id != 0) {
836 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
837 intval($gcontact_id));
839 if (dbm::is_result($r)) {
840 return strtolower($r[0]["addr"]);
844 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
845 intval($contact_id));
847 if (dbm::is_result($r)) {
850 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
852 if ($contact['addr'] != "") {
853 $handle = $contact['addr'];
855 $baseurl_start = strpos($contact['url'],'://') + 3;
856 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
857 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
858 $handle = $contact['nick'].'@'.$baseurl;
862 return strtolower($handle);
866 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
869 * @param mixed $fcontact_guid Hexadecimal string guid
871 * @return string the contact url or null
873 public static function url_from_contact_guid($fcontact_guid) {
874 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
876 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
877 dbesc(NETWORK_DIASPORA),
878 dbesc($fcontact_guid)
881 if (dbm::is_result($r)) {
889 * @brief Get a contact id for a given handle
891 * @param int $uid The user id
892 * @param string $handle The handle in the format user@domain.tld
894 * @return The contact id
896 private static function contact_by_handle($uid, $handle) {
898 // First do a direct search on the contact table
899 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
904 if (dbm::is_result($r)) {
908 * We haven't found it?
909 * We use another function for it that will possibly create a contact entry.
911 $cid = get_contact($handle, $uid);
914 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
915 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
917 if (dbm::is_result($r)) {
923 $handle_parts = explode("@", $handle);
924 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
925 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
930 if (dbm::is_result($r)) {
934 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
939 * @brief Check if posting is allowed for this contact
941 * @param array $importer Array of the importer user
942 * @param array $contact The contact that is checked
943 * @param bool $is_comment Is the check for a comment?
945 * @return bool is the contact allowed to post?
947 private static function post_allow($importer, $contact, $is_comment = false) {
950 * Perhaps we were already sharing with this person. Now they're sharing with us.
951 * That makes us friends.
952 * Normally this should have handled by getting a request - but this could get lost
954 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
955 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
956 array('id' => $contact["id"], 'uid' => $contact["uid"]));
958 $contact["rel"] = CONTACT_IS_FRIEND;
959 logger("defining user ".$contact["nick"]." as friend");
962 // We don't seem to like that person
963 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
964 // Maybe blocked, don't accept.
966 // We are following this person?
967 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
968 // Yes, then it is fine.
970 // Is it a post to a community?
971 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
974 // Is the message a global user or a comment?
975 } elseif (($importer["uid"] == 0) || $is_comment) {
976 // Messages for the global users and comments are always accepted
984 * @brief Fetches the contact id for a handle and checks if posting is allowed
986 * @param array $importer Array of the importer user
987 * @param string $handle The checked handle in the format user@domain.tld
988 * @param bool $is_comment Is the check for a comment?
990 * @return array The contact data
992 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
993 $contact = self::contact_by_handle($importer["uid"], $handle);
995 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
996 // If a contact isn't found, we accept it anyway if it is a comment
1004 if (!self::post_allow($importer, $contact, $is_comment)) {
1005 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1012 * @brief Does the message already exists on the system?
1014 * @param int $uid The user id
1015 * @param string $guid The guid of the message
1017 * @return int|bool message id if the message already was stored into the system - or false.
1019 private static function message_exists($uid, $guid) {
1020 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1025 if (dbm::is_result($r)) {
1026 logger("message ".$guid." already exists for user ".$uid);
1034 * @brief Checks for links to posts in a message
1036 * @param array $item The item array
1038 private static function fetch_guid($item) {
1039 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1040 preg_replace_callback($expression,
1041 function ($match) use ($item) {
1042 return self::fetch_guid_sub($match, $item);
1045 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1046 function ($match) use ($item) {
1047 return self::fetch_guid_sub($match, $item);
1052 * @brief Checks for relative /people/* links in an item body to match local
1053 * contacts or prepends the remote host taken from the author link.
1055 * @param string $body The item body to replace links from
1056 * @param string $author_link The author link for missing local contact fallback
1058 * @return the replaced string
1060 public static function replace_people_guid($body, $author_link) {
1061 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1062 function ($match) use ($author_link) {
1064 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1065 // 1 => '0123456789abcdef'
1067 $handle = self::url_from_contact_guid($match[1]);
1070 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1072 // No local match, restoring absolute remote URL from author scheme and host
1073 $author_url = parse_url($author_link);
1074 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1084 * @brief sub function of "fetch_guid" which checks for links in messages
1086 * @param array $match array containing a link that has to be checked for a message link
1087 * @param array $item The item array
1089 private static function fetch_guid_sub($match, $item) {
1090 if (!self::store_by_guid($match[1], $item["author-link"]))
1091 self::store_by_guid($match[1], $item["owner-link"]);
1095 * @brief Fetches an item with a given guid from a given server
1097 * @param string $guid the message guid
1098 * @param string $server The server address
1099 * @param int $uid The user id of the user
1101 * @return int the message id of the stored message or false
1103 private static function store_by_guid($guid, $server, $uid = 0) {
1104 $serverparts = parse_url($server);
1105 $server = $serverparts["scheme"]."://".$serverparts["host"];
1107 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1109 $msg = self::message($guid, $server);
1114 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1116 // Now call the dispatcher
1117 return self::dispatch_public($msg);
1121 * @brief Fetches a message from a server
1123 * @param string $guid message guid
1124 * @param string $server The url of the server
1125 * @param int $level Endless loop prevention
1128 * 'message' => The message XML
1129 * 'author' => The author handle
1130 * 'key' => The public key of the author
1132 private static function message($guid, $server, $level = 0) {
1137 // This will work for new Diaspora servers and Friendica servers from 3.5
1138 $source_url = $server."/fetch/post/".urlencode($guid);
1140 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1142 $envelope = fetch_url($source_url);
1144 logger("Envelope was fetched.", LOGGER_DEBUG);
1145 $x = self::verify_magic_envelope($envelope);
1147 logger("Envelope could not be verified.", LOGGER_DEBUG);
1149 logger("Envelope was verified.", LOGGER_DEBUG);
1153 // This will work for older Diaspora and Friendica servers
1155 $source_url = $server."/p/".urlencode($guid).".xml";
1156 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1158 $x = fetch_url($source_url);
1163 $source_xml = parse_xml_string($x);
1165 if (!is_object($source_xml))
1168 if ($source_xml->post->reshare) {
1169 // Reshare of a reshare - old Diaspora version
1170 logger("Message is a reshare", LOGGER_DEBUG);
1171 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1172 } elseif ($source_xml->getName() == "reshare") {
1173 // Reshare of a reshare - new Diaspora version
1174 logger("Message is a new reshare", LOGGER_DEBUG);
1175 return self::message($source_xml->root_guid, $server, ++$level);
1180 // Fetch the author - for the old and the new Diaspora version
1181 if ($source_xml->post->status_message->diaspora_handle)
1182 $author = (string)$source_xml->post->status_message->diaspora_handle;
1183 elseif ($source_xml->author && ($source_xml->getName() == "status_message"))
1184 $author = (string)$source_xml->author;
1186 // If this isn't a "status_message" then quit
1188 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1192 $msg = array("message" => $x, "author" => $author);
1194 $msg["key"] = self::key($msg["author"]);
1200 * @brief Fetches the item record of a given guid
1202 * @param int $uid The user id
1203 * @param string $guid message guid
1204 * @param string $author The handle of the item
1205 * @param array $contact The contact of the item owner
1207 * @return array the item record
1209 private static function parent_item($uid, $guid, $author, $contact) {
1210 $r = q("SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1211 `author-name`, `author-link`, `author-avatar`,
1212 `owner-name`, `owner-link`, `owner-avatar`
1213 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1214 intval($uid), dbesc($guid));
1217 $result = self::store_by_guid($guid, $contact["url"], $uid);
1220 $person = self::person_by_handle($author);
1221 $result = self::store_by_guid($guid, $person["url"], $uid);
1225 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1227 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1228 `author-name`, `author-link`, `author-avatar`,
1229 `owner-name`, `owner-link`, `owner-avatar`
1230 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1231 intval($uid), dbesc($guid));
1236 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1239 logger("parent item found: parent: ".$guid." - user: ".$uid);
1245 * @brief returns contact details
1247 * @param array $contact The default contact if the person isn't found
1248 * @param array $person The record of the person
1249 * @param int $uid The user id
1252 * 'cid' => contact id
1253 * 'network' => network type
1255 private static function author_contact_by_url($contact, $person, $uid) {
1257 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1258 dbesc(normalise_link($person["url"])), intval($uid));
1261 $network = $r[0]["network"];
1263 // We are receiving content from a user that possibly is about to be terminated
1264 // This means the user is vital, so we remove a possible termination date.
1265 unmark_for_death($r[0]);
1267 $cid = $contact["id"];
1268 $network = NETWORK_DIASPORA;
1271 return array("cid" => $cid, "network" => $network);
1275 * @brief Is the profile a hubzilla profile?
1277 * @param string $url The profile link
1279 * @return bool is it a hubzilla server?
1281 public static function is_redmatrix($url) {
1282 return(strstr($url, "/channel/"));
1286 * @brief Generate a post link with a given handle and message guid
1288 * @param string $addr The user handle
1289 * @param string $guid message guid
1291 * @return string the post link
1293 private static function plink($addr, $guid, $parent_guid = '') {
1294 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1297 if (!dbm::is_result($r)) {
1298 if ($parent_guid != '') {
1299 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$parent_guid."#".$guid;
1301 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$guid;
1305 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1306 // So we try another way as well.
1307 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1308 if (dbm::is_result($s)) {
1309 $r[0]["network"] = $s[0]["network"];
1312 if ($r[0]["network"] == NETWORK_DFRN) {
1313 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1316 if (self::is_redmatrix($r[0]["url"])) {
1317 return $r[0]["url"]."/?f=&mid=".$guid;
1320 if ($parent_guid != '') {
1321 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$parent_guid."#".$guid;
1323 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1328 * @brief Receives account migration
1330 * @param array $importer Array of the importer user
1331 * @param object $data The message object
1333 * @return bool Success
1335 private static function receiveAccountMigration($importer, $data) {
1336 $old_handle = notags(unxmlify($data->author));
1337 $new_handle = notags(unxmlify($data->profile->author));
1338 $signature = notags(unxmlify($data->signature));
1340 $contact = self::contact_by_handle($importer["uid"], $old_handle);
1342 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1346 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1349 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1350 $key = self::key($old_handle);
1351 if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
1352 logger('No valid signature for migration.');
1356 // Update the profile
1357 self::receive_profile($importer, $data->profile);
1359 // change the technical stuff in contact and gcontact
1360 $data = Probe::uri($new_handle);
1361 if ($data['network'] == NETWORK_PHANTOM) {
1362 logger('Account for '.$new_handle." couldn't be probed.");
1366 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1367 'name' => $data['name'], 'nick' => $data['nick'],
1368 'addr' => $data['addr'], 'batch' => $data['batch'],
1369 'notify' => $data['notify'], 'poll' => $data['poll'],
1370 'network' => $data['network']);
1372 dba::update('contact', $fields, array('addr' => $old_handle));
1374 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1375 'name' => $data['name'], 'nick' => $data['nick'],
1376 'addr' => $data['addr'], 'connect' => $data['addr'],
1377 'notify' => $data['notify'], 'photo' => $data['photo'],
1378 'server_url' => $data['baseurl'], 'network' => $data['network']);
1380 dba::update('gcontact', $fields, array('addr' => $old_handle));
1382 logger('Contacts are updated.');
1385 /// @todo This is an extreme performance killer
1387 'owner-link' => array($contact["url"], $data["url"]),
1388 'author-link' => array($contact["url"], $data["url"]),
1390 foreach ($fields as $n=>$f) {
1391 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1393 intval($importer["uid"]));
1395 if (dbm::is_result($r)) {
1396 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1399 intval($importer["uid"]));
1407 logger('Items are updated.');
1413 * @brief Processes an account deletion
1415 * @param array $importer Array of the importer user
1416 * @param object $data The message object
1418 * @return bool Success
1420 private static function receive_account_deletion($importer, $data) {
1422 /// @todo Account deletion should remove the contact from the global contacts as well
1424 $author = notags(unxmlify($data->author));
1426 $contact = self::contact_by_handle($importer["uid"], $author);
1428 logger("cannot find contact for author: ".$author);
1432 // We now remove the contact
1433 contact_remove($contact["id"]);
1438 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1440 * @param string $author Author handle
1441 * @param string $guid Message guid
1442 * @param boolean $onlyfound Only return uri when found in the database
1444 * @return string The constructed uri or the one from our database
1446 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1448 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1449 if (dbm::is_result($r)) {
1450 return $r[0]["uri"];
1451 } elseif (!$onlyfound) {
1452 return $author.":".$guid;
1459 * @brief Fetch the guid from our database with a given uri
1461 * @param string $author Author handle
1462 * @param string $uri Message uri
1464 * @return string The post guid
1466 private static function get_guid_from_uri($uri, $uid) {
1468 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1469 if (dbm::is_result($r)) {
1470 return $r[0]["guid"];
1477 * @brief Find the best importer for a comment, like, ...
1479 * @param string $guid The guid of the item
1481 * @return array|boolean the origin owner of that post - or false
1483 private static function importer_for_guid($guid) {
1484 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1486 if (dbm::is_result($item)) {
1487 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1488 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1489 if (dbm::is_result($contact)) {
1497 * @brief Processes an incoming comment
1499 * @param array $importer Array of the importer user
1500 * @param string $sender The sender of the message
1501 * @param object $data The message object
1502 * @param string $xml The original XML of the message
1504 * @return int The message id of the generated comment or "false" if there was an error
1506 private static function receive_comment($importer, $sender, $data, $xml) {
1507 $author = notags(unxmlify($data->author));
1508 $guid = notags(unxmlify($data->guid));
1509 $parent_guid = notags(unxmlify($data->parent_guid));
1510 $text = unxmlify($data->text);
1512 if (isset($data->created_at)) {
1513 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1515 $created_at = datetime_convert();
1518 if (isset($data->thread_parent_guid)) {
1519 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1520 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1525 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1530 $message_id = self::message_exists($importer["uid"], $guid);
1535 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1536 if (!$parent_item) {
1540 $person = self::person_by_handle($author);
1541 if (!is_array($person)) {
1542 logger("unable to find author details");
1546 // Fetch the contact id - if we know this contact
1547 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1549 $datarray = array();
1551 $datarray["uid"] = $importer["uid"];
1552 $datarray["contact-id"] = $author_contact["cid"];
1553 $datarray["network"] = $author_contact["network"];
1555 $datarray["author-name"] = $person["name"];
1556 $datarray["author-link"] = $person["url"];
1557 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1559 $datarray["owner-name"] = $contact["name"];
1560 $datarray["owner-link"] = $contact["url"];
1561 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1563 $datarray["guid"] = $guid;
1564 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1566 $datarray["type"] = "remote-comment";
1567 $datarray["verb"] = ACTIVITY_POST;
1568 $datarray["gravity"] = GRAVITY_COMMENT;
1570 if ($thr_uri != "") {
1571 $datarray["parent-uri"] = $thr_uri;
1573 $datarray["parent-uri"] = $parent_item["uri"];
1576 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1578 $datarray["protocol"] = PROTOCOL_DIASPORA;
1579 $datarray["source"] = $xml;
1581 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1583 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1585 $body = diaspora2bb($text);
1587 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1589 self::fetch_guid($datarray);
1591 $message_id = item_store($datarray);
1593 if ($message_id <= 0) {
1598 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1601 // If we are the origin of the parent we store the original data and notify our followers
1602 if ($message_id && $parent_item["origin"]) {
1604 // Formerly we stored the signed text, the signature and the author in different fields.
1605 // We now store the raw data so that we are more flexible.
1606 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1609 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $message_id);
1616 * @brief processes and stores private messages
1618 * @param array $importer Array of the importer user
1619 * @param array $contact The contact of the message
1620 * @param object $data The message object
1621 * @param array $msg Array of the processed message, author handle and key
1622 * @param object $mesg The private message
1623 * @param array $conversation The conversation record to which this message belongs
1625 * @return bool "true" if it was successful
1627 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1628 $author = notags(unxmlify($data->author));
1629 $guid = notags(unxmlify($data->guid));
1630 $subject = notags(unxmlify($data->subject));
1632 // "diaspora_handle" is the element name from the old version
1633 // "author" is the element name from the new version
1634 if ($mesg->author) {
1635 $msg_author = notags(unxmlify($mesg->author));
1636 } elseif ($mesg->diaspora_handle) {
1637 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1642 $msg_guid = notags(unxmlify($mesg->guid));
1643 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1644 $msg_text = unxmlify($mesg->text);
1645 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1647 if ($msg_conversation_guid != $guid) {
1648 logger("message conversation guid does not belong to the current conversation.");
1652 $body = diaspora2bb($msg_text);
1653 $message_uri = $msg_author.":".$msg_guid;
1655 $person = self::person_by_handle($msg_author);
1659 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1661 intval($importer["uid"])
1663 if (dbm::is_result($r)) {
1664 logger("duplicate message already delivered.", LOGGER_DEBUG);
1668 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1669 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1670 intval($importer["uid"]),
1672 intval($conversation["id"]),
1673 dbesc($person["name"]),
1674 dbesc($person["photo"]),
1675 dbesc($person["url"]),
1676 intval($contact["id"]),
1681 dbesc($message_uri),
1682 dbesc($author.":".$guid),
1683 dbesc($msg_created_at)
1688 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1691 "type" => NOTIFY_MAIL,
1692 "notify_flags" => $importer["notify-flags"],
1693 "language" => $importer["language"],
1694 "to_name" => $importer["username"],
1695 "to_email" => $importer["email"],
1696 "uid" =>$importer["uid"],
1697 "item" => array("subject" => $subject, "body" => $body),
1698 "source_name" => $person["name"],
1699 "source_link" => $person["url"],
1700 "source_photo" => $person["thumb"],
1701 "verb" => ACTIVITY_POST,
1708 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1710 * @param array $importer Array of the importer user
1711 * @param array $msg Array of the processed message, author handle and key
1712 * @param object $data The message object
1714 * @return bool Success
1716 private static function receive_conversation($importer, $msg, $data) {
1717 $author = notags(unxmlify($data->author));
1718 $guid = notags(unxmlify($data->guid));
1719 $subject = notags(unxmlify($data->subject));
1720 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1721 $participants = notags(unxmlify($data->participants));
1723 $messages = $data->message;
1725 if (!count($messages)) {
1726 logger("empty conversation");
1730 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1734 $conversation = null;
1736 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1737 intval($importer["uid"]),
1741 $conversation = $c[0];
1743 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1744 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1745 intval($importer["uid"]),
1749 dbesc(datetime_convert()),
1751 dbesc($participants)
1754 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1755 intval($importer["uid"]),
1760 $conversation = $c[0];
1762 if (!$conversation) {
1763 logger("unable to create conversation.");
1767 foreach ($messages as $mesg)
1768 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1774 * @brief Creates the body for a "like" message
1776 * @param array $contact The contact that send us the "like"
1777 * @param array $parent_item The item array of the parent item
1778 * @param string $guid message guid
1780 * @return string the body
1782 private static function construct_like_body($contact, $parent_item, $guid) {
1783 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1785 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1786 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1787 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1789 return sprintf($bodyverb, $ulink, $alink, $plink);
1793 * @brief Creates a XML object for a "like"
1795 * @param array $importer Array of the importer user
1796 * @param array $parent_item The item array of the parent item
1798 * @return string The XML
1800 private static function construct_like_object($importer, $parent_item) {
1801 $objtype = ACTIVITY_OBJ_NOTE;
1802 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1803 $parent_body = $parent_item["body"];
1805 $xmldata = array("object" => array("type" => $objtype,
1807 "id" => $parent_item["uri"],
1810 "content" => $parent_body));
1812 return xml::from_array($xmldata, $xml, true);
1816 * @brief Processes "like" messages
1818 * @param array $importer Array of the importer user
1819 * @param string $sender The sender of the message
1820 * @param object $data The message object
1822 * @return int The message id of the generated like or "false" if there was an error
1824 private static function receive_like($importer, $sender, $data) {
1825 $author = notags(unxmlify($data->author));
1826 $guid = notags(unxmlify($data->guid));
1827 $parent_guid = notags(unxmlify($data->parent_guid));
1828 $parent_type = notags(unxmlify($data->parent_type));
1829 $positive = notags(unxmlify($data->positive));
1831 // likes on comments aren't supported by Diaspora - only on posts
1832 // But maybe this will be supported in the future, so we will accept it.
1833 if (!in_array($parent_type, array("Post", "Comment")))
1836 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1840 $message_id = self::message_exists($importer["uid"], $guid);
1844 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1848 $person = self::person_by_handle($author);
1849 if (!is_array($person)) {
1850 logger("unable to find author details");
1854 // Fetch the contact id - if we know this contact
1855 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1857 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1858 // We would accept this anyhow.
1859 if ($positive == "true")
1860 $verb = ACTIVITY_LIKE;
1862 $verb = ACTIVITY_DISLIKE;
1864 $datarray = array();
1866 $datarray["protocol"] = PROTOCOL_DIASPORA;
1868 $datarray["uid"] = $importer["uid"];
1869 $datarray["contact-id"] = $author_contact["cid"];
1870 $datarray["network"] = $author_contact["network"];
1872 $datarray["author-name"] = $person["name"];
1873 $datarray["author-link"] = $person["url"];
1874 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1876 $datarray["owner-name"] = $contact["name"];
1877 $datarray["owner-link"] = $contact["url"];
1878 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1880 $datarray["guid"] = $guid;
1881 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1883 $datarray["type"] = "activity";
1884 $datarray["verb"] = $verb;
1885 $datarray["gravity"] = GRAVITY_LIKE;
1886 $datarray["parent-uri"] = $parent_item["uri"];
1888 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1889 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1891 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1893 $message_id = item_store($datarray);
1895 if ($message_id <= 0) {
1900 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1903 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1904 if ($parent_item["id"] != $parent_item["parent"]) {
1905 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
1906 $origin = $toplevel["origin"];
1908 $origin = $parent_item["origin"];
1911 // If we are the origin of the parent we store the original data and notify our followers
1912 if ($message_id && $origin) {
1914 // Formerly we stored the signed text, the signature and the author in different fields.
1915 // We now store the raw data so that we are more flexible.
1916 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1919 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $message_id);
1926 * @brief Processes private messages
1928 * @param array $importer Array of the importer user
1929 * @param object $data The message object
1931 * @return bool Success?
1933 private static function receive_message($importer, $data) {
1934 $author = notags(unxmlify($data->author));
1935 $guid = notags(unxmlify($data->guid));
1936 $conversation_guid = notags(unxmlify($data->conversation_guid));
1937 $text = unxmlify($data->text);
1938 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1940 $contact = self::allowed_contact_by_handle($importer, $author, true);
1945 $conversation = null;
1947 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1948 intval($importer["uid"]),
1949 dbesc($conversation_guid)
1952 $conversation = $c[0];
1954 logger("conversation not available.");
1958 $message_uri = $author.":".$guid;
1960 $person = self::person_by_handle($author);
1962 logger("unable to find author details");
1966 $body = diaspora2bb($text);
1968 $body = self::replace_people_guid($body, $person["url"]);
1972 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1974 intval($importer["uid"])
1976 if (dbm::is_result($r)) {
1977 logger("duplicate message already delivered.", LOGGER_DEBUG);
1981 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1982 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1983 intval($importer["uid"]),
1985 intval($conversation["id"]),
1986 dbesc($person["name"]),
1987 dbesc($person["photo"]),
1988 dbesc($person["url"]),
1989 intval($contact["id"]),
1990 dbesc($conversation["subject"]),
1994 dbesc($message_uri),
1995 dbesc($author.":".$conversation["guid"]),
2001 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
2006 * @brief Processes participations - unsupported by now
2008 * @param array $importer Array of the importer user
2009 * @param object $data The message object
2011 * @return bool always true
2013 private static function receive_participation($importer, $data) {
2014 // I'm not sure if we can fully support this message type
2019 * @brief Processes photos - unneeded
2021 * @param array $importer Array of the importer user
2022 * @param object $data The message object
2024 * @return bool always true
2026 private static function receive_photo($importer, $data) {
2027 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
2032 * @brief Processes poll participations - unssupported
2034 * @param array $importer Array of the importer user
2035 * @param object $data The message object
2037 * @return bool always true
2039 private static function receive_poll_participation($importer, $data) {
2040 // We don't support polls by now
2045 * @brief Processes incoming profile updates
2047 * @param array $importer Array of the importer user
2048 * @param object $data The message object
2050 * @return bool Success
2052 private static function receive_profile($importer, $data) {
2053 $author = strtolower(notags(unxmlify($data->author)));
2055 $contact = self::contact_by_handle($importer["uid"], $author);
2059 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2060 $image_url = unxmlify($data->image_url);
2061 $birthday = unxmlify($data->birthday);
2062 $gender = unxmlify($data->gender);
2063 $about = diaspora2bb(unxmlify($data->bio));
2064 $location = diaspora2bb(unxmlify($data->location));
2065 $searchable = (unxmlify($data->searchable) == "true");
2066 $nsfw = (unxmlify($data->nsfw) == "true");
2067 $tags = unxmlify($data->tag_string);
2069 $tags = explode("#", $tags);
2071 $keywords = array();
2072 foreach ($tags as $tag) {
2073 $tag = trim(strtolower($tag));
2078 $keywords = implode(", ", $keywords);
2080 $handle_parts = explode("@", $author);
2081 $nick = $handle_parts[0];
2084 $name = $handle_parts[0];
2086 if ( preg_match("|^https?://|", $image_url) === 0)
2087 $image_url = "http://".$handle_parts[1].$image_url;
2089 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
2091 // Generic birthday. We don't know the timezone. The year is irrelevant.
2093 $birthday = str_replace("1000", "1901", $birthday);
2095 if ($birthday != "")
2096 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2098 // this is to prevent multiple birthday notifications in a single year
2099 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2101 if (substr($birthday,5) === substr($contact["bd"],5))
2102 $birthday = $contact["bd"];
2104 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2105 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2109 dbesc(datetime_convert()),
2115 intval($contact["id"]),
2116 intval($importer["uid"])
2119 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2120 "photo" => $image_url, "name" => $name, "location" => $location,
2121 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2122 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2123 "hide" => !$searchable, "nsfw" => $nsfw);
2125 $gcid = update_gcontact($gcontact);
2127 link_gcontact($gcid, $importer["uid"], $contact["id"]);
2129 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2135 * @brief Processes incoming friend requests
2137 * @param array $importer Array of the importer user
2138 * @param array $contact The contact that send the request
2140 private static function receive_request_make_friend($importer, $contact) {
2144 if ($contact["rel"] == CONTACT_IS_SHARING) {
2145 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2146 array('id' => $contact["id"], 'uid' => $importer["uid"]));
2148 // send notification
2150 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2151 intval($importer["uid"])
2154 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2156 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2157 intval($importer["uid"])
2160 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2162 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2165 $arr["protocol"] = PROTOCOL_DIASPORA;
2166 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2167 $arr["uid"] = $importer["uid"];
2168 $arr["contact-id"] = $self[0]["id"];
2170 $arr["type"] = 'wall';
2171 $arr["gravity"] = 0;
2173 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2174 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2175 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2176 $arr["verb"] = ACTIVITY_FRIEND;
2177 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2179 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2180 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2181 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2182 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2184 $arr["object"] = self::construct_new_friend_object($contact);
2186 $arr["last-child"] = 1;
2188 $arr["allow_cid"] = $user[0]["allow_cid"];
2189 $arr["allow_gid"] = $user[0]["allow_gid"];
2190 $arr["deny_cid"] = $user[0]["deny_cid"];
2191 $arr["deny_gid"] = $user[0]["deny_gid"];
2193 $i = item_store($arr);
2195 Worker::add(PRIORITY_HIGH, "notifier", "activity", $i);
2201 * @brief Creates a XML object for a "new friend" message
2203 * @param array $contact Array of the contact
2205 * @return string The XML
2207 private static function construct_new_friend_object($contact) {
2208 $objtype = ACTIVITY_OBJ_PERSON;
2209 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2210 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2212 $xmldata = array("object" => array("type" => $objtype,
2213 "title" => $contact["name"],
2214 "id" => $contact["url"]."/".$contact["name"],
2217 return xml::from_array($xmldata, $xml, true);
2221 * @brief Processes incoming sharing notification
2223 * @param array $importer Array of the importer user
2224 * @param object $data The message object
2226 * @return bool Success
2228 private static function receive_contact_request($importer, $data) {
2229 $author = unxmlify($data->author);
2230 $recipient = unxmlify($data->recipient);
2232 if (!$author || !$recipient) {
2236 // the current protocol version doesn't know these fields
2237 // That means that we will assume their existance
2238 if (isset($data->following)) {
2239 $following = (unxmlify($data->following) == "true");
2244 if (isset($data->sharing)) {
2245 $sharing = (unxmlify($data->sharing) == "true");
2250 $contact = self::contact_by_handle($importer["uid"],$author);
2252 // perhaps we were already sharing with this person. Now they're sharing with us.
2253 // That makes us friends.
2256 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2257 self::receive_request_make_friend($importer, $contact);
2259 // refetch the contact array
2260 $contact = self::contact_by_handle($importer["uid"],$author);
2262 // If we are now friends, we are sending a share message.
2263 // Normally we needn't to do so, but the first message could have been vanished.
2264 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2265 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2267 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2268 $ret = self::send_share($u[0], $contact);
2273 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2274 lose_follower($importer, $contact);
2279 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2280 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2282 } elseif (!$following && !$sharing) {
2283 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2285 } elseif (!$following && $sharing) {
2286 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2287 } elseif ($following && $sharing) {
2288 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2289 } elseif ($following && !$sharing) {
2290 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2293 $ret = self::person_by_handle($author);
2295 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2296 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2300 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2302 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2303 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2304 intval($importer["uid"]),
2305 dbesc($ret["network"]),
2306 dbesc($ret["addr"]),
2309 dbesc(normalise_link($ret["url"])),
2311 dbesc($ret["name"]),
2312 dbesc($ret["nick"]),
2313 dbesc($ret["photo"]),
2314 dbesc($ret["pubkey"]),
2315 dbesc($ret["notify"]),
2316 dbesc($ret["poll"]),
2321 // find the contact record we just created
2323 $contact_record = self::contact_by_handle($importer["uid"],$author);
2325 if (!$contact_record) {
2326 logger("unable to locate newly created contact record.");
2330 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2332 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2334 if (intval($def_gid))
2335 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2337 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2339 if ($importer["page-flags"] == PAGE_NORMAL) {
2341 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2343 $hash = random_string().(string)time(); // Generate a confirm_key
2345 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2346 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2347 intval($importer["uid"]),
2348 intval($contact_record["id"]),
2351 dbesc(t("Sharing notification from Diaspora network")),
2353 dbesc(datetime_convert())
2357 // automatic friend approval
2359 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2361 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2363 // technically they are sharing with us (CONTACT_IS_SHARING),
2364 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2365 // we are going to change the relationship and make them a follower.
2367 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following)
2368 $new_relation = CONTACT_IS_FRIEND;
2369 elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing)
2370 $new_relation = CONTACT_IS_SHARING;
2372 $new_relation = CONTACT_IS_FOLLOWER;
2374 $r = q("UPDATE `contact` SET `rel` = %d,
2382 intval($new_relation),
2383 dbesc(datetime_convert()),
2384 dbesc(datetime_convert()),
2385 intval($contact_record["id"])
2388 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2390 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2391 $ret = self::send_share($u[0], $contact_record);
2393 // Send the profile data, maybe it weren't transmitted before
2394 self::send_profile($importer["uid"], array($contact_record));
2402 * @brief Fetches a message with a given guid
2404 * @param string $guid message guid
2405 * @param string $orig_author handle of the original post
2406 * @param string $author handle of the sharer
2408 * @return array The fetched item
2410 private static function original_item($guid, $orig_author, $author) {
2412 // Do we already have this item?
2413 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2414 `author-name`, `author-link`, `author-avatar`
2415 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2418 if (dbm::is_result($r)) {
2419 logger("reshared message ".$guid." already exists on system.");
2421 // Maybe it is already a reshared item?
2422 // Then refetch the content, if it is a reshare from a reshare.
2423 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2424 if (self::is_reshare($r[0]["body"], true)) {
2426 } elseif (self::is_reshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2427 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2429 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2431 // Add OEmbed and other information to the body
2432 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2440 if (!dbm::is_result($r)) {
2441 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2442 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2443 $item_id = self::store_by_guid($guid, $server);
2446 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2447 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2448 $item_id = self::store_by_guid($guid, $server);
2452 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2453 `author-name`, `author-link`, `author-avatar`
2454 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2457 if (dbm::is_result($r)) {
2458 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2459 if (self::is_reshare($r[0]["body"], false)) {
2460 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2461 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2473 * @brief Processes a reshare message
2475 * @param array $importer Array of the importer user
2476 * @param object $data The message object
2477 * @param string $xml The original XML of the message
2479 * @return int the message id
2481 private static function receive_reshare($importer, $data, $xml) {
2482 $author = notags(unxmlify($data->author));
2483 $guid = notags(unxmlify($data->guid));
2484 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2485 $root_author = notags(unxmlify($data->root_author));
2486 $root_guid = notags(unxmlify($data->root_guid));
2487 /// @todo handle unprocessed property "provider_display_name"
2488 $public = notags(unxmlify($data->public));
2490 $contact = self::allowed_contact_by_handle($importer, $author, false);
2495 $message_id = self::message_exists($importer["uid"], $guid);
2500 $original_item = self::original_item($root_guid, $root_author, $author);
2501 if (!$original_item) {
2505 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2507 $datarray = array();
2509 $datarray["uid"] = $importer["uid"];
2510 $datarray["contact-id"] = $contact["id"];
2511 $datarray["network"] = NETWORK_DIASPORA;
2513 $datarray["author-name"] = $contact["name"];
2514 $datarray["author-link"] = $contact["url"];
2515 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2517 $datarray["owner-name"] = $datarray["author-name"];
2518 $datarray["owner-link"] = $datarray["author-link"];
2519 $datarray["owner-avatar"] = $datarray["author-avatar"];
2521 $datarray["guid"] = $guid;
2522 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2524 $datarray["verb"] = ACTIVITY_POST;
2525 $datarray["gravity"] = GRAVITY_PARENT;
2527 $datarray["protocol"] = PROTOCOL_DIASPORA;
2528 $datarray["source"] = $xml;
2530 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2531 $original_item["guid"], $original_item["created"], $orig_url);
2532 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2534 $datarray["tag"] = $original_item["tag"];
2535 $datarray["app"] = $original_item["app"];
2537 $datarray["plink"] = self::plink($author, $guid);
2538 $datarray["private"] = (($public == "false") ? 1 : 0);
2539 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2541 $datarray["object-type"] = $original_item["object-type"];
2543 self::fetch_guid($datarray);
2544 $message_id = item_store($datarray);
2547 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2555 * @brief Processes retractions
2557 * @param array $importer Array of the importer user
2558 * @param array $contact The contact of the item owner
2559 * @param object $data The message object
2561 * @return bool success
2563 private static function item_retraction($importer, $contact, $data) {
2564 $author = notags(unxmlify($data->author));
2565 $target_guid = notags(unxmlify($data->target_guid));
2566 $target_type = notags(unxmlify($data->target_type));
2568 $person = self::person_by_handle($author);
2569 if (!is_array($person)) {
2570 logger("unable to find author detail for ".$author);
2574 if (empty($contact["url"])) {
2575 $contact["url"] = $person["url"];
2578 // Fetch items that are about to be deleted
2579 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2581 // When we receive a public retraction, we delete every item that we find.
2582 if ($importer['uid'] == 0) {
2583 $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2585 $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2587 $r = dba::select('item', $fields, $condition);
2588 if (!dbm::is_result($r)) {
2589 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2593 while ($item = dba::fetch($r)) {
2594 // Fetch the parent item
2595 $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2597 // Only delete it if the parent author really fits
2598 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2599 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2603 // 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
2604 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
2605 'edited' => datetime_convert(), 'changed' => datetime_convert()),
2606 array('id' => $item["id"]));
2608 // Delete the thread - if it is a starting post and not a comment
2609 if ($target_type != 'Comment') {
2610 delete_thread($item["id"], $item["parent-uri"]);
2613 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2615 // Now check if the retraction needs to be relayed by us
2616 if ($parent["origin"]) {
2618 Worker::add(PRIORITY_HIGH, "notifier", "drop", $item["id"]);
2626 * @brief Receives retraction messages
2628 * @param array $importer Array of the importer user
2629 * @param string $sender The sender of the message
2630 * @param object $data The message object
2632 * @return bool Success
2634 private static function receive_retraction($importer, $sender, $data) {
2635 $target_type = notags(unxmlify($data->target_type));
2637 $contact = self::contact_by_handle($importer["uid"], $sender);
2638 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2639 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2643 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2645 switch ($target_type) {
2650 case "StatusMessage":
2651 return self::item_retraction($importer, $contact, $data);
2655 /// @todo What should we do with an "unshare"?
2656 // Removing the contact isn't correct since we still can read the public items
2657 contact_remove($contact["id"]);
2661 logger("Unknown target type ".$target_type);
2668 * @brief Receives status messages
2670 * @param array $importer Array of the importer user
2671 * @param object $data The message object
2672 * @param string $xml The original XML of the message
2674 * @return int The message id of the newly created item
2676 private static function receive_status_message($importer, $data, $xml) {
2677 $author = notags(unxmlify($data->author));
2678 $guid = notags(unxmlify($data->guid));
2679 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2680 $public = notags(unxmlify($data->public));
2681 $text = unxmlify($data->text);
2682 $provider_display_name = notags(unxmlify($data->provider_display_name));
2684 $contact = self::allowed_contact_by_handle($importer, $author, false);
2689 $message_id = self::message_exists($importer["uid"], $guid);
2695 if ($data->location) {
2696 foreach ($data->location->children() AS $fieldname => $data) {
2697 $address[$fieldname] = notags(unxmlify($data));
2701 $body = diaspora2bb($text);
2703 $datarray = array();
2705 // Attach embedded pictures to the body
2707 foreach ($data->photo AS $photo) {
2708 $body = "[img]".unxmlify($photo->remote_photo_path).
2709 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2712 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2714 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2716 // Add OEmbed and other information to the body
2717 if (!self::is_redmatrix($contact["url"])) {
2718 $body = add_page_info_to_body($body, false, true);
2722 /// @todo enable support for polls
2723 //if ($data->poll) {
2724 // foreach ($data->poll AS $poll)
2729 /// @todo enable support for events
2731 $datarray["uid"] = $importer["uid"];
2732 $datarray["contact-id"] = $contact["id"];
2733 $datarray["network"] = NETWORK_DIASPORA;
2735 $datarray["author-name"] = $contact["name"];
2736 $datarray["author-link"] = $contact["url"];
2737 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2739 $datarray["owner-name"] = $datarray["author-name"];
2740 $datarray["owner-link"] = $datarray["author-link"];
2741 $datarray["owner-avatar"] = $datarray["author-avatar"];
2743 $datarray["guid"] = $guid;
2744 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2746 $datarray["verb"] = ACTIVITY_POST;
2747 $datarray["gravity"] = GRAVITY_PARENT;
2749 $datarray["protocol"] = PROTOCOL_DIASPORA;
2750 $datarray["source"] = $xml;
2752 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2754 if ($provider_display_name != "") {
2755 $datarray["app"] = $provider_display_name;
2758 $datarray["plink"] = self::plink($author, $guid);
2759 $datarray["private"] = (($public == "false") ? 1 : 0);
2760 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2762 if (isset($address["address"])) {
2763 $datarray["location"] = $address["address"];
2766 if (isset($address["lat"]) && isset($address["lng"])) {
2767 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2770 self::fetch_guid($datarray);
2771 $message_id = item_store($datarray);
2774 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2781 /* ************************************************************************************** *
2782 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2783 * ************************************************************************************** */
2786 * @brief returnes the handle of a contact
2788 * @param array $me contact array
2790 * @return string the handle in the format user@domain.tld
2792 private static function my_handle($contact) {
2793 if ($contact["addr"] != "") {
2794 return $contact["addr"];
2797 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2798 // So - just in case - we build the the address here.
2799 if ($contact["nickname"] != "") {
2800 $nick = $contact["nickname"];
2802 $nick = $contact["nick"];
2805 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(),"://") + 3);
2810 * @brief Creates the data for a private message in the new format
2812 * @param string $msg The message that is to be transmitted
2813 * @param array $user The record of the sender
2814 * @param array $contact Target of the communication
2815 * @param string $prvkey The private key of the sender
2816 * @param string $pubkey The public key of the receiver
2818 * @return string The encrypted data
2820 public static function encode_private_data($msg, $user, $contact, $prvkey, $pubkey) {
2822 logger("Message: ".$msg, LOGGER_DATA);
2824 // without a public key nothing will work
2826 logger("pubkey missing: contact id: ".$contact["id"]);
2830 $aes_key = openssl_random_pseudo_bytes(32);
2831 $b_aes_key = base64_encode($aes_key);
2832 $iv = openssl_random_pseudo_bytes(16);
2833 $b_iv = base64_encode($iv);
2835 $ciphertext = self::aes_encrypt($aes_key, $iv, $msg);
2837 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2839 $encrypted_key_bundle = "";
2840 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2842 $json_object = json_encode(array("aes_key" => base64_encode($encrypted_key_bundle),
2843 "encrypted_magic_envelope" => base64_encode($ciphertext)));
2845 return $json_object;
2849 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2851 * @param string $msg The message that is to be transmitted
2852 * @param array $user The record of the sender
2854 * @return string The envelope
2856 public static function build_magic_envelope($msg, $user) {
2858 $b64url_data = base64url_encode($msg);
2859 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2861 $key_id = base64url_encode(self::my_handle($user));
2862 $type = "application/xml";
2863 $encoding = "base64url";
2864 $alg = "RSA-SHA256";
2865 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2867 // Fallback if the private key wasn't transmitted in the expected field
2868 if ($user['uprvkey'] == "")
2869 $user['uprvkey'] = $user['prvkey'];
2871 $signature = rsa_sign($signable_data, $user["uprvkey"]);
2872 $sig = base64url_encode($signature);
2874 $xmldata = array("me:env" => array("me:data" => $data,
2875 "@attributes" => array("type" => $type),
2876 "me:encoding" => $encoding,
2879 "@attributes2" => array("key_id" => $key_id)));
2881 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2883 return xml::from_array($xmldata, $xml, false, $namespaces);
2887 * @brief Create the envelope for a message
2889 * @param string $msg The message that is to be transmitted
2890 * @param array $user The record of the sender
2891 * @param array $contact Target of the communication
2892 * @param string $prvkey The private key of the sender
2893 * @param string $pubkey The public key of the receiver
2894 * @param bool $public Is the message public?
2896 * @return string The message that will be transmitted to other servers
2898 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2900 // The message is put into an envelope with the sender's signature
2901 $envelope = self::build_magic_envelope($msg, $user);
2903 // Private messages are put into a second envelope, encrypted with the receivers public key
2905 $envelope = self::encode_private_data($envelope, $user, $contact, $prvkey, $pubkey);
2912 * @brief Creates a signature for a message
2914 * @param array $owner the array of the owner of the message
2915 * @param array $message The message that is to be signed
2917 * @return string The signature
2919 private static function signature($owner, $message) {
2921 unset($sigmsg["author_signature"]);
2922 unset($sigmsg["parent_author_signature"]);
2924 $signed_text = implode(";", $sigmsg);
2926 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2930 * @brief Transmit a message to a target server
2932 * @param array $owner the array of the item owner
2933 * @param array $contact Target of the communication
2934 * @param string $envelope The message that is to be transmitted
2935 * @param bool $public_batch Is it a public post?
2936 * @param bool $queue_run Is the transmission called from the queue?
2937 * @param string $guid message guid
2939 * @return int Result of the transmission
2941 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run=false, $guid = "") {
2945 $enabled = intval(Config::get("system", "diaspora_enabled"));
2949 $logid = random_string(4);
2950 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2952 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2956 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2958 if (!$queue_run && was_recently_delayed($contact["id"])) {
2961 if (!intval(Config::get("system", "diaspora_test"))) {
2962 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
2964 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
2965 $return_code = $a->get_curl_code();
2967 logger("test_mode");
2972 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2974 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2975 logger("queue message");
2977 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2978 intval($contact["id"]),
2979 dbesc(NETWORK_DIASPORA),
2981 intval($public_batch)
2984 logger("add_to_queue ignored - identical item already in queue");
2986 // queue message for redelivery
2987 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
2989 // The message could not be delivered. We mark the contact as "dead"
2990 mark_for_death($contact);
2992 } elseif (($return_code >= 200) && ($return_code <= 299)) {
2993 // We successfully delivered a message, the contact is alive
2994 unmark_for_death($contact);
2997 return(($return_code) ? $return_code : (-1));
3002 * @brief Build the post xml
3004 * @param string $type The message type
3005 * @param array $message The message data
3007 * @return string The post XML
3009 public static function build_post_xml($type, $message) {
3011 $data = array($type => $message);
3013 return xml::from_array($data, $xml);
3017 * @brief Builds and transmit messages
3019 * @param array $owner the array of the item owner
3020 * @param array $contact Target of the communication
3021 * @param string $type The message type
3022 * @param array $message The message data
3023 * @param bool $public_batch Is it a public post?
3024 * @param string $guid message guid
3025 * @param bool $spool Should the transmission be spooled or transmitted?
3027 * @return int Result of the transmission
3029 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
3031 $msg = self::build_post_xml($type, $message);
3033 logger('message: '.$msg, LOGGER_DATA);
3034 logger('send guid '.$guid, LOGGER_DEBUG);
3036 // Fallback if the private key wasn't transmitted in the expected field
3037 if ($owner['uprvkey'] == "")
3038 $owner['uprvkey'] = $owner['prvkey'];
3040 $envelope = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3043 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3046 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3048 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3050 return $return_code;
3054 * @brief sends an account migration
3056 * @param array $owner the array of the item owner
3057 * @param array $contact Target of the communication
3058 * @param int $uid User ID
3060 * @return int The result of the transmission
3062 public static function sendAccountMigration($owner, $contact, $uid) {
3064 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3065 $profile = self::createProfileData($uid);
3067 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3068 $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3070 $message = array("author" => $old_handle,
3071 "profile" => $profile,
3072 "signature" => $signature);
3074 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3076 return self::build_and_transmit($owner, $contact, "account_migration", $message);
3080 * @brief Sends a "share" message
3082 * @param array $owner the array of the item owner
3083 * @param array $contact Target of the communication
3085 * @return int The result of the transmission
3087 public static function send_share($owner, $contact) {
3090 * @todo support the different possible combinations of "following" and "sharing"
3091 * Currently, Diaspora only interprets the "sharing" field
3093 * Before switching this code productive, we have to check all "send_share" calls if "rel" is set correctly
3097 switch ($contact["rel"]) {
3098 case CONTACT_IS_FRIEND:
3101 case CONTACT_IS_SHARING:
3104 case CONTACT_IS_FOLLOWER:
3110 $message = array("author" => self::my_handle($owner),
3111 "recipient" => $contact["addr"],
3112 "following" => "true",
3113 "sharing" => "true");
3115 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3117 return self::build_and_transmit($owner, $contact, "contact", $message);
3121 * @brief sends an "unshare"
3123 * @param array $owner the array of the item owner
3124 * @param array $contact Target of the communication
3126 * @return int The result of the transmission
3128 public static function send_unshare($owner, $contact) {
3130 $message = array("author" => self::my_handle($owner),
3131 "recipient" => $contact["addr"],
3132 "following" => "false",
3133 "sharing" => "false");
3135 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3137 return self::build_and_transmit($owner, $contact, "contact", $message);
3141 * @brief Checks a message body if it is a reshare
3143 * @param string $body The message body that is to be check
3144 * @param bool $complete Should it be a complete check or a simple check?
3146 * @return array|bool Reshare details or "false" if no reshare
3148 public static function is_reshare($body, $complete = true) {
3149 $body = trim($body);
3151 // Skip if it isn't a pure repeated messages
3152 // Does it start with a share?
3153 if ((strpos($body, "[share") > 0) && $complete)
3156 // Does it end with a share?
3157 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3160 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3161 // Skip if there is no shared message in there
3162 if ($body == $attributes)
3165 // If we don't do the complete check we quit here
3170 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3171 if ($matches[1] != "")
3172 $guid = $matches[1];
3174 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3175 if ($matches[1] != "")
3176 $guid = $matches[1];
3179 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3180 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3183 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3184 $ret["root_guid"] = $guid;
3190 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3191 if ($matches[1] != "")
3192 $profile = $matches[1];
3194 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3195 if ($matches[1] != "")
3196 $profile = $matches[1];
3200 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3201 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == ""))
3205 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3206 if ($matches[1] != "")
3207 $link = $matches[1];
3209 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3210 if ($matches[1] != "")
3211 $link = $matches[1];
3213 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3214 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == ""))
3221 * @brief Create an event array
3223 * @param integer $event_id The id of the event
3225 * @return array with event data
3227 private static function build_event($event_id) {
3229 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3230 if (!dbm::is_result($r)) {
3236 $eventdata = array();
3238 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3239 if (!dbm::is_result($r)) {
3245 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3246 if (!dbm::is_result($r)) {
3252 $eventdata['author'] = self::my_handle($owner);
3254 if ($event['guid']) {
3255 $eventdata['guid'] = $event['guid'];
3258 $mask = 'Y-m-d\TH:i:s\Z';
3260 /// @todo - establish "all day" events in Friendica
3261 $eventdata["all_day"] = "false";
3263 if (!$event['adjust']) {
3264 $eventdata['timezone'] = $user['timezone'];
3266 if ($eventdata['timezone'] == "") {
3267 $eventdata['timezone'] = 'UTC';
3271 if ($event['start']) {
3272 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3274 if ($event['finish'] && !$event['nofinish']) {
3275 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3277 if ($event['summary']) {
3278 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3280 if ($event['desc']) {
3281 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3283 if ($event['location']) {
3284 $location = array();
3285 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3286 $location["lat"] = 0;
3287 $location["lng"] = 0;
3288 $eventdata['location'] = $location;
3295 * @brief Create a post (status message or reshare)
3297 * @param array $item The item that will be exported
3298 * @param array $owner the array of the item owner
3301 * 'type' -> Message type ("status_message" or "reshare")
3302 * 'message' -> Array of XML elements of the status
3304 public static function build_status($item, $owner) {
3306 $cachekey = "diaspora:build_status:".$item['guid'];
3308 $result = Cache::get($cachekey);
3309 if (!is_null($result)) {
3313 $myaddr = self::my_handle($owner);
3315 $public = (($item["private"]) ? "false" : "true");
3317 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3319 // Detect a share element and do a reshare
3320 if (!$item['private'] && ($ret = self::is_reshare($item["body"]))) {
3321 $message = array("author" => $myaddr,
3322 "guid" => $item["guid"],
3323 "created_at" => $created,
3324 "root_author" => $ret["root_handle"],
3325 "root_guid" => $ret["root_guid"],
3326 "provider_display_name" => $item["app"],
3327 "public" => $public);
3331 $title = $item["title"];
3332 $body = $item["body"];
3334 // convert to markdown
3335 $body = html_entity_decode(bb2diaspora($body));
3339 $body = "## ".html_entity_decode($title)."\n\n".$body;
3341 if ($item["attach"]) {
3342 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3344 $body .= "\n".t("Attachments:")."\n";
3345 foreach ($matches as $mtch)
3346 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3350 $location = array();
3352 if ($item["location"] != "")
3353 $location["address"] = $item["location"];
3355 if ($item["coord"] != "") {
3356 $coord = explode(" ", $item["coord"]);
3357 $location["lat"] = $coord[0];
3358 $location["lng"] = $coord[1];
3361 $message = array("author" => $myaddr,
3362 "guid" => $item["guid"],
3363 "created_at" => $created,
3364 "public" => $public,
3366 "provider_display_name" => $item["app"],
3367 "location" => $location);
3369 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3370 if (!isset($location["lat"]) || !isset($location["lng"])) {
3371 unset($message["location"]);
3374 if ($item['event-id'] > 0) {
3375 $event = self::build_event($item['event-id']);
3376 if (count($event)) {
3377 $message['event'] = $event;
3379 /// @todo Once Diaspora supports it, we will remove the body
3380 // $message['text'] = '';
3384 $type = "status_message";
3387 $msg = array("type" => $type, "message" => $message);
3389 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3395 * @brief Sends a post
3397 * @param array $item The item that will be exported
3398 * @param array $owner the array of the item owner
3399 * @param array $contact Target of the communication
3400 * @param bool $public_batch Is it a public post?
3402 * @return int The result of the transmission
3404 public static function send_status($item, $owner, $contact, $public_batch = false) {
3406 $status = self::build_status($item, $owner);
3408 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3412 * @brief Creates a "like" object
3414 * @param array $item The item that will be exported
3415 * @param array $owner the array of the item owner
3417 * @return array The data for a "like"
3419 private static function construct_like($item, $owner) {
3421 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3422 dbesc($item["thr-parent"]));
3423 if (!dbm::is_result($p))
3428 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3429 if ($item['verb'] === ACTIVITY_LIKE) {
3431 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3432 $positive = "false";
3435 return(array("author" => self::my_handle($owner),
3436 "guid" => $item["guid"],
3437 "parent_guid" => $parent["guid"],
3438 "parent_type" => $target_type,
3439 "positive" => $positive,
3440 "author_signature" => ""));
3444 * @brief Creates an "EventParticipation" object
3446 * @param array $item The item that will be exported
3447 * @param array $owner the array of the item owner
3449 * @return array The data for an "EventParticipation"
3451 private static function construct_attend($item, $owner) {
3453 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3454 dbesc($item["thr-parent"]));
3455 if (!dbm::is_result($p))
3460 switch ($item['verb']) {
3461 case ACTIVITY_ATTEND:
3462 $attend_answer = 'accepted';
3464 case ACTIVITY_ATTENDNO:
3465 $attend_answer = 'declined';
3467 case ACTIVITY_ATTENDMAYBE:
3468 $attend_answer = 'tentative';
3471 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3475 return(array("author" => self::my_handle($owner),
3476 "guid" => $item["guid"],
3477 "parent_guid" => $parent["guid"],
3478 "status" => $attend_answer,
3479 "author_signature" => ""));
3483 * @brief Creates the object for a comment
3485 * @param array $item The item that will be exported
3486 * @param array $owner the array of the item owner
3488 * @return array The data for a comment
3490 private static function construct_comment($item, $owner) {
3492 $cachekey = "diaspora:construct_comment:".$item['guid'];
3494 $result = Cache::get($cachekey);
3495 if (!is_null($result)) {
3499 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3500 intval($item["parent"]),
3501 intval($item["parent"])
3504 if (!dbm::is_result($p))
3509 $text = html_entity_decode(bb2diaspora($item["body"]));
3510 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3512 $comment = array("author" => self::my_handle($owner),
3513 "guid" => $item["guid"],
3514 "created_at" => $created,
3515 "parent_guid" => $parent["guid"],
3517 "author_signature" => "");
3519 // Send the thread parent guid only if it is a threaded comment
3520 if ($item['thr-parent'] != $item['parent-uri']) {
3521 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3524 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3530 * @brief Send a like or a comment
3532 * @param array $item The item that will be exported
3533 * @param array $owner the array of the item owner
3534 * @param array $contact Target of the communication
3535 * @param bool $public_batch Is it a public post?
3537 * @return int The result of the transmission
3539 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3541 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3542 $message = self::construct_attend($item, $owner);
3543 $type = "event_participation";
3544 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3545 $message = self::construct_like($item, $owner);
3548 $message = self::construct_comment($item, $owner);
3555 $message["author_signature"] = self::signature($owner, $message);
3557 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3561 * @brief Creates a message from a signature record entry
3563 * @param array $item The item that will be exported
3564 * @param array $signature The entry of the "sign" record
3566 * @return string The message
3568 private static function message_from_signature($item, $signature) {
3570 // Split the signed text
3571 $signed_parts = explode(";", $signature['signed_text']);
3573 if ($item["deleted"]) {
3574 $message = array("author" => $signature['signer'],
3575 "target_guid" => $signed_parts[0],
3576 "target_type" => $signed_parts[1]);
3577 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3578 $message = array("author" => $signed_parts[4],
3579 "guid" => $signed_parts[1],
3580 "parent_guid" => $signed_parts[3],
3581 "parent_type" => $signed_parts[2],
3582 "positive" => $signed_parts[0],
3583 "author_signature" => $signature['signature'],
3584 "parent_author_signature" => "");
3586 // Remove the comment guid
3587 $guid = array_shift($signed_parts);
3589 // Remove the parent guid
3590 $parent_guid = array_shift($signed_parts);
3592 // Remove the handle
3593 $handle = array_pop($signed_parts);
3595 // Glue the parts together
3596 $text = implode(";", $signed_parts);
3598 $message = array("author" => $handle,
3600 "parent_guid" => $parent_guid,
3601 "text" => implode(";", $signed_parts),
3602 "author_signature" => $signature['signature'],
3603 "parent_author_signature" => "");
3609 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3611 * @param array $item The item that will be exported
3612 * @param array $owner the array of the item owner
3613 * @param array $contact Target of the communication
3614 * @param bool $public_batch Is it a public post?
3616 * @return int The result of the transmission
3618 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3620 if ($item["deleted"]) {
3621 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3622 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3628 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3630 // fetch the original signature
3632 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3633 intval($item["id"]));
3636 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3642 // Old way - is used by the internal Friendica functions
3643 /// @todo Change all signatur storing functions to the new format
3644 if ($signature['signed_text'] && $signature['signature'] && $signature['signer'])
3645 $message = self::message_from_signature($item, $signature);
3647 $msg = json_decode($signature['signed_text'], true);
3650 if (is_array($msg)) {
3651 foreach ($msg AS $field => $data) {
3652 if (!$item["deleted"]) {
3653 if ($field == "diaspora_handle") {
3656 if ($field == "target_type") {
3657 $field = "parent_type";
3661 $message[$field] = $data;
3664 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3667 $message["parent_author_signature"] = self::signature($owner, $message);
3669 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3671 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3675 * @brief Sends a retraction (deletion) of a message, like or comment
3677 * @param array $item The item that will be exported
3678 * @param array $owner the array of the item owner
3679 * @param array $contact Target of the communication
3680 * @param bool $public_batch Is it a public post?
3681 * @param bool $relay Is the retraction transmitted from a relay?
3683 * @return int The result of the transmission
3685 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3687 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3689 $msg_type = "retraction";
3691 if ($item['id'] == $item['parent']) {
3692 $target_type = "Post";
3693 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3694 $target_type = "Like";
3696 $target_type = "Comment";
3699 $message = array("author" => $itemaddr,
3700 "target_guid" => $item['guid'],
3701 "target_type" => $target_type);
3703 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3705 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3709 * @brief Sends a mail
3711 * @param array $item The item that will be exported
3712 * @param array $owner The owner
3713 * @param array $contact Target of the communication
3715 * @return int The result of the transmission
3717 public static function send_mail($item, $owner, $contact) {
3719 $myaddr = self::my_handle($owner);
3721 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3722 intval($item["convid"]),
3723 intval($item["uid"])
3726 if (!dbm::is_result($r)) {
3727 logger("conversation not found.");
3733 "author" => $cnv["creator"],
3734 "guid" => $cnv["guid"],
3735 "subject" => $cnv["subject"],
3736 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3737 "participants" => $cnv["recips"]
3740 $body = bb2diaspora($item["body"]);
3741 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3744 "author" => $myaddr,
3745 "guid" => $item["guid"],
3746 "conversation_guid" => $cnv["guid"],
3748 "created_at" => $created,
3751 if ($item["reply"]) {
3756 "author" => $cnv["creator"],
3757 "guid" => $cnv["guid"],
3758 "subject" => $cnv["subject"],
3759 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3760 "participants" => $cnv["recips"],
3763 $type = "conversation";
3766 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3770 * @brief Create profile data
3772 * @param int $uid The user id
3774 * @return array The profile data
3776 private static function createProfileData($uid) {
3777 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3779 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3780 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3781 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3791 $handle = $profile["addr"];
3792 $first = ((strpos($profile['name'],' ')
3793 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3794 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3795 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3796 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3797 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3798 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3800 if ($searchable === 'true') {
3801 $dob = '1000-00-00';
3803 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3804 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3806 $about = $profile['about'];
3807 $about = strip_tags(bbcode($about));
3809 $location = formatted_location($profile);
3811 if ($profile['pub_keywords']) {
3812 $kw = str_replace(',',' ',$profile['pub_keywords']);
3813 $kw = str_replace(' ',' ',$kw);
3814 $arr = explode(' ',$profile['pub_keywords']);
3816 for ($x = 0; $x < 5; $x ++) {
3818 $tags .= '#'. trim($arr[$x]) .' ';
3822 $tags = trim($tags);
3825 return array("author" => $handle,
3826 "first_name" => $first,
3827 "last_name" => $last,
3828 "image_url" => $large,
3829 "image_url_medium" => $medium,
3830 "image_url_small" => $small,
3832 "gender" => $profile['gender'],
3834 "location" => $location,
3835 "searchable" => $searchable,
3837 "tag_string" => $tags);
3841 * @brief Sends profile data
3843 * @param int $uid The user id
3845 public static function send_profile($uid, $recips = false) {
3851 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3852 AND `uid` = %d AND `rel` != %d",
3853 dbesc(NETWORK_DIASPORA),
3855 intval(CONTACT_IS_SHARING)
3860 $message = self::createProfileData($uid);
3862 foreach ($recips as $recip) {
3863 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3864 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3869 * @brief Stores the signature for likes that are created on our system
3871 * @param array $contact The contact array of the "like"
3872 * @param int $post_id The post id of the "like"
3874 * @return bool Success
3876 public static function store_like_signature($contact, $post_id) {
3878 // Is the contact the owner? Then fetch the private key
3879 if (!$contact['self'] || ($contact['uid'] == 0)) {
3880 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3884 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3885 if (!dbm::is_result($r)) {
3889 $contact["uprvkey"] = $r[0]['prvkey'];
3891 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3892 if (!dbm::is_result($r)) {
3896 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3900 $message = self::construct_like($r[0], $contact);
3901 $message["author_signature"] = self::signature($contact, $message);
3904 * Now store the signature more flexible to dynamically support new fields.
3905 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3907 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
3909 logger('Stored diaspora like signature');
3914 * @brief Stores the signature for comments that are created on our system
3916 * @param array $item The item array of the comment
3917 * @param array $contact The contact array of the item owner
3918 * @param string $uprvkey The private key of the sender
3919 * @param int $message_id The message id of the comment
3921 * @return bool Success
3923 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3925 if ($uprvkey == "") {
3926 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3930 $contact["uprvkey"] = $uprvkey;
3932 $message = self::construct_comment($item, $contact);
3933 $message["author_signature"] = self::signature($contact, $message);
3936 * Now store the signature more flexible to dynamically support new fields.
3937 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3939 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
3941 logger('Stored diaspora comment signature');