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 "validPosting" 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\Model\Profile;
21 use Friendica\Network\Probe;
22 use Friendica\Object\Contact;
23 use Friendica\Util\XML;
28 require_once 'include/items.php';
29 require_once 'include/bb2diaspora.php';
30 require_once 'include/group.php';
31 require_once 'include/datetime.php';
32 require_once 'include/queue_fn.php';
35 * @brief This class contain functions to create and send Diaspora XML files
42 * @brief Return a list of relay servers
44 * This is an experimental Diaspora feature.
46 * @return array of relay servers
48 public static function relayList()
50 $serverdata = Config::get("system", "relay_server");
51 if ($serverdata == "") {
57 $servers = explode(",", $serverdata);
59 foreach ($servers as $server) {
60 $server = trim($server);
61 $addr = "relay@".str_replace("http://", "", normalise_link($server));
62 $batch = $server."/receive/public";
65 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
68 dbesc(normalise_link($server))
73 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
74 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
79 dbesc(normalise_link($server)),
81 dbesc(NETWORK_DIASPORA),
82 intval(CONTACT_IS_FOLLOWER),
83 dbesc(datetime_convert()),
84 dbesc(datetime_convert()),
85 dbesc(datetime_convert())
88 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
90 $relay[] = $relais[0];
93 $relay[] = $relais[0];
101 * @brief repairs a signature that was double encoded
103 * The function is unused at the moment. It was copied from the old implementation.
105 * @param string $signature The signature
106 * @param string $handle The handle of the signature owner
107 * @param integer $level This value is only set inside this function to avoid endless loops
109 * @return string the repaired signature
111 private static function repairSignature($signature, $handle = "", $level = 1)
113 if ($signature == "") {
117 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
118 $signature = base64_decode($signature);
119 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
121 // Do a recursive call to be able to fix even multiple levels
123 $signature = self::repairSignature($signature, $handle, ++$level);
131 * @brief verify the envelope and return the verified data
133 * @param string $envelope The magic envelope
135 * @return string verified data
137 private static function verifyMagicEnvelope($envelope)
139 $basedom = parse_xml_string($envelope);
141 if (!is_object($basedom)) {
142 logger("Envelope is no XML file");
146 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
148 if (sizeof($children) == 0) {
149 logger("XML has no children");
155 $data = base64url_decode($children->data);
156 $type = $children->data->attributes()->type[0];
158 $encoding = $children->encoding;
160 $alg = $children->alg;
162 $sig = base64url_decode($children->sig);
163 $key_id = $children->sig->attributes()->key_id[0];
165 $handle = base64url_decode($key_id);
168 $b64url_data = base64url_encode($data);
169 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
171 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
173 $key = self::key($handle);
175 $verify = rsa_verify($signable_data, $sig, $key);
177 logger('Message did not verify. Discarding.');
185 * @brief encrypts data via AES
187 * @param string $key The AES key
188 * @param string $iv The IV (is used for CBC encoding)
189 * @param string $data The data that is to be encrypted
191 * @return string encrypted data
193 private static function aesEncrypt($key, $iv, $data)
195 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
199 * @brief decrypts data via AES
201 * @param string $key The AES key
202 * @param string $iv The IV (is used for CBC encoding)
203 * @param string $encrypted The encrypted data
205 * @return string decrypted data
207 private static function aesDecrypt($key, $iv, $encrypted)
209 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
213 * @brief: Decodes incoming Diaspora message in the new format
215 * @param array $importer Array of the importer user
216 * @param string $raw raw post message
219 * 'message' -> decoded Diaspora XML message
220 * 'author' -> author diaspora handle
221 * 'key' -> author public key (converted to pkcs#8)
223 public static function decodeRaw($importer, $raw)
225 $data = json_decode($raw);
227 // Is it a private post? Then decrypt the outer Salmon
228 if (is_object($data)) {
229 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
230 $ciphertext = base64_decode($data->encrypted_magic_envelope);
232 $outer_key_bundle = '';
233 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
234 $j_outer_key_bundle = json_decode($outer_key_bundle);
236 if (!is_object($j_outer_key_bundle)) {
237 logger('Outer Salmon did not verify. Discarding.');
238 http_status_exit(400);
241 $outer_iv = base64_decode($j_outer_key_bundle->iv);
242 $outer_key = base64_decode($j_outer_key_bundle->key);
244 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
249 $basedom = parse_xml_string($xml);
251 if (!is_object($basedom)) {
252 logger('Received data does not seem to be an XML. Discarding. '.$xml);
253 http_status_exit(400);
256 $base = $basedom->children(NAMESPACE_SALMON_ME);
258 // Not sure if this cleaning is needed
259 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
261 // Build the signed data
262 $type = $base->data[0]->attributes()->type[0];
263 $encoding = $base->encoding;
265 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
267 // This is the signature
268 $signature = base64url_decode($base->sig);
270 // Get the senders' public key
271 $key_id = $base->sig[0]->attributes()->key_id[0];
272 $author_addr = base64_decode($key_id);
273 $key = self::key($author_addr);
275 $verify = rsa_verify($signed_data, $signature, $key);
277 logger('Message did not verify. Discarding.');
278 http_status_exit(400);
281 return array('message' => (string)base64url_decode($base->data),
282 'author' => unxmlify($author_addr),
283 'key' => (string)$key);
287 * @brief: Decodes incoming Diaspora message in the deprecated format
289 * @param array $importer Array of the importer user
290 * @param string $xml urldecoded Diaspora salmon
293 * 'message' -> decoded Diaspora XML message
294 * 'author' -> author diaspora handle
295 * 'key' -> author public key (converted to pkcs#8)
297 public static function decode($importer, $xml)
300 $basedom = parse_xml_string($xml);
302 if (!is_object($basedom)) {
303 logger("XML is not parseable.");
306 $children = $basedom->children('https://joindiaspora.com/protocol');
308 if ($children->header) {
310 $author_link = str_replace('acct:', '', $children->header->author_id);
312 // This happens with posts from a relais
314 logger("This is no private post in the old format", LOGGER_DEBUG);
318 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
320 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
321 $ciphertext = base64_decode($encrypted_header->ciphertext);
323 $outer_key_bundle = '';
324 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
326 $j_outer_key_bundle = json_decode($outer_key_bundle);
328 $outer_iv = base64_decode($j_outer_key_bundle->iv);
329 $outer_key = base64_decode($j_outer_key_bundle->key);
331 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
333 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
334 $idom = parse_xml_string($decrypted);
336 $inner_iv = base64_decode($idom->iv);
337 $inner_aes_key = base64_decode($idom->aes_key);
339 $author_link = str_replace('acct:', '', $idom->author_id);
342 $dom = $basedom->children(NAMESPACE_SALMON_ME);
344 // figure out where in the DOM tree our data is hiding
346 if ($dom->provenance->data) {
347 $base = $dom->provenance;
348 } elseif ($dom->env->data) {
350 } elseif ($dom->data) {
355 logger('unable to locate salmon data in xml');
356 http_status_exit(400);
360 // Stash the signature away for now. We have to find their key or it won't be good for anything.
361 $signature = base64url_decode($base->sig);
365 // strip whitespace so our data element will return to one big base64 blob
366 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
369 // stash away some other stuff for later
371 $type = $base->data[0]->attributes()->type[0];
372 $keyhash = $base->sig[0]->attributes()->keyhash[0];
373 $encoding = $base->encoding;
377 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
381 $data = base64url_decode($data);
385 $inner_decrypted = $data;
387 // Decode the encrypted blob
388 $inner_encrypted = base64_decode($data);
389 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
393 logger('Could not retrieve author URI.');
394 http_status_exit(400);
396 // Once we have the author URI, go to the web and try to find their public key
397 // (first this will look it up locally if it is in the fcontact cache)
398 // This will also convert diaspora public key from pkcs#1 to pkcs#8
400 logger('Fetching key for '.$author_link);
401 $key = self::key($author_link);
404 logger('Could not retrieve author key.');
405 http_status_exit(400);
408 $verify = rsa_verify($signed_data, $signature, $key);
411 logger('Message did not verify. Discarding.');
412 http_status_exit(400);
415 logger('Message verified.');
417 return array('message' => (string)$inner_decrypted,
418 'author' => unxmlify($author_link),
419 'key' => (string)$key);
424 * @brief Dispatches public messages and find the fitting receivers
426 * @param array $msg The post that will be dispatched
428 * @return int The message id of the generated message, "true" or "false" if there was an error
430 public static function dispatchPublic($msg)
432 $enabled = intval(Config::get("system", "diaspora_enabled"));
434 logger("diaspora is disabled");
438 if (!($postdata = self::validPosting($msg))) {
439 logger("Invalid posting");
443 $fields = $postdata['fields'];
445 // Is it a an action (comment, like, ...) for our own post?
446 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
447 $guid = notags(unxmlify($fields->parent_guid));
448 $importer = self::importerForGuid($guid);
449 if (is_array($importer)) {
450 logger("delivering to origin: ".$importer["name"]);
451 $message_id = self::dispatch($importer, $msg, $fields);
456 // Process item retractions. This has to be done separated from the other stuff,
457 // since retractions for comments could come even from non followers.
458 if (!empty($fields) && in_array($fields->getName(), array('retraction'))) {
459 $target = notags(unxmlify($fields->target_type));
460 if (in_array($target, array("Comment", "Like", "Post", "Reshare", "StatusMessage"))) {
461 logger('processing retraction for '.$target, LOGGER_DEBUG);
462 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
463 $message_id = self::dispatch($importer, $msg, $fields);
468 // Now distribute it to the followers
470 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
471 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
472 AND NOT `account_expired` AND NOT `account_removed`",
473 dbesc(NETWORK_DIASPORA),
474 dbesc($msg["author"])
477 if (DBM::is_result($r)) {
478 foreach ($r as $rr) {
479 logger("delivering to: ".$rr["username"]);
480 self::dispatch($rr, $msg, $fields);
482 } elseif (!Config::get('system', 'relay_subscribe', false)) {
483 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
485 // Use a dummy importer to import the data for the public copy
486 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
487 $message_id = self::dispatch($importer, $msg, $fields);
494 * @brief Dispatches the different message types to the different functions
496 * @param array $importer Array of the importer user
497 * @param array $msg The post that will be dispatched
498 * @param object $fields SimpleXML object that contains the message
500 * @return int The message id of the generated message, "true" or "false" if there was an error
502 public static function dispatch($importer, $msg, $fields = null)
504 // The sender is the handle of the contact that sent the message.
505 // This will often be different with relayed messages (for example "like" and "comment")
506 $sender = $msg["author"];
508 // This is only needed for private postings since this is already done for public ones before
509 if (is_null($fields)) {
510 if (!($postdata = self::validPosting($msg))) {
511 logger("Invalid posting");
514 $fields = $postdata['fields'];
517 $type = $fields->getName();
519 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
522 case "account_migration":
523 return self::receiveAccountMigration($importer, $fields);
525 case "account_deletion":
526 return self::receiveAccountDeletion($importer, $fields);
529 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
532 return self::receiveContactRequest($importer, $fields);
535 return self::receiveConversation($importer, $msg, $fields);
538 return self::receiveLike($importer, $sender, $fields);
541 return self::receiveMessage($importer, $fields);
543 case "participation": // Not implemented
544 return self::receiveParticipation($importer, $fields);
546 case "photo": // Not implemented
547 return self::receivePhoto($importer, $fields);
549 case "poll_participation": // Not implemented
550 return self::receivePollParticipation($importer, $fields);
553 return self::receiveProfile($importer, $fields);
556 return self::receiveReshare($importer, $fields, $msg["message"]);
559 return self::receiveRetraction($importer, $sender, $fields);
561 case "status_message":
562 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
565 logger("Unknown message type ".$type);
573 * @brief Checks if a posting is valid and fetches the data fields.
575 * This function does not only check the signature.
576 * It also does the conversion between the old and the new diaspora format.
578 * @param array $msg Array with the XML, the sender handle and the sender signature
580 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
582 private static function validPosting($msg)
584 $data = parse_xml_string($msg["message"]);
586 if (!is_object($data)) {
587 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
591 $first_child = $data->getName();
593 // Is this the new or the old version?
594 if ($data->getName() == "XML") {
596 foreach ($data->post->children() as $child) {
604 $type = $element->getName();
607 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
609 // All retractions are handled identically from now on.
610 // In the new version there will only be "retraction".
611 if (in_array($type, array("signed_retraction", "relayable_retraction")))
612 $type = "retraction";
614 if ($type == "request") {
618 $fields = new SimpleXMLElement("<".$type."/>");
622 foreach ($element->children() as $fieldname => $entry) {
624 // Translation for the old XML structure
625 if ($fieldname == "diaspora_handle") {
626 $fieldname = "author";
628 if ($fieldname == "participant_handles") {
629 $fieldname = "participants";
631 if (in_array($type, array("like", "participation"))) {
632 if ($fieldname == "target_type") {
633 $fieldname = "parent_type";
636 if ($fieldname == "sender_handle") {
637 $fieldname = "author";
639 if ($fieldname == "recipient_handle") {
640 $fieldname = "recipient";
642 if ($fieldname == "root_diaspora_id") {
643 $fieldname = "root_author";
645 if ($type == "status_message") {
646 if ($fieldname == "raw_message") {
650 if ($type == "retraction") {
651 if ($fieldname == "post_guid") {
652 $fieldname = "target_guid";
654 if ($fieldname == "type") {
655 $fieldname = "target_type";
660 if (($fieldname == "author_signature") && ($entry != "")) {
661 $author_signature = base64_decode($entry);
662 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
663 $parent_author_signature = base64_decode($entry);
664 } elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
665 if ($signed_data != "") {
667 $signed_data_parent .= ";";
670 $signed_data .= $entry;
672 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature"))
673 || ($orig_type == "relayable_retraction")
675 XML::copy($entry, $fields, $fieldname);
679 // This is something that shouldn't happen at all.
680 if (in_array($type, array("status_message", "reshare", "profile"))) {
681 if ($msg["author"] != $fields->author) {
682 logger("Message handle is not the same as envelope sender. Quitting this message.");
687 // Only some message types have signatures. So we quit here for the other types.
688 if (!in_array($type, array("comment", "like"))) {
689 return array("fields" => $fields, "relayed" => false);
691 // No author_signature? This is a must, so we quit.
692 if (!isset($author_signature)) {
693 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
697 if (isset($parent_author_signature)) {
700 $key = self::key($msg["author"]);
702 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
703 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);
710 $key = self::key($fields->author);
712 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
713 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
716 return array("fields" => $fields, "relayed" => $relayed);
721 * @brief Fetches the public key for a given handle
723 * @param string $handle The handle
725 * @return string The public key
727 private static function key($handle)
729 $handle = strval($handle);
731 logger("Fetching diaspora key for: ".$handle);
733 $r = self::personByHandle($handle);
742 * @brief Fetches data for a given handle
744 * @param string $handle The handle
746 * @return array the queried data
748 public static function personByHandle($handle)
751 "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
752 dbesc(NETWORK_DIASPORA),
757 logger("In cache " . print_r($r, true), LOGGER_DEBUG);
759 // update record occasionally so it doesn't get stale
760 $d = strtotime($person["updated"]." +00:00");
761 if ($d < strtotime("now - 14 days")) {
765 if ($person["guid"] == "") {
770 if (!$person || $update) {
771 logger("create or refresh", LOGGER_DEBUG);
772 $r = Probe::uri($handle, NETWORK_DIASPORA);
774 // Note that Friendica contacts will return a "Diaspora person"
775 // if Diaspora connectivity is enabled on their server
776 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
777 self::addFContact($r, $update);
785 * @brief Updates the fcontact table
787 * @param array $arr The fcontact data
788 * @param bool $update Update or insert?
790 * @return string The id of the fcontact entry
792 private static function addFContact($arr, $update = false)
796 "UPDATE `fcontact` SET
810 WHERE `url` = '%s' AND `network` = '%s'",
812 dbesc($arr["photo"]),
813 dbesc($arr["request"]),
815 dbesc(strtolower($arr["addr"])),
817 dbesc($arr["batch"]),
818 dbesc($arr["notify"]),
820 dbesc($arr["confirm"]),
821 dbesc($arr["alias"]),
822 dbesc($arr["pubkey"]),
823 dbesc(datetime_convert()),
825 dbesc($arr["network"])
829 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
830 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
831 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
834 dbesc($arr["photo"]),
835 dbesc($arr["request"]),
839 dbesc($arr["batch"]),
840 dbesc($arr["notify"]),
842 dbesc($arr["confirm"]),
843 dbesc($arr["network"]),
844 dbesc($arr["alias"]),
845 dbesc($arr["pubkey"]),
846 dbesc(datetime_convert())
854 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
856 * @param int $contact_id The id in the contact table
857 * @param int $gcontact_id The id in the gcontact table
859 * @return string the handle
861 public static function handleFromContact($contact_id, $gcontact_id = 0)
865 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
867 if ($gcontact_id != 0) {
869 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
873 if (DBM::is_result($r)) {
874 return strtolower($r[0]["addr"]);
879 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
883 if (DBM::is_result($r)) {
886 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
888 if ($contact['addr'] != "") {
889 $handle = $contact['addr'];
891 $baseurl_start = strpos($contact['url'], '://') + 3;
892 // allows installations in a subdirectory--not sure how Diaspora will handle
893 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
894 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
895 $handle = $contact['nick'].'@'.$baseurl;
899 return strtolower($handle);
903 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
906 * @param mixed $fcontact_guid Hexadecimal string guid
908 * @return string the contact url or null
910 public static function urlFromContactGuid($fcontact_guid)
912 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
915 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
916 dbesc(NETWORK_DIASPORA),
917 dbesc($fcontact_guid)
920 if (DBM::is_result($r)) {
928 * @brief Get a contact id for a given handle
930 * @param int $uid The user id
931 * @param string $handle The handle in the format user@domain.tld
933 * @return The contact id
935 private static function contactByHandle($uid, $handle)
937 // First do a direct search on the contact table
939 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
944 if (DBM::is_result($r)) {
948 * We haven't found it?
949 * We use another function for it that will possibly create a contact entry.
951 $cid = Contact::getIdForURL($handle, $uid);
954 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
955 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
957 if (DBM::is_result($r)) {
963 $handle_parts = explode("@", $handle);
964 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
966 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
971 if (DBM::is_result($r)) {
975 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
980 * @brief Check if posting is allowed for this contact
982 * @param array $importer Array of the importer user
983 * @param array $contact The contact that is checked
984 * @param bool $is_comment Is the check for a comment?
986 * @return bool is the contact allowed to post?
988 private static function postAllow($importer, $contact, $is_comment = false)
991 * Perhaps we were already sharing with this person. Now they're sharing with us.
992 * That makes us friends.
993 * Normally this should have handled by getting a request - but this could get lost
995 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
996 // It is not removed by now. Possibly the code is needed?
997 //if (!$is_comment && $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 allowedContactByHandle($importer, $handle, $is_comment = false)
1040 $contact = self::contactByHandle($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::postAllow($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 messageExists($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
1088 private static function fetchGuid($item)
1090 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1091 preg_replace_callback(
1093 function ($match) use ($item) {
1094 return self::fetchGuidSub($match, $item);
1099 preg_replace_callback(
1100 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1101 function ($match) use ($item) {
1102 return self::fetchGuidSub($match, $item);
1109 * @brief Checks for relative /people/* links in an item body to match local
1110 * contacts or prepends the remote host taken from the author link.
1112 * @param string $body The item body to replace links from
1113 * @param string $author_link The author link for missing local contact fallback
1115 * @return the replaced string
1117 public static function replacePeopleGuid($body, $author_link)
1119 $return = preg_replace_callback(
1120 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1121 function ($match) use ($author_link) {
1123 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1124 // 1 => '0123456789abcdef'
1126 $handle = self::urlFromContactGuid($match[1]);
1129 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1131 // No local match, restoring absolute remote URL from author scheme and host
1132 $author_url = parse_url($author_link);
1133 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1145 * @brief sub function of "fetchGuid" which checks for links in messages
1147 * @param array $match array containing a link that has to be checked for a message link
1148 * @param array $item The item array
1151 private static function fetchGuidSub($match, $item)
1153 if (!self::storeByGuid($match[1], $item["author-link"])) {
1154 self::storeByGuid($match[1], $item["owner-link"]);
1159 * @brief Fetches an item with a given guid from a given server
1161 * @param string $guid the message guid
1162 * @param string $server The server address
1163 * @param int $uid The user id of the user
1165 * @return int the message id of the stored message or false
1167 private static function storeByGuid($guid, $server, $uid = 0)
1169 $serverparts = parse_url($server);
1170 $server = $serverparts["scheme"]."://".$serverparts["host"];
1172 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1174 $msg = self::message($guid, $server);
1180 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1182 // Now call the dispatcher
1183 return self::dispatchPublic($msg);
1187 * @brief Fetches a message from a server
1189 * @param string $guid message guid
1190 * @param string $server The url of the server
1191 * @param int $level Endless loop prevention
1194 * 'message' => The message XML
1195 * 'author' => The author handle
1196 * 'key' => The public key of the author
1198 private static function message($guid, $server, $level = 0)
1204 // This will work for new Diaspora servers and Friendica servers from 3.5
1205 $source_url = $server."/fetch/post/".urlencode($guid);
1207 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1209 $envelope = fetch_url($source_url);
1211 logger("Envelope was fetched.", LOGGER_DEBUG);
1212 $x = self::verifyMagicEnvelope($envelope);
1214 logger("Envelope could not be verified.", LOGGER_DEBUG);
1216 logger("Envelope was verified.", LOGGER_DEBUG);
1222 // This will work for older Diaspora and Friendica servers
1224 $source_url = $server."/p/".urlencode($guid).".xml";
1225 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1227 $x = fetch_url($source_url);
1233 $source_xml = parse_xml_string($x);
1235 if (!is_object($source_xml)) {
1239 if ($source_xml->post->reshare) {
1240 // Reshare of a reshare - old Diaspora version
1241 logger("Message is a reshare", LOGGER_DEBUG);
1242 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1243 } elseif ($source_xml->getName() == "reshare") {
1244 // Reshare of a reshare - new Diaspora version
1245 logger("Message is a new reshare", LOGGER_DEBUG);
1246 return self::message($source_xml->root_guid, $server, ++$level);
1251 // Fetch the author - for the old and the new Diaspora version
1252 if ($source_xml->post->status_message->diaspora_handle) {
1253 $author = (string)$source_xml->post->status_message->diaspora_handle;
1254 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1255 $author = (string)$source_xml->author;
1258 // If this isn't a "status_message" then quit
1260 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1264 $msg = array("message" => $x, "author" => $author);
1266 $msg["key"] = self::key($msg["author"]);
1272 * @brief Fetches the item record of a given guid
1274 * @param int $uid The user id
1275 * @param string $guid message guid
1276 * @param string $author The handle of the item
1277 * @param array $contact The contact of the item owner
1279 * @return array the item record
1281 private static function parentItem($uid, $guid, $author, $contact)
1284 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1285 `author-name`, `author-link`, `author-avatar`,
1286 `owner-name`, `owner-link`, `owner-avatar`
1287 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1293 $result = self::storeByGuid($guid, $contact["url"], $uid);
1296 $person = self::personByHandle($author);
1297 $result = self::storeByGuid($guid, $person["url"], $uid);
1301 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1304 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1305 `author-name`, `author-link`, `author-avatar`,
1306 `owner-name`, `owner-link`, `owner-avatar`
1307 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1315 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1318 logger("parent item found: parent: ".$guid." - user: ".$uid);
1324 * @brief returns contact details
1326 * @param array $contact The default contact if the person isn't found
1327 * @param array $person The record of the person
1328 * @param int $uid The user id
1331 * 'cid' => contact id
1332 * 'network' => network type
1334 private static function authorContactByUrl($contact, $person, $uid)
1337 "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1338 dbesc(normalise_link($person["url"])),
1343 $network = $r[0]["network"];
1345 $cid = $contact["id"];
1346 $network = NETWORK_DIASPORA;
1349 return array("cid" => $cid, "network" => $network);
1353 * @brief Is the profile a hubzilla profile?
1355 * @param string $url The profile link
1357 * @return bool is it a hubzilla server?
1359 public static function isRedmatrix($url)
1361 return(strstr($url, "/channel/"));
1365 * @brief Generate a post link with a given handle and message guid
1367 * @param string $addr The user handle
1368 * @param string $guid message guid
1369 * @param string $parent_guid optional parent guid
1371 * @return string the post link
1373 private static function plink($addr, $guid, $parent_guid = '')
1375 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1378 if (!DBM::is_result($r)) {
1379 if ($parent_guid != '') {
1380 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1382 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1386 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1387 // So we try another way as well.
1388 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1389 if (DBM::is_result($s)) {
1390 $r[0]["network"] = $s[0]["network"];
1393 if ($r[0]["network"] == NETWORK_DFRN) {
1394 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1397 if (self::isRedmatrix($r[0]["url"])) {
1398 return $r[0]["url"]."/?f=&mid=".$guid;
1401 if ($parent_guid != '') {
1402 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1404 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1409 * @brief Receives account migration
1411 * @param array $importer Array of the importer user
1412 * @param object $data The message object
1414 * @return bool Success
1416 private static function receiveAccountMigration($importer, $data)
1418 $old_handle = notags(unxmlify($data->author));
1419 $new_handle = notags(unxmlify($data->profile->author));
1420 $signature = notags(unxmlify($data->signature));
1422 $contact = self::contactByHandle($importer["uid"], $old_handle);
1424 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1428 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1431 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1432 $key = self::key($old_handle);
1433 if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
1434 logger('No valid signature for migration.');
1438 // Update the profile
1439 self::receiveProfile($importer, $data->profile);
1441 // change the technical stuff in contact and gcontact
1442 $data = Probe::uri($new_handle);
1443 if ($data['network'] == NETWORK_PHANTOM) {
1444 logger('Account for '.$new_handle." couldn't be probed.");
1448 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1449 'name' => $data['name'], 'nick' => $data['nick'],
1450 'addr' => $data['addr'], 'batch' => $data['batch'],
1451 'notify' => $data['notify'], 'poll' => $data['poll'],
1452 'network' => $data['network']);
1454 dba::update('contact', $fields, array('addr' => $old_handle));
1456 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1457 'name' => $data['name'], 'nick' => $data['nick'],
1458 'addr' => $data['addr'], 'connect' => $data['addr'],
1459 'notify' => $data['notify'], 'photo' => $data['photo'],
1460 'server_url' => $data['baseurl'], 'network' => $data['network']);
1462 dba::update('gcontact', $fields, array('addr' => $old_handle));
1464 logger('Contacts are updated.');
1467 /// @todo This is an extreme performance killer
1469 'owner-link' => array($contact["url"], $data["url"]),
1470 'author-link' => array($contact["url"], $data["url"]),
1472 foreach ($fields as $n => $f) {
1474 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1477 intval($importer["uid"])
1480 if (DBM::is_result($r)) {
1482 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1487 intval($importer["uid"])
1496 logger('Items are updated.');
1502 * @brief Processes an account deletion
1504 * @param array $importer Array of the importer user
1505 * @param object $data The message object
1507 * @return bool Success
1509 private static function receiveAccountDeletion($importer, $data)
1511 /// @todo Account deletion should remove the contact from the global contacts as well
1513 $author = notags(unxmlify($data->author));
1515 $contact = self::contactByHandle($importer["uid"], $author);
1517 logger("cannot find contact for author: ".$author);
1521 // We now remove the contact
1522 Contact::remove($contact["id"]);
1527 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1529 * @param string $author Author handle
1530 * @param string $guid Message guid
1531 * @param boolean $onlyfound Only return uri when found in the database
1533 * @return string The constructed uri or the one from our database
1535 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1537 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1538 if (DBM::is_result($r)) {
1539 return $r[0]["uri"];
1540 } elseif (!$onlyfound) {
1541 return $author.":".$guid;
1548 * @brief Fetch the guid from our database with a given uri
1550 * @param string $uri Message uri
1551 * @param string $uid Author handle
1553 * @return string The post guid
1555 private static function getGuidFromUri($uri, $uid)
1557 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1558 if (DBM::is_result($r)) {
1559 return $r[0]["guid"];
1566 * @brief Find the best importer for a comment, like, ...
1568 * @param string $guid The guid of the item
1570 * @return array|boolean the origin owner of that post - or false
1572 private static function importerForGuid($guid)
1574 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1576 if (DBM::is_result($item)) {
1577 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1578 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1579 if (DBM::is_result($contact)) {
1587 * @brief Processes an incoming comment
1589 * @param array $importer Array of the importer user
1590 * @param string $sender The sender of the message
1591 * @param object $data The message object
1592 * @param string $xml The original XML of the message
1594 * @return int The message id of the generated comment or "false" if there was an error
1596 private static function receiveComment($importer, $sender, $data, $xml)
1598 $author = notags(unxmlify($data->author));
1599 $guid = notags(unxmlify($data->guid));
1600 $parent_guid = notags(unxmlify($data->parent_guid));
1601 $text = unxmlify($data->text);
1603 if (isset($data->created_at)) {
1604 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1606 $created_at = datetime_convert();
1609 if (isset($data->thread_parent_guid)) {
1610 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1611 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1616 $contact = self::allowedContactByHandle($importer, $sender, true);
1621 $message_id = self::messageExists($importer["uid"], $guid);
1626 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1627 if (!$parent_item) {
1631 $person = self::personByHandle($author);
1632 if (!is_array($person)) {
1633 logger("unable to find author details");
1637 // Fetch the contact id - if we know this contact
1638 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1640 $datarray = array();
1642 $datarray["uid"] = $importer["uid"];
1643 $datarray["contact-id"] = $author_contact["cid"];
1644 $datarray["network"] = $author_contact["network"];
1646 $datarray["author-name"] = $person["name"];
1647 $datarray["author-link"] = $person["url"];
1648 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1650 $datarray["owner-name"] = $contact["name"];
1651 $datarray["owner-link"] = $contact["url"];
1652 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1654 $datarray["guid"] = $guid;
1655 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1657 $datarray["type"] = "remote-comment";
1658 $datarray["verb"] = ACTIVITY_POST;
1659 $datarray["gravity"] = GRAVITY_COMMENT;
1661 if ($thr_uri != "") {
1662 $datarray["parent-uri"] = $thr_uri;
1664 $datarray["parent-uri"] = $parent_item["uri"];
1667 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1669 $datarray["protocol"] = PROTOCOL_DIASPORA;
1670 $datarray["source"] = $xml;
1672 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1674 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1676 $body = diaspora2bb($text);
1678 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1680 self::fetchGuid($datarray);
1682 $message_id = item_store($datarray);
1684 if ($message_id <= 0) {
1689 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1692 // If we are the origin of the parent we store the original data and notify our followers
1693 if ($message_id && $parent_item["origin"]) {
1694 // Formerly we stored the signed text, the signature and the author in different fields.
1695 // We now store the raw data so that we are more flexible.
1696 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1699 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1706 * @brief processes and stores private messages
1708 * @param array $importer Array of the importer user
1709 * @param array $contact The contact of the message
1710 * @param object $data The message object
1711 * @param array $msg Array of the processed message, author handle and key
1712 * @param object $mesg The private message
1713 * @param array $conversation The conversation record to which this message belongs
1715 * @return bool "true" if it was successful
1717 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1719 $author = notags(unxmlify($data->author));
1720 $guid = notags(unxmlify($data->guid));
1721 $subject = notags(unxmlify($data->subject));
1723 // "diaspora_handle" is the element name from the old version
1724 // "author" is the element name from the new version
1725 if ($mesg->author) {
1726 $msg_author = notags(unxmlify($mesg->author));
1727 } elseif ($mesg->diaspora_handle) {
1728 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1733 $msg_guid = notags(unxmlify($mesg->guid));
1734 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1735 $msg_text = unxmlify($mesg->text);
1736 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1738 if ($msg_conversation_guid != $guid) {
1739 logger("message conversation guid does not belong to the current conversation.");
1743 $body = diaspora2bb($msg_text);
1744 $message_uri = $msg_author.":".$msg_guid;
1746 $person = self::personByHandle($msg_author);
1751 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1753 intval($importer["uid"])
1755 if (DBM::is_result($r)) {
1756 logger("duplicate message already delivered.", LOGGER_DEBUG);
1761 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1762 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1763 intval($importer["uid"]),
1765 intval($conversation["id"]),
1766 dbesc($person["name"]),
1767 dbesc($person["photo"]),
1768 dbesc($person["url"]),
1769 intval($contact["id"]),
1774 dbesc($message_uri),
1775 dbesc($author.":".$guid),
1776 dbesc($msg_created_at)
1781 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1785 "type" => NOTIFY_MAIL,
1786 "notify_flags" => $importer["notify-flags"],
1787 "language" => $importer["language"],
1788 "to_name" => $importer["username"],
1789 "to_email" => $importer["email"],
1790 "uid" =>$importer["uid"],
1791 "item" => array("subject" => $subject, "body" => $body),
1792 "source_name" => $person["name"],
1793 "source_link" => $person["url"],
1794 "source_photo" => $person["thumb"],
1795 "verb" => ACTIVITY_POST,
1802 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1804 * @param array $importer Array of the importer user
1805 * @param array $msg Array of the processed message, author handle and key
1806 * @param object $data The message object
1808 * @return bool Success
1810 private static function receiveConversation($importer, $msg, $data)
1812 $author = notags(unxmlify($data->author));
1813 $guid = notags(unxmlify($data->guid));
1814 $subject = notags(unxmlify($data->subject));
1815 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1816 $participants = notags(unxmlify($data->participants));
1818 $messages = $data->message;
1820 if (!count($messages)) {
1821 logger("empty conversation");
1825 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1830 $conversation = null;
1833 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1834 intval($importer["uid"]),
1838 $conversation = $c[0];
1841 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1842 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1843 intval($importer["uid"]),
1847 dbesc(datetime_convert()),
1849 dbesc($participants)
1853 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1854 intval($importer["uid"]),
1860 $conversation = $c[0];
1863 if (!$conversation) {
1864 logger("unable to create conversation.");
1868 foreach ($messages as $mesg) {
1869 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1876 * @brief Creates the body for a "like" message
1878 * @param array $contact The contact that send us the "like"
1879 * @param array $parent_item The item array of the parent item
1880 * @param string $guid message guid
1882 * @return string the body
1884 private static function constructLikeBody($contact, $parent_item, $guid)
1886 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1888 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1889 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1890 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1892 return sprintf($bodyverb, $ulink, $alink, $plink);
1896 * @brief Creates a XML object for a "like"
1898 * @param array $importer Array of the importer user
1899 * @param array $parent_item The item array of the parent item
1901 * @return string The XML
1903 private static function constructLikeObject($importer, $parent_item)
1905 $objtype = ACTIVITY_OBJ_NOTE;
1906 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1907 $parent_body = $parent_item["body"];
1909 $xmldata = array("object" => array("type" => $objtype,
1911 "id" => $parent_item["uri"],
1914 "content" => $parent_body));
1916 return XML::fromArray($xmldata, $xml, true);
1920 * @brief Processes "like" messages
1922 * @param array $importer Array of the importer user
1923 * @param string $sender The sender of the message
1924 * @param object $data The message object
1926 * @return int The message id of the generated like or "false" if there was an error
1928 private static function receiveLike($importer, $sender, $data)
1930 $author = notags(unxmlify($data->author));
1931 $guid = notags(unxmlify($data->guid));
1932 $parent_guid = notags(unxmlify($data->parent_guid));
1933 $parent_type = notags(unxmlify($data->parent_type));
1934 $positive = notags(unxmlify($data->positive));
1936 // likes on comments aren't supported by Diaspora - only on posts
1937 // But maybe this will be supported in the future, so we will accept it.
1938 if (!in_array($parent_type, array("Post", "Comment"))) {
1942 $contact = self::allowedContactByHandle($importer, $sender, true);
1947 $message_id = self::messageExists($importer["uid"], $guid);
1952 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1953 if (!$parent_item) {
1957 $person = self::personByHandle($author);
1958 if (!is_array($person)) {
1959 logger("unable to find author details");
1963 // Fetch the contact id - if we know this contact
1964 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1966 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1967 // We would accept this anyhow.
1968 if ($positive == "true") {
1969 $verb = ACTIVITY_LIKE;
1971 $verb = ACTIVITY_DISLIKE;
1974 $datarray = array();
1976 $datarray["protocol"] = PROTOCOL_DIASPORA;
1978 $datarray["uid"] = $importer["uid"];
1979 $datarray["contact-id"] = $author_contact["cid"];
1980 $datarray["network"] = $author_contact["network"];
1982 $datarray["author-name"] = $person["name"];
1983 $datarray["author-link"] = $person["url"];
1984 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1986 $datarray["owner-name"] = $contact["name"];
1987 $datarray["owner-link"] = $contact["url"];
1988 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1990 $datarray["guid"] = $guid;
1991 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1993 $datarray["type"] = "activity";
1994 $datarray["verb"] = $verb;
1995 $datarray["gravity"] = GRAVITY_LIKE;
1996 $datarray["parent-uri"] = $parent_item["uri"];
1998 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1999 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2001 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2003 $message_id = item_store($datarray);
2005 if ($message_id <= 0) {
2010 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2013 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2014 if ($parent_item["id"] != $parent_item["parent"]) {
2015 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
2016 $origin = $toplevel["origin"];
2018 $origin = $parent_item["origin"];
2021 // If we are the origin of the parent we store the original data and notify our followers
2022 if ($message_id && $origin) {
2023 // Formerly we stored the signed text, the signature and the author in different fields.
2024 // We now store the raw data so that we are more flexible.
2025 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
2028 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2035 * @brief Processes private messages
2037 * @param array $importer Array of the importer user
2038 * @param object $data The message object
2040 * @return bool Success?
2042 private static function receiveMessage($importer, $data)
2044 $author = notags(unxmlify($data->author));
2045 $guid = notags(unxmlify($data->guid));
2046 $conversation_guid = notags(unxmlify($data->conversation_guid));
2047 $text = unxmlify($data->text);
2048 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2050 $contact = self::allowedContactByHandle($importer, $author, true);
2055 $conversation = null;
2058 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2059 intval($importer["uid"]),
2060 dbesc($conversation_guid)
2063 $conversation = $c[0];
2065 logger("conversation not available.");
2069 $message_uri = $author.":".$guid;
2071 $person = self::personByHandle($author);
2073 logger("unable to find author details");
2077 $body = diaspora2bb($text);
2079 $body = self::replacePeopleGuid($body, $person["url"]);
2084 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2086 intval($importer["uid"])
2088 if (DBM::is_result($r)) {
2089 logger("duplicate message already delivered.", LOGGER_DEBUG);
2094 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2095 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2096 intval($importer["uid"]),
2098 intval($conversation["id"]),
2099 dbesc($person["name"]),
2100 dbesc($person["photo"]),
2101 dbesc($person["url"]),
2102 intval($contact["id"]),
2103 dbesc($conversation["subject"]),
2107 dbesc($message_uri),
2108 dbesc($author.":".$conversation["guid"]),
2114 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
2119 * @brief Processes participations - unsupported by now
2121 * @param array $importer Array of the importer user
2122 * @param object $data The message object
2124 * @return bool always true
2126 private static function receiveParticipation($importer, $data)
2128 // I'm not sure if we can fully support this message type
2133 * @brief Processes photos - unneeded
2135 * @param array $importer Array of the importer user
2136 * @param object $data The message object
2138 * @return bool always true
2140 private static function receivePhoto($importer, $data)
2142 // There doesn't seem to be a reason for this function,
2143 // since the photo data is transmitted in the status message as well
2148 * @brief Processes poll participations - unssupported
2150 * @param array $importer Array of the importer user
2151 * @param object $data The message object
2153 * @return bool always true
2155 private static function receivePollParticipation($importer, $data)
2157 // We don't support polls by now
2162 * @brief Processes incoming profile updates
2164 * @param array $importer Array of the importer user
2165 * @param object $data The message object
2167 * @return bool Success
2169 private static function receiveProfile($importer, $data)
2171 $author = strtolower(notags(unxmlify($data->author)));
2173 $contact = self::contactByHandle($importer["uid"], $author);
2178 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2179 $image_url = unxmlify($data->image_url);
2180 $birthday = unxmlify($data->birthday);
2181 $gender = unxmlify($data->gender);
2182 $about = diaspora2bb(unxmlify($data->bio));
2183 $location = diaspora2bb(unxmlify($data->location));
2184 $searchable = (unxmlify($data->searchable) == "true");
2185 $nsfw = (unxmlify($data->nsfw) == "true");
2186 $tags = unxmlify($data->tag_string);
2188 $tags = explode("#", $tags);
2190 $keywords = array();
2191 foreach ($tags as $tag) {
2192 $tag = trim(strtolower($tag));
2198 $keywords = implode(", ", $keywords);
2200 $handle_parts = explode("@", $author);
2201 $nick = $handle_parts[0];
2204 $name = $handle_parts[0];
2207 if (preg_match("|^https?://|", $image_url) === 0) {
2208 $image_url = "http://".$handle_parts[1].$image_url;
2211 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2213 // Generic birthday. We don't know the timezone. The year is irrelevant.
2215 $birthday = str_replace("1000", "1901", $birthday);
2217 if ($birthday != "") {
2218 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2221 // this is to prevent multiple birthday notifications in a single year
2222 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2224 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2225 $birthday = $contact["bd"];
2229 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2230 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2234 dbesc(datetime_convert()),
2240 intval($contact["id"]),
2241 intval($importer["uid"])
2244 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2245 "photo" => $image_url, "name" => $name, "location" => $location,
2246 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2247 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2248 "hide" => !$searchable, "nsfw" => $nsfw);
2250 $gcid = GlobalContact::update($gcontact);
2252 GlobalContact::link($gcid, $importer["uid"], $contact["id"]);
2254 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2260 * @brief Processes incoming friend requests
2262 * @param array $importer Array of the importer user
2263 * @param array $contact The contact that send the request
2266 private static function receiveRequestMakeFriend($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"))) {
2286 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2287 intval($importer["uid"])
2290 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2292 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2294 $arr["protocol"] = PROTOCOL_DIASPORA;
2295 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2296 $arr["uid"] = $importer["uid"];
2297 $arr["contact-id"] = $self[0]["id"];
2299 $arr["type"] = 'wall';
2300 $arr["gravity"] = 0;
2302 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2303 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2304 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2305 $arr["verb"] = ACTIVITY_FRIEND;
2306 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2308 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2309 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2310 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2311 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2313 $arr["object"] = self::constructNewFriendObject($contact);
2315 $arr["last-child"] = 1;
2317 $arr["allow_cid"] = $user[0]["allow_cid"];
2318 $arr["allow_gid"] = $user[0]["allow_gid"];
2319 $arr["deny_cid"] = $user[0]["deny_cid"];
2320 $arr["deny_gid"] = $user[0]["deny_gid"];
2322 $i = item_store($arr);
2324 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2331 * @brief Creates a XML object for a "new friend" message
2333 * @param array $contact Array of the contact
2335 * @return string The XML
2337 private static function constructNewFriendObject($contact)
2339 $objtype = ACTIVITY_OBJ_PERSON;
2340 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2341 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2343 $xmldata = array("object" => array("type" => $objtype,
2344 "title" => $contact["name"],
2345 "id" => $contact["url"]."/".$contact["name"],
2348 return XML::fromArray($xmldata, $xml, true);
2352 * @brief Processes incoming sharing notification
2354 * @param array $importer Array of the importer user
2355 * @param object $data The message object
2357 * @return bool Success
2359 private static function receiveContactRequest($importer, $data)
2361 $author = unxmlify($data->author);
2362 $recipient = unxmlify($data->recipient);
2364 if (!$author || !$recipient) {
2368 // the current protocol version doesn't know these fields
2369 // That means that we will assume their existance
2370 if (isset($data->following)) {
2371 $following = (unxmlify($data->following) == "true");
2376 if (isset($data->sharing)) {
2377 $sharing = (unxmlify($data->sharing) == "true");
2382 $contact = self::contactByHandle($importer["uid"], $author);
2384 // perhaps we were already sharing with this person. Now they're sharing with us.
2385 // That makes us friends.
2388 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2389 self::receiveRequestMakeFriend($importer, $contact);
2391 // refetch the contact array
2392 $contact = self::contactByHandle($importer["uid"], $author);
2394 // If we are now friends, we are sending a share message.
2395 // Normally we needn't to do so, but the first message could have been vanished.
2396 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2397 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2399 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2400 $ret = self::sendShare($u[0], $contact);
2405 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2406 lose_follower($importer, $contact);
2411 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2412 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2414 } elseif (!$following && !$sharing) {
2415 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2417 } elseif (!$following && $sharing) {
2418 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2419 } elseif ($following && $sharing) {
2420 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2421 } elseif ($following && !$sharing) {
2422 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2425 $ret = self::personByHandle($author);
2427 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2428 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2432 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2435 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2436 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2437 intval($importer["uid"]),
2438 dbesc($ret["network"]),
2439 dbesc($ret["addr"]),
2442 dbesc(normalise_link($ret["url"])),
2444 dbesc($ret["name"]),
2445 dbesc($ret["nick"]),
2446 dbesc($ret["photo"]),
2447 dbesc($ret["pubkey"]),
2448 dbesc($ret["notify"]),
2449 dbesc($ret["poll"]),
2454 // find the contact record we just created
2456 $contact_record = self::contactByHandle($importer["uid"], $author);
2458 if (!$contact_record) {
2459 logger("unable to locate newly created contact record.");
2463 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2465 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2467 if (intval($def_gid)) {
2468 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2471 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2473 if ($importer["page-flags"] == PAGE_NORMAL) {
2474 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2476 $hash = random_string().(string)time(); // Generate a confirm_key
2479 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2480 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2481 intval($importer["uid"]),
2482 intval($contact_record["id"]),
2485 dbesc(t("Sharing notification from Diaspora network")),
2487 dbesc(datetime_convert())
2490 // automatic friend approval
2492 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2494 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2496 // technically they are sharing with us (CONTACT_IS_SHARING),
2497 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2498 // we are going to change the relationship and make them a follower.
2500 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2501 $new_relation = CONTACT_IS_FRIEND;
2502 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2503 $new_relation = CONTACT_IS_SHARING;
2505 $new_relation = CONTACT_IS_FOLLOWER;
2509 "UPDATE `contact` SET `rel` = %d,
2517 intval($new_relation),
2518 dbesc(datetime_convert()),
2519 dbesc(datetime_convert()),
2520 intval($contact_record["id"])
2523 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2525 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2526 $ret = self::sendShare($u[0], $contact_record);
2528 // Send the profile data, maybe it weren't transmitted before
2529 self::sendProfile($importer["uid"], array($contact_record));
2537 * @brief Fetches a message with a given guid
2539 * @param string $guid message guid
2540 * @param string $orig_author handle of the original post
2541 * @param string $author handle of the sharer
2543 * @return array The fetched item
2545 private static function originalItem($guid, $orig_author, $author)
2547 // Do we already have this item?
2549 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2550 `author-name`, `author-link`, `author-avatar`
2551 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2555 if (DBM::is_result($r)) {
2556 logger("reshared message ".$guid." already exists on system.");
2558 // Maybe it is already a reshared item?
2559 // Then refetch the content, if it is a reshare from a reshare.
2560 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2561 if (self::isReshare($r[0]["body"], true)) {
2563 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2564 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2566 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2568 // Add OEmbed and other information to the body
2569 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2577 if (!DBM::is_result($r)) {
2578 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2579 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2580 $item_id = self::storeByGuid($guid, $server);
2583 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2584 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2585 $item_id = self::storeByGuid($guid, $server);
2590 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2591 `author-name`, `author-link`, `author-avatar`
2592 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2596 if (DBM::is_result($r)) {
2597 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2598 if (self::isReshare($r[0]["body"], false)) {
2599 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2600 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2611 * @brief Processes a reshare message
2613 * @param array $importer Array of the importer user
2614 * @param object $data The message object
2615 * @param string $xml The original XML of the message
2617 * @return int the message id
2619 private static function receiveReshare($importer, $data, $xml)
2621 $author = notags(unxmlify($data->author));
2622 $guid = notags(unxmlify($data->guid));
2623 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2624 $root_author = notags(unxmlify($data->root_author));
2625 $root_guid = notags(unxmlify($data->root_guid));
2626 /// @todo handle unprocessed property "provider_display_name"
2627 $public = notags(unxmlify($data->public));
2629 $contact = self::allowedContactByHandle($importer, $author, false);
2634 $message_id = self::messageExists($importer["uid"], $guid);
2639 $original_item = self::originalItem($root_guid, $root_author, $author);
2640 if (!$original_item) {
2644 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2646 $datarray = array();
2648 $datarray["uid"] = $importer["uid"];
2649 $datarray["contact-id"] = $contact["id"];
2650 $datarray["network"] = NETWORK_DIASPORA;
2652 $datarray["author-name"] = $contact["name"];
2653 $datarray["author-link"] = $contact["url"];
2654 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2656 $datarray["owner-name"] = $datarray["author-name"];
2657 $datarray["owner-link"] = $datarray["author-link"];
2658 $datarray["owner-avatar"] = $datarray["author-avatar"];
2660 $datarray["guid"] = $guid;
2661 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2663 $datarray["verb"] = ACTIVITY_POST;
2664 $datarray["gravity"] = GRAVITY_PARENT;
2666 $datarray["protocol"] = PROTOCOL_DIASPORA;
2667 $datarray["source"] = $xml;
2669 $prefix = share_header(
2670 $original_item["author-name"],
2671 $original_item["author-link"],
2672 $original_item["author-avatar"],
2673 $original_item["guid"],
2674 $original_item["created"],
2677 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2679 $datarray["tag"] = $original_item["tag"];
2680 $datarray["app"] = $original_item["app"];
2682 $datarray["plink"] = self::plink($author, $guid);
2683 $datarray["private"] = (($public == "false") ? 1 : 0);
2684 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2686 $datarray["object-type"] = $original_item["object-type"];
2688 self::fetchGuid($datarray);
2689 $message_id = item_store($datarray);
2692 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2700 * @brief Processes retractions
2702 * @param array $importer Array of the importer user
2703 * @param array $contact The contact of the item owner
2704 * @param object $data The message object
2706 * @return bool success
2708 private static function itemRetraction($importer, $contact, $data)
2710 $author = notags(unxmlify($data->author));
2711 $target_guid = notags(unxmlify($data->target_guid));
2712 $target_type = notags(unxmlify($data->target_type));
2714 $person = self::personByHandle($author);
2715 if (!is_array($person)) {
2716 logger("unable to find author detail for ".$author);
2720 if (empty($contact["url"])) {
2721 $contact["url"] = $person["url"];
2724 // Fetch items that are about to be deleted
2725 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2727 // When we receive a public retraction, we delete every item that we find.
2728 if ($importer['uid'] == 0) {
2729 $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2731 $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2733 $r = dba::select('item', $fields, $condition);
2734 if (!DBM::is_result($r)) {
2735 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2739 while ($item = dba::fetch($r)) {
2740 // Fetch the parent item
2741 $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2743 // Only delete it if the parent author really fits
2744 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2745 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2749 // Currently we don't have a central deletion function that we could use in this case.
2750 // The function "item_drop" doesn't work for that case
2757 'edited' => datetime_convert(),
2758 'changed' => datetime_convert()),
2759 array('id' => $item["id"])
2762 // Delete the thread - if it is a starting post and not a comment
2763 if ($target_type != 'Comment') {
2764 delete_thread($item["id"], $item["parent-uri"]);
2767 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2769 // Now check if the retraction needs to be relayed by us
2770 if ($parent["origin"]) {
2772 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2780 * @brief Receives retraction messages
2782 * @param array $importer Array of the importer user
2783 * @param string $sender The sender of the message
2784 * @param object $data The message object
2786 * @return bool Success
2788 private static function receiveRetraction($importer, $sender, $data)
2790 $target_type = notags(unxmlify($data->target_type));
2792 $contact = self::contactByHandle($importer["uid"], $sender);
2793 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2794 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2798 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2800 switch ($target_type) {
2805 case "StatusMessage":
2806 return self::itemRetraction($importer, $contact, $data);
2810 /// @todo What should we do with an "unshare"?
2811 // Removing the contact isn't correct since we still can read the public items
2812 Contact::remove($contact["id"]);
2816 logger("Unknown target type ".$target_type);
2823 * @brief Receives status messages
2825 * @param array $importer Array of the importer user
2826 * @param object $data The message object
2827 * @param string $xml The original XML of the message
2829 * @return int The message id of the newly created item
2831 private static function receiveStatusMessage($importer, $data, $xml)
2833 $author = notags(unxmlify($data->author));
2834 $guid = notags(unxmlify($data->guid));
2835 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2836 $public = notags(unxmlify($data->public));
2837 $text = unxmlify($data->text);
2838 $provider_display_name = notags(unxmlify($data->provider_display_name));
2840 $contact = self::allowedContactByHandle($importer, $author, false);
2845 $message_id = self::messageExists($importer["uid"], $guid);
2851 if ($data->location) {
2852 foreach ($data->location->children() as $fieldname => $data) {
2853 $address[$fieldname] = notags(unxmlify($data));
2857 $body = diaspora2bb($text);
2859 $datarray = array();
2861 // Attach embedded pictures to the body
2863 foreach ($data->photo as $photo) {
2864 $body = "[img]".unxmlify($photo->remote_photo_path).
2865 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2868 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2870 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2872 // Add OEmbed and other information to the body
2873 if (!self::isRedmatrix($contact["url"])) {
2874 $body = add_page_info_to_body($body, false, true);
2878 /// @todo enable support for polls
2879 //if ($data->poll) {
2880 // foreach ($data->poll AS $poll)
2885 /// @todo enable support for events
2887 $datarray["uid"] = $importer["uid"];
2888 $datarray["contact-id"] = $contact["id"];
2889 $datarray["network"] = NETWORK_DIASPORA;
2891 $datarray["author-name"] = $contact["name"];
2892 $datarray["author-link"] = $contact["url"];
2893 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2895 $datarray["owner-name"] = $datarray["author-name"];
2896 $datarray["owner-link"] = $datarray["author-link"];
2897 $datarray["owner-avatar"] = $datarray["author-avatar"];
2899 $datarray["guid"] = $guid;
2900 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2902 $datarray["verb"] = ACTIVITY_POST;
2903 $datarray["gravity"] = GRAVITY_PARENT;
2905 $datarray["protocol"] = PROTOCOL_DIASPORA;
2906 $datarray["source"] = $xml;
2908 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2910 if ($provider_display_name != "") {
2911 $datarray["app"] = $provider_display_name;
2914 $datarray["plink"] = self::plink($author, $guid);
2915 $datarray["private"] = (($public == "false") ? 1 : 0);
2916 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2918 if (isset($address["address"])) {
2919 $datarray["location"] = $address["address"];
2922 if (isset($address["lat"]) && isset($address["lng"])) {
2923 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2926 self::fetchGuid($datarray);
2927 $message_id = item_store($datarray);
2930 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2937 /* ************************************************************************************** *
2938 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2939 * ************************************************************************************** */
2942 * @brief returnes the handle of a contact
2944 * @param array $contact contact array
2946 * @return string the handle in the format user@domain.tld
2948 private static function myHandle($contact)
2950 if ($contact["addr"] != "") {
2951 return $contact["addr"];
2954 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2955 // So - just in case - we build the the address here.
2956 if ($contact["nickname"] != "") {
2957 $nick = $contact["nickname"];
2959 $nick = $contact["nick"];
2962 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2967 * @brief Creates the data for a private message in the new format
2969 * @param string $msg The message that is to be transmitted
2970 * @param array $user The record of the sender
2971 * @param array $contact Target of the communication
2972 * @param string $prvkey The private key of the sender
2973 * @param string $pubkey The public key of the receiver
2975 * @return string The encrypted data
2977 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
2979 logger("Message: ".$msg, LOGGER_DATA);
2981 // without a public key nothing will work
2983 logger("pubkey missing: contact id: ".$contact["id"]);
2987 $aes_key = openssl_random_pseudo_bytes(32);
2988 $b_aes_key = base64_encode($aes_key);
2989 $iv = openssl_random_pseudo_bytes(16);
2990 $b_iv = base64_encode($iv);
2992 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2994 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2996 $encrypted_key_bundle = "";
2997 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2999 $json_object = json_encode(
3000 array("aes_key" => base64_encode($encrypted_key_bundle),
3001 "encrypted_magic_envelope" => base64_encode($ciphertext))
3004 return $json_object;
3008 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3010 * @param string $msg The message that is to be transmitted
3011 * @param array $user The record of the sender
3013 * @return string The envelope
3015 public static function buildMagicEnvelope($msg, $user)
3017 $b64url_data = base64url_encode($msg);
3018 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
3020 $key_id = base64url_encode(self::myHandle($user));
3021 $type = "application/xml";
3022 $encoding = "base64url";
3023 $alg = "RSA-SHA256";
3024 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3026 // Fallback if the private key wasn't transmitted in the expected field
3027 if ($user['uprvkey'] == "") {
3028 $user['uprvkey'] = $user['prvkey'];
3031 $signature = rsa_sign($signable_data, $user["uprvkey"]);
3032 $sig = base64url_encode($signature);
3034 $xmldata = array("me:env" => array("me:data" => $data,
3035 "@attributes" => array("type" => $type),
3036 "me:encoding" => $encoding,
3039 "@attributes2" => array("key_id" => $key_id)));
3041 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
3043 return XML::fromArray($xmldata, $xml, false, $namespaces);
3047 * @brief Create the envelope for a message
3049 * @param string $msg The message that is to be transmitted
3050 * @param array $user The record of the sender
3051 * @param array $contact Target of the communication
3052 * @param string $prvkey The private key of the sender
3053 * @param string $pubkey The public key of the receiver
3054 * @param bool $public Is the message public?
3056 * @return string The message that will be transmitted to other servers
3058 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3060 // The message is put into an envelope with the sender's signature
3061 $envelope = self::buildMagicEnvelope($msg, $user);
3063 // Private messages are put into a second envelope, encrypted with the receivers public key
3065 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3072 * @brief Creates a signature for a message
3074 * @param array $owner the array of the owner of the message
3075 * @param array $message The message that is to be signed
3077 * @return string The signature
3079 private static function signature($owner, $message)
3082 unset($sigmsg["author_signature"]);
3083 unset($sigmsg["parent_author_signature"]);
3085 $signed_text = implode(";", $sigmsg);
3087 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3091 * @brief Transmit a message to a target server
3093 * @param array $owner the array of the item owner
3094 * @param array $contact Target of the communication
3095 * @param string $envelope The message that is to be transmitted
3096 * @param bool $public_batch Is it a public post?
3097 * @param bool $queue_run Is the transmission called from the queue?
3098 * @param string $guid message guid
3100 * @return int Result of the transmission
3102 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3106 $enabled = intval(Config::get("system", "diaspora_enabled"));
3111 $logid = random_string(4);
3112 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
3114 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3118 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3120 if (!$queue_run && was_recently_delayed($contact["id"])) {
3123 if (!intval(Config::get("system", "diaspora_test"))) {
3124 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3126 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
3127 $return_code = $a->get_curl_code();
3129 logger("test_mode");
3134 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3136 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3137 logger("queue message");
3140 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3141 intval($contact["id"]),
3142 dbesc(NETWORK_DIASPORA),
3144 intval($public_batch)
3147 logger("add_to_queue ignored - identical item already in queue");
3149 // queue message for redelivery
3150 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3152 // The message could not be delivered. We mark the contact as "dead"
3153 Contact::markForArchival($contact);
3155 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3156 // We successfully delivered a message, the contact is alive
3157 Contact::unmarkForArchival($contact);
3160 return(($return_code) ? $return_code : (-1));
3165 * @brief Build the post xml
3167 * @param string $type The message type
3168 * @param array $message The message data
3170 * @return string The post XML
3172 public static function buildPostXml($type, $message)
3174 $data = array($type => $message);
3176 return XML::fromArray($data, $xml);
3180 * @brief Builds and transmit messages
3182 * @param array $owner the array of the item owner
3183 * @param array $contact Target of the communication
3184 * @param string $type The message type
3185 * @param array $message The message data
3186 * @param bool $public_batch Is it a public post?
3187 * @param string $guid message guid
3188 * @param bool $spool Should the transmission be spooled or transmitted?
3190 * @return int Result of the transmission
3192 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3194 $msg = self::buildPostXml($type, $message);
3196 logger('message: '.$msg, LOGGER_DATA);
3197 logger('send guid '.$guid, LOGGER_DEBUG);
3199 // Fallback if the private key wasn't transmitted in the expected field
3200 if ($owner['uprvkey'] == "") {
3201 $owner['uprvkey'] = $owner['prvkey'];
3204 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3207 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3210 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3213 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3215 return $return_code;
3219 * @brief sends an account migration
3221 * @param array $owner the array of the item owner
3222 * @param array $contact Target of the communication
3223 * @param int $uid User ID
3225 * @return int The result of the transmission
3227 public static function sendAccountMigration($owner, $contact, $uid)
3229 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3230 $profile = self::createProfileData($uid);
3232 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3233 $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3235 $message = array("author" => $old_handle,
3236 "profile" => $profile,
3237 "signature" => $signature);
3239 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3241 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3245 * @brief Sends a "share" message
3247 * @param array $owner the array of the item owner
3248 * @param array $contact Target of the communication
3250 * @return int The result of the transmission
3252 public static function sendShare($owner, $contact)
3255 * @todo support the different possible combinations of "following" and "sharing"
3256 * Currently, Diaspora only interprets the "sharing" field
3258 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3262 switch ($contact["rel"]) {
3263 case CONTACT_IS_FRIEND:
3266 case CONTACT_IS_SHARING:
3269 case CONTACT_IS_FOLLOWER:
3275 $message = array("author" => self::myHandle($owner),
3276 "recipient" => $contact["addr"],
3277 "following" => "true",
3278 "sharing" => "true");
3280 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3282 return self::buildAndTransmit($owner, $contact, "contact", $message);
3286 * @brief sends an "unshare"
3288 * @param array $owner the array of the item owner
3289 * @param array $contact Target of the communication
3291 * @return int The result of the transmission
3293 public static function sendUnshare($owner, $contact)
3295 $message = array("author" => self::myHandle($owner),
3296 "recipient" => $contact["addr"],
3297 "following" => "false",
3298 "sharing" => "false");
3300 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3302 return self::buildAndTransmit($owner, $contact, "contact", $message);
3306 * @brief Checks a message body if it is a reshare
3308 * @param string $body The message body that is to be check
3309 * @param bool $complete Should it be a complete check or a simple check?
3311 * @return array|bool Reshare details or "false" if no reshare
3313 public static function isReshare($body, $complete = true)
3315 $body = trim($body);
3317 // Skip if it isn't a pure repeated messages
3318 // Does it start with a share?
3319 if ((strpos($body, "[share") > 0) && $complete) {
3323 // Does it end with a share?
3324 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3328 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3329 // Skip if there is no shared message in there
3330 if ($body == $attributes) {
3334 // If we don't do the complete check we quit here
3340 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3341 if ($matches[1] != "") {
3342 $guid = $matches[1];
3345 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3346 if ($matches[1] != "") {
3347 $guid = $matches[1];
3352 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3359 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3360 $ret["root_guid"] = $guid;
3366 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3367 if ($matches[1] != "") {
3368 $profile = $matches[1];
3371 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3372 if ($matches[1] != "") {
3373 $profile = $matches[1];
3378 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3379 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3384 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3385 if ($matches[1] != "") {
3386 $link = $matches[1];
3389 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3390 if ($matches[1] != "") {
3391 $link = $matches[1];
3394 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3395 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3403 * @brief Create an event array
3405 * @param integer $event_id The id of the event
3407 * @return array with event data
3409 private static function buildEvent($event_id)
3411 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3412 if (!DBM::is_result($r)) {
3418 $eventdata = array();
3420 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3421 if (!DBM::is_result($r)) {
3427 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3428 if (!DBM::is_result($r)) {
3434 $eventdata['author'] = self::myHandle($owner);
3436 if ($event['guid']) {
3437 $eventdata['guid'] = $event['guid'];
3440 $mask = 'Y-m-d\TH:i:s\Z';
3442 /// @todo - establish "all day" events in Friendica
3443 $eventdata["all_day"] = "false";
3445 if (!$event['adjust']) {
3446 $eventdata['timezone'] = $user['timezone'];
3448 if ($eventdata['timezone'] == "") {
3449 $eventdata['timezone'] = 'UTC';
3453 if ($event['start']) {
3454 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3456 if ($event['finish'] && !$event['nofinish']) {
3457 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3459 if ($event['summary']) {
3460 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3462 if ($event['desc']) {
3463 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3465 if ($event['location']) {
3466 $location = array();
3467 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3468 $location["lat"] = 0;
3469 $location["lng"] = 0;
3470 $eventdata['location'] = $location;
3477 * @brief Create a post (status message or reshare)
3479 * @param array $item The item that will be exported
3480 * @param array $owner the array of the item owner
3483 * 'type' -> Message type ("status_message" or "reshare")
3484 * 'message' -> Array of XML elements of the status
3486 public static function buildStatus($item, $owner)
3488 $cachekey = "diaspora:buildStatus:".$item['guid'];
3490 $result = Cache::get($cachekey);
3491 if (!is_null($result)) {
3495 $myaddr = self::myHandle($owner);
3497 $public = (($item["private"]) ? "false" : "true");
3499 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3501 // Detect a share element and do a reshare
3502 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3503 $message = array("author" => $myaddr,
3504 "guid" => $item["guid"],
3505 "created_at" => $created,
3506 "root_author" => $ret["root_handle"],
3507 "root_guid" => $ret["root_guid"],
3508 "provider_display_name" => $item["app"],
3509 "public" => $public);
3513 $title = $item["title"];
3514 $body = $item["body"];
3516 // convert to markdown
3517 $body = html_entity_decode(bb2diaspora($body));
3520 if (strlen($title)) {
3521 $body = "## ".html_entity_decode($title)."\n\n".$body;
3524 if ($item["attach"]) {
3525 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3527 $body .= "\n".t("Attachments:")."\n";
3528 foreach ($matches as $mtch) {
3529 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3534 $location = array();
3536 if ($item["location"] != "")
3537 $location["address"] = $item["location"];
3539 if ($item["coord"] != "") {
3540 $coord = explode(" ", $item["coord"]);
3541 $location["lat"] = $coord[0];
3542 $location["lng"] = $coord[1];
3545 $message = array("author" => $myaddr,
3546 "guid" => $item["guid"],
3547 "created_at" => $created,
3548 "public" => $public,
3550 "provider_display_name" => $item["app"],
3551 "location" => $location);
3553 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3554 if (!isset($location["lat"]) || !isset($location["lng"])) {
3555 unset($message["location"]);
3558 if ($item['event-id'] > 0) {
3559 $event = self::buildEvent($item['event-id']);
3560 if (count($event)) {
3561 $message['event'] = $event;
3563 /// @todo Once Diaspora supports it, we will remove the body
3564 // $message['text'] = '';
3568 $type = "status_message";
3571 $msg = array("type" => $type, "message" => $message);
3573 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3579 * @brief Sends a post
3581 * @param array $item The item that will be exported
3582 * @param array $owner the array of the item owner
3583 * @param array $contact Target of the communication
3584 * @param bool $public_batch Is it a public post?
3586 * @return int The result of the transmission
3588 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3590 $status = self::buildStatus($item, $owner);
3592 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3596 * @brief Creates a "like" object
3598 * @param array $item The item that will be exported
3599 * @param array $owner the array of the item owner
3601 * @return array The data for a "like"
3603 private static function constructLike($item, $owner)
3606 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3607 dbesc($item["thr-parent"])
3609 if (!DBM::is_result($p)) {
3615 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3616 if ($item['verb'] === ACTIVITY_LIKE) {
3618 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3619 $positive = "false";
3622 return(array("author" => self::myHandle($owner),
3623 "guid" => $item["guid"],
3624 "parent_guid" => $parent["guid"],
3625 "parent_type" => $target_type,
3626 "positive" => $positive,
3627 "author_signature" => ""));
3631 * @brief Creates an "EventParticipation" object
3633 * @param array $item The item that will be exported
3634 * @param array $owner the array of the item owner
3636 * @return array The data for an "EventParticipation"
3638 private static function constructAttend($item, $owner)
3641 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3642 dbesc($item["thr-parent"])
3644 if (!DBM::is_result($p)) {
3650 switch ($item['verb']) {
3651 case ACTIVITY_ATTEND:
3652 $attend_answer = 'accepted';
3654 case ACTIVITY_ATTENDNO:
3655 $attend_answer = 'declined';
3657 case ACTIVITY_ATTENDMAYBE:
3658 $attend_answer = 'tentative';
3661 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3665 return(array("author" => self::myHandle($owner),
3666 "guid" => $item["guid"],
3667 "parent_guid" => $parent["guid"],
3668 "status" => $attend_answer,
3669 "author_signature" => ""));
3673 * @brief Creates the object for a comment
3675 * @param array $item The item that will be exported
3676 * @param array $owner the array of the item owner
3678 * @return array The data for a comment
3680 private static function constructComment($item, $owner)
3682 $cachekey = "diaspora:constructComment:".$item['guid'];
3684 $result = Cache::get($cachekey);
3685 if (!is_null($result)) {
3690 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3691 intval($item["parent"]),
3692 intval($item["parent"])
3695 if (!DBM::is_result($p)) {
3701 $text = html_entity_decode(bb2diaspora($item["body"]));
3702 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3704 $comment = array("author" => self::myHandle($owner),
3705 "guid" => $item["guid"],
3706 "created_at" => $created,
3707 "parent_guid" => $parent["guid"],
3709 "author_signature" => "");
3711 // Send the thread parent guid only if it is a threaded comment
3712 if ($item['thr-parent'] != $item['parent-uri']) {
3713 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3716 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3722 * @brief Send a like or a comment
3724 * @param array $item The item that will be exported
3725 * @param array $owner the array of the item owner
3726 * @param array $contact Target of the communication
3727 * @param bool $public_batch Is it a public post?
3729 * @return int The result of the transmission
3731 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3733 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3734 $message = self::constructAttend($item, $owner);
3735 $type = "event_participation";
3736 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3737 $message = self::constructLike($item, $owner);
3740 $message = self::constructComment($item, $owner);
3748 $message["author_signature"] = self::signature($owner, $message);
3750 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3754 * @brief Creates a message from a signature record entry
3756 * @param array $item The item that will be exported
3757 * @param array $signature The entry of the "sign" record
3759 * @return string The message
3761 private static function messageFromSignature($item, $signature)
3763 // Split the signed text
3764 $signed_parts = explode(";", $signature['signed_text']);
3766 if ($item["deleted"]) {
3767 $message = array("author" => $signature['signer'],
3768 "target_guid" => $signed_parts[0],
3769 "target_type" => $signed_parts[1]);
3770 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3771 $message = array("author" => $signed_parts[4],
3772 "guid" => $signed_parts[1],
3773 "parent_guid" => $signed_parts[3],
3774 "parent_type" => $signed_parts[2],
3775 "positive" => $signed_parts[0],
3776 "author_signature" => $signature['signature'],
3777 "parent_author_signature" => "");
3779 // Remove the comment guid
3780 $guid = array_shift($signed_parts);
3782 // Remove the parent guid
3783 $parent_guid = array_shift($signed_parts);
3785 // Remove the handle
3786 $handle = array_pop($signed_parts);
3788 // Glue the parts together
3789 $text = implode(";", $signed_parts);
3791 $message = array("author" => $handle,
3793 "parent_guid" => $parent_guid,
3794 "text" => implode(";", $signed_parts),
3795 "author_signature" => $signature['signature'],
3796 "parent_author_signature" => "");
3802 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3804 * @param array $item The item that will be exported
3805 * @param array $owner the array of the item owner
3806 * @param array $contact Target of the communication
3807 * @param bool $public_batch Is it a public post?
3809 * @return int The result of the transmission
3811 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3813 if ($item["deleted"]) {
3814 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3815 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3821 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3823 // fetch the original signature
3826 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3831 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3837 // Old way - is used by the internal Friendica functions
3838 /// @todo Change all signatur storing functions to the new format
3839 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3840 $message = self::messageFromSignature($item, $signature);
3842 $msg = json_decode($signature['signed_text'], true);
3845 if (is_array($msg)) {
3846 foreach ($msg as $field => $data) {
3847 if (!$item["deleted"]) {
3848 if ($field == "diaspora_handle") {
3851 if ($field == "target_type") {
3852 $field = "parent_type";
3856 $message[$field] = $data;
3859 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3863 $message["parent_author_signature"] = self::signature($owner, $message);
3865 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3867 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3871 * @brief Sends a retraction (deletion) of a message, like or comment
3873 * @param array $item The item that will be exported
3874 * @param array $owner the array of the item owner
3875 * @param array $contact Target of the communication
3876 * @param bool $public_batch Is it a public post?
3877 * @param bool $relay Is the retraction transmitted from a relay?
3879 * @return int The result of the transmission
3881 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
3883 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
3885 $msg_type = "retraction";
3887 if ($item['id'] == $item['parent']) {
3888 $target_type = "Post";
3889 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3890 $target_type = "Like";
3892 $target_type = "Comment";
3895 $message = array("author" => $itemaddr,
3896 "target_guid" => $item['guid'],
3897 "target_type" => $target_type);
3899 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3901 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3905 * @brief Sends a mail
3907 * @param array $item The item that will be exported
3908 * @param array $owner The owner
3909 * @param array $contact Target of the communication
3911 * @return int The result of the transmission
3913 public static function sendMail($item, $owner, $contact)
3915 $myaddr = self::myHandle($owner);
3918 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3919 intval($item["convid"]),
3920 intval($item["uid"])
3923 if (!DBM::is_result($r)) {
3924 logger("conversation not found.");
3930 "author" => $cnv["creator"],
3931 "guid" => $cnv["guid"],
3932 "subject" => $cnv["subject"],
3933 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3934 "participants" => $cnv["recips"]
3937 $body = bb2diaspora($item["body"]);
3938 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3941 "author" => $myaddr,
3942 "guid" => $item["guid"],
3943 "conversation_guid" => $cnv["guid"],
3945 "created_at" => $created,
3948 if ($item["reply"]) {
3953 "author" => $cnv["creator"],
3954 "guid" => $cnv["guid"],
3955 "subject" => $cnv["subject"],
3956 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3957 "participants" => $cnv["recips"],
3960 $type = "conversation";
3963 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3967 * @brief Create profile data
3969 * @param int $uid The user id
3971 * @return array The profile data
3973 private static function createProfileData($uid)
3976 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3978 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3979 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3980 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3990 $handle = $profile["addr"];
3991 $first = ((strpos($profile['name'], ' ')
3992 ? trim(substr($profile['name'], 0, strpos($profile['name'], ' '))) : $profile['name']));
3993 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3994 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3995 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3996 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3997 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3999 if ($searchable === 'true') {
4000 $dob = '1000-00-00';
4002 if (($profile['dob']) && ($profile['dob'] > '0001-01-01')) {
4003 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC', 'UTC', $profile['dob'],'m-d');
4006 $about = $profile['about'];
4007 $about = strip_tags(bbcode($about));
4009 $location = Profile::formatLocation($profile);
4011 if ($profile['pub_keywords']) {
4012 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4013 $kw = str_replace(' ', ' ', $kw);
4014 $arr = explode(' ', $profile['pub_keywords']);
4016 for ($x = 0; $x < 5; $x ++) {
4017 if (trim($arr[$x])) {
4018 $tags .= '#'. trim($arr[$x]) .' ';
4023 $tags = trim($tags);
4026 return array("author" => $handle,
4027 "first_name" => $first,
4028 "last_name" => $last,
4029 "image_url" => $large,
4030 "image_url_medium" => $medium,
4031 "image_url_small" => $small,
4033 "gender" => $profile['gender'],
4035 "location" => $location,
4036 "searchable" => $searchable,
4038 "tag_string" => $tags);
4042 * @brief Sends profile data
4044 * @param int $uid The user id
4045 * @param bool $recips optional, default false
4048 public static function sendProfile($uid, $recips = false)
4056 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4057 AND `uid` = %d AND `rel` != %d",
4058 dbesc(NETWORK_DIASPORA),
4060 intval(CONTACT_IS_SHARING)
4068 $message = self::createProfileData($uid);
4070 foreach ($recips as $recip) {
4071 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4072 self::buildAndTransmit($profile, $recip, "profile", $message, false, "", true);
4077 * @brief Stores the signature for likes that are created on our system
4079 * @param array $contact The contact array of the "like"
4080 * @param int $post_id The post id of the "like"
4082 * @return bool Success
4084 public static function storeLikeSignature($contact, $post_id)
4086 // Is the contact the owner? Then fetch the private key
4087 if (!$contact['self'] || ($contact['uid'] == 0)) {
4088 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4092 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4093 if (!DBM::is_result($r)) {
4097 $contact["uprvkey"] = $r[0]['prvkey'];
4099 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4100 if (!DBM::is_result($r)) {
4104 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
4108 $message = self::constructLike($r[0], $contact);
4109 $message["author_signature"] = self::signature($contact, $message);
4112 * Now store the signature more flexible to dynamically support new fields.
4113 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4115 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
4117 logger('Stored diaspora like signature');
4122 * @brief Stores the signature for comments that are created on our system
4124 * @param array $item The item array of the comment
4125 * @param array $contact The contact array of the item owner
4126 * @param string $uprvkey The private key of the sender
4127 * @param int $message_id The message id of the comment
4129 * @return bool Success
4131 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4133 if ($uprvkey == "") {
4134 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4138 $contact["uprvkey"] = $uprvkey;
4140 $message = self::constructComment($item, $contact);
4141 $message["author_signature"] = self::signature($contact, $message);
4144 * Now store the signature more flexible to dynamically support new fields.
4145 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4147 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
4149 logger('Stored diaspora comment signature');