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.
10 namespace Friendica\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBM;
19 use Friendica\Model\GlobalContact;
20 use Friendica\Network\Probe;
21 use Friendica\Object\Contact;
22 use Friendica\Object\Profile;
23 use Friendica\Util\XML;
28 require_once 'include/items.php';
29 require_once 'include/bb2diaspora.php';
30 require_once 'include/Contact.php';
31 require_once 'include/Photo.php';
32 require_once 'include/group.php';
33 require_once 'include/datetime.php';
34 require_once 'include/queue_fn.php';
37 * @brief This class contain functions to create and send Diaspora XML files
44 * @brief Return a list of relay servers
46 * This is an experimental Diaspora feature.
48 * @return array of relay servers
50 public static function relay_list()
52 $serverdata = Config::get("system", "relay_server");
53 if ($serverdata == "") {
59 $servers = explode(",", $serverdata);
61 foreach ($servers as $server) {
62 $server = trim($server);
63 $addr = "relay@".str_replace("http://", "", normalise_link($server));
64 $batch = $server."/receive/public";
67 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
70 dbesc(normalise_link($server))
75 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
76 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
81 dbesc(normalise_link($server)),
83 dbesc(NETWORK_DIASPORA),
84 intval(CONTACT_IS_FOLLOWER),
85 dbesc(datetime_convert()),
86 dbesc(datetime_convert()),
87 dbesc(datetime_convert())
90 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
92 $relay[] = $relais[0];
95 $relay[] = $relais[0];
103 * @brief repairs a signature that was double encoded
105 * The function is unused at the moment. It was copied from the old implementation.
107 * @param string $signature The signature
108 * @param string $handle The handle of the signature owner
109 * @param integer $level This value is only set inside this function to avoid endless loops
111 * @return string the repaired signature
113 private static function repair_signature($signature, $handle = "", $level = 1)
115 if ($signature == "") {
119 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
120 $signature = base64_decode($signature);
121 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
123 // Do a recursive call to be able to fix even multiple levels
125 $signature = self::repair_signature($signature, $handle, ++$level);
133 * @brief verify the envelope and return the verified data
135 * @param string $envelope The magic envelope
137 * @return string verified data
139 private static function verify_magic_envelope($envelope)
141 $basedom = parse_xml_string($envelope);
143 if (!is_object($basedom)) {
144 logger("Envelope is no XML file");
148 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
150 if (sizeof($children) == 0) {
151 logger("XML has no children");
157 $data = base64url_decode($children->data);
158 $type = $children->data->attributes()->type[0];
160 $encoding = $children->encoding;
162 $alg = $children->alg;
164 $sig = base64url_decode($children->sig);
165 $key_id = $children->sig->attributes()->key_id[0];
167 $handle = base64url_decode($key_id);
170 $b64url_data = base64url_encode($data);
171 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
173 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
175 $key = self::key($handle);
177 $verify = rsa_verify($signable_data, $sig, $key);
179 logger('Message did not verify. Discarding.');
187 * @brief encrypts data via AES
189 * @param string $key The AES key
190 * @param string $iv The IV (is used for CBC encoding)
191 * @param string $data The data that is to be encrypted
193 * @return string encrypted data
195 private static function aes_encrypt($key, $iv, $data)
197 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
201 * @brief decrypts data via AES
203 * @param string $key The AES key
204 * @param string $iv The IV (is used for CBC encoding)
205 * @param string $encrypted The encrypted data
207 * @return string decrypted data
209 private static function aes_decrypt($key, $iv, $encrypted)
211 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
215 * @brief: Decodes incoming Diaspora message in the new format
217 * @param array $importer Array of the importer user
218 * @param string $raw raw post message
221 * 'message' -> decoded Diaspora XML message
222 * 'author' -> author diaspora handle
223 * 'key' -> author public key (converted to pkcs#8)
225 public static function decode_raw($importer, $raw)
227 $data = json_decode($raw);
229 // Is it a private post? Then decrypt the outer Salmon
230 if (is_object($data)) {
231 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
232 $ciphertext = base64_decode($data->encrypted_magic_envelope);
234 $outer_key_bundle = '';
235 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
236 $j_outer_key_bundle = json_decode($outer_key_bundle);
238 if (!is_object($j_outer_key_bundle)) {
239 logger('Outer Salmon did not verify. Discarding.');
240 http_status_exit(400);
243 $outer_iv = base64_decode($j_outer_key_bundle->iv);
244 $outer_key = base64_decode($j_outer_key_bundle->key);
246 $xml = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
251 $basedom = parse_xml_string($xml);
253 if (!is_object($basedom)) {
254 logger('Received data does not seem to be an XML. Discarding. '.$xml);
255 http_status_exit(400);
258 $base = $basedom->children(NAMESPACE_SALMON_ME);
260 // Not sure if this cleaning is needed
261 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
263 // Build the signed data
264 $type = $base->data[0]->attributes()->type[0];
265 $encoding = $base->encoding;
267 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
269 // This is the signature
270 $signature = base64url_decode($base->sig);
272 // Get the senders' public key
273 $key_id = $base->sig[0]->attributes()->key_id[0];
274 $author_addr = base64_decode($key_id);
275 $key = self::key($author_addr);
277 $verify = rsa_verify($signed_data, $signature, $key);
279 logger('Message did not verify. Discarding.');
280 http_status_exit(400);
283 return array('message' => (string)base64url_decode($base->data),
284 'author' => unxmlify($author_addr),
285 'key' => (string)$key);
289 * @brief: Decodes incoming Diaspora message in the deprecated format
291 * @param array $importer Array of the importer user
292 * @param string $xml urldecoded Diaspora salmon
295 * 'message' -> decoded Diaspora XML message
296 * 'author' -> author diaspora handle
297 * 'key' -> author public key (converted to pkcs#8)
299 public static function decode($importer, $xml)
302 $basedom = parse_xml_string($xml);
304 if (!is_object($basedom)) {
305 logger("XML is not parseable.");
308 $children = $basedom->children('https://joindiaspora.com/protocol');
310 if ($children->header) {
312 $author_link = str_replace('acct:', '', $children->header->author_id);
314 // This happens with posts from a relais
316 logger("This is no private post in the old format", LOGGER_DEBUG);
320 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
322 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
323 $ciphertext = base64_decode($encrypted_header->ciphertext);
325 $outer_key_bundle = '';
326 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
328 $j_outer_key_bundle = json_decode($outer_key_bundle);
330 $outer_iv = base64_decode($j_outer_key_bundle->iv);
331 $outer_key = base64_decode($j_outer_key_bundle->key);
333 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
335 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
336 $idom = parse_xml_string($decrypted);
338 $inner_iv = base64_decode($idom->iv);
339 $inner_aes_key = base64_decode($idom->aes_key);
341 $author_link = str_replace('acct:', '', $idom->author_id);
344 $dom = $basedom->children(NAMESPACE_SALMON_ME);
346 // figure out where in the DOM tree our data is hiding
348 if ($dom->provenance->data) {
349 $base = $dom->provenance;
350 } elseif ($dom->env->data) {
352 } elseif ($dom->data) {
357 logger('unable to locate salmon data in xml');
358 http_status_exit(400);
362 // Stash the signature away for now. We have to find their key or it won't be good for anything.
363 $signature = base64url_decode($base->sig);
367 // strip whitespace so our data element will return to one big base64 blob
368 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
371 // stash away some other stuff for later
373 $type = $base->data[0]->attributes()->type[0];
374 $keyhash = $base->sig[0]->attributes()->keyhash[0];
375 $encoding = $base->encoding;
379 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
383 $data = base64url_decode($data);
387 $inner_decrypted = $data;
389 // Decode the encrypted blob
390 $inner_encrypted = base64_decode($data);
391 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
395 logger('Could not retrieve author URI.');
396 http_status_exit(400);
398 // Once we have the author URI, go to the web and try to find their public key
399 // (first this will look it up locally if it is in the fcontact cache)
400 // This will also convert diaspora public key from pkcs#1 to pkcs#8
402 logger('Fetching key for '.$author_link);
403 $key = self::key($author_link);
406 logger('Could not retrieve author key.');
407 http_status_exit(400);
410 $verify = rsa_verify($signed_data, $signature, $key);
413 logger('Message did not verify. Discarding.');
414 http_status_exit(400);
417 logger('Message verified.');
419 return array('message' => (string)$inner_decrypted,
420 'author' => unxmlify($author_link),
421 'key' => (string)$key);
426 * @brief Dispatches public messages and find the fitting receivers
428 * @param array $msg The post that will be dispatched
430 * @return int The message id of the generated message, "true" or "false" if there was an error
432 public static function dispatch_public($msg)
434 $enabled = intval(Config::get("system", "diaspora_enabled"));
436 logger("diaspora is disabled");
440 if (!($postdata = self::valid_posting($msg))) {
441 logger("Invalid posting");
445 $fields = $postdata['fields'];
447 // Is it a an action (comment, like, ...) for our own post?
448 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
449 $guid = notags(unxmlify($fields->parent_guid));
450 $importer = self::importer_for_guid($guid);
451 if (is_array($importer)) {
452 logger("delivering to origin: ".$importer["name"]);
453 $message_id = self::dispatch($importer, $msg, $fields);
458 // Process item retractions. This has to be done separated from the other stuff,
459 // since retractions for comments could come even from non followers.
460 if (!empty($fields) && in_array($fields->getName(), array('retraction'))) {
461 $target = notags(unxmlify($fields->target_type));
462 if (in_array($target, array("Comment", "Like", "Post", "Reshare", "StatusMessage"))) {
463 logger('processing retraction for '.$target, LOGGER_DEBUG);
464 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
465 $message_id = self::dispatch($importer, $msg, $fields);
470 // Now distribute it to the followers
472 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
473 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
474 AND NOT `account_expired` AND NOT `account_removed`",
475 dbesc(NETWORK_DIASPORA),
476 dbesc($msg["author"])
479 if (DBM::is_result($r)) {
480 foreach ($r as $rr) {
481 logger("delivering to: ".$rr["username"]);
482 self::dispatch($rr, $msg, $fields);
484 } elseif (!Config::get('system', 'relay_subscribe', false)) {
485 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
487 // Use a dummy importer to import the data for the public copy
488 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
489 $message_id = self::dispatch($importer, $msg, $fields);
496 * @brief Dispatches the different message types to the different functions
498 * @param array $importer Array of the importer user
499 * @param array $msg The post that will be dispatched
500 * @param object $fields SimpleXML object that contains the message
502 * @return int The message id of the generated message, "true" or "false" if there was an error
504 public static function dispatch($importer, $msg, $fields = null)
506 // The sender is the handle of the contact that sent the message.
507 // This will often be different with relayed messages (for example "like" and "comment")
508 $sender = $msg["author"];
510 // This is only needed for private postings since this is already done for public ones before
511 if (is_null($fields)) {
512 if (!($postdata = self::valid_posting($msg))) {
513 logger("Invalid posting");
516 $fields = $postdata['fields'];
519 $type = $fields->getName();
521 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
524 case "account_migration":
525 return self::receiveAccountMigration($importer, $fields);
527 case "account_deletion":
528 return self::receive_account_deletion($importer, $fields);
531 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
534 return self::receive_contact_request($importer, $fields);
537 return self::receive_conversation($importer, $msg, $fields);
540 return self::receive_like($importer, $sender, $fields);
543 return self::receive_message($importer, $fields);
545 case "participation": // Not implemented
546 return self::receive_participation($importer, $fields);
548 case "photo": // Not implemented
549 return self::receive_photo($importer, $fields);
551 case "poll_participation": // Not implemented
552 return self::receive_poll_participation($importer, $fields);
555 return self::receive_profile($importer, $fields);
558 return self::receive_reshare($importer, $fields, $msg["message"]);
561 return self::receive_retraction($importer, $sender, $fields);
563 case "status_message":
564 return self::receive_status_message($importer, $fields, $msg["message"]);
567 logger("Unknown message type ".$type);
575 * @brief Checks if a posting is valid and fetches the data fields.
577 * This function does not only check the signature.
578 * It also does the conversion between the old and the new diaspora format.
580 * @param array $msg Array with the XML, the sender handle and the sender signature
582 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
584 private static function valid_posting($msg)
586 $data = parse_xml_string($msg["message"]);
588 if (!is_object($data)) {
589 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
593 $first_child = $data->getName();
595 // Is this the new or the old version?
596 if ($data->getName() == "XML") {
598 foreach ($data->post->children() as $child) {
606 $type = $element->getName();
609 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
611 // All retractions are handled identically from now on.
612 // In the new version there will only be "retraction".
613 if (in_array($type, array("signed_retraction", "relayable_retraction")))
614 $type = "retraction";
616 if ($type == "request") {
620 $fields = new SimpleXMLElement("<".$type."/>");
624 foreach ($element->children() as $fieldname => $entry) {
626 // Translation for the old XML structure
627 if ($fieldname == "diaspora_handle") {
628 $fieldname = "author";
630 if ($fieldname == "participant_handles") {
631 $fieldname = "participants";
633 if (in_array($type, array("like", "participation"))) {
634 if ($fieldname == "target_type") {
635 $fieldname = "parent_type";
638 if ($fieldname == "sender_handle") {
639 $fieldname = "author";
641 if ($fieldname == "recipient_handle") {
642 $fieldname = "recipient";
644 if ($fieldname == "root_diaspora_id") {
645 $fieldname = "root_author";
647 if ($type == "status_message") {
648 if ($fieldname == "raw_message") {
652 if ($type == "retraction") {
653 if ($fieldname == "post_guid") {
654 $fieldname = "target_guid";
656 if ($fieldname == "type") {
657 $fieldname = "target_type";
662 if (($fieldname == "author_signature") && ($entry != "")) {
663 $author_signature = base64_decode($entry);
664 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
665 $parent_author_signature = base64_decode($entry);
666 } elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
667 if ($signed_data != "") {
669 $signed_data_parent .= ";";
672 $signed_data .= $entry;
674 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature"))
675 || ($orig_type == "relayable_retraction")
677 XML::copy($entry, $fields, $fieldname);
681 // This is something that shouldn't happen at all.
682 if (in_array($type, array("status_message", "reshare", "profile"))) {
683 if ($msg["author"] != $fields->author) {
684 logger("Message handle is not the same as envelope sender. Quitting this message.");
689 // Only some message types have signatures. So we quit here for the other types.
690 if (!in_array($type, array("comment", "like"))) {
691 return array("fields" => $fields, "relayed" => false);
693 // No author_signature? This is a must, so we quit.
694 if (!isset($author_signature)) {
695 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
699 if (isset($parent_author_signature)) {
702 $key = self::key($msg["author"]);
704 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
705 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);
712 $key = self::key($fields->author);
714 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
715 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
718 return array("fields" => $fields, "relayed" => $relayed);
723 * @brief Fetches the public key for a given handle
725 * @param string $handle The handle
727 * @return string The public key
729 private static function key($handle)
731 $handle = strval($handle);
733 logger("Fetching diaspora key for: ".$handle);
735 $r = self::person_by_handle($handle);
744 * @brief Fetches data for a given handle
746 * @param string $handle The handle
748 * @return array the queried data
750 public static function person_by_handle($handle)
753 "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
754 dbesc(NETWORK_DIASPORA),
759 logger("In cache " . print_r($r, true), LOGGER_DEBUG);
761 // update record occasionally so it doesn't get stale
762 $d = strtotime($person["updated"]." +00:00");
763 if ($d < strtotime("now - 14 days")) {
767 if ($person["guid"] == "") {
772 if (!$person || $update) {
773 logger("create or refresh", LOGGER_DEBUG);
774 $r = Probe::uri($handle, NETWORK_DIASPORA);
776 // Note that Friendica contacts will return a "Diaspora person"
777 // if Diaspora connectivity is enabled on their server
778 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
779 self::add_fcontact($r, $update);
787 * @brief Updates the fcontact table
789 * @param array $arr The fcontact data
790 * @param bool $update Update or insert?
792 * @return string The id of the fcontact entry
794 private static function add_fcontact($arr, $update = false)
798 "UPDATE `fcontact` SET
812 WHERE `url` = '%s' AND `network` = '%s'",
814 dbesc($arr["photo"]),
815 dbesc($arr["request"]),
817 dbesc(strtolower($arr["addr"])),
819 dbesc($arr["batch"]),
820 dbesc($arr["notify"]),
822 dbesc($arr["confirm"]),
823 dbesc($arr["alias"]),
824 dbesc($arr["pubkey"]),
825 dbesc(datetime_convert()),
827 dbesc($arr["network"])
831 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
832 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
833 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
836 dbesc($arr["photo"]),
837 dbesc($arr["request"]),
841 dbesc($arr["batch"]),
842 dbesc($arr["notify"]),
844 dbesc($arr["confirm"]),
845 dbesc($arr["network"]),
846 dbesc($arr["alias"]),
847 dbesc($arr["pubkey"]),
848 dbesc(datetime_convert())
856 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
858 * @param int $contact_id The id in the contact table
859 * @param int $gcontact_id The id in the gcontact table
861 * @return string the handle
863 public static function handle_from_contact($contact_id, $gcontact_id = 0)
867 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
869 if ($gcontact_id != 0) {
871 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
875 if (DBM::is_result($r)) {
876 return strtolower($r[0]["addr"]);
881 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
885 if (DBM::is_result($r)) {
888 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
890 if ($contact['addr'] != "") {
891 $handle = $contact['addr'];
893 $baseurl_start = strpos($contact['url'], '://') + 3;
894 // allows installations in a subdirectory--not sure how Diaspora will handle
895 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
896 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
897 $handle = $contact['nick'].'@'.$baseurl;
901 return strtolower($handle);
905 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
908 * @param mixed $fcontact_guid Hexadecimal string guid
910 * @return string the contact url or null
912 public static function url_from_contact_guid($fcontact_guid)
914 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
917 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
918 dbesc(NETWORK_DIASPORA),
919 dbesc($fcontact_guid)
922 if (DBM::is_result($r)) {
930 * @brief Get a contact id for a given handle
932 * @param int $uid The user id
933 * @param string $handle The handle in the format user@domain.tld
935 * @return The contact id
937 private static function contact_by_handle($uid, $handle)
939 // First do a direct search on the contact table
941 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
946 if (DBM::is_result($r)) {
950 * We haven't found it?
951 * We use another function for it that will possibly create a contact entry.
953 $cid = Contact::getIdForURL($handle, $uid);
956 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
957 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
959 if (DBM::is_result($r)) {
965 $handle_parts = explode("@", $handle);
966 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
968 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
973 if (DBM::is_result($r)) {
977 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
982 * @brief Check if posting is allowed for this contact
984 * @param array $importer Array of the importer user
985 * @param array $contact The contact that is checked
986 * @param bool $is_comment Is the check for a comment?
988 * @return bool is the contact allowed to post?
990 private static function post_allow($importer, $contact, $is_comment = false) {
993 * Perhaps we were already sharing with this person. Now they're sharing with us.
994 * That makes us friends.
995 * Normally this should have handled by getting a request - but this could get lost
997 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1000 array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1001 array('id' => $contact["id"], 'uid' => $contact["uid"])
1004 $contact["rel"] = CONTACT_IS_FRIEND;
1005 logger("defining user ".$contact["nick"]." as friend");
1008 // We don't seem to like that person
1009 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
1010 // Maybe blocked, don't accept.
1012 // We are following this person?
1013 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1014 // Yes, then it is fine.
1016 // Is it a post to a community?
1017 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1020 // Is the message a global user or a comment?
1021 } elseif (($importer["uid"] == 0) || $is_comment) {
1022 // Messages for the global users and comments are always accepted
1030 * @brief Fetches the contact id for a handle and checks if posting is allowed
1032 * @param array $importer Array of the importer user
1033 * @param string $handle The checked handle in the format user@domain.tld
1034 * @param bool $is_comment Is the check for a comment?
1036 * @return array The contact data
1038 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false)
1040 $contact = self::contact_by_handle($importer["uid"], $handle);
1042 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1043 // If a contact isn't found, we accept it anyway if it is a comment
1051 if (!self::post_allow($importer, $contact, $is_comment)) {
1052 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1059 * @brief Does the message already exists on the system?
1061 * @param int $uid The user id
1062 * @param string $guid The guid of the message
1064 * @return int|bool message id if the message already was stored into the system - or false.
1066 private static function message_exists($uid, $guid)
1069 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1074 if (DBM::is_result($r)) {
1075 logger("message ".$guid." already exists for user ".$uid);
1083 * @brief Checks for links to posts in a message
1085 * @param array $item The item array
1087 private static function fetch_guid($item)
1089 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1090 preg_replace_callback(
1092 function ($match) use ($item) {
1093 return self::fetch_guid_sub($match, $item);
1098 preg_replace_callback(
1099 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1100 function ($match) use ($item) {
1101 return self::fetch_guid_sub($match, $item);
1108 * @brief Checks for relative /people/* links in an item body to match local
1109 * contacts or prepends the remote host taken from the author link.
1111 * @param string $body The item body to replace links from
1112 * @param string $author_link The author link for missing local contact fallback
1114 * @return the replaced string
1116 public static function replace_people_guid($body, $author_link)
1118 $return = preg_replace_callback(
1119 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1120 function ($match) use ($author_link) {
1122 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1123 // 1 => '0123456789abcdef'
1125 $handle = self::url_from_contact_guid($match[1]);
1128 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1130 // No local match, restoring absolute remote URL from author scheme and host
1131 $author_url = parse_url($author_link);
1132 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1144 * @brief sub function of "fetch_guid" which checks for links in messages
1146 * @param array $match array containing a link that has to be checked for a message link
1147 * @param array $item The item array
1149 private static function fetch_guid_sub($match, $item)
1151 if (!self::store_by_guid($match[1], $item["author-link"])) {
1152 self::store_by_guid($match[1], $item["owner-link"]);
1157 * @brief Fetches an item with a given guid from a given server
1159 * @param string $guid the message guid
1160 * @param string $server The server address
1161 * @param int $uid The user id of the user
1163 * @return int the message id of the stored message or false
1165 private static function store_by_guid($guid, $server, $uid = 0)
1167 $serverparts = parse_url($server);
1168 $server = $serverparts["scheme"]."://".$serverparts["host"];
1170 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1172 $msg = self::message($guid, $server);
1178 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1180 // Now call the dispatcher
1181 return self::dispatch_public($msg);
1185 * @brief Fetches a message from a server
1187 * @param string $guid message guid
1188 * @param string $server The url of the server
1189 * @param int $level Endless loop prevention
1192 * 'message' => The message XML
1193 * 'author' => The author handle
1194 * 'key' => The public key of the author
1196 private static function message($guid, $server, $level = 0)
1202 // This will work for new Diaspora servers and Friendica servers from 3.5
1203 $source_url = $server."/fetch/post/".urlencode($guid);
1205 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1207 $envelope = fetch_url($source_url);
1209 logger("Envelope was fetched.", LOGGER_DEBUG);
1210 $x = self::verify_magic_envelope($envelope);
1212 logger("Envelope could not be verified.", LOGGER_DEBUG);
1214 logger("Envelope was verified.", LOGGER_DEBUG);
1220 // This will work for older Diaspora and Friendica servers
1222 $source_url = $server."/p/".urlencode($guid).".xml";
1223 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1225 $x = fetch_url($source_url);
1231 $source_xml = parse_xml_string($x);
1233 if (!is_object($source_xml)) {
1237 if ($source_xml->post->reshare) {
1238 // Reshare of a reshare - old Diaspora version
1239 logger("Message is a reshare", LOGGER_DEBUG);
1240 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1241 } elseif ($source_xml->getName() == "reshare") {
1242 // Reshare of a reshare - new Diaspora version
1243 logger("Message is a new reshare", LOGGER_DEBUG);
1244 return self::message($source_xml->root_guid, $server, ++$level);
1249 // Fetch the author - for the old and the new Diaspora version
1250 if ($source_xml->post->status_message->diaspora_handle) {
1251 $author = (string)$source_xml->post->status_message->diaspora_handle;
1252 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1253 $author = (string)$source_xml->author;
1256 // If this isn't a "status_message" then quit
1258 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1262 $msg = array("message" => $x, "author" => $author);
1264 $msg["key"] = self::key($msg["author"]);
1270 * @brief Fetches the item record of a given guid
1272 * @param int $uid The user id
1273 * @param string $guid message guid
1274 * @param string $author The handle of the item
1275 * @param array $contact The contact of the item owner
1277 * @return array the item record
1279 private static function parent_item($uid, $guid, $author, $contact)
1282 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1283 `author-name`, `author-link`, `author-avatar`,
1284 `owner-name`, `owner-link`, `owner-avatar`
1285 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1291 $result = self::store_by_guid($guid, $contact["url"], $uid);
1294 $person = self::person_by_handle($author);
1295 $result = self::store_by_guid($guid, $person["url"], $uid);
1299 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1302 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1303 `author-name`, `author-link`, `author-avatar`,
1304 `owner-name`, `owner-link`, `owner-avatar`
1305 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1313 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1316 logger("parent item found: parent: ".$guid." - user: ".$uid);
1322 * @brief returns contact details
1324 * @param array $contact The default contact if the person isn't found
1325 * @param array $person The record of the person
1326 * @param int $uid The user id
1329 * 'cid' => contact id
1330 * 'network' => network type
1332 private static function author_contact_by_url($contact, $person, $uid)
1335 "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1336 dbesc(normalise_link($person["url"])),
1341 $network = $r[0]["network"];
1343 // We are receiving content from a user that possibly is about to be terminated
1344 // This means the user is vital, so we remove a possible termination date.
1345 Contact::unmarkForArchival($r[0]);
1347 $cid = $contact["id"];
1348 $network = NETWORK_DIASPORA;
1351 return array("cid" => $cid, "network" => $network);
1355 * @brief Is the profile a hubzilla profile?
1357 * @param string $url The profile link
1359 * @return bool is it a hubzilla server?
1361 public static function is_redmatrix($url)
1363 return(strstr($url, "/channel/"));
1367 * @brief Generate a post link with a given handle and message guid
1369 * @param string $addr The user handle
1370 * @param string $guid message guid
1371 * @param string $parent_guid optional parent guid
1373 * @return string the post link
1375 private static function plink($addr, $guid, $parent_guid = '')
1377 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1380 if (!DBM::is_result($r)) {
1381 if ($parent_guid != '') {
1382 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1384 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1388 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1389 // So we try another way as well.
1390 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1391 if (DBM::is_result($s)) {
1392 $r[0]["network"] = $s[0]["network"];
1395 if ($r[0]["network"] == NETWORK_DFRN) {
1396 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1399 if (self::is_redmatrix($r[0]["url"])) {
1400 return $r[0]["url"]."/?f=&mid=".$guid;
1403 if ($parent_guid != '') {
1404 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1406 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1411 * @brief Receives account migration
1413 * @param array $importer Array of the importer user
1414 * @param object $data The message object
1416 * @return bool Success
1418 private static function receiveAccountMigration($importer, $data)
1420 $old_handle = notags(unxmlify($data->author));
1421 $new_handle = notags(unxmlify($data->profile->author));
1422 $signature = notags(unxmlify($data->signature));
1424 $contact = self::contact_by_handle($importer["uid"], $old_handle);
1426 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1430 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1433 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1434 $key = self::key($old_handle);
1435 if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
1436 logger('No valid signature for migration.');
1440 // Update the profile
1441 self::receive_profile($importer, $data->profile);
1443 // change the technical stuff in contact and gcontact
1444 $data = Probe::uri($new_handle);
1445 if ($data['network'] == NETWORK_PHANTOM) {
1446 logger('Account for '.$new_handle." couldn't be probed.");
1450 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1451 'name' => $data['name'], 'nick' => $data['nick'],
1452 'addr' => $data['addr'], 'batch' => $data['batch'],
1453 'notify' => $data['notify'], 'poll' => $data['poll'],
1454 'network' => $data['network']);
1456 dba::update('contact', $fields, array('addr' => $old_handle));
1458 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1459 'name' => $data['name'], 'nick' => $data['nick'],
1460 'addr' => $data['addr'], 'connect' => $data['addr'],
1461 'notify' => $data['notify'], 'photo' => $data['photo'],
1462 'server_url' => $data['baseurl'], 'network' => $data['network']);
1464 dba::update('gcontact', $fields, array('addr' => $old_handle));
1466 logger('Contacts are updated.');
1469 /// @todo This is an extreme performance killer
1471 'owner-link' => array($contact["url"], $data["url"]),
1472 'author-link' => array($contact["url"], $data["url"]),
1474 foreach ($fields as $n => $f) {
1476 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1479 intval($importer["uid"])
1482 if (DBM::is_result($r)) {
1484 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1489 intval($importer["uid"])
1498 logger('Items are updated.');
1504 * @brief Processes an account deletion
1506 * @param array $importer Array of the importer user
1507 * @param object $data The message object
1509 * @return bool Success
1511 private static function receive_account_deletion($importer, $data)
1513 /// @todo Account deletion should remove the contact from the global contacts as well
1515 $author = notags(unxmlify($data->author));
1517 $contact = self::contact_by_handle($importer["uid"], $author);
1519 logger("cannot find contact for author: ".$author);
1523 // We now remove the contact
1524 Contact::remove($contact["id"]);
1529 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1531 * @param string $author Author handle
1532 * @param string $guid Message guid
1533 * @param boolean $onlyfound Only return uri when found in the database
1535 * @return string The constructed uri or the one from our database
1537 private static function get_uri_from_guid($author, $guid, $onlyfound = false)
1539 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1540 if (DBM::is_result($r)) {
1541 return $r[0]["uri"];
1542 } elseif (!$onlyfound) {
1543 return $author.":".$guid;
1550 * @brief Fetch the guid from our database with a given uri
1552 * @param string $uri Message uri
1553 * @param string $uid Author handle
1555 * @return string The post guid
1557 private static function get_guid_from_uri($uri, $uid)
1559 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1560 if (DBM::is_result($r)) {
1561 return $r[0]["guid"];
1568 * @brief Find the best importer for a comment, like, ...
1570 * @param string $guid The guid of the item
1572 * @return array|boolean the origin owner of that post - or false
1574 private static function importer_for_guid($guid)
1576 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1578 if (DBM::is_result($item)) {
1579 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1580 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1581 if (DBM::is_result($contact)) {
1589 * @brief Processes an incoming comment
1591 * @param array $importer Array of the importer user
1592 * @param string $sender The sender of the message
1593 * @param object $data The message object
1594 * @param string $xml The original XML of the message
1596 * @return int The message id of the generated comment or "false" if there was an error
1598 private static function receive_comment($importer, $sender, $data, $xml)
1600 $author = notags(unxmlify($data->author));
1601 $guid = notags(unxmlify($data->guid));
1602 $parent_guid = notags(unxmlify($data->parent_guid));
1603 $text = unxmlify($data->text);
1605 if (isset($data->created_at)) {
1606 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1608 $created_at = datetime_convert();
1611 if (isset($data->thread_parent_guid)) {
1612 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1613 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1618 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1623 $message_id = self::message_exists($importer["uid"], $guid);
1628 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1629 if (!$parent_item) {
1633 $person = self::person_by_handle($author);
1634 if (!is_array($person)) {
1635 logger("unable to find author details");
1639 // Fetch the contact id - if we know this contact
1640 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1642 $datarray = array();
1644 $datarray["uid"] = $importer["uid"];
1645 $datarray["contact-id"] = $author_contact["cid"];
1646 $datarray["network"] = $author_contact["network"];
1648 $datarray["author-name"] = $person["name"];
1649 $datarray["author-link"] = $person["url"];
1650 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1652 $datarray["owner-name"] = $contact["name"];
1653 $datarray["owner-link"] = $contact["url"];
1654 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1656 $datarray["guid"] = $guid;
1657 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1659 $datarray["type"] = "remote-comment";
1660 $datarray["verb"] = ACTIVITY_POST;
1661 $datarray["gravity"] = GRAVITY_COMMENT;
1663 if ($thr_uri != "") {
1664 $datarray["parent-uri"] = $thr_uri;
1666 $datarray["parent-uri"] = $parent_item["uri"];
1669 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1671 $datarray["protocol"] = PROTOCOL_DIASPORA;
1672 $datarray["source"] = $xml;
1674 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1676 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1678 $body = diaspora2bb($text);
1680 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1682 self::fetch_guid($datarray);
1684 $message_id = item_store($datarray);
1686 if ($message_id <= 0) {
1691 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1694 // If we are the origin of the parent we store the original data and notify our followers
1695 if ($message_id && $parent_item["origin"]) {
1696 // Formerly we stored the signed text, the signature and the author in different fields.
1697 // We now store the raw data so that we are more flexible.
1698 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1701 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1708 * @brief processes and stores private messages
1710 * @param array $importer Array of the importer user
1711 * @param array $contact The contact of the message
1712 * @param object $data The message object
1713 * @param array $msg Array of the processed message, author handle and key
1714 * @param object $mesg The private message
1715 * @param array $conversation The conversation record to which this message belongs
1717 * @return bool "true" if it was successful
1719 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation)
1721 $author = notags(unxmlify($data->author));
1722 $guid = notags(unxmlify($data->guid));
1723 $subject = notags(unxmlify($data->subject));
1725 // "diaspora_handle" is the element name from the old version
1726 // "author" is the element name from the new version
1727 if ($mesg->author) {
1728 $msg_author = notags(unxmlify($mesg->author));
1729 } elseif ($mesg->diaspora_handle) {
1730 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1735 $msg_guid = notags(unxmlify($mesg->guid));
1736 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1737 $msg_text = unxmlify($mesg->text);
1738 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1740 if ($msg_conversation_guid != $guid) {
1741 logger("message conversation guid does not belong to the current conversation.");
1745 $body = diaspora2bb($msg_text);
1746 $message_uri = $msg_author.":".$msg_guid;
1748 $person = self::person_by_handle($msg_author);
1753 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1755 intval($importer["uid"])
1757 if (DBM::is_result($r)) {
1758 logger("duplicate message already delivered.", LOGGER_DEBUG);
1763 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1764 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1765 intval($importer["uid"]),
1767 intval($conversation["id"]),
1768 dbesc($person["name"]),
1769 dbesc($person["photo"]),
1770 dbesc($person["url"]),
1771 intval($contact["id"]),
1776 dbesc($message_uri),
1777 dbesc($author.":".$guid),
1778 dbesc($msg_created_at)
1783 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1787 "type" => NOTIFY_MAIL,
1788 "notify_flags" => $importer["notify-flags"],
1789 "language" => $importer["language"],
1790 "to_name" => $importer["username"],
1791 "to_email" => $importer["email"],
1792 "uid" =>$importer["uid"],
1793 "item" => array("subject" => $subject, "body" => $body),
1794 "source_name" => $person["name"],
1795 "source_link" => $person["url"],
1796 "source_photo" => $person["thumb"],
1797 "verb" => ACTIVITY_POST,
1804 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1806 * @param array $importer Array of the importer user
1807 * @param array $msg Array of the processed message, author handle and key
1808 * @param object $data The message object
1810 * @return bool Success
1812 private static function receive_conversation($importer, $msg, $data)
1814 $author = notags(unxmlify($data->author));
1815 $guid = notags(unxmlify($data->guid));
1816 $subject = notags(unxmlify($data->subject));
1817 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1818 $participants = notags(unxmlify($data->participants));
1820 $messages = $data->message;
1822 if (!count($messages)) {
1823 logger("empty conversation");
1827 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1832 $conversation = null;
1835 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1836 intval($importer["uid"]),
1840 $conversation = $c[0];
1843 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1844 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1845 intval($importer["uid"]),
1849 dbesc(datetime_convert()),
1851 dbesc($participants)
1855 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1856 intval($importer["uid"]),
1862 $conversation = $c[0];
1865 if (!$conversation) {
1866 logger("unable to create conversation.");
1870 foreach ($messages as $mesg) {
1871 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1878 * @brief Creates the body for a "like" message
1880 * @param array $contact The contact that send us the "like"
1881 * @param array $parent_item The item array of the parent item
1882 * @param string $guid message guid
1884 * @return string the body
1886 private static function construct_like_body($contact, $parent_item, $guid) {
1887 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1889 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1890 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1891 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1893 return sprintf($bodyverb, $ulink, $alink, $plink);
1897 * @brief Creates a XML object for a "like"
1899 * @param array $importer Array of the importer user
1900 * @param array $parent_item The item array of the parent item
1902 * @return string The XML
1904 private static function construct_like_object($importer, $parent_item)
1906 $objtype = ACTIVITY_OBJ_NOTE;
1907 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1908 $parent_body = $parent_item["body"];
1910 $xmldata = array("object" => array("type" => $objtype,
1912 "id" => $parent_item["uri"],
1915 "content" => $parent_body));
1917 return XML::from_array($xmldata, $xml, true);
1921 * @brief Processes "like" messages
1923 * @param array $importer Array of the importer user
1924 * @param string $sender The sender of the message
1925 * @param object $data The message object
1927 * @return int The message id of the generated like or "false" if there was an error
1929 private static function receive_like($importer, $sender, $data)
1931 $author = notags(unxmlify($data->author));
1932 $guid = notags(unxmlify($data->guid));
1933 $parent_guid = notags(unxmlify($data->parent_guid));
1934 $parent_type = notags(unxmlify($data->parent_type));
1935 $positive = notags(unxmlify($data->positive));
1937 // likes on comments aren't supported by Diaspora - only on posts
1938 // But maybe this will be supported in the future, so we will accept it.
1939 if (!in_array($parent_type, array("Post", "Comment"))) {
1943 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1948 $message_id = self::message_exists($importer["uid"], $guid);
1953 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1954 if (!$parent_item) {
1958 $person = self::person_by_handle($author);
1959 if (!is_array($person)) {
1960 logger("unable to find author details");
1964 // Fetch the contact id - if we know this contact
1965 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1967 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1968 // We would accept this anyhow.
1969 if ($positive == "true") {
1970 $verb = ACTIVITY_LIKE;
1972 $verb = ACTIVITY_DISLIKE;
1975 $datarray = array();
1977 $datarray["protocol"] = PROTOCOL_DIASPORA;
1979 $datarray["uid"] = $importer["uid"];
1980 $datarray["contact-id"] = $author_contact["cid"];
1981 $datarray["network"] = $author_contact["network"];
1983 $datarray["author-name"] = $person["name"];
1984 $datarray["author-link"] = $person["url"];
1985 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1987 $datarray["owner-name"] = $contact["name"];
1988 $datarray["owner-link"] = $contact["url"];
1989 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1991 $datarray["guid"] = $guid;
1992 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1994 $datarray["type"] = "activity";
1995 $datarray["verb"] = $verb;
1996 $datarray["gravity"] = GRAVITY_LIKE;
1997 $datarray["parent-uri"] = $parent_item["uri"];
1999 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2000 $datarray["object"] = self::construct_like_object($importer, $parent_item);
2002 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
2004 $message_id = item_store($datarray);
2006 if ($message_id <= 0) {
2011 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2014 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2015 if ($parent_item["id"] != $parent_item["parent"]) {
2016 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
2017 $origin = $toplevel["origin"];
2019 $origin = $parent_item["origin"];
2022 // If we are the origin of the parent we store the original data and notify our followers
2023 if ($message_id && $origin) {
2024 // Formerly we stored the signed text, the signature and the author in different fields.
2025 // We now store the raw data so that we are more flexible.
2026 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
2029 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2036 * @brief Processes private messages
2038 * @param array $importer Array of the importer user
2039 * @param object $data The message object
2041 * @return bool Success?
2043 private static function receive_message($importer, $data)
2045 $author = notags(unxmlify($data->author));
2046 $guid = notags(unxmlify($data->guid));
2047 $conversation_guid = notags(unxmlify($data->conversation_guid));
2048 $text = unxmlify($data->text);
2049 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2051 $contact = self::allowed_contact_by_handle($importer, $author, true);
2056 $conversation = null;
2059 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2060 intval($importer["uid"]),
2061 dbesc($conversation_guid)
2064 $conversation = $c[0];
2066 logger("conversation not available.");
2070 $message_uri = $author.":".$guid;
2072 $person = self::person_by_handle($author);
2074 logger("unable to find author details");
2078 $body = diaspora2bb($text);
2080 $body = self::replace_people_guid($body, $person["url"]);
2085 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2087 intval($importer["uid"])
2089 if (DBM::is_result($r)) {
2090 logger("duplicate message already delivered.", LOGGER_DEBUG);
2095 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2096 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2097 intval($importer["uid"]),
2099 intval($conversation["id"]),
2100 dbesc($person["name"]),
2101 dbesc($person["photo"]),
2102 dbesc($person["url"]),
2103 intval($contact["id"]),
2104 dbesc($conversation["subject"]),
2108 dbesc($message_uri),
2109 dbesc($author.":".$conversation["guid"]),
2115 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
2120 * @brief Processes participations - unsupported by now
2122 * @param array $importer Array of the importer user
2123 * @param object $data The message object
2125 * @return bool always true
2127 private static function receive_participation($importer, $data)
2129 // I'm not sure if we can fully support this message type
2134 * @brief Processes photos - unneeded
2136 * @param array $importer Array of the importer user
2137 * @param object $data The message object
2139 * @return bool always true
2141 private static function receive_photo($importer, $data)
2143 // There doesn't seem to be a reason for this function,
2144 // since the photo data is transmitted in the status message as well
2149 * @brief Processes poll participations - unssupported
2151 * @param array $importer Array of the importer user
2152 * @param object $data The message object
2154 * @return bool always true
2156 private static function receive_poll_participation($importer, $data)
2158 // We don't support polls by now
2163 * @brief Processes incoming profile updates
2165 * @param array $importer Array of the importer user
2166 * @param object $data The message object
2168 * @return bool Success
2170 private static function receive_profile($importer, $data)
2172 $author = strtolower(notags(unxmlify($data->author)));
2174 $contact = self::contact_by_handle($importer["uid"], $author);
2179 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2180 $image_url = unxmlify($data->image_url);
2181 $birthday = unxmlify($data->birthday);
2182 $gender = unxmlify($data->gender);
2183 $about = diaspora2bb(unxmlify($data->bio));
2184 $location = diaspora2bb(unxmlify($data->location));
2185 $searchable = (unxmlify($data->searchable) == "true");
2186 $nsfw = (unxmlify($data->nsfw) == "true");
2187 $tags = unxmlify($data->tag_string);
2189 $tags = explode("#", $tags);
2191 $keywords = array();
2192 foreach ($tags as $tag) {
2193 $tag = trim(strtolower($tag));
2199 $keywords = implode(", ", $keywords);
2201 $handle_parts = explode("@", $author);
2202 $nick = $handle_parts[0];
2205 $name = $handle_parts[0];
2208 if (preg_match("|^https?://|", $image_url) === 0) {
2209 $image_url = "http://".$handle_parts[1].$image_url;
2212 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
2214 // Generic birthday. We don't know the timezone. The year is irrelevant.
2216 $birthday = str_replace("1000", "1901", $birthday);
2218 if ($birthday != "") {
2219 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2222 // this is to prevent multiple birthday notifications in a single year
2223 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2225 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2226 $birthday = $contact["bd"];
2230 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2231 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2235 dbesc(datetime_convert()),
2241 intval($contact["id"]),
2242 intval($importer["uid"])
2245 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2246 "photo" => $image_url, "name" => $name, "location" => $location,
2247 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2248 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2249 "hide" => !$searchable, "nsfw" => $nsfw);
2251 $gcid = GlobalContact::update($gcontact);
2253 GlobalContact::link($gcid, $importer["uid"], $contact["id"]);
2255 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2261 * @brief Processes incoming friend requests
2263 * @param array $importer Array of the importer user
2264 * @param array $contact The contact that send the request
2266 private static function receive_request_make_friend($importer, $contact)
2270 if ($contact["rel"] == CONTACT_IS_SHARING) {
2273 array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2274 array('id' => $contact["id"], 'uid' => $importer["uid"])
2277 // send notification
2280 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2281 intval($importer["uid"])
2284 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2287 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2288 intval($importer["uid"])
2291 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2293 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2295 $arr["protocol"] = PROTOCOL_DIASPORA;
2296 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2297 $arr["uid"] = $importer["uid"];
2298 $arr["contact-id"] = $self[0]["id"];
2300 $arr["type"] = 'wall';
2301 $arr["gravity"] = 0;
2303 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2304 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2305 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2306 $arr["verb"] = ACTIVITY_FRIEND;
2307 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2309 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2310 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2311 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2312 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2314 $arr["object"] = self::construct_new_friend_object($contact);
2316 $arr["last-child"] = 1;
2318 $arr["allow_cid"] = $user[0]["allow_cid"];
2319 $arr["allow_gid"] = $user[0]["allow_gid"];
2320 $arr["deny_cid"] = $user[0]["deny_cid"];
2321 $arr["deny_gid"] = $user[0]["deny_gid"];
2323 $i = item_store($arr);
2325 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2332 * @brief Creates a XML object for a "new friend" message
2334 * @param array $contact Array of the contact
2336 * @return string The XML
2338 private static function construct_new_friend_object($contact)
2340 $objtype = ACTIVITY_OBJ_PERSON;
2341 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2342 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2344 $xmldata = array("object" => array("type" => $objtype,
2345 "title" => $contact["name"],
2346 "id" => $contact["url"]."/".$contact["name"],
2349 return XML::from_array($xmldata, $xml, true);
2353 * @brief Processes incoming sharing notification
2355 * @param array $importer Array of the importer user
2356 * @param object $data The message object
2358 * @return bool Success
2360 private static function receive_contact_request($importer, $data)
2362 $author = unxmlify($data->author);
2363 $recipient = unxmlify($data->recipient);
2365 if (!$author || !$recipient) {
2369 // the current protocol version doesn't know these fields
2370 // That means that we will assume their existance
2371 if (isset($data->following)) {
2372 $following = (unxmlify($data->following) == "true");
2377 if (isset($data->sharing)) {
2378 $sharing = (unxmlify($data->sharing) == "true");
2383 $contact = self::contact_by_handle($importer["uid"], $author);
2385 // perhaps we were already sharing with this person. Now they're sharing with us.
2386 // That makes us friends.
2389 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2390 self::receive_request_make_friend($importer, $contact);
2392 // refetch the contact array
2393 $contact = self::contact_by_handle($importer["uid"], $author);
2395 // If we are now friends, we are sending a share message.
2396 // Normally we needn't to do so, but the first message could have been vanished.
2397 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2398 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2400 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2401 $ret = self::send_share($u[0], $contact);
2406 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2407 lose_follower($importer, $contact);
2412 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2413 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2415 } elseif (!$following && !$sharing) {
2416 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2418 } elseif (!$following && $sharing) {
2419 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2420 } elseif ($following && $sharing) {
2421 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2422 } elseif ($following && !$sharing) {
2423 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2426 $ret = self::person_by_handle($author);
2428 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2429 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2433 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2436 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2437 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2438 intval($importer["uid"]),
2439 dbesc($ret["network"]),
2440 dbesc($ret["addr"]),
2443 dbesc(normalise_link($ret["url"])),
2445 dbesc($ret["name"]),
2446 dbesc($ret["nick"]),
2447 dbesc($ret["photo"]),
2448 dbesc($ret["pubkey"]),
2449 dbesc($ret["notify"]),
2450 dbesc($ret["poll"]),
2455 // find the contact record we just created
2457 $contact_record = self::contact_by_handle($importer["uid"], $author);
2459 if (!$contact_record) {
2460 logger("unable to locate newly created contact record.");
2464 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2466 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2468 if (intval($def_gid)) {
2469 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2472 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2474 if ($importer["page-flags"] == PAGE_NORMAL) {
2475 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2477 $hash = random_string().(string)time(); // Generate a confirm_key
2480 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2481 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2482 intval($importer["uid"]),
2483 intval($contact_record["id"]),
2486 dbesc(t("Sharing notification from Diaspora network")),
2488 dbesc(datetime_convert())
2491 // automatic friend approval
2493 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2495 update_contact_avatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2497 // technically they are sharing with us (CONTACT_IS_SHARING),
2498 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2499 // we are going to change the relationship and make them a follower.
2501 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2502 $new_relation = CONTACT_IS_FRIEND;
2503 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2504 $new_relation = CONTACT_IS_SHARING;
2506 $new_relation = CONTACT_IS_FOLLOWER;
2510 "UPDATE `contact` SET `rel` = %d,
2518 intval($new_relation),
2519 dbesc(datetime_convert()),
2520 dbesc(datetime_convert()),
2521 intval($contact_record["id"])
2524 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2526 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2527 $ret = self::send_share($u[0], $contact_record);
2529 // Send the profile data, maybe it weren't transmitted before
2530 self::send_profile($importer["uid"], array($contact_record));
2538 * @brief Fetches a message with a given guid
2540 * @param string $guid message guid
2541 * @param string $orig_author handle of the original post
2542 * @param string $author handle of the sharer
2544 * @return array The fetched item
2546 private static function original_item($guid, $orig_author, $author)
2548 // Do we already have this item?
2550 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2551 `author-name`, `author-link`, `author-avatar`
2552 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2556 if (DBM::is_result($r)) {
2557 logger("reshared message ".$guid." already exists on system.");
2559 // Maybe it is already a reshared item?
2560 // Then refetch the content, if it is a reshare from a reshare.
2561 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2562 if (self::is_reshare($r[0]["body"], true)) {
2564 } elseif (self::is_reshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2565 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2567 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2569 // Add OEmbed and other information to the body
2570 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2578 if (!DBM::is_result($r)) {
2579 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2580 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2581 $item_id = self::store_by_guid($guid, $server);
2584 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2585 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2586 $item_id = self::store_by_guid($guid, $server);
2591 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2592 `author-name`, `author-link`, `author-avatar`
2593 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2597 if (DBM::is_result($r)) {
2598 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2599 if (self::is_reshare($r[0]["body"], false)) {
2600 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2601 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2612 * @brief Processes a reshare message
2614 * @param array $importer Array of the importer user
2615 * @param object $data The message object
2616 * @param string $xml The original XML of the message
2618 * @return int the message id
2620 private static function receive_reshare($importer, $data, $xml)
2622 $author = notags(unxmlify($data->author));
2623 $guid = notags(unxmlify($data->guid));
2624 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2625 $root_author = notags(unxmlify($data->root_author));
2626 $root_guid = notags(unxmlify($data->root_guid));
2627 /// @todo handle unprocessed property "provider_display_name"
2628 $public = notags(unxmlify($data->public));
2630 $contact = self::allowed_contact_by_handle($importer, $author, false);
2635 $message_id = self::message_exists($importer["uid"], $guid);
2640 $original_item = self::original_item($root_guid, $root_author, $author);
2641 if (!$original_item) {
2645 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2647 $datarray = array();
2649 $datarray["uid"] = $importer["uid"];
2650 $datarray["contact-id"] = $contact["id"];
2651 $datarray["network"] = NETWORK_DIASPORA;
2653 $datarray["author-name"] = $contact["name"];
2654 $datarray["author-link"] = $contact["url"];
2655 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2657 $datarray["owner-name"] = $datarray["author-name"];
2658 $datarray["owner-link"] = $datarray["author-link"];
2659 $datarray["owner-avatar"] = $datarray["author-avatar"];
2661 $datarray["guid"] = $guid;
2662 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2664 $datarray["verb"] = ACTIVITY_POST;
2665 $datarray["gravity"] = GRAVITY_PARENT;
2667 $datarray["protocol"] = PROTOCOL_DIASPORA;
2668 $datarray["source"] = $xml;
2670 $prefix = share_header(
2671 $original_item["author-name"],
2672 $original_item["author-link"],
2673 $original_item["author-avatar"],
2674 $original_item["guid"],
2675 $original_item["created"],
2678 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2680 $datarray["tag"] = $original_item["tag"];
2681 $datarray["app"] = $original_item["app"];
2683 $datarray["plink"] = self::plink($author, $guid);
2684 $datarray["private"] = (($public == "false") ? 1 : 0);
2685 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2687 $datarray["object-type"] = $original_item["object-type"];
2689 self::fetch_guid($datarray);
2690 $message_id = item_store($datarray);
2693 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2701 * @brief Processes retractions
2703 * @param array $importer Array of the importer user
2704 * @param array $contact The contact of the item owner
2705 * @param object $data The message object
2707 * @return bool success
2709 private static function item_retraction($importer, $contact, $data)
2711 $author = notags(unxmlify($data->author));
2712 $target_guid = notags(unxmlify($data->target_guid));
2713 $target_type = notags(unxmlify($data->target_type));
2715 $person = self::person_by_handle($author);
2716 if (!is_array($person)) {
2717 logger("unable to find author detail for ".$author);
2721 if (empty($contact["url"])) {
2722 $contact["url"] = $person["url"];
2725 // Fetch items that are about to be deleted
2726 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2728 // When we receive a public retraction, we delete every item that we find.
2729 if ($importer['uid'] == 0) {
2730 $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2732 $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2734 $r = dba::select('item', $fields, $condition);
2735 if (!DBM::is_result($r)) {
2736 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2740 while ($item = dba::fetch($r)) {
2741 // Fetch the parent item
2742 $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2744 // Only delete it if the parent author really fits
2745 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2746 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2750 // Currently we don't have a central deletion function that we could use in this case.
2751 // The function "item_drop" doesn't work for that case
2758 'edited' => datetime_convert(),
2759 'changed' => datetime_convert()),
2760 array('id' => $item["id"])
2763 // Delete the thread - if it is a starting post and not a comment
2764 if ($target_type != 'Comment') {
2765 delete_thread($item["id"], $item["parent-uri"]);
2768 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2770 // Now check if the retraction needs to be relayed by us
2771 if ($parent["origin"]) {
2773 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2781 * @brief Receives retraction messages
2783 * @param array $importer Array of the importer user
2784 * @param string $sender The sender of the message
2785 * @param object $data The message object
2787 * @return bool Success
2789 private static function receive_retraction($importer, $sender, $data)
2791 $target_type = notags(unxmlify($data->target_type));
2793 $contact = self::contact_by_handle($importer["uid"], $sender);
2794 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2795 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2799 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2801 switch ($target_type) {
2806 case "StatusMessage":
2807 return self::item_retraction($importer, $contact, $data);
2811 /// @todo What should we do with an "unshare"?
2812 // Removing the contact isn't correct since we still can read the public items
2813 Contact::remove($contact["id"]);
2817 logger("Unknown target type ".$target_type);
2824 * @brief Receives status messages
2826 * @param array $importer Array of the importer user
2827 * @param object $data The message object
2828 * @param string $xml The original XML of the message
2830 * @return int The message id of the newly created item
2832 private static function receive_status_message($importer, $data, $xml)
2834 $author = notags(unxmlify($data->author));
2835 $guid = notags(unxmlify($data->guid));
2836 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2837 $public = notags(unxmlify($data->public));
2838 $text = unxmlify($data->text);
2839 $provider_display_name = notags(unxmlify($data->provider_display_name));
2841 $contact = self::allowed_contact_by_handle($importer, $author, false);
2846 $message_id = self::message_exists($importer["uid"], $guid);
2852 if ($data->location) {
2853 foreach ($data->location->children() as $fieldname => $data) {
2854 $address[$fieldname] = notags(unxmlify($data));
2858 $body = diaspora2bb($text);
2860 $datarray = array();
2862 // Attach embedded pictures to the body
2864 foreach ($data->photo as $photo) {
2865 $body = "[img]".unxmlify($photo->remote_photo_path).
2866 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2869 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2871 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2873 // Add OEmbed and other information to the body
2874 if (!self::is_redmatrix($contact["url"])) {
2875 $body = add_page_info_to_body($body, false, true);
2879 /// @todo enable support for polls
2880 //if ($data->poll) {
2881 // foreach ($data->poll AS $poll)
2886 /// @todo enable support for events
2888 $datarray["uid"] = $importer["uid"];
2889 $datarray["contact-id"] = $contact["id"];
2890 $datarray["network"] = NETWORK_DIASPORA;
2892 $datarray["author-name"] = $contact["name"];
2893 $datarray["author-link"] = $contact["url"];
2894 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2896 $datarray["owner-name"] = $datarray["author-name"];
2897 $datarray["owner-link"] = $datarray["author-link"];
2898 $datarray["owner-avatar"] = $datarray["author-avatar"];
2900 $datarray["guid"] = $guid;
2901 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2903 $datarray["verb"] = ACTIVITY_POST;
2904 $datarray["gravity"] = GRAVITY_PARENT;
2906 $datarray["protocol"] = PROTOCOL_DIASPORA;
2907 $datarray["source"] = $xml;
2909 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2911 if ($provider_display_name != "") {
2912 $datarray["app"] = $provider_display_name;
2915 $datarray["plink"] = self::plink($author, $guid);
2916 $datarray["private"] = (($public == "false") ? 1 : 0);
2917 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2919 if (isset($address["address"])) {
2920 $datarray["location"] = $address["address"];
2923 if (isset($address["lat"]) && isset($address["lng"])) {
2924 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2927 self::fetch_guid($datarray);
2928 $message_id = item_store($datarray);
2931 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2938 /* ************************************************************************************** *
2939 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2940 * ************************************************************************************** */
2943 * @brief returnes the handle of a contact
2945 * @param array $contact contact array
2947 * @return string the handle in the format user@domain.tld
2949 private static function my_handle($contact)
2951 if ($contact["addr"] != "") {
2952 return $contact["addr"];
2955 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2956 // So - just in case - we build the the address here.
2957 if ($contact["nickname"] != "") {
2958 $nick = $contact["nickname"];
2960 $nick = $contact["nick"];
2963 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2968 * @brief Creates the data for a private message in the new format
2970 * @param string $msg The message that is to be transmitted
2971 * @param array $user The record of the sender
2972 * @param array $contact Target of the communication
2973 * @param string $prvkey The private key of the sender
2974 * @param string $pubkey The public key of the receiver
2976 * @return string The encrypted data
2978 public static function encode_private_data($msg, $user, $contact, $prvkey, $pubkey)
2980 logger("Message: ".$msg, LOGGER_DATA);
2982 // without a public key nothing will work
2984 logger("pubkey missing: contact id: ".$contact["id"]);
2988 $aes_key = openssl_random_pseudo_bytes(32);
2989 $b_aes_key = base64_encode($aes_key);
2990 $iv = openssl_random_pseudo_bytes(16);
2991 $b_iv = base64_encode($iv);
2993 $ciphertext = self::aes_encrypt($aes_key, $iv, $msg);
2995 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2997 $encrypted_key_bundle = "";
2998 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3000 $json_object = json_encode(
3001 array("aes_key" => base64_encode($encrypted_key_bundle),
3002 "encrypted_magic_envelope" => base64_encode($ciphertext))
3005 return $json_object;
3009 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3011 * @param string $msg The message that is to be transmitted
3012 * @param array $user The record of the sender
3014 * @return string The envelope
3016 public static function build_magic_envelope($msg, $user)
3018 $b64url_data = base64url_encode($msg);
3019 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
3021 $key_id = base64url_encode(self::my_handle($user));
3022 $type = "application/xml";
3023 $encoding = "base64url";
3024 $alg = "RSA-SHA256";
3025 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3027 // Fallback if the private key wasn't transmitted in the expected field
3028 if ($user['uprvkey'] == "") {
3029 $user['uprvkey'] = $user['prvkey'];
3032 $signature = rsa_sign($signable_data, $user["uprvkey"]);
3033 $sig = base64url_encode($signature);
3035 $xmldata = array("me:env" => array("me:data" => $data,
3036 "@attributes" => array("type" => $type),
3037 "me:encoding" => $encoding,
3040 "@attributes2" => array("key_id" => $key_id)));
3042 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
3044 return XML::from_array($xmldata, $xml, false, $namespaces);
3048 * @brief Create the envelope for a message
3050 * @param string $msg The message that is to be transmitted
3051 * @param array $user The record of the sender
3052 * @param array $contact Target of the communication
3053 * @param string $prvkey The private key of the sender
3054 * @param string $pubkey The public key of the receiver
3055 * @param bool $public Is the message public?
3057 * @return string The message that will be transmitted to other servers
3059 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3061 // The message is put into an envelope with the sender's signature
3062 $envelope = self::build_magic_envelope($msg, $user);
3064 // Private messages are put into a second envelope, encrypted with the receivers public key
3066 $envelope = self::encode_private_data($envelope, $user, $contact, $prvkey, $pubkey);
3073 * @brief Creates a signature for a message
3075 * @param array $owner the array of the owner of the message
3076 * @param array $message The message that is to be signed
3078 * @return string The signature
3080 private static function signature($owner, $message)
3083 unset($sigmsg["author_signature"]);
3084 unset($sigmsg["parent_author_signature"]);
3086 $signed_text = implode(";", $sigmsg);
3088 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3092 * @brief Transmit a message to a target server
3094 * @param array $owner the array of the item owner
3095 * @param array $contact Target of the communication
3096 * @param string $envelope The message that is to be transmitted
3097 * @param bool $public_batch Is it a public post?
3098 * @param bool $queue_run Is the transmission called from the queue?
3099 * @param string $guid message guid
3101 * @return int Result of the transmission
3103 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3107 $enabled = intval(Config::get("system", "diaspora_enabled"));
3112 $logid = random_string(4);
3113 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
3115 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3119 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3121 if (!$queue_run && was_recently_delayed($contact["id"])) {
3124 if (!intval(Config::get("system", "diaspora_test"))) {
3125 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3127 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
3128 $return_code = $a->get_curl_code();
3130 logger("test_mode");
3135 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3137 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3138 logger("queue message");
3141 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3142 intval($contact["id"]),
3143 dbesc(NETWORK_DIASPORA),
3145 intval($public_batch)
3148 logger("add_to_queue ignored - identical item already in queue");
3150 // queue message for redelivery
3151 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3153 // The message could not be delivered. We mark the contact as "dead"
3154 Contact::markForArchival($contact);
3156 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3157 // We successfully delivered a message, the contact is alive
3158 Contact::unmarkForArchival($contact);
3161 return(($return_code) ? $return_code : (-1));
3166 * @brief Build the post xml
3168 * @param string $type The message type
3169 * @param array $message The message data
3171 * @return string The post XML
3173 public static function build_post_xml($type, $message)
3175 $data = array($type => $message);
3177 return XML::from_array($data, $xml);
3181 * @brief Builds and transmit messages
3183 * @param array $owner the array of the item owner
3184 * @param array $contact Target of the communication
3185 * @param string $type The message type
3186 * @param array $message The message data
3187 * @param bool $public_batch Is it a public post?
3188 * @param string $guid message guid
3189 * @param bool $spool Should the transmission be spooled or transmitted?
3191 * @return int Result of the transmission
3193 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3195 $msg = self::build_post_xml($type, $message);
3197 logger('message: '.$msg, LOGGER_DATA);
3198 logger('send guid '.$guid, LOGGER_DEBUG);
3200 // Fallback if the private key wasn't transmitted in the expected field
3201 if ($owner['uprvkey'] == "") {
3202 $owner['uprvkey'] = $owner['prvkey'];
3205 $envelope = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3208 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3211 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3214 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3216 return $return_code;
3220 * @brief sends an account migration
3222 * @param array $owner the array of the item owner
3223 * @param array $contact Target of the communication
3224 * @param int $uid User ID
3226 * @return int The result of the transmission
3228 public static function sendAccountMigration($owner, $contact, $uid)
3230 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3231 $profile = self::createProfileData($uid);
3233 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3234 $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3236 $message = array("author" => $old_handle,
3237 "profile" => $profile,
3238 "signature" => $signature);
3240 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3242 return self::build_and_transmit($owner, $contact, "account_migration", $message);
3246 * @brief Sends a "share" message
3248 * @param array $owner the array of the item owner
3249 * @param array $contact Target of the communication
3251 * @return int The result of the transmission
3253 public static function send_share($owner, $contact)
3256 * @todo support the different possible combinations of "following" and "sharing"
3257 * Currently, Diaspora only interprets the "sharing" field
3259 * Before switching this code productive, we have to check all "send_share" calls if "rel" is set correctly
3263 switch ($contact["rel"]) {
3264 case CONTACT_IS_FRIEND:
3267 case CONTACT_IS_SHARING:
3270 case CONTACT_IS_FOLLOWER:
3276 $message = array("author" => self::my_handle($owner),
3277 "recipient" => $contact["addr"],
3278 "following" => "true",
3279 "sharing" => "true");
3281 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3283 return self::build_and_transmit($owner, $contact, "contact", $message);
3287 * @brief sends an "unshare"
3289 * @param array $owner the array of the item owner
3290 * @param array $contact Target of the communication
3292 * @return int The result of the transmission
3294 public static function sendUnshare($owner, $contact)
3296 $message = array("author" => self::my_handle($owner),
3297 "recipient" => $contact["addr"],
3298 "following" => "false",
3299 "sharing" => "false");
3301 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3303 return self::build_and_transmit($owner, $contact, "contact", $message);
3307 * @brief Checks a message body if it is a reshare
3309 * @param string $body The message body that is to be check
3310 * @param bool $complete Should it be a complete check or a simple check?
3312 * @return array|bool Reshare details or "false" if no reshare
3314 public static function is_reshare($body, $complete = true)
3316 $body = trim($body);
3318 // Skip if it isn't a pure repeated messages
3319 // Does it start with a share?
3320 if ((strpos($body, "[share") > 0) && $complete) {
3324 // Does it end with a share?
3325 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3329 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3330 // Skip if there is no shared message in there
3331 if ($body == $attributes) {
3335 // If we don't do the complete check we quit here
3341 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3342 if ($matches[1] != "") {
3343 $guid = $matches[1];
3346 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3347 if ($matches[1] != "") {
3348 $guid = $matches[1];
3353 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3360 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3361 $ret["root_guid"] = $guid;
3367 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3368 if ($matches[1] != "") {
3369 $profile = $matches[1];
3372 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3373 if ($matches[1] != "") {
3374 $profile = $matches[1];
3379 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3380 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3385 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3386 if ($matches[1] != "") {
3387 $link = $matches[1];
3390 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3391 if ($matches[1] != "") {
3392 $link = $matches[1];
3395 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3396 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3404 * @brief Create an event array
3406 * @param integer $event_id The id of the event
3408 * @return array with event data
3410 private static function build_event($event_id)
3412 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3413 if (!DBM::is_result($r)) {
3419 $eventdata = array();
3421 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3422 if (!DBM::is_result($r)) {
3428 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3429 if (!DBM::is_result($r)) {
3435 $eventdata['author'] = self::my_handle($owner);
3437 if ($event['guid']) {
3438 $eventdata['guid'] = $event['guid'];
3441 $mask = 'Y-m-d\TH:i:s\Z';
3443 /// @todo - establish "all day" events in Friendica
3444 $eventdata["all_day"] = "false";
3446 if (!$event['adjust']) {
3447 $eventdata['timezone'] = $user['timezone'];
3449 if ($eventdata['timezone'] == "") {
3450 $eventdata['timezone'] = 'UTC';
3454 if ($event['start']) {
3455 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3457 if ($event['finish'] && !$event['nofinish']) {
3458 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3460 if ($event['summary']) {
3461 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3463 if ($event['desc']) {
3464 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3466 if ($event['location']) {
3467 $location = array();
3468 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3469 $location["lat"] = 0;
3470 $location["lng"] = 0;
3471 $eventdata['location'] = $location;
3478 * @brief Create a post (status message or reshare)
3480 * @param array $item The item that will be exported
3481 * @param array $owner the array of the item owner
3484 * 'type' -> Message type ("status_message" or "reshare")
3485 * 'message' -> Array of XML elements of the status
3487 public static function build_status($item, $owner)
3489 $cachekey = "diaspora:build_status:".$item['guid'];
3491 $result = Cache::get($cachekey);
3492 if (!is_null($result)) {
3496 $myaddr = self::my_handle($owner);
3498 $public = (($item["private"]) ? "false" : "true");
3500 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3502 // Detect a share element and do a reshare
3503 if (!$item['private'] && ($ret = self::is_reshare($item["body"]))) {
3504 $message = array("author" => $myaddr,
3505 "guid" => $item["guid"],
3506 "created_at" => $created,
3507 "root_author" => $ret["root_handle"],
3508 "root_guid" => $ret["root_guid"],
3509 "provider_display_name" => $item["app"],
3510 "public" => $public);
3514 $title = $item["title"];
3515 $body = $item["body"];
3517 // convert to markdown
3518 $body = html_entity_decode(bb2diaspora($body));
3521 if (strlen($title)) {
3522 $body = "## ".html_entity_decode($title)."\n\n".$body;
3525 if ($item["attach"]) {
3526 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3528 $body .= "\n".t("Attachments:")."\n";
3529 foreach ($matches as $mtch) {
3530 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3535 $location = array();
3537 if ($item["location"] != "")
3538 $location["address"] = $item["location"];
3540 if ($item["coord"] != "") {
3541 $coord = explode(" ", $item["coord"]);
3542 $location["lat"] = $coord[0];
3543 $location["lng"] = $coord[1];
3546 $message = array("author" => $myaddr,
3547 "guid" => $item["guid"],
3548 "created_at" => $created,
3549 "public" => $public,
3551 "provider_display_name" => $item["app"],
3552 "location" => $location);
3554 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3555 if (!isset($location["lat"]) || !isset($location["lng"])) {
3556 unset($message["location"]);
3559 if ($item['event-id'] > 0) {
3560 $event = self::build_event($item['event-id']);
3561 if (count($event)) {
3562 $message['event'] = $event;
3564 /// @todo Once Diaspora supports it, we will remove the body
3565 // $message['text'] = '';
3569 $type = "status_message";
3572 $msg = array("type" => $type, "message" => $message);
3574 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3580 * @brief Sends a post
3582 * @param array $item The item that will be exported
3583 * @param array $owner the array of the item owner
3584 * @param array $contact Target of the communication
3585 * @param bool $public_batch Is it a public post?
3587 * @return int The result of the transmission
3589 public static function send_status($item, $owner, $contact, $public_batch = false)
3591 $status = self::build_status($item, $owner);
3593 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3597 * @brief Creates a "like" object
3599 * @param array $item The item that will be exported
3600 * @param array $owner the array of the item owner
3602 * @return array The data for a "like"
3604 private static function construct_like($item, $owner)
3607 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3608 dbesc($item["thr-parent"])
3610 if (!DBM::is_result($p)) {
3616 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3617 if ($item['verb'] === ACTIVITY_LIKE) {
3619 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3620 $positive = "false";
3623 return(array("author" => self::my_handle($owner),
3624 "guid" => $item["guid"],
3625 "parent_guid" => $parent["guid"],
3626 "parent_type" => $target_type,
3627 "positive" => $positive,
3628 "author_signature" => ""));
3632 * @brief Creates an "EventParticipation" object
3634 * @param array $item The item that will be exported
3635 * @param array $owner the array of the item owner
3637 * @return array The data for an "EventParticipation"
3639 private static function construct_attend($item, $owner) {
3642 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3643 dbesc($item["thr-parent"])
3645 if (!DBM::is_result($p)) {
3651 switch ($item['verb']) {
3652 case ACTIVITY_ATTEND:
3653 $attend_answer = 'accepted';
3655 case ACTIVITY_ATTENDNO:
3656 $attend_answer = 'declined';
3658 case ACTIVITY_ATTENDMAYBE:
3659 $attend_answer = 'tentative';
3662 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3666 return(array("author" => self::my_handle($owner),
3667 "guid" => $item["guid"],
3668 "parent_guid" => $parent["guid"],
3669 "status" => $attend_answer,
3670 "author_signature" => ""));
3674 * @brief Creates the object for a comment
3676 * @param array $item The item that will be exported
3677 * @param array $owner the array of the item owner
3679 * @return array The data for a comment
3681 private static function construct_comment($item, $owner)
3683 $cachekey = "diaspora:construct_comment:".$item['guid'];
3685 $result = Cache::get($cachekey);
3686 if (!is_null($result)) {
3691 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3692 intval($item["parent"]),
3693 intval($item["parent"])
3696 if (!DBM::is_result($p)) {
3702 $text = html_entity_decode(bb2diaspora($item["body"]));
3703 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3705 $comment = array("author" => self::my_handle($owner),
3706 "guid" => $item["guid"],
3707 "created_at" => $created,
3708 "parent_guid" => $parent["guid"],
3710 "author_signature" => "");
3712 // Send the thread parent guid only if it is a threaded comment
3713 if ($item['thr-parent'] != $item['parent-uri']) {
3714 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3717 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3723 * @brief Send a like or a comment
3725 * @param array $item The item that will be exported
3726 * @param array $owner the array of the item owner
3727 * @param array $contact Target of the communication
3728 * @param bool $public_batch Is it a public post?
3730 * @return int The result of the transmission
3732 public static function send_followup($item, $owner, $contact, $public_batch = false)
3734 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3735 $message = self::construct_attend($item, $owner);
3736 $type = "event_participation";
3737 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3738 $message = self::construct_like($item, $owner);
3741 $message = self::construct_comment($item, $owner);
3749 $message["author_signature"] = self::signature($owner, $message);
3751 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3755 * @brief Creates a message from a signature record entry
3757 * @param array $item The item that will be exported
3758 * @param array $signature The entry of the "sign" record
3760 * @return string The message
3762 private static function message_from_signature($item, $signature)
3764 // Split the signed text
3765 $signed_parts = explode(";", $signature['signed_text']);
3767 if ($item["deleted"]) {
3768 $message = array("author" => $signature['signer'],
3769 "target_guid" => $signed_parts[0],
3770 "target_type" => $signed_parts[1]);
3771 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3772 $message = array("author" => $signed_parts[4],
3773 "guid" => $signed_parts[1],
3774 "parent_guid" => $signed_parts[3],
3775 "parent_type" => $signed_parts[2],
3776 "positive" => $signed_parts[0],
3777 "author_signature" => $signature['signature'],
3778 "parent_author_signature" => "");
3780 // Remove the comment guid
3781 $guid = array_shift($signed_parts);
3783 // Remove the parent guid
3784 $parent_guid = array_shift($signed_parts);
3786 // Remove the handle
3787 $handle = array_pop($signed_parts);
3789 // Glue the parts together
3790 $text = implode(";", $signed_parts);
3792 $message = array("author" => $handle,
3794 "parent_guid" => $parent_guid,
3795 "text" => implode(";", $signed_parts),
3796 "author_signature" => $signature['signature'],
3797 "parent_author_signature" => "");
3803 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3805 * @param array $item The item that will be exported
3806 * @param array $owner the array of the item owner
3807 * @param array $contact Target of the communication
3808 * @param bool $public_batch Is it a public post?
3810 * @return int The result of the transmission
3812 public static function send_relay($item, $owner, $contact, $public_batch = false)
3814 if ($item["deleted"]) {
3815 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3816 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3822 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3824 // fetch the original signature
3827 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3832 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3838 // Old way - is used by the internal Friendica functions
3839 /// @todo Change all signatur storing functions to the new format
3840 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3841 $message = self::message_from_signature($item, $signature);
3843 $msg = json_decode($signature['signed_text'], true);
3846 if (is_array($msg)) {
3847 foreach ($msg AS $field => $data) {
3848 if (!$item["deleted"]) {
3849 if ($field == "diaspora_handle") {
3852 if ($field == "target_type") {
3853 $field = "parent_type";
3857 $message[$field] = $data;
3860 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3864 $message["parent_author_signature"] = self::signature($owner, $message);
3866 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3868 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3872 * @brief Sends a retraction (deletion) of a message, like or comment
3874 * @param array $item The item that will be exported
3875 * @param array $owner the array of the item owner
3876 * @param array $contact Target of the communication
3877 * @param bool $public_batch Is it a public post?
3878 * @param bool $relay Is the retraction transmitted from a relay?
3880 * @return int The result of the transmission
3882 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false)
3884 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3886 $msg_type = "retraction";
3888 if ($item['id'] == $item['parent']) {
3889 $target_type = "Post";
3890 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3891 $target_type = "Like";
3893 $target_type = "Comment";
3896 $message = array("author" => $itemaddr,
3897 "target_guid" => $item['guid'],
3898 "target_type" => $target_type);
3900 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3902 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3906 * @brief Sends a mail
3908 * @param array $item The item that will be exported
3909 * @param array $owner The owner
3910 * @param array $contact Target of the communication
3912 * @return int The result of the transmission
3914 public static function send_mail($item, $owner, $contact)
3916 $myaddr = self::my_handle($owner);
3919 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3920 intval($item["convid"]),
3921 intval($item["uid"])
3924 if (!DBM::is_result($r)) {
3925 logger("conversation not found.");
3931 "author" => $cnv["creator"],
3932 "guid" => $cnv["guid"],
3933 "subject" => $cnv["subject"],
3934 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3935 "participants" => $cnv["recips"]
3938 $body = bb2diaspora($item["body"]);
3939 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3942 "author" => $myaddr,
3943 "guid" => $item["guid"],
3944 "conversation_guid" => $cnv["guid"],
3946 "created_at" => $created,
3949 if ($item["reply"]) {
3954 "author" => $cnv["creator"],
3955 "guid" => $cnv["guid"],
3956 "subject" => $cnv["subject"],
3957 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3958 "participants" => $cnv["recips"],
3961 $type = "conversation";
3964 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3968 * @brief Create profile data
3970 * @param int $uid The user id
3972 * @return array The profile data
3974 private static function createProfileData($uid)
3977 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3979 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3980 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3981 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3991 $handle = $profile["addr"];
3992 $first = ((strpos($profile['name'], ' ')
3993 ? trim(substr($profile['name'], 0, strpos($profile['name'], ' '))) : $profile['name']));
3994 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3995 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3996 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3997 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3998 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4000 if ($searchable === 'true') {
4001 $dob = '1000-00-00';
4003 if (($profile['dob']) && ($profile['dob'] > '0001-01-01')) {
4004 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC', 'UTC', $profile['dob'],'m-d');
4007 $about = $profile['about'];
4008 $about = strip_tags(bbcode($about));
4010 $location = Profile::formatLocation($profile);
4012 if ($profile['pub_keywords']) {
4013 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4014 $kw = str_replace(' ', ' ', $kw);
4015 $arr = explode(' ', $profile['pub_keywords']);
4017 for ($x = 0; $x < 5; $x ++) {
4018 if (trim($arr[$x])) {
4019 $tags .= '#'. trim($arr[$x]) .' ';
4024 $tags = trim($tags);
4027 return array("author" => $handle,
4028 "first_name" => $first,
4029 "last_name" => $last,
4030 "image_url" => $large,
4031 "image_url_medium" => $medium,
4032 "image_url_small" => $small,
4034 "gender" => $profile['gender'],
4036 "location" => $location,
4037 "searchable" => $searchable,
4039 "tag_string" => $tags);
4043 * @brief Sends profile data
4045 * @param int $uid The user id
4047 public static function send_profile($uid, $recips = false)
4055 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4056 AND `uid` = %d AND `rel` != %d",
4057 dbesc(NETWORK_DIASPORA),
4059 intval(CONTACT_IS_SHARING)
4067 $message = self::createProfileData($uid);
4069 foreach ($recips as $recip) {
4070 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4071 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
4076 * @brief Stores the signature for likes that are created on our system
4078 * @param array $contact The contact array of the "like"
4079 * @param int $post_id The post id of the "like"
4081 * @return bool Success
4083 public static function store_like_signature($contact, $post_id)
4085 // Is the contact the owner? Then fetch the private key
4086 if (!$contact['self'] || ($contact['uid'] == 0)) {
4087 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4091 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4092 if (!DBM::is_result($r)) {
4096 $contact["uprvkey"] = $r[0]['prvkey'];
4098 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4099 if (!DBM::is_result($r)) {
4103 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
4107 $message = self::construct_like($r[0], $contact);
4108 $message["author_signature"] = self::signature($contact, $message);
4111 * Now store the signature more flexible to dynamically support new fields.
4112 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4114 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
4116 logger('Stored diaspora like signature');
4121 * @brief Stores the signature for comments that are created on our system
4123 * @param array $item The item array of the comment
4124 * @param array $contact The contact array of the item owner
4125 * @param string $uprvkey The private key of the sender
4126 * @param int $message_id The message id of the comment
4128 * @return bool Success
4130 public static function store_comment_signature($item, $contact, $uprvkey, $message_id)
4132 if ($uprvkey == "") {
4133 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4137 $contact["uprvkey"] = $uprvkey;
4139 $message = self::construct_comment($item, $contact);
4140 $message["author_signature"] = self::signature($contact, $message);
4143 * Now store the signature more flexible to dynamically support new fields.
4144 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4146 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
4148 logger('Stored diaspora comment signature');