3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "valid_posting" and interpret only the new protocol.
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
15 require_once 'include/items.php';
16 require_once 'include/bb2diaspora.php';
17 require_once 'include/probe.php';
18 require_once 'include/Contact.php';
19 require_once 'include/Photo.php';
20 require_once 'include/socgraph.php';
21 require_once 'include/group.php';
22 require_once 'include/xml.php';
23 require_once 'include/datetime.php';
24 require_once 'include/queue_fn.php';
25 require_once 'include/cache.php';
28 * @brief This class contain functions to create and send Diaspora XML files
34 * @brief Return a list of relay servers
36 * This is an experimental Diaspora feature.
38 * @return array of relay servers
40 public static function relay_list() {
42 $serverdata = get_config("system", "relay_server");
43 if ($serverdata == "")
48 $servers = explode(",", $serverdata);
50 foreach ($servers AS $server) {
51 $server = trim($server);
52 $addr = "relay@".str_replace("http://", "", normalise_link($server));
53 $batch = $server."/receive/public";
55 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
56 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
59 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
60 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
65 dbesc(normalise_link($server)),
67 dbesc(NETWORK_DIASPORA),
68 intval(CONTACT_IS_FOLLOWER),
69 dbesc(datetime_convert()),
70 dbesc(datetime_convert()),
71 dbesc(datetime_convert())
74 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
76 $relay[] = $relais[0];
78 $relay[] = $relais[0];
85 * @brief repairs a signature that was double encoded
87 * The function is unused at the moment. It was copied from the old implementation.
89 * @param string $signature The signature
90 * @param string $handle The handle of the signature owner
91 * @param integer $level This value is only set inside this function to avoid endless loops
93 * @return string the repaired signature
95 private static function repair_signature($signature, $handle = "", $level = 1) {
100 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
101 $signature = base64_decode($signature);
102 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
104 // Do a recursive call to be able to fix even multiple levels
106 $signature = self::repair_signature($signature, $handle, ++$level);
113 * @brief verify the envelope and return the verified data
115 * @param string $envelope The magic envelope
117 * @return string verified data
119 private static function verify_magic_envelope($envelope) {
121 $basedom = parse_xml_string($envelope);
123 if (!is_object($basedom)) {
124 logger("Envelope is no XML file");
128 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
130 if (sizeof($children) == 0) {
131 logger("XML has no children");
137 $data = base64url_decode($children->data);
138 $type = $children->data->attributes()->type[0];
140 $encoding = $children->encoding;
142 $alg = $children->alg;
144 $sig = base64url_decode($children->sig);
145 $key_id = $children->sig->attributes()->key_id[0];
147 $handle = base64url_decode($key_id);
149 $b64url_data = base64url_encode($data);
150 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
152 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
154 $key = self::key($handle);
156 $verify = rsa_verify($signable_data, $sig, $key);
158 logger('Message did not verify. Discarding.');
166 * @brief encrypts data via AES
168 * @param string $key The AES key
169 * @param string $iv The IV (is used for CBC encoding)
170 * @param string $data The data that is to be encrypted
172 * @return string encrypted data
174 private static function aes_encrypt($key, $iv, $data) {
175 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
179 * @brief decrypts data via AES
181 * @param string $key The AES key
182 * @param string $iv The IV (is used for CBC encoding)
183 * @param string $encrypted The encrypted data
185 * @return string decrypted data
187 private static function aes_decrypt($key, $iv, $encrypted) {
188 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
192 * @brief: Decodes incoming Diaspora message in the new format
194 * @param array $importer Array of the importer user
195 * @param string $raw raw post message
198 * 'message' -> decoded Diaspora XML message
199 * 'author' -> author diaspora handle
200 * 'key' -> author public key (converted to pkcs#8)
202 public static function decode_raw($importer, $raw) {
203 $data = json_decode($raw);
205 // Is it a private post? Then decrypt the outer Salmon
206 if (is_object($data)) {
207 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
208 $ciphertext = base64_decode($data->encrypted_magic_envelope);
210 $outer_key_bundle = '';
211 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
212 $j_outer_key_bundle = json_decode($outer_key_bundle);
214 if (!is_object($j_outer_key_bundle)) {
215 logger('Outer Salmon did not verify. Discarding.');
216 http_status_exit(400);
219 $outer_iv = base64_decode($j_outer_key_bundle->iv);
220 $outer_key = base64_decode($j_outer_key_bundle->key);
222 $xml = diaspora::aes_decrypt($outer_key, $outer_iv, $ciphertext);
227 $basedom = parse_xml_string($xml);
229 if (!is_object($basedom)) {
230 logger('Received data does not seem to be an XML. Discarding. '.$xml);
231 http_status_exit(400);
234 $base = $basedom->children(NAMESPACE_SALMON_ME);
236 // Not sure if this cleaning is needed
237 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
239 // Build the signed data
240 $type = $base->data[0]->attributes()->type[0];
241 $encoding = $base->encoding;
243 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
245 // This is the signature
246 $signature = base64url_decode($base->sig);
248 // Get the senders' public key
249 $key_id = $base->sig[0]->attributes()->key_id[0];
250 $author_addr = base64_decode($key_id);
251 $key = diaspora::key($author_addr);
253 $verify = rsa_verify($signed_data, $signature, $key);
255 logger('Message did not verify. Discarding.');
256 http_status_exit(400);
259 return array('message' => (string)base64url_decode($base->data),
260 'author' => unxmlify($author_addr),
261 'key' => (string)$key);
265 * @brief: Decodes incoming Diaspora message in the deprecated format
267 * @param array $importer Array of the importer user
268 * @param string $xml urldecoded Diaspora salmon
271 * 'message' -> decoded Diaspora XML message
272 * 'author' -> author diaspora handle
273 * 'key' -> author public key (converted to pkcs#8)
275 public static function decode($importer, $xml) {
278 $basedom = parse_xml_string($xml);
280 if (!is_object($basedom)) {
281 logger("XML is not parseable.");
284 $children = $basedom->children('https://joindiaspora.com/protocol');
286 if ($children->header) {
288 $author_link = str_replace('acct:','',$children->header->author_id);
290 // This happens with posts from a relais
292 logger("This is no private post in the old format", LOGGER_DEBUG);
296 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
298 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
299 $ciphertext = base64_decode($encrypted_header->ciphertext);
301 $outer_key_bundle = '';
302 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
304 $j_outer_key_bundle = json_decode($outer_key_bundle);
306 $outer_iv = base64_decode($j_outer_key_bundle->iv);
307 $outer_key = base64_decode($j_outer_key_bundle->key);
309 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
311 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
312 $idom = parse_xml_string($decrypted);
314 $inner_iv = base64_decode($idom->iv);
315 $inner_aes_key = base64_decode($idom->aes_key);
317 $author_link = str_replace('acct:','',$idom->author_id);
320 $dom = $basedom->children(NAMESPACE_SALMON_ME);
322 // figure out where in the DOM tree our data is hiding
324 if ($dom->provenance->data)
325 $base = $dom->provenance;
326 elseif ($dom->env->data)
332 logger('unable to locate salmon data in xml');
333 http_status_exit(400);
337 // Stash the signature away for now. We have to find their key or it won't be good for anything.
338 $signature = base64url_decode($base->sig);
342 // strip whitespace so our data element will return to one big base64 blob
343 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
346 // stash away some other stuff for later
348 $type = $base->data[0]->attributes()->type[0];
349 $keyhash = $base->sig[0]->attributes()->keyhash[0];
350 $encoding = $base->encoding;
354 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
358 $data = base64url_decode($data);
362 $inner_decrypted = $data;
365 // Decode the encrypted blob
367 $inner_encrypted = base64_decode($data);
368 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
372 logger('Could not retrieve author URI.');
373 http_status_exit(400);
375 // Once we have the author URI, go to the web and try to find their public key
376 // (first this will look it up locally if it is in the fcontact cache)
377 // This will also convert diaspora public key from pkcs#1 to pkcs#8
379 logger('Fetching key for '.$author_link);
380 $key = self::key($author_link);
383 logger('Could not retrieve author key.');
384 http_status_exit(400);
387 $verify = rsa_verify($signed_data,$signature,$key);
390 logger('Message did not verify. Discarding.');
391 http_status_exit(400);
394 logger('Message verified.');
396 return array('message' => (string)$inner_decrypted,
397 'author' => unxmlify($author_link),
398 'key' => (string)$key);
403 * @brief Dispatches public messages and find the fitting receivers
405 * @param array $msg The post that will be dispatched
407 * @return int The message id of the generated message, "true" or "false" if there was an error
409 public static function dispatch_public($msg) {
411 $enabled = intval(get_config("system", "diaspora_enabled"));
413 logger("diaspora is disabled");
417 if (!($postdata = self::valid_posting($msg))) {
418 logger("Invalid posting");
422 $fields = $postdata['fields'];
424 // Is it a an action (comment, like, ...) for our own post?
425 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
426 $guid = notags(unxmlify($fields->parent_guid));
427 $importer = self::importer_for_guid($guid);
428 if (is_array($importer)) {
429 logger("delivering to origin: ".$importer["name"]);
430 $message_id = self::dispatch($importer, $msg, $fields);
435 // Process item retractions. This has to be done separated from the other stuff,
436 // since retractions for comments could come even from non followers.
437 if (!empty($fields) && in_array($fields->getName(), array('retraction'))) {
438 $target = notags(unxmlify($fields->target_type));
439 if (in_array($target, array("Comment", "Like", "Post", "Reshare", "StatusMessage"))) {
440 logger('processing retraction for '.$target, LOGGER_DEBUG);
441 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
442 $message_id = self::dispatch($importer, $msg, $fields);
447 // Now distribute it to the followers
448 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
449 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
450 AND NOT `account_expired` AND NOT `account_removed`",
451 dbesc(NETWORK_DIASPORA),
452 dbesc($msg["author"])
455 if (dbm::is_result($r)) {
456 foreach ($r as $rr) {
457 logger("delivering to: ".$rr["username"]);
458 self::dispatch($rr, $msg, $fields);
460 } elseif (!Config::get('system', 'relay_subscribe', false)) {
461 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
463 // Use a dummy importer to import the data for the public copy
464 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
465 $message_id = self::dispatch($importer, $msg, $fields);
472 * @brief Dispatches the different message types to the different functions
474 * @param array $importer Array of the importer user
475 * @param array $msg The post that will be dispatched
476 * @param object $fields SimpleXML object that contains the message
478 * @return int The message id of the generated message, "true" or "false" if there was an error
480 public static function dispatch($importer, $msg, $fields = null) {
482 // The sender is the handle of the contact that sent the message.
483 // This will often be different with relayed messages (for example "like" and "comment")
484 $sender = $msg["author"];
486 // This is only needed for private postings since this is already done for public ones before
487 if (is_null($fields)) {
488 if (!($postdata = self::valid_posting($msg))) {
489 logger("Invalid posting");
492 $fields = $postdata['fields'];
495 $type = $fields->getName();
497 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
500 case "account_deletion":
501 return self::receive_account_deletion($importer, $fields);
504 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
507 return self::receive_contact_request($importer, $fields);
510 return self::receive_conversation($importer, $msg, $fields);
513 return self::receive_like($importer, $sender, $fields);
516 return self::receive_message($importer, $fields);
518 case "participation": // Not implemented
519 return self::receive_participation($importer, $fields);
521 case "photo": // Not implemented
522 return self::receive_photo($importer, $fields);
524 case "poll_participation": // Not implemented
525 return self::receive_poll_participation($importer, $fields);
528 return self::receive_profile($importer, $fields);
531 return self::receive_reshare($importer, $fields, $msg["message"]);
534 return self::receive_retraction($importer, $sender, $fields);
536 case "status_message":
537 return self::receive_status_message($importer, $fields, $msg["message"]);
540 logger("Unknown message type ".$type);
548 * @brief Checks if a posting is valid and fetches the data fields.
550 * This function does not only check the signature.
551 * It also does the conversion between the old and the new diaspora format.
553 * @param array $msg Array with the XML, the sender handle and the sender signature
555 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
557 private static function valid_posting($msg) {
559 $data = parse_xml_string($msg["message"]);
561 if (!is_object($data)) {
562 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
566 $first_child = $data->getName();
568 // Is this the new or the old version?
569 if ($data->getName() == "XML") {
571 foreach ($data->post->children() as $child)
578 $type = $element->getName();
581 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
583 // All retractions are handled identically from now on.
584 // In the new version there will only be "retraction".
585 if (in_array($type, array("signed_retraction", "relayable_retraction")))
586 $type = "retraction";
588 if ($type == "request")
591 $fields = new SimpleXMLElement("<".$type."/>");
595 foreach ($element->children() AS $fieldname => $entry) {
597 // Translation for the old XML structure
598 if ($fieldname == "diaspora_handle") {
599 $fieldname = "author";
601 if ($fieldname == "participant_handles") {
602 $fieldname = "participants";
604 if (in_array($type, array("like", "participation"))) {
605 if ($fieldname == "target_type") {
606 $fieldname = "parent_type";
609 if ($fieldname == "sender_handle") {
610 $fieldname = "author";
612 if ($fieldname == "recipient_handle") {
613 $fieldname = "recipient";
615 if ($fieldname == "root_diaspora_id") {
616 $fieldname = "root_author";
618 if ($type == "status_message") {
619 if ($fieldname == "raw_message") {
623 if ($type == "retraction") {
624 if ($fieldname == "post_guid") {
625 $fieldname = "target_guid";
627 if ($fieldname == "type") {
628 $fieldname = "target_type";
633 if (($fieldname == "author_signature") && ($entry != ""))
634 $author_signature = base64_decode($entry);
635 elseif (($fieldname == "parent_author_signature") && ($entry != ""))
636 $parent_author_signature = base64_decode($entry);
637 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
638 if ($signed_data != "") {
640 $signed_data_parent .= ";";
643 $signed_data .= $entry;
645 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) ||
646 ($orig_type == "relayable_retraction"))
647 xml::copy($entry, $fields, $fieldname);
650 // This is something that shouldn't happen at all.
651 if (in_array($type, array("status_message", "reshare", "profile")))
652 if ($msg["author"] != $fields->author) {
653 logger("Message handle is not the same as envelope sender. Quitting this message.");
657 // Only some message types have signatures. So we quit here for the other types.
658 if (!in_array($type, array("comment", "like"))) {
659 return array("fields" => $fields, "relayed" => false);
661 // No author_signature? This is a must, so we quit.
662 if (!isset($author_signature)) {
663 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
667 if (isset($parent_author_signature)) {
670 $key = self::key($msg["author"]);
672 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
673 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);
680 $key = self::key($fields->author);
682 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
683 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
686 return array("fields" => $fields, "relayed" => $relayed);
691 * @brief Fetches the public key for a given handle
693 * @param string $handle The handle
695 * @return string The public key
697 private static function key($handle) {
698 $handle = strval($handle);
700 logger("Fetching diaspora key for: ".$handle);
702 $r = self::person_by_handle($handle);
710 * @brief Fetches data for a given handle
712 * @param string $handle The handle
714 * @return array the queried data
716 public static function person_by_handle($handle) {
718 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
719 dbesc(NETWORK_DIASPORA),
724 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
726 // update record occasionally so it doesn't get stale
727 $d = strtotime($person["updated"]." +00:00");
728 if ($d < strtotime("now - 14 days"))
731 if ($person["guid"] == "")
735 if (!$person || $update) {
736 logger("create or refresh", LOGGER_DEBUG);
737 $r = probe_url($handle, PROBE_DIASPORA);
739 // Note that Friendica contacts will return a "Diaspora person"
740 // if Diaspora connectivity is enabled on their server
741 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
742 self::add_fcontact($r, $update);
750 * @brief Updates the fcontact table
752 * @param array $arr The fcontact data
753 * @param bool $update Update or insert?
755 * @return string The id of the fcontact entry
757 private static function add_fcontact($arr, $update = false) {
760 $r = q("UPDATE `fcontact` SET
774 WHERE `url` = '%s' AND `network` = '%s'",
776 dbesc($arr["photo"]),
777 dbesc($arr["request"]),
779 dbesc(strtolower($arr["addr"])),
781 dbesc($arr["batch"]),
782 dbesc($arr["notify"]),
784 dbesc($arr["confirm"]),
785 dbesc($arr["alias"]),
786 dbesc($arr["pubkey"]),
787 dbesc(datetime_convert()),
789 dbesc($arr["network"])
792 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
793 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
794 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
797 dbesc($arr["photo"]),
798 dbesc($arr["request"]),
802 dbesc($arr["batch"]),
803 dbesc($arr["notify"]),
805 dbesc($arr["confirm"]),
806 dbesc($arr["network"]),
807 dbesc($arr["alias"]),
808 dbesc($arr["pubkey"]),
809 dbesc(datetime_convert())
817 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
819 * @param int $contact_id The id in the contact table
820 * @param int $gcontact_id The id in the gcontact table
822 * @return string the handle
824 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
827 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
829 if ($gcontact_id != 0) {
830 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
831 intval($gcontact_id));
833 if (dbm::is_result($r)) {
834 return strtolower($r[0]["addr"]);
838 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
839 intval($contact_id));
841 if (dbm::is_result($r)) {
844 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
846 if ($contact['addr'] != "") {
847 $handle = $contact['addr'];
849 $baseurl_start = strpos($contact['url'],'://') + 3;
850 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
851 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
852 $handle = $contact['nick'].'@'.$baseurl;
856 return strtolower($handle);
860 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
863 * @param mixed $fcontact_guid Hexadecimal string guid
865 * @return string the contact url or null
867 public static function url_from_contact_guid($fcontact_guid) {
868 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
870 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
871 dbesc(NETWORK_DIASPORA),
872 dbesc($fcontact_guid)
875 if (dbm::is_result($r)) {
883 * @brief Get a contact id for a given handle
885 * @param int $uid The user id
886 * @param string $handle The handle in the format user@domain.tld
888 * @return The contact id
890 private static function contact_by_handle($uid, $handle) {
892 // First do a direct search on the contact table
893 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
898 if (dbm::is_result($r)) {
902 * We haven't found it?
903 * We use another function for it that will possibly create a contact entry.
905 $cid = get_contact($handle, $uid);
908 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
909 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
911 if (dbm::is_result($r)) {
917 $handle_parts = explode("@", $handle);
918 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
919 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
924 if (dbm::is_result($r)) {
928 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
933 * @brief Check if posting is allowed for this contact
935 * @param array $importer Array of the importer user
936 * @param array $contact The contact that is checked
937 * @param bool $is_comment Is the check for a comment?
939 * @return bool is the contact allowed to post?
941 private static function post_allow($importer, $contact, $is_comment = false) {
944 * Perhaps we were already sharing with this person. Now they're sharing with us.
945 * That makes us friends.
946 * Normally this should have handled by getting a request - but this could get lost
948 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
949 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
950 array('id' => $contact["id"], 'uid' => $contact["uid"]));
952 $contact["rel"] = CONTACT_IS_FRIEND;
953 logger("defining user ".$contact["nick"]." as friend");
956 // We don't seem to like that person
957 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
958 // Maybe blocked, don't accept.
960 // We are following this person?
961 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
962 // Yes, then it is fine.
964 // Is it a post to a community?
965 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
968 // Is the message a global user or a comment?
969 } elseif (($importer["uid"] == 0) || $is_comment) {
970 // Messages for the global users and comments are always accepted
978 * @brief Fetches the contact id for a handle and checks if posting is allowed
980 * @param array $importer Array of the importer user
981 * @param string $handle The checked handle in the format user@domain.tld
982 * @param bool $is_comment Is the check for a comment?
984 * @return array The contact data
986 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
987 $contact = self::contact_by_handle($importer["uid"], $handle);
989 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
990 // If a contact isn't found, we accept it anyway if it is a comment
998 if (!self::post_allow($importer, $contact, $is_comment)) {
999 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1006 * @brief Does the message already exists on the system?
1008 * @param int $uid The user id
1009 * @param string $guid The guid of the message
1011 * @return int|bool message id if the message already was stored into the system - or false.
1013 private static function message_exists($uid, $guid) {
1014 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1019 if (dbm::is_result($r)) {
1020 logger("message ".$guid." already exists for user ".$uid);
1028 * @brief Checks for links to posts in a message
1030 * @param array $item The item array
1032 private static function fetch_guid($item) {
1033 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1034 preg_replace_callback($expression,
1035 function ($match) use ($item) {
1036 return self::fetch_guid_sub($match, $item);
1039 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1040 function ($match) use ($item) {
1041 return self::fetch_guid_sub($match, $item);
1046 * @brief Checks for relative /people/* links in an item body to match local
1047 * contacts or prepends the remote host taken from the author link.
1049 * @param string $body The item body to replace links from
1050 * @param string $author_link The author link for missing local contact fallback
1052 * @return the replaced string
1054 public static function replace_people_guid($body, $author_link) {
1055 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1056 function ($match) use ($author_link) {
1058 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1059 // 1 => '0123456789abcdef'
1061 $handle = self::url_from_contact_guid($match[1]);
1064 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1066 // No local match, restoring absolute remote URL from author scheme and host
1067 $author_url = parse_url($author_link);
1068 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1078 * @brief sub function of "fetch_guid" which checks for links in messages
1080 * @param array $match array containing a link that has to be checked for a message link
1081 * @param array $item The item array
1083 private static function fetch_guid_sub($match, $item) {
1084 if (!self::store_by_guid($match[1], $item["author-link"]))
1085 self::store_by_guid($match[1], $item["owner-link"]);
1089 * @brief Fetches an item with a given guid from a given server
1091 * @param string $guid the message guid
1092 * @param string $server The server address
1093 * @param int $uid The user id of the user
1095 * @return int the message id of the stored message or false
1097 private static function store_by_guid($guid, $server, $uid = 0) {
1098 $serverparts = parse_url($server);
1099 $server = $serverparts["scheme"]."://".$serverparts["host"];
1101 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1103 $msg = self::message($guid, $server);
1108 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1110 // Now call the dispatcher
1111 return self::dispatch_public($msg);
1115 * @brief Fetches a message from a server
1117 * @param string $guid message guid
1118 * @param string $server The url of the server
1119 * @param int $level Endless loop prevention
1122 * 'message' => The message XML
1123 * 'author' => The author handle
1124 * 'key' => The public key of the author
1126 private static function message($guid, $server, $level = 0) {
1131 // This will work for new Diaspora servers and Friendica servers from 3.5
1132 $source_url = $server."/fetch/post/".$guid;
1133 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1135 $envelope = fetch_url($source_url);
1137 logger("Envelope was fetched.", LOGGER_DEBUG);
1138 $x = self::verify_magic_envelope($envelope);
1140 logger("Envelope could not be verified.", LOGGER_DEBUG);
1142 logger("Envelope was verified.", LOGGER_DEBUG);
1146 // This will work for older Diaspora and Friendica servers
1148 $source_url = $server."/p/".$guid.".xml";
1149 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1151 $x = fetch_url($source_url);
1156 $source_xml = parse_xml_string($x);
1158 if (!is_object($source_xml))
1161 if ($source_xml->post->reshare) {
1162 // Reshare of a reshare - old Diaspora version
1163 logger("Message is a reshare", LOGGER_DEBUG);
1164 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1165 } elseif ($source_xml->getName() == "reshare") {
1166 // Reshare of a reshare - new Diaspora version
1167 logger("Message is a new reshare", LOGGER_DEBUG);
1168 return self::message($source_xml->root_guid, $server, ++$level);
1173 // Fetch the author - for the old and the new Diaspora version
1174 if ($source_xml->post->status_message->diaspora_handle)
1175 $author = (string)$source_xml->post->status_message->diaspora_handle;
1176 elseif ($source_xml->author && ($source_xml->getName() == "status_message"))
1177 $author = (string)$source_xml->author;
1179 // If this isn't a "status_message" then quit
1181 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1185 $msg = array("message" => $x, "author" => $author);
1187 $msg["key"] = self::key($msg["author"]);
1193 * @brief Fetches the item record of a given guid
1195 * @param int $uid The user id
1196 * @param string $guid message guid
1197 * @param string $author The handle of the item
1198 * @param array $contact The contact of the item owner
1200 * @return array the item record
1202 private static function parent_item($uid, $guid, $author, $contact) {
1203 $r = q("SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1204 `author-name`, `author-link`, `author-avatar`,
1205 `owner-name`, `owner-link`, `owner-avatar`
1206 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1207 intval($uid), dbesc($guid));
1210 $result = self::store_by_guid($guid, $contact["url"], $uid);
1213 $person = self::person_by_handle($author);
1214 $result = self::store_by_guid($guid, $person["url"], $uid);
1218 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1220 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1221 `author-name`, `author-link`, `author-avatar`,
1222 `owner-name`, `owner-link`, `owner-avatar`
1223 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1224 intval($uid), dbesc($guid));
1229 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1232 logger("parent item found: parent: ".$guid." - user: ".$uid);
1238 * @brief returns contact details
1240 * @param array $contact The default contact if the person isn't found
1241 * @param array $person The record of the person
1242 * @param int $uid The user id
1245 * 'cid' => contact id
1246 * 'network' => network type
1248 private static function author_contact_by_url($contact, $person, $uid) {
1250 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1251 dbesc(normalise_link($person["url"])), intval($uid));
1254 $network = $r[0]["network"];
1256 // We are receiving content from a user that possibly is about to be terminated
1257 // This means the user is vital, so we remove a possible termination date.
1258 unmark_for_death($r[0]);
1260 $cid = $contact["id"];
1261 $network = NETWORK_DIASPORA;
1264 return array("cid" => $cid, "network" => $network);
1268 * @brief Is the profile a hubzilla profile?
1270 * @param string $url The profile link
1272 * @return bool is it a hubzilla server?
1274 public static function is_redmatrix($url) {
1275 return(strstr($url, "/channel/"));
1279 * @brief Generate a post link with a given handle and message guid
1281 * @param string $addr The user handle
1282 * @param string $guid message guid
1284 * @return string the post link
1286 private static function plink($addr, $guid, $parent_guid = '') {
1287 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1290 if (!dbm::is_result($r)) {
1291 if ($parent_guid != '') {
1292 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$parent_guid."#".$guid;
1294 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$guid;
1298 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1299 // So we try another way as well.
1300 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1301 if (dbm::is_result($s)) {
1302 $r[0]["network"] = $s[0]["network"];
1305 if ($r[0]["network"] == NETWORK_DFRN) {
1306 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1309 if (self::is_redmatrix($r[0]["url"])) {
1310 return $r[0]["url"]."/?f=&mid=".$guid;
1313 if ($parent_guid != '') {
1314 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$parent_guid."#".$guid;
1316 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1321 * @brief Processes an account deletion
1323 * @param array $importer Array of the importer user
1324 * @param object $data The message object
1326 * @return bool Success
1328 private static function receive_account_deletion($importer, $data) {
1330 /// @todo Account deletion should remove the contact from the global contacts as well
1332 $author = notags(unxmlify($data->author));
1334 $contact = self::contact_by_handle($importer["uid"], $author);
1336 logger("cannot find contact for author: ".$author);
1340 // We now remove the contact
1341 contact_remove($contact["id"]);
1346 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1348 * @param string $author Author handle
1349 * @param string $guid Message guid
1350 * @param boolean $onlyfound Only return uri when found in the database
1352 * @return string The constructed uri or the one from our database
1354 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1356 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1357 if (dbm::is_result($r)) {
1358 return $r[0]["uri"];
1359 } elseif (!$onlyfound) {
1360 return $author.":".$guid;
1367 * @brief Fetch the guid from our database with a given uri
1369 * @param string $author Author handle
1370 * @param string $uri Message uri
1372 * @return string The post guid
1374 private static function get_guid_from_uri($uri, $uid) {
1376 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1377 if (dbm::is_result($r)) {
1378 return $r[0]["guid"];
1385 * @brief Find the best importer for a comment, like, ...
1387 * @param string $guid The guid of the item
1389 * @return array|boolean the origin owner of that post - or false
1391 private static function importer_for_guid($guid) {
1392 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1394 if (dbm::is_result($item)) {
1395 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1396 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1397 if (dbm::is_result($contact)) {
1405 * @brief Processes an incoming comment
1407 * @param array $importer Array of the importer user
1408 * @param string $sender The sender of the message
1409 * @param object $data The message object
1410 * @param string $xml The original XML of the message
1412 * @return int The message id of the generated comment or "false" if there was an error
1414 private static function receive_comment($importer, $sender, $data, $xml) {
1415 $author = notags(unxmlify($data->author));
1416 $guid = notags(unxmlify($data->guid));
1417 $parent_guid = notags(unxmlify($data->parent_guid));
1418 $text = unxmlify($data->text);
1420 if (isset($data->created_at)) {
1421 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1423 $created_at = datetime_convert();
1426 if (isset($data->thread_parent_guid)) {
1427 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1428 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1433 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1438 $message_id = self::message_exists($importer["uid"], $guid);
1443 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1444 if (!$parent_item) {
1448 $person = self::person_by_handle($author);
1449 if (!is_array($person)) {
1450 logger("unable to find author details");
1454 // Fetch the contact id - if we know this contact
1455 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1457 $datarray = array();
1459 $datarray["uid"] = $importer["uid"];
1460 $datarray["contact-id"] = $author_contact["cid"];
1461 $datarray["network"] = $author_contact["network"];
1463 $datarray["author-name"] = $person["name"];
1464 $datarray["author-link"] = $person["url"];
1465 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1467 $datarray["owner-name"] = $contact["name"];
1468 $datarray["owner-link"] = $contact["url"];
1469 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1471 $datarray["guid"] = $guid;
1472 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1474 $datarray["type"] = "remote-comment";
1475 $datarray["verb"] = ACTIVITY_POST;
1476 $datarray["gravity"] = GRAVITY_COMMENT;
1478 if ($thr_uri != "") {
1479 $datarray["parent-uri"] = $thr_uri;
1481 $datarray["parent-uri"] = $parent_item["uri"];
1484 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1486 $datarray["protocol"] = PROTOCOL_DIASPORA;
1487 $datarray["source"] = $xml;
1489 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1491 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1493 $body = diaspora2bb($text);
1495 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1497 self::fetch_guid($datarray);
1499 $message_id = item_store($datarray);
1501 if ($message_id <= 0) {
1506 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1509 // If we are the origin of the parent we store the original data and notify our followers
1510 if ($message_id && $parent_item["origin"]) {
1512 // Formerly we stored the signed text, the signature and the author in different fields.
1513 // We now store the raw data so that we are more flexible.
1514 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1517 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1524 * @brief processes and stores private messages
1526 * @param array $importer Array of the importer user
1527 * @param array $contact The contact of the message
1528 * @param object $data The message object
1529 * @param array $msg Array of the processed message, author handle and key
1530 * @param object $mesg The private message
1531 * @param array $conversation The conversation record to which this message belongs
1533 * @return bool "true" if it was successful
1535 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1536 $author = notags(unxmlify($data->author));
1537 $guid = notags(unxmlify($data->guid));
1538 $subject = notags(unxmlify($data->subject));
1540 // "diaspora_handle" is the element name from the old version
1541 // "author" is the element name from the new version
1542 if ($mesg->author) {
1543 $msg_author = notags(unxmlify($mesg->author));
1544 } elseif ($mesg->diaspora_handle) {
1545 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1550 $msg_guid = notags(unxmlify($mesg->guid));
1551 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1552 $msg_text = unxmlify($mesg->text);
1553 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1555 if ($msg_conversation_guid != $guid) {
1556 logger("message conversation guid does not belong to the current conversation.");
1560 $body = diaspora2bb($msg_text);
1561 $message_uri = $msg_author.":".$msg_guid;
1563 $person = self::person_by_handle($msg_author);
1567 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1569 intval($importer["uid"])
1571 if (dbm::is_result($r)) {
1572 logger("duplicate message already delivered.", LOGGER_DEBUG);
1576 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1577 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1578 intval($importer["uid"]),
1580 intval($conversation["id"]),
1581 dbesc($person["name"]),
1582 dbesc($person["photo"]),
1583 dbesc($person["url"]),
1584 intval($contact["id"]),
1589 dbesc($message_uri),
1590 dbesc($author.":".$guid),
1591 dbesc($msg_created_at)
1596 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1599 "type" => NOTIFY_MAIL,
1600 "notify_flags" => $importer["notify-flags"],
1601 "language" => $importer["language"],
1602 "to_name" => $importer["username"],
1603 "to_email" => $importer["email"],
1604 "uid" =>$importer["uid"],
1605 "item" => array("subject" => $subject, "body" => $body),
1606 "source_name" => $person["name"],
1607 "source_link" => $person["url"],
1608 "source_photo" => $person["thumb"],
1609 "verb" => ACTIVITY_POST,
1616 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1618 * @param array $importer Array of the importer user
1619 * @param array $msg Array of the processed message, author handle and key
1620 * @param object $data The message object
1622 * @return bool Success
1624 private static function receive_conversation($importer, $msg, $data) {
1625 $author = notags(unxmlify($data->author));
1626 $guid = notags(unxmlify($data->guid));
1627 $subject = notags(unxmlify($data->subject));
1628 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1629 $participants = notags(unxmlify($data->participants));
1631 $messages = $data->message;
1633 if (!count($messages)) {
1634 logger("empty conversation");
1638 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1642 $conversation = null;
1644 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1645 intval($importer["uid"]),
1649 $conversation = $c[0];
1651 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1652 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1653 intval($importer["uid"]),
1657 dbesc(datetime_convert()),
1659 dbesc($participants)
1662 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1663 intval($importer["uid"]),
1668 $conversation = $c[0];
1670 if (!$conversation) {
1671 logger("unable to create conversation.");
1675 foreach ($messages as $mesg)
1676 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1682 * @brief Creates the body for a "like" message
1684 * @param array $contact The contact that send us the "like"
1685 * @param array $parent_item The item array of the parent item
1686 * @param string $guid message guid
1688 * @return string the body
1690 private static function construct_like_body($contact, $parent_item, $guid) {
1691 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1693 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1694 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1695 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1697 return sprintf($bodyverb, $ulink, $alink, $plink);
1701 * @brief Creates a XML object for a "like"
1703 * @param array $importer Array of the importer user
1704 * @param array $parent_item The item array of the parent item
1706 * @return string The XML
1708 private static function construct_like_object($importer, $parent_item) {
1709 $objtype = ACTIVITY_OBJ_NOTE;
1710 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1711 $parent_body = $parent_item["body"];
1713 $xmldata = array("object" => array("type" => $objtype,
1715 "id" => $parent_item["uri"],
1718 "content" => $parent_body));
1720 return xml::from_array($xmldata, $xml, true);
1724 * @brief Processes "like" messages
1726 * @param array $importer Array of the importer user
1727 * @param string $sender The sender of the message
1728 * @param object $data The message object
1730 * @return int The message id of the generated like or "false" if there was an error
1732 private static function receive_like($importer, $sender, $data) {
1733 $author = notags(unxmlify($data->author));
1734 $guid = notags(unxmlify($data->guid));
1735 $parent_guid = notags(unxmlify($data->parent_guid));
1736 $parent_type = notags(unxmlify($data->parent_type));
1737 $positive = notags(unxmlify($data->positive));
1739 // likes on comments aren't supported by Diaspora - only on posts
1740 // But maybe this will be supported in the future, so we will accept it.
1741 if (!in_array($parent_type, array("Post", "Comment")))
1744 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1748 $message_id = self::message_exists($importer["uid"], $guid);
1752 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1756 $person = self::person_by_handle($author);
1757 if (!is_array($person)) {
1758 logger("unable to find author details");
1762 // Fetch the contact id - if we know this contact
1763 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1765 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1766 // We would accept this anyhow.
1767 if ($positive == "true")
1768 $verb = ACTIVITY_LIKE;
1770 $verb = ACTIVITY_DISLIKE;
1772 $datarray = array();
1774 $datarray["protocol"] = PROTOCOL_DIASPORA;
1776 $datarray["uid"] = $importer["uid"];
1777 $datarray["contact-id"] = $author_contact["cid"];
1778 $datarray["network"] = $author_contact["network"];
1780 $datarray["author-name"] = $person["name"];
1781 $datarray["author-link"] = $person["url"];
1782 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1784 $datarray["owner-name"] = $contact["name"];
1785 $datarray["owner-link"] = $contact["url"];
1786 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1788 $datarray["guid"] = $guid;
1789 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1791 $datarray["type"] = "activity";
1792 $datarray["verb"] = $verb;
1793 $datarray["gravity"] = GRAVITY_LIKE;
1794 $datarray["parent-uri"] = $parent_item["uri"];
1796 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1797 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1799 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1801 $message_id = item_store($datarray);
1803 if ($message_id <= 0) {
1808 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1811 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1812 if ($parent_item["id"] != $parent_item["parent"]) {
1813 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
1814 $origin = $toplevel["origin"];
1816 $origin = $parent_item["origin"];
1819 // If we are the origin of the parent we store the original data and notify our followers
1820 if ($message_id && $origin) {
1822 // Formerly we stored the signed text, the signature and the author in different fields.
1823 // We now store the raw data so that we are more flexible.
1824 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1827 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1834 * @brief Processes private messages
1836 * @param array $importer Array of the importer user
1837 * @param object $data The message object
1839 * @return bool Success?
1841 private static function receive_message($importer, $data) {
1842 $author = notags(unxmlify($data->author));
1843 $guid = notags(unxmlify($data->guid));
1844 $conversation_guid = notags(unxmlify($data->conversation_guid));
1845 $text = unxmlify($data->text);
1846 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1848 $contact = self::allowed_contact_by_handle($importer, $author, true);
1853 $conversation = null;
1855 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1856 intval($importer["uid"]),
1857 dbesc($conversation_guid)
1860 $conversation = $c[0];
1862 logger("conversation not available.");
1866 $message_uri = $author.":".$guid;
1868 $person = self::person_by_handle($author);
1870 logger("unable to find author details");
1874 $body = diaspora2bb($text);
1876 $body = self::replace_people_guid($body, $person["url"]);
1880 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1882 intval($importer["uid"])
1884 if (dbm::is_result($r)) {
1885 logger("duplicate message already delivered.", LOGGER_DEBUG);
1889 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1890 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1891 intval($importer["uid"]),
1893 intval($conversation["id"]),
1894 dbesc($person["name"]),
1895 dbesc($person["photo"]),
1896 dbesc($person["url"]),
1897 intval($contact["id"]),
1898 dbesc($conversation["subject"]),
1902 dbesc($message_uri),
1903 dbesc($author.":".$conversation["guid"]),
1909 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1914 * @brief Processes participations - unsupported by now
1916 * @param array $importer Array of the importer user
1917 * @param object $data The message object
1919 * @return bool always true
1921 private static function receive_participation($importer, $data) {
1922 // I'm not sure if we can fully support this message type
1927 * @brief Processes photos - unneeded
1929 * @param array $importer Array of the importer user
1930 * @param object $data The message object
1932 * @return bool always true
1934 private static function receive_photo($importer, $data) {
1935 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1940 * @brief Processes poll participations - unssupported
1942 * @param array $importer Array of the importer user
1943 * @param object $data The message object
1945 * @return bool always true
1947 private static function receive_poll_participation($importer, $data) {
1948 // We don't support polls by now
1953 * @brief Processes incoming profile updates
1955 * @param array $importer Array of the importer user
1956 * @param object $data The message object
1958 * @return bool Success
1960 private static function receive_profile($importer, $data) {
1961 $author = strtolower(notags(unxmlify($data->author)));
1963 $contact = self::contact_by_handle($importer["uid"], $author);
1967 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1968 $image_url = unxmlify($data->image_url);
1969 $birthday = unxmlify($data->birthday);
1970 $gender = unxmlify($data->gender);
1971 $about = diaspora2bb(unxmlify($data->bio));
1972 $location = diaspora2bb(unxmlify($data->location));
1973 $searchable = (unxmlify($data->searchable) == "true");
1974 $nsfw = (unxmlify($data->nsfw) == "true");
1975 $tags = unxmlify($data->tag_string);
1977 $tags = explode("#", $tags);
1979 $keywords = array();
1980 foreach ($tags as $tag) {
1981 $tag = trim(strtolower($tag));
1986 $keywords = implode(", ", $keywords);
1988 $handle_parts = explode("@", $author);
1989 $nick = $handle_parts[0];
1992 $name = $handle_parts[0];
1994 if ( preg_match("|^https?://|", $image_url) === 0)
1995 $image_url = "http://".$handle_parts[1].$image_url;
1997 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1999 // Generic birthday. We don't know the timezone. The year is irrelevant.
2001 $birthday = str_replace("1000", "1901", $birthday);
2003 if ($birthday != "")
2004 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2006 // this is to prevent multiple birthday notifications in a single year
2007 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2009 if (substr($birthday,5) === substr($contact["bd"],5))
2010 $birthday = $contact["bd"];
2012 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2013 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2017 dbesc(datetime_convert()),
2023 intval($contact["id"]),
2024 intval($importer["uid"])
2027 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2028 "photo" => $image_url, "name" => $name, "location" => $location,
2029 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2030 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2031 "hide" => !$searchable, "nsfw" => $nsfw);
2033 $gcid = update_gcontact($gcontact);
2035 link_gcontact($gcid, $importer["uid"], $contact["id"]);
2037 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2043 * @brief Processes incoming friend requests
2045 * @param array $importer Array of the importer user
2046 * @param array $contact The contact that send the request
2048 private static function receive_request_make_friend($importer, $contact) {
2052 if ($contact["rel"] == CONTACT_IS_SHARING) {
2053 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2054 array('id' => $contact["id"], 'uid' => $importer["uid"]));
2056 // send notification
2058 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2059 intval($importer["uid"])
2062 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
2064 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2065 intval($importer["uid"])
2068 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2070 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2073 $arr["protocol"] = PROTOCOL_DIASPORA;
2074 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2075 $arr["uid"] = $importer["uid"];
2076 $arr["contact-id"] = $self[0]["id"];
2078 $arr["type"] = 'wall';
2079 $arr["gravity"] = 0;
2081 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2082 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2083 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2084 $arr["verb"] = ACTIVITY_FRIEND;
2085 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2087 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2088 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2089 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2090 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2092 $arr["object"] = self::construct_new_friend_object($contact);
2094 $arr["last-child"] = 1;
2096 $arr["allow_cid"] = $user[0]["allow_cid"];
2097 $arr["allow_gid"] = $user[0]["allow_gid"];
2098 $arr["deny_cid"] = $user[0]["deny_cid"];
2099 $arr["deny_gid"] = $user[0]["deny_gid"];
2101 $i = item_store($arr);
2103 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2109 * @brief Creates a XML object for a "new friend" message
2111 * @param array $contact Array of the contact
2113 * @return string The XML
2115 private static function construct_new_friend_object($contact) {
2116 $objtype = ACTIVITY_OBJ_PERSON;
2117 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2118 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2120 $xmldata = array("object" => array("type" => $objtype,
2121 "title" => $contact["name"],
2122 "id" => $contact["url"]."/".$contact["name"],
2125 return xml::from_array($xmldata, $xml, true);
2129 * @brief Processes incoming sharing notification
2131 * @param array $importer Array of the importer user
2132 * @param object $data The message object
2134 * @return bool Success
2136 private static function receive_contact_request($importer, $data) {
2137 $author = unxmlify($data->author);
2138 $recipient = unxmlify($data->recipient);
2140 if (!$author || !$recipient) {
2144 // the current protocol version doesn't know these fields
2145 // That means that we will assume their existance
2146 if (isset($data->following)) {
2147 $following = (unxmlify($data->following) == "true");
2152 if (isset($data->sharing)) {
2153 $sharing = (unxmlify($data->sharing) == "true");
2158 $contact = self::contact_by_handle($importer["uid"],$author);
2160 // perhaps we were already sharing with this person. Now they're sharing with us.
2161 // That makes us friends.
2164 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2165 self::receive_request_make_friend($importer, $contact);
2167 // refetch the contact array
2168 $contact = self::contact_by_handle($importer["uid"],$author);
2170 // If we are now friends, we are sending a share message.
2171 // Normally we needn't to do so, but the first message could have been vanished.
2172 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2173 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2175 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2176 $ret = self::send_share($u[0], $contact);
2181 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2182 lose_follower($importer, $contact);
2187 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2188 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2190 } elseif (!$following && !$sharing) {
2191 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2193 } elseif (!$following && $sharing) {
2194 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2195 } elseif ($following && $sharing) {
2196 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2197 } elseif ($following && !$sharing) {
2198 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2201 $ret = self::person_by_handle($author);
2203 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2204 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2208 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2210 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2211 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2212 intval($importer["uid"]),
2213 dbesc($ret["network"]),
2214 dbesc($ret["addr"]),
2217 dbesc(normalise_link($ret["url"])),
2219 dbesc($ret["name"]),
2220 dbesc($ret["nick"]),
2221 dbesc($ret["photo"]),
2222 dbesc($ret["pubkey"]),
2223 dbesc($ret["notify"]),
2224 dbesc($ret["poll"]),
2229 // find the contact record we just created
2231 $contact_record = self::contact_by_handle($importer["uid"],$author);
2233 if (!$contact_record) {
2234 logger("unable to locate newly created contact record.");
2238 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2240 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2242 if (intval($def_gid))
2243 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2245 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2247 if ($importer["page-flags"] == PAGE_NORMAL) {
2249 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2251 $hash = random_string().(string)time(); // Generate a confirm_key
2253 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2254 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2255 intval($importer["uid"]),
2256 intval($contact_record["id"]),
2259 dbesc(t("Sharing notification from Diaspora network")),
2261 dbesc(datetime_convert())
2265 // automatic friend approval
2267 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2269 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2271 // technically they are sharing with us (CONTACT_IS_SHARING),
2272 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2273 // we are going to change the relationship and make them a follower.
2275 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following)
2276 $new_relation = CONTACT_IS_FRIEND;
2277 elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing)
2278 $new_relation = CONTACT_IS_SHARING;
2280 $new_relation = CONTACT_IS_FOLLOWER;
2282 $r = q("UPDATE `contact` SET `rel` = %d,
2290 intval($new_relation),
2291 dbesc(datetime_convert()),
2292 dbesc(datetime_convert()),
2293 intval($contact_record["id"])
2296 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2298 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2299 $ret = self::send_share($u[0], $contact_record);
2301 // Send the profile data, maybe it weren't transmitted before
2302 self::send_profile($importer["uid"], array($contact_record));
2310 * @brief Fetches a message with a given guid
2312 * @param string $guid message guid
2313 * @param string $orig_author handle of the original post
2314 * @param string $author handle of the sharer
2316 * @return array The fetched item
2318 private static function original_item($guid, $orig_author, $author) {
2320 // Do we already have this item?
2321 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2322 `author-name`, `author-link`, `author-avatar`
2323 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2326 if (dbm::is_result($r)) {
2327 logger("reshared message ".$guid." already exists on system.");
2329 // Maybe it is already a reshared item?
2330 // Then refetch the content, if it is a reshare from a reshare.
2331 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2332 if (self::is_reshare($r[0]["body"], true)) {
2334 } elseif (self::is_reshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2335 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2337 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2339 // Add OEmbed and other information to the body
2340 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2348 if (!dbm::is_result($r)) {
2349 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2350 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2351 $item_id = self::store_by_guid($guid, $server);
2354 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2355 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2356 $item_id = self::store_by_guid($guid, $server);
2360 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2361 `author-name`, `author-link`, `author-avatar`
2362 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2365 if (dbm::is_result($r)) {
2366 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2367 if (self::is_reshare($r[0]["body"], false)) {
2368 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2369 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2381 * @brief Processes a reshare message
2383 * @param array $importer Array of the importer user
2384 * @param object $data The message object
2385 * @param string $xml The original XML of the message
2387 * @return int the message id
2389 private static function receive_reshare($importer, $data, $xml) {
2390 $author = notags(unxmlify($data->author));
2391 $guid = notags(unxmlify($data->guid));
2392 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2393 $root_author = notags(unxmlify($data->root_author));
2394 $root_guid = notags(unxmlify($data->root_guid));
2395 /// @todo handle unprocessed property "provider_display_name"
2396 $public = notags(unxmlify($data->public));
2398 $contact = self::allowed_contact_by_handle($importer, $author, false);
2403 $message_id = self::message_exists($importer["uid"], $guid);
2408 $original_item = self::original_item($root_guid, $root_author, $author);
2409 if (!$original_item) {
2413 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2415 $datarray = array();
2417 $datarray["uid"] = $importer["uid"];
2418 $datarray["contact-id"] = $contact["id"];
2419 $datarray["network"] = NETWORK_DIASPORA;
2421 $datarray["author-name"] = $contact["name"];
2422 $datarray["author-link"] = $contact["url"];
2423 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2425 $datarray["owner-name"] = $datarray["author-name"];
2426 $datarray["owner-link"] = $datarray["author-link"];
2427 $datarray["owner-avatar"] = $datarray["author-avatar"];
2429 $datarray["guid"] = $guid;
2430 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2432 $datarray["verb"] = ACTIVITY_POST;
2433 $datarray["gravity"] = GRAVITY_PARENT;
2435 $datarray["protocol"] = PROTOCOL_DIASPORA;
2436 $datarray["source"] = $xml;
2438 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2439 $original_item["guid"], $original_item["created"], $orig_url);
2440 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2442 $datarray["tag"] = $original_item["tag"];
2443 $datarray["app"] = $original_item["app"];
2445 $datarray["plink"] = self::plink($author, $guid);
2446 $datarray["private"] = (($public == "false") ? 1 : 0);
2447 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2449 $datarray["object-type"] = $original_item["object-type"];
2451 self::fetch_guid($datarray);
2452 $message_id = item_store($datarray);
2455 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2463 * @brief Processes retractions
2465 * @param array $importer Array of the importer user
2466 * @param array $contact The contact of the item owner
2467 * @param object $data The message object
2469 * @return bool success
2471 private static function item_retraction($importer, $contact, $data) {
2472 $author = notags(unxmlify($data->author));
2473 $target_guid = notags(unxmlify($data->target_guid));
2474 $target_type = notags(unxmlify($data->target_type));
2476 $person = self::person_by_handle($author);
2477 if (!is_array($person)) {
2478 logger("unable to find author detail for ".$author);
2482 if (empty($contact["url"])) {
2483 $contact["url"] = $person["url"];
2486 // Fetch items that are about to be deleted
2487 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2489 // When we receive a public retraction, we delete every item that we find.
2490 if ($importer['uid'] == 0) {
2491 $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2493 $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2495 $r = dba::select('item', $fields, $condition);
2496 if (!dbm::is_result($r)) {
2497 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2501 while ($item = dba::fetch($r)) {
2502 // Fetch the parent item
2503 $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2505 // Only delete it if the parent author really fits
2506 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2507 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2511 // 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
2512 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
2513 'edited' => datetime_convert(), 'changed' => datetime_convert()),
2514 array('id' => $item["id"]));
2516 // Delete the thread - if it is a starting post and not a comment
2517 if ($target_type != 'Comment') {
2518 delete_thread($item["id"], $item["parent-uri"]);
2521 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2523 // Now check if the retraction needs to be relayed by us
2524 if ($parent["origin"]) {
2526 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $item["id"]);
2534 * @brief Receives retraction messages
2536 * @param array $importer Array of the importer user
2537 * @param string $sender The sender of the message
2538 * @param object $data The message object
2540 * @return bool Success
2542 private static function receive_retraction($importer, $sender, $data) {
2543 $target_type = notags(unxmlify($data->target_type));
2545 $contact = self::contact_by_handle($importer["uid"], $sender);
2546 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2547 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2551 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2553 switch ($target_type) {
2558 case "StatusMessage":
2559 return self::item_retraction($importer, $contact, $data);
2563 /// @todo What should we do with an "unshare"?
2564 // Removing the contact isn't correct since we still can read the public items
2565 contact_remove($contact["id"]);
2569 logger("Unknown target type ".$target_type);
2576 * @brief Receives status messages
2578 * @param array $importer Array of the importer user
2579 * @param object $data The message object
2580 * @param string $xml The original XML of the message
2582 * @return int The message id of the newly created item
2584 private static function receive_status_message($importer, $data, $xml) {
2585 $author = notags(unxmlify($data->author));
2586 $guid = notags(unxmlify($data->guid));
2587 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2588 $public = notags(unxmlify($data->public));
2589 $text = unxmlify($data->text);
2590 $provider_display_name = notags(unxmlify($data->provider_display_name));
2592 $contact = self::allowed_contact_by_handle($importer, $author, false);
2597 $message_id = self::message_exists($importer["uid"], $guid);
2603 if ($data->location) {
2604 foreach ($data->location->children() AS $fieldname => $data) {
2605 $address[$fieldname] = notags(unxmlify($data));
2609 $body = diaspora2bb($text);
2611 $datarray = array();
2613 // Attach embedded pictures to the body
2615 foreach ($data->photo AS $photo) {
2616 $body = "[img]".unxmlify($photo->remote_photo_path).
2617 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2620 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2622 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2624 // Add OEmbed and other information to the body
2625 if (!self::is_redmatrix($contact["url"])) {
2626 $body = add_page_info_to_body($body, false, true);
2630 /// @todo enable support for polls
2631 //if ($data->poll) {
2632 // foreach ($data->poll AS $poll)
2637 /// @todo enable support for events
2639 $datarray["uid"] = $importer["uid"];
2640 $datarray["contact-id"] = $contact["id"];
2641 $datarray["network"] = NETWORK_DIASPORA;
2643 $datarray["author-name"] = $contact["name"];
2644 $datarray["author-link"] = $contact["url"];
2645 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2647 $datarray["owner-name"] = $datarray["author-name"];
2648 $datarray["owner-link"] = $datarray["author-link"];
2649 $datarray["owner-avatar"] = $datarray["author-avatar"];
2651 $datarray["guid"] = $guid;
2652 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2654 $datarray["verb"] = ACTIVITY_POST;
2655 $datarray["gravity"] = GRAVITY_PARENT;
2657 $datarray["protocol"] = PROTOCOL_DIASPORA;
2658 $datarray["source"] = $xml;
2660 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2662 if ($provider_display_name != "") {
2663 $datarray["app"] = $provider_display_name;
2666 $datarray["plink"] = self::plink($author, $guid);
2667 $datarray["private"] = (($public == "false") ? 1 : 0);
2668 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2670 if (isset($address["address"])) {
2671 $datarray["location"] = $address["address"];
2674 if (isset($address["lat"]) && isset($address["lng"])) {
2675 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2678 self::fetch_guid($datarray);
2679 $message_id = item_store($datarray);
2682 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2689 /* ************************************************************************************** *
2690 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2691 * ************************************************************************************** */
2694 * @brief returnes the handle of a contact
2696 * @param array $me contact array
2698 * @return string the handle in the format user@domain.tld
2700 private static function my_handle($contact) {
2701 if ($contact["addr"] != "") {
2702 return $contact["addr"];
2705 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2706 // So - just in case - we build the the address here.
2707 if ($contact["nickname"] != "") {
2708 $nick = $contact["nickname"];
2710 $nick = $contact["nick"];
2713 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(),"://") + 3);
2718 * @brief Creates the data for a private message in the new format
2720 * @param string $msg The message that is to be transmitted
2721 * @param array $user The record of the sender
2722 * @param array $contact Target of the communication
2723 * @param string $prvkey The private key of the sender
2724 * @param string $pubkey The public key of the receiver
2726 * @return string The encrypted data
2728 public static function encode_private_data($msg, $user, $contact, $prvkey, $pubkey) {
2730 logger("Message: ".$msg, LOGGER_DATA);
2732 // without a public key nothing will work
2734 logger("pubkey missing: contact id: ".$contact["id"]);
2738 $aes_key = openssl_random_pseudo_bytes(32);
2739 $b_aes_key = base64_encode($aes_key);
2740 $iv = openssl_random_pseudo_bytes(16);
2741 $b_iv = base64_encode($iv);
2743 $ciphertext = self::aes_encrypt($aes_key, $iv, $msg);
2745 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2747 $encrypted_key_bundle = "";
2748 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2750 $json_object = json_encode(array("aes_key" => base64_encode($encrypted_key_bundle),
2751 "encrypted_magic_envelope" => base64_encode($ciphertext)));
2753 return $json_object;
2757 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2759 * @param string $msg The message that is to be transmitted
2760 * @param array $user The record of the sender
2762 * @return string The envelope
2764 public static function build_magic_envelope($msg, $user) {
2766 $b64url_data = base64url_encode($msg);
2767 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2769 $key_id = base64url_encode(self::my_handle($user));
2770 $type = "application/xml";
2771 $encoding = "base64url";
2772 $alg = "RSA-SHA256";
2773 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2775 // Fallback if the private key wasn't transmitted in the expected field
2776 if ($user['uprvkey'] == "")
2777 $user['uprvkey'] = $user['prvkey'];
2779 $signature = rsa_sign($signable_data, $user["uprvkey"]);
2780 $sig = base64url_encode($signature);
2782 $xmldata = array("me:env" => array("me:data" => $data,
2783 "@attributes" => array("type" => $type),
2784 "me:encoding" => $encoding,
2787 "@attributes2" => array("key_id" => $key_id)));
2789 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2791 return xml::from_array($xmldata, $xml, false, $namespaces);
2795 * @brief Create the envelope for a message
2797 * @param string $msg The message that is to be transmitted
2798 * @param array $user The record of the sender
2799 * @param array $contact Target of the communication
2800 * @param string $prvkey The private key of the sender
2801 * @param string $pubkey The public key of the receiver
2802 * @param bool $public Is the message public?
2804 * @return string The message that will be transmitted to other servers
2806 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2808 // The message is put into an envelope with the sender's signature
2809 $envelope = self::build_magic_envelope($msg, $user);
2811 // Private messages are put into a second envelope, encrypted with the receivers public key
2813 $envelope = self::encode_private_data($envelope, $user, $contact, $prvkey, $pubkey);
2820 * @brief Creates a signature for a message
2822 * @param array $owner the array of the owner of the message
2823 * @param array $message The message that is to be signed
2825 * @return string The signature
2827 private static function signature($owner, $message) {
2829 unset($sigmsg["author_signature"]);
2830 unset($sigmsg["parent_author_signature"]);
2832 $signed_text = implode(";", $sigmsg);
2834 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2838 * @brief Transmit a message to a target server
2840 * @param array $owner the array of the item owner
2841 * @param array $contact Target of the communication
2842 * @param string $envelope The message that is to be transmitted
2843 * @param bool $public_batch Is it a public post?
2844 * @param bool $queue_run Is the transmission called from the queue?
2845 * @param string $guid message guid
2847 * @return int Result of the transmission
2849 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run=false, $guid = "") {
2853 $enabled = intval(get_config("system", "diaspora_enabled"));
2857 $logid = random_string(4);
2858 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2860 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2864 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2866 if (!$queue_run && was_recently_delayed($contact["id"])) {
2869 if (!intval(get_config("system", "diaspora_test"))) {
2870 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
2872 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
2873 $return_code = $a->get_curl_code();
2875 logger("test_mode");
2880 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2882 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2883 logger("queue message");
2885 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2886 intval($contact["id"]),
2887 dbesc(NETWORK_DIASPORA),
2889 intval($public_batch)
2892 logger("add_to_queue ignored - identical item already in queue");
2894 // queue message for redelivery
2895 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
2897 // The message could not be delivered. We mark the contact as "dead"
2898 mark_for_death($contact);
2900 } elseif (($return_code >= 200) && ($return_code <= 299)) {
2901 // We successfully delivered a message, the contact is alive
2902 unmark_for_death($contact);
2905 return(($return_code) ? $return_code : (-1));
2910 * @brief Build the post xml
2912 * @param string $type The message type
2913 * @param array $message The message data
2915 * @return string The post XML
2917 public static function build_post_xml($type, $message) {
2919 $data = array($type => $message);
2921 return xml::from_array($data, $xml);
2925 * @brief Builds and transmit messages
2927 * @param array $owner the array of the item owner
2928 * @param array $contact Target of the communication
2929 * @param string $type The message type
2930 * @param array $message The message data
2931 * @param bool $public_batch Is it a public post?
2932 * @param string $guid message guid
2933 * @param bool $spool Should the transmission be spooled or transmitted?
2935 * @return int Result of the transmission
2937 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2939 $msg = self::build_post_xml($type, $message);
2941 logger('message: '.$msg, LOGGER_DATA);
2942 logger('send guid '.$guid, LOGGER_DEBUG);
2944 // Fallback if the private key wasn't transmitted in the expected field
2945 if ($owner['uprvkey'] == "")
2946 $owner['uprvkey'] = $owner['prvkey'];
2948 $envelope = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2951 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
2954 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
2956 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2958 return $return_code;
2962 * @brief Sends a "share" message
2964 * @param array $owner the array of the item owner
2965 * @param array $contact Target of the communication
2967 * @return int The result of the transmission
2969 public static function send_share($owner, $contact) {
2972 * @todo support the different possible combinations of "following" and "sharing"
2973 * Currently, Diaspora only interprets the "sharing" field
2975 * Before switching this code productive, we have to check all "send_share" calls if "rel" is set correctly
2979 switch ($contact["rel"]) {
2980 case CONTACT_IS_FRIEND:
2983 case CONTACT_IS_SHARING:
2986 case CONTACT_IS_FOLLOWER:
2992 $message = array("author" => self::my_handle($owner),
2993 "recipient" => $contact["addr"],
2994 "following" => "true",
2995 "sharing" => "true");
2997 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2999 return self::build_and_transmit($owner, $contact, "contact", $message);
3003 * @brief sends an "unshare"
3005 * @param array $owner the array of the item owner
3006 * @param array $contact Target of the communication
3008 * @return int The result of the transmission
3010 public static function send_unshare($owner, $contact) {
3012 $message = array("author" => self::my_handle($owner),
3013 "recipient" => $contact["addr"],
3014 "following" => "false",
3015 "sharing" => "false");
3017 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3019 return self::build_and_transmit($owner, $contact, "contact", $message);
3023 * @brief Checks a message body if it is a reshare
3025 * @param string $body The message body that is to be check
3026 * @param bool $complete Should it be a complete check or a simple check?
3028 * @return array|bool Reshare details or "false" if no reshare
3030 public static function is_reshare($body, $complete = true) {
3031 $body = trim($body);
3033 // Skip if it isn't a pure repeated messages
3034 // Does it start with a share?
3035 if ((strpos($body, "[share") > 0) && $complete)
3038 // Does it end with a share?
3039 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3042 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3043 // Skip if there is no shared message in there
3044 if ($body == $attributes)
3047 // If we don't do the complete check we quit here
3052 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3053 if ($matches[1] != "")
3054 $guid = $matches[1];
3056 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3057 if ($matches[1] != "")
3058 $guid = $matches[1];
3061 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3062 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3065 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3066 $ret["root_guid"] = $guid;
3072 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3073 if ($matches[1] != "")
3074 $profile = $matches[1];
3076 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3077 if ($matches[1] != "")
3078 $profile = $matches[1];
3082 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3083 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == ""))
3087 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3088 if ($matches[1] != "")
3089 $link = $matches[1];
3091 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3092 if ($matches[1] != "")
3093 $link = $matches[1];
3095 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3096 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == ""))
3103 * @brief Create an event array
3105 * @param integer $event_id The id of the event
3107 * @return array with event data
3109 private static function build_event($event_id) {
3111 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3112 if (!dbm::is_result($r)) {
3118 $eventdata = array();
3120 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3121 if (!dbm::is_result($r)) {
3127 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3128 if (!dbm::is_result($r)) {
3134 $eventdata['author'] = self::my_handle($owner);
3136 if ($event['guid']) {
3137 $eventdata['guid'] = $event['guid'];
3140 $mask = 'Y-m-d\TH:i:s\Z';
3142 /// @todo - establish "all day" events in Friendica
3143 $eventdata["all_day"] = "false";
3145 if (!$event['adjust']) {
3146 $eventdata['timezone'] = $user['timezone'];
3148 if ($eventdata['timezone'] == "") {
3149 $eventdata['timezone'] = 'UTC';
3153 if ($event['start']) {
3154 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3156 if ($event['finish'] && !$event['nofinish']) {
3157 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3159 if ($event['summary']) {
3160 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3162 if ($event['desc']) {
3163 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3165 if ($event['location']) {
3166 $location = array();
3167 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3168 $location["lat"] = 0;
3169 $location["lng"] = 0;
3170 $eventdata['location'] = $location;
3177 * @brief Create a post (status message or reshare)
3179 * @param array $item The item that will be exported
3180 * @param array $owner the array of the item owner
3183 * 'type' -> Message type ("status_message" or "reshare")
3184 * 'message' -> Array of XML elements of the status
3186 public static function build_status($item, $owner) {
3188 $cachekey = "diaspora:build_status:".$item['guid'];
3190 $result = Cache::get($cachekey);
3191 if (!is_null($result)) {
3195 $myaddr = self::my_handle($owner);
3197 $public = (($item["private"]) ? "false" : "true");
3199 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3201 // Detect a share element and do a reshare
3202 if (!$item['private'] && ($ret = self::is_reshare($item["body"]))) {
3203 $message = array("author" => $myaddr,
3204 "guid" => $item["guid"],
3205 "created_at" => $created,
3206 "root_author" => $ret["root_handle"],
3207 "root_guid" => $ret["root_guid"],
3208 "provider_display_name" => $item["app"],
3209 "public" => $public);
3213 $title = $item["title"];
3214 $body = $item["body"];
3216 // convert to markdown
3217 $body = html_entity_decode(bb2diaspora($body));
3221 $body = "## ".html_entity_decode($title)."\n\n".$body;
3223 if ($item["attach"]) {
3224 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3226 $body .= "\n".t("Attachments:")."\n";
3227 foreach ($matches as $mtch)
3228 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3232 $location = array();
3234 if ($item["location"] != "")
3235 $location["address"] = $item["location"];
3237 if ($item["coord"] != "") {
3238 $coord = explode(" ", $item["coord"]);
3239 $location["lat"] = $coord[0];
3240 $location["lng"] = $coord[1];
3243 $message = array("author" => $myaddr,
3244 "guid" => $item["guid"],
3245 "created_at" => $created,
3246 "public" => $public,
3248 "provider_display_name" => $item["app"],
3249 "location" => $location);
3251 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3252 if (!isset($location["lat"]) || !isset($location["lng"])) {
3253 unset($message["location"]);
3256 if ($item['event-id'] > 0) {
3257 $event = self::build_event($item['event-id']);
3258 if (count($event)) {
3259 $message['event'] = $event;
3261 /// @todo Once Diaspora supports it, we will remove the body
3262 // $message['text'] = '';
3266 $type = "status_message";
3269 $msg = array("type" => $type, "message" => $message);
3271 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3277 * @brief Sends a post
3279 * @param array $item The item that will be exported
3280 * @param array $owner the array of the item owner
3281 * @param array $contact Target of the communication
3282 * @param bool $public_batch Is it a public post?
3284 * @return int The result of the transmission
3286 public static function send_status($item, $owner, $contact, $public_batch = false) {
3288 $status = self::build_status($item, $owner);
3290 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3294 * @brief Creates a "like" object
3296 * @param array $item The item that will be exported
3297 * @param array $owner the array of the item owner
3299 * @return array The data for a "like"
3301 private static function construct_like($item, $owner) {
3303 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3304 dbesc($item["thr-parent"]));
3305 if (!dbm::is_result($p))
3310 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3311 if ($item['verb'] === ACTIVITY_LIKE) {
3313 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3314 $positive = "false";
3317 return(array("author" => self::my_handle($owner),
3318 "guid" => $item["guid"],
3319 "parent_guid" => $parent["guid"],
3320 "parent_type" => $target_type,
3321 "positive" => $positive,
3322 "author_signature" => ""));
3326 * @brief Creates an "EventParticipation" object
3328 * @param array $item The item that will be exported
3329 * @param array $owner the array of the item owner
3331 * @return array The data for an "EventParticipation"
3333 private static function construct_attend($item, $owner) {
3335 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3336 dbesc($item["thr-parent"]));
3337 if (!dbm::is_result($p))
3342 switch ($item['verb']) {
3343 case ACTIVITY_ATTEND:
3344 $attend_answer = 'accepted';
3346 case ACTIVITY_ATTENDNO:
3347 $attend_answer = 'declined';
3349 case ACTIVITY_ATTENDMAYBE:
3350 $attend_answer = 'tentative';
3353 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3357 return(array("author" => self::my_handle($owner),
3358 "guid" => $item["guid"],
3359 "parent_guid" => $parent["guid"],
3360 "status" => $attend_answer,
3361 "author_signature" => ""));
3365 * @brief Creates the object for a comment
3367 * @param array $item The item that will be exported
3368 * @param array $owner the array of the item owner
3370 * @return array The data for a comment
3372 private static function construct_comment($item, $owner) {
3374 $cachekey = "diaspora:construct_comment:".$item['guid'];
3376 $result = Cache::get($cachekey);
3377 if (!is_null($result)) {
3381 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3382 intval($item["parent"]),
3383 intval($item["parent"])
3386 if (!dbm::is_result($p))
3391 $text = html_entity_decode(bb2diaspora($item["body"]));
3392 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3394 $comment = array("author" => self::my_handle($owner),
3395 "guid" => $item["guid"],
3396 "created_at" => $created,
3397 "parent_guid" => $parent["guid"],
3399 "author_signature" => "");
3401 // Send the thread parent guid only if it is a threaded comment
3402 if ($item['thr-parent'] != $item['parent-uri']) {
3403 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3406 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3412 * @brief Send a like or a comment
3414 * @param array $item The item that will be exported
3415 * @param array $owner the array of the item owner
3416 * @param array $contact Target of the communication
3417 * @param bool $public_batch Is it a public post?
3419 * @return int The result of the transmission
3421 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3423 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3424 $message = self::construct_attend($item, $owner);
3425 $type = "event_participation";
3426 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3427 $message = self::construct_like($item, $owner);
3430 $message = self::construct_comment($item, $owner);
3437 $message["author_signature"] = self::signature($owner, $message);
3439 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3443 * @brief Creates a message from a signature record entry
3445 * @param array $item The item that will be exported
3446 * @param array $signature The entry of the "sign" record
3448 * @return string The message
3450 private static function message_from_signature($item, $signature) {
3452 // Split the signed text
3453 $signed_parts = explode(";", $signature['signed_text']);
3455 if ($item["deleted"])
3456 $message = array("author" => $signature['signer'],
3457 "target_guid" => $signed_parts[0],
3458 "target_type" => $signed_parts[1]);
3459 elseif ($item['verb'] === ACTIVITY_LIKE)
3460 $message = array("author" => $signed_parts[4],
3461 "guid" => $signed_parts[1],
3462 "parent_guid" => $signed_parts[3],
3463 "parent_type" => $signed_parts[2],
3464 "positive" => $signed_parts[0],
3465 "author_signature" => $signature['signature'],
3466 "parent_author_signature" => "");
3468 // Remove the comment guid
3469 $guid = array_shift($signed_parts);
3471 // Remove the parent guid
3472 $parent_guid = array_shift($signed_parts);
3474 // Remove the handle
3475 $handle = array_pop($signed_parts);
3477 // Glue the parts together
3478 $text = implode(";", $signed_parts);
3480 $message = array("author" => $handle,
3482 "parent_guid" => $parent_guid,
3483 "text" => implode(";", $signed_parts),
3484 "author_signature" => $signature['signature'],
3485 "parent_author_signature" => "");
3491 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3493 * @param array $item The item that will be exported
3494 * @param array $owner the array of the item owner
3495 * @param array $contact Target of the communication
3496 * @param bool $public_batch Is it a public post?
3498 * @return int The result of the transmission
3500 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3502 if ($item["deleted"])
3503 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3504 elseif ($item['verb'] === ACTIVITY_LIKE)
3509 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3511 // fetch the original signature
3513 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3514 intval($item["id"]));
3517 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3523 // Old way - is used by the internal Friendica functions
3524 /// @todo Change all signatur storing functions to the new format
3525 if ($signature['signed_text'] && $signature['signature'] && $signature['signer'])
3526 $message = self::message_from_signature($item, $signature);
3528 $msg = json_decode($signature['signed_text'], true);
3531 if (is_array($msg)) {
3532 foreach ($msg AS $field => $data) {
3533 if (!$item["deleted"]) {
3534 if ($field == "diaspora_handle") {
3537 if ($field == "target_type") {
3538 $field = "parent_type";
3542 $message[$field] = $data;
3545 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3548 $message["parent_author_signature"] = self::signature($owner, $message);
3550 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3552 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3556 * @brief Sends a retraction (deletion) of a message, like or comment
3558 * @param array $item The item that will be exported
3559 * @param array $owner the array of the item owner
3560 * @param array $contact Target of the communication
3561 * @param bool $public_batch Is it a public post?
3562 * @param bool $relay Is the retraction transmitted from a relay?
3564 * @return int The result of the transmission
3566 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3568 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3570 $msg_type = "retraction";
3572 if ($item['id'] == $item['parent']) {
3573 $target_type = "Post";
3574 } elseif ($item["verb"] == ACTIVITY_LIKE) {
3575 $target_type = "Like";
3577 $target_type = "Comment";
3580 $message = array("author" => $itemaddr,
3581 "target_guid" => $item['guid'],
3582 "target_type" => $target_type);
3584 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3586 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3590 * @brief Sends a mail
3592 * @param array $item The item that will be exported
3593 * @param array $owner The owner
3594 * @param array $contact Target of the communication
3596 * @return int The result of the transmission
3598 public static function send_mail($item, $owner, $contact) {
3600 $myaddr = self::my_handle($owner);
3602 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3603 intval($item["convid"]),
3604 intval($item["uid"])
3607 if (!dbm::is_result($r)) {
3608 logger("conversation not found.");
3614 "author" => $cnv["creator"],
3615 "guid" => $cnv["guid"],
3616 "subject" => $cnv["subject"],
3617 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3618 "participants" => $cnv["recips"]
3621 $body = bb2diaspora($item["body"]);
3622 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3625 "author" => $myaddr,
3626 "guid" => $item["guid"],
3627 "conversation_guid" => $cnv["guid"],
3629 "created_at" => $created,
3632 if ($item["reply"]) {
3637 "author" => $cnv["creator"],
3638 "guid" => $cnv["guid"],
3639 "subject" => $cnv["subject"],
3640 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3641 "participants" => $cnv["recips"],
3644 $type = "conversation";
3647 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3651 * @brief Sends profile data
3653 * @param int $uid The user id
3655 public static function send_profile($uid, $recips = false) {
3661 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3662 AND `uid` = %d AND `rel` != %d",
3663 dbesc(NETWORK_DIASPORA),
3665 intval(CONTACT_IS_SHARING)
3670 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3672 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3673 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3674 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3683 $handle = $profile["addr"];
3684 $first = ((strpos($profile['name'],' ')
3685 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3686 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3687 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3688 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3689 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3690 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3692 if ($searchable === 'true') {
3693 $dob = '1000-00-00';
3695 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3696 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3698 $about = $profile['about'];
3699 $about = strip_tags(bbcode($about));
3701 $location = formatted_location($profile);
3703 if ($profile['pub_keywords']) {
3704 $kw = str_replace(',',' ',$profile['pub_keywords']);
3705 $kw = str_replace(' ',' ',$kw);
3706 $arr = explode(' ',$profile['pub_keywords']);
3708 for ($x = 0; $x < 5; $x ++) {
3710 $tags .= '#'. trim($arr[$x]) .' ';
3714 $tags = trim($tags);
3717 $message = array("author" => $handle,
3718 "first_name" => $first,
3719 "last_name" => $last,
3720 "image_url" => $large,
3721 "image_url_medium" => $medium,
3722 "image_url_small" => $small,
3724 "gender" => $profile['gender'],
3726 "location" => $location,
3727 "searchable" => $searchable,
3729 "tag_string" => $tags);
3731 foreach ($recips as $recip) {
3732 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3733 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3738 * @brief Stores the signature for likes that are created on our system
3740 * @param array $contact The contact array of the "like"
3741 * @param int $post_id The post id of the "like"
3743 * @return bool Success
3745 public static function store_like_signature($contact, $post_id) {
3747 // Is the contact the owner? Then fetch the private key
3748 if (!$contact['self'] || ($contact['uid'] == 0)) {
3749 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3753 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3754 if (!dbm::is_result($r)) {
3758 $contact["uprvkey"] = $r[0]['prvkey'];
3760 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3761 if (!dbm::is_result($r)) {
3765 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3769 $message = self::construct_like($r[0], $contact);
3770 $message["author_signature"] = self::signature($contact, $message);
3773 * Now store the signature more flexible to dynamically support new fields.
3774 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3776 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
3778 logger('Stored diaspora like signature');
3783 * @brief Stores the signature for comments that are created on our system
3785 * @param array $item The item array of the comment
3786 * @param array $contact The contact array of the item owner
3787 * @param string $uprvkey The private key of the sender
3788 * @param int $message_id The message id of the comment
3790 * @return bool Success
3792 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3794 if ($uprvkey == "") {
3795 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3799 $contact["uprvkey"] = $uprvkey;
3801 $message = self::construct_comment($item, $contact);
3802 $message["author_signature"] = self::signature($contact, $message);
3805 * Now store the signature more flexible to dynamically support new fields.
3806 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3808 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
3810 logger('Stored diaspora comment signature');