3 * @file src/Protocol/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.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\Markdown;
15 use Friendica\Core\Cache;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\Queue;
28 use Friendica\Model\User;
29 use Friendica\Network\Probe;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Util\Map;
38 require_once 'include/dba.php';
39 require_once 'include/items.php';
42 * @brief This class contain functions to create and send Diaspora XML files
48 * @brief Return a list of relay servers
50 * The list contains not only the official relays but also servers that we serve directly
52 * @param integer $item_id The id of the item that is sent
53 * @return array of relay servers
55 public static function relayList($item_id)
59 // Fetching relay servers
60 $serverdata = Config::get("system", "relay_server");
61 if ($serverdata != "") {
62 $servers = explode(",", $serverdata);
63 foreach ($servers as $server) {
64 $serverlist[$server] = trim($server);
68 if (Config::get("system", "relay_directly", false)) {
69 // Servers that want to get all content
70 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
71 while ($server = dba::fetch($servers)) {
72 $serverlist[$server['url']] = $server['url'];
75 // All tags of the current post
76 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $item_id];
77 $tags = dba::select('term', ['term'], $condition);
79 while ($tag = dba::fetch($tags)) {
80 $taglist[] = $tag['term'];
83 // All servers who wants content with this tag
85 if (!empty($taglist)) {
86 $tagserver = dba::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
87 while ($server = dba::fetch($tagserver)) {
88 $tagserverlist[] = $server['gserver-id'];
92 // All adresses with the given id
93 if (!empty($tagserverlist)) {
94 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
95 while ($server = dba::fetch($servers)) {
96 $serverlist[$server['url']] = $server['url'];
101 // Now we are collecting all relay contacts
103 foreach ($serverlist as $server_url) {
104 // We don't send messages to ourselves
105 if (!link_compare($server_url, System::baseUrl())) {
106 $cid = self::getRelayContactId($server_url);
107 if (!is_bool($cid)) {
117 * @brief Return a contact for a given server address or creates a dummy entry
119 * @param string $server_url The url of the server
120 * @return array with the contact
122 private static function getRelayContactId($server_url)
124 $batch = $server_url . '/receive/public';
126 $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
128 // Fetch the relay contact
129 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
130 'contact-type' => ACCOUNT_TYPE_RELAY];
131 $contact = dba::selectFirst('contact', $fields, $condition);
133 // If there is nothing found, we check if there is some unmarked relay
134 // This code segment can be removed before the release 2018-05
135 if (!DBM::is_result($contact)) {
136 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
137 'name' => 'relay', 'nick' => 'relay', 'url' => $server_url];
138 $contact = dba::selectFirst('contact', $fields, $condition);
140 if (DBM::is_result($contact)) {
141 // Mark the relay account as a relay account
142 $fields = ['contact-type' => ACCOUNT_TYPE_RELAY];
143 dba::update('contact', $fields, ['id' => $contact['id']]);
146 if (DBM::is_result($contact)) {
147 if ($contact['archive'] || $contact['blocked']) {
152 $fields = ['uid' => 0, 'created' => DateTimeFormat::utcNow(),
153 'name' => 'relay', 'nick' => 'relay',
154 'url' => $server_url, 'nurl' => normalise_link($server_url),
155 'batch' => $batch, 'network' => NETWORK_DIASPORA,
156 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
157 'contact-type' => ACCOUNT_TYPE_RELAY,
158 'pending' => false, 'writable' => true];
159 dba::insert('contact', $fields);
161 $fields = ['batch', 'id', 'name', 'network'];
162 $contact = dba::selectFirst('contact', $fields, $condition);
163 if (DBM::is_result($contact)) {
169 // It should never happen that we arrive here
174 * @brief Return a list of participating contacts for a thread
176 * This is used for the participation feature.
177 * One of the parameters is a contact array.
178 * This is done to avoid duplicates.
180 * @param integer $thread The id of the thread
181 * @param array $contacts The previously fetched contacts
183 * @return array of relay servers
185 public static function participantsForThread($thread, $contacts)
187 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
188 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
189 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
190 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
191 WHERE `participation`.`iid` = ?", $thread);
193 while ($contact = dba::fetch($r)) {
194 if (!empty($contact['fnetwork'])) {
195 $contact['network'] = $contact['fnetwork'];
197 unset($contact['fnetwork']);
199 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
200 $contact['batch'] = $contact['fbatch'];
202 unset($contact['fbatch']);
205 foreach ($contacts as $entry) {
206 if ($entry['batch'] == $contact['batch']) {
212 $contacts[] = $contact;
221 * @brief repairs a signature that was double encoded
223 * The function is unused at the moment. It was copied from the old implementation.
225 * @param string $signature The signature
226 * @param string $handle The handle of the signature owner
227 * @param integer $level This value is only set inside this function to avoid endless loops
229 * @return string the repaired signature
231 private static function repairSignature($signature, $handle = "", $level = 1)
233 if ($signature == "") {
237 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
238 $signature = base64_decode($signature);
239 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
241 // Do a recursive call to be able to fix even multiple levels
243 $signature = self::repairSignature($signature, $handle, ++$level);
251 * @brief verify the envelope and return the verified data
253 * @param string $envelope The magic envelope
255 * @return string verified data
257 private static function verifyMagicEnvelope($envelope)
259 $basedom = XML::parseString($envelope);
261 if (!is_object($basedom)) {
262 logger("Envelope is no XML file");
266 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
268 if (sizeof($children) == 0) {
269 logger("XML has no children");
275 $data = base64url_decode($children->data);
276 $type = $children->data->attributes()->type[0];
278 $encoding = $children->encoding;
280 $alg = $children->alg;
282 $sig = base64url_decode($children->sig);
283 $key_id = $children->sig->attributes()->key_id[0];
285 $handle = base64url_decode($key_id);
288 $b64url_data = base64url_encode($data);
289 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
291 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
294 logger('No author could be decoded. Discarding. Message: ' . $envelope);
298 $key = self::key($handle);
300 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
304 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
306 logger('Message from ' . $handle . ' did not verify. Discarding.');
314 * @brief encrypts data via AES
316 * @param string $key The AES key
317 * @param string $iv The IV (is used for CBC encoding)
318 * @param string $data The data that is to be encrypted
320 * @return string encrypted data
322 private static function aesEncrypt($key, $iv, $data)
324 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
328 * @brief decrypts data via AES
330 * @param string $key The AES key
331 * @param string $iv The IV (is used for CBC encoding)
332 * @param string $encrypted The encrypted data
334 * @return string decrypted data
336 private static function aesDecrypt($key, $iv, $encrypted)
338 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
342 * @brief: Decodes incoming Diaspora message in the new format
344 * @param array $importer Array of the importer user
345 * @param string $raw raw post message
348 * 'message' -> decoded Diaspora XML message
349 * 'author' -> author diaspora handle
350 * 'key' -> author public key (converted to pkcs#8)
352 public static function decodeRaw($importer, $raw)
354 $data = json_decode($raw);
356 // Is it a private post? Then decrypt the outer Salmon
357 if (is_object($data)) {
358 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
359 $ciphertext = base64_decode($data->encrypted_magic_envelope);
361 $outer_key_bundle = '';
362 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
363 $j_outer_key_bundle = json_decode($outer_key_bundle);
365 if (!is_object($j_outer_key_bundle)) {
366 logger('Outer Salmon did not verify. Discarding.');
367 System::httpExit(400);
370 $outer_iv = base64_decode($j_outer_key_bundle->iv);
371 $outer_key = base64_decode($j_outer_key_bundle->key);
373 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
378 $basedom = XML::parseString($xml);
380 if (!is_object($basedom)) {
381 logger('Received data does not seem to be an XML. Discarding. '.$xml);
382 System::httpExit(400);
385 $base = $basedom->children(NAMESPACE_SALMON_ME);
387 // Not sure if this cleaning is needed
388 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
390 // Build the signed data
391 $type = $base->data[0]->attributes()->type[0];
392 $encoding = $base->encoding;
394 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
396 // This is the signature
397 $signature = base64url_decode($base->sig);
399 // Get the senders' public key
400 $key_id = $base->sig[0]->attributes()->key_id[0];
401 $author_addr = base64_decode($key_id);
402 if ($author_addr == '') {
403 logger('No author could be decoded. Discarding. Message: ' . $xml);
404 System::httpExit(400);
407 $key = self::key($author_addr);
409 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
410 System::httpExit(400);
413 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
415 logger('Message did not verify. Discarding.');
416 System::httpExit(400);
419 return ['message' => (string)base64url_decode($base->data),
420 'author' => unxmlify($author_addr),
421 'key' => (string)$key];
425 * @brief: Decodes incoming Diaspora message in the deprecated format
427 * @param array $importer Array of the importer user
428 * @param string $xml urldecoded Diaspora salmon
431 * 'message' -> decoded Diaspora XML message
432 * 'author' -> author diaspora handle
433 * 'key' -> author public key (converted to pkcs#8)
435 public static function decode($importer, $xml)
438 $basedom = XML::parseString($xml);
440 if (!is_object($basedom)) {
441 logger("XML is not parseable.");
444 $children = $basedom->children('https://joindiaspora.com/protocol');
446 $inner_aes_key = null;
449 if ($children->header) {
451 $author_link = str_replace('acct:', '', $children->header->author_id);
453 // This happens with posts from a relais
455 logger("This is no private post in the old format", LOGGER_DEBUG);
459 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
461 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
462 $ciphertext = base64_decode($encrypted_header->ciphertext);
464 $outer_key_bundle = '';
465 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
467 $j_outer_key_bundle = json_decode($outer_key_bundle);
469 $outer_iv = base64_decode($j_outer_key_bundle->iv);
470 $outer_key = base64_decode($j_outer_key_bundle->key);
472 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
474 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
475 $idom = XML::parseString($decrypted);
477 $inner_iv = base64_decode($idom->iv);
478 $inner_aes_key = base64_decode($idom->aes_key);
480 $author_link = str_replace('acct:', '', $idom->author_id);
483 $dom = $basedom->children(NAMESPACE_SALMON_ME);
485 // figure out where in the DOM tree our data is hiding
488 if ($dom->provenance->data) {
489 $base = $dom->provenance;
490 } elseif ($dom->env->data) {
492 } elseif ($dom->data) {
497 logger('unable to locate salmon data in xml');
498 System::httpExit(400);
502 // Stash the signature away for now. We have to find their key or it won't be good for anything.
503 $signature = base64url_decode($base->sig);
507 // strip whitespace so our data element will return to one big base64 blob
508 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
511 // stash away some other stuff for later
513 $type = $base->data[0]->attributes()->type[0];
514 $keyhash = $base->sig[0]->attributes()->keyhash[0];
515 $encoding = $base->encoding;
519 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
523 $data = base64url_decode($data);
527 $inner_decrypted = $data;
529 // Decode the encrypted blob
530 $inner_encrypted = base64_decode($data);
531 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
535 logger('Could not retrieve author URI.');
536 System::httpExit(400);
538 // Once we have the author URI, go to the web and try to find their public key
539 // (first this will look it up locally if it is in the fcontact cache)
540 // This will also convert diaspora public key from pkcs#1 to pkcs#8
542 logger('Fetching key for '.$author_link);
543 $key = self::key($author_link);
546 logger('Could not retrieve author key.');
547 System::httpExit(400);
550 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
553 logger('Message did not verify. Discarding.');
554 System::httpExit(400);
557 logger('Message verified.');
559 return ['message' => (string)$inner_decrypted,
560 'author' => unxmlify($author_link),
561 'key' => (string)$key];
566 * @brief Dispatches public messages and find the fitting receivers
568 * @param array $msg The post that will be dispatched
570 * @return int The message id of the generated message, "true" or "false" if there was an error
572 public static function dispatchPublic($msg)
574 $enabled = intval(Config::get("system", "diaspora_enabled"));
576 logger("diaspora is disabled");
580 if (!($postdata = self::validPosting($msg))) {
581 logger("Invalid posting");
585 $fields = $postdata['fields'];
587 // Is it a an action (comment, like, ...) for our own post?
588 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
589 $guid = notags(unxmlify($fields->parent_guid));
590 $importer = self::importerForGuid($guid);
591 if (is_array($importer)) {
592 logger("delivering to origin: ".$importer["name"]);
593 $message_id = self::dispatch($importer, $msg, $fields);
598 // Process item retractions. This has to be done separated from the other stuff,
599 // since retractions for comments could come even from non followers.
600 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
601 $target = notags(unxmlify($fields->target_type));
602 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
603 logger('processing retraction for '.$target, LOGGER_DEBUG);
604 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
605 $message_id = self::dispatch($importer, $msg, $fields);
610 // Now distribute it to the followers
612 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
613 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
614 AND NOT `account_expired` AND NOT `account_removed`",
615 dbesc(NETWORK_DIASPORA),
616 dbesc($msg["author"])
619 if (DBM::is_result($r)) {
620 foreach ($r as $rr) {
621 logger("delivering to: ".$rr["username"]);
622 self::dispatch($rr, $msg, $fields);
624 } elseif (!Config::get('system', 'relay_subscribe', false)) {
625 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
627 // Use a dummy importer to import the data for the public copy
628 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
629 $message_id = self::dispatch($importer, $msg, $fields);
636 * @brief Dispatches the different message types to the different functions
638 * @param array $importer Array of the importer user
639 * @param array $msg The post that will be dispatched
640 * @param object $fields SimpleXML object that contains the message
642 * @return int The message id of the generated message, "true" or "false" if there was an error
644 public static function dispatch($importer, $msg, $fields = null)
646 // The sender is the handle of the contact that sent the message.
647 // This will often be different with relayed messages (for example "like" and "comment")
648 $sender = $msg["author"];
650 // This is only needed for private postings since this is already done for public ones before
651 if (is_null($fields)) {
652 if (!($postdata = self::validPosting($msg))) {
653 logger("Invalid posting");
656 $fields = $postdata['fields'];
659 $type = $fields->getName();
661 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
664 case "account_migration":
665 return self::receiveAccountMigration($importer, $fields);
667 case "account_deletion":
668 return self::receiveAccountDeletion($importer, $fields);
671 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
674 return self::receiveContactRequest($importer, $fields);
677 return self::receiveConversation($importer, $msg, $fields);
680 return self::receiveLike($importer, $sender, $fields);
683 return self::receiveMessage($importer, $fields);
685 case "participation":
686 return self::receiveParticipation($importer, $fields);
688 case "photo": // Not implemented
689 return self::receivePhoto($importer, $fields);
691 case "poll_participation": // Not implemented
692 return self::receivePollParticipation($importer, $fields);
695 return self::receiveProfile($importer, $fields);
698 return self::receiveReshare($importer, $fields, $msg["message"]);
701 return self::receiveRetraction($importer, $sender, $fields);
703 case "status_message":
704 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
707 logger("Unknown message type ".$type);
715 * @brief Checks if a posting is valid and fetches the data fields.
717 * This function does not only check the signature.
718 * It also does the conversion between the old and the new diaspora format.
720 * @param array $msg Array with the XML, the sender handle and the sender signature
722 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
724 private static function validPosting($msg)
726 $data = XML::parseString($msg["message"]);
728 if (!is_object($data)) {
729 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
733 // Is this the new or the old version?
734 if ($data->getName() == "XML") {
736 foreach ($data->post->children() as $child) {
744 $type = $element->getName();
747 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
749 // All retractions are handled identically from now on.
750 // In the new version there will only be "retraction".
751 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
752 $type = "retraction";
754 if ($type == "request") {
758 $fields = new SimpleXMLElement("<".$type."/>");
761 $author_signature = null;
762 $parent_author_signature = null;
764 foreach ($element->children() as $fieldname => $entry) {
766 // Translation for the old XML structure
767 if ($fieldname == "diaspora_handle") {
768 $fieldname = "author";
770 if ($fieldname == "participant_handles") {
771 $fieldname = "participants";
773 if (in_array($type, ["like", "participation"])) {
774 if ($fieldname == "target_type") {
775 $fieldname = "parent_type";
778 if ($fieldname == "sender_handle") {
779 $fieldname = "author";
781 if ($fieldname == "recipient_handle") {
782 $fieldname = "recipient";
784 if ($fieldname == "root_diaspora_id") {
785 $fieldname = "root_author";
787 if ($type == "status_message") {
788 if ($fieldname == "raw_message") {
792 if ($type == "retraction") {
793 if ($fieldname == "post_guid") {
794 $fieldname = "target_guid";
796 if ($fieldname == "type") {
797 $fieldname = "target_type";
802 if (($fieldname == "author_signature") && ($entry != "")) {
803 $author_signature = base64_decode($entry);
804 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
805 $parent_author_signature = base64_decode($entry);
806 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
807 if ($signed_data != "") {
811 $signed_data .= $entry;
813 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
814 || ($orig_type == "relayable_retraction")
816 XML::copy($entry, $fields, $fieldname);
820 // This is something that shouldn't happen at all.
821 if (in_array($type, ["status_message", "reshare", "profile"])) {
822 if ($msg["author"] != $fields->author) {
823 logger("Message handle is not the same as envelope sender. Quitting this message.");
828 // Only some message types have signatures. So we quit here for the other types.
829 if (!in_array($type, ["comment", "like"])) {
830 return ["fields" => $fields, "relayed" => false];
832 // No author_signature? This is a must, so we quit.
833 if (!isset($author_signature)) {
834 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
838 if (isset($parent_author_signature)) {
841 $key = self::key($msg["author"]);
843 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
844 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);
851 $key = self::key($fields->author);
853 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
854 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
857 return ["fields" => $fields, "relayed" => $relayed];
862 * @brief Fetches the public key for a given handle
864 * @param string $handle The handle
866 * @return string The public key
868 private static function key($handle)
870 $handle = strval($handle);
872 logger("Fetching diaspora key for: ".$handle);
874 $r = self::personByHandle($handle);
883 * @brief Fetches data for a given handle
885 * @param string $handle The handle
887 * @return array the queried data
889 public static function personByHandle($handle)
893 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
894 if (DBM::is_result($person)) {
895 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
897 // update record occasionally so it doesn't get stale
898 $d = strtotime($person["updated"]." +00:00");
899 if ($d < strtotime("now - 14 days")) {
903 if ($person["guid"] == "") {
908 if (!DBM::is_result($person) || $update) {
909 logger("create or refresh", LOGGER_DEBUG);
910 $r = Probe::uri($handle, NETWORK_DIASPORA);
912 // Note that Friendica contacts will return a "Diaspora person"
913 // if Diaspora connectivity is enabled on their server
914 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
915 self::addFContact($r, $update);
917 // Fetch the updated or added contact
918 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
919 if (!DBM::is_result($person)) {
929 * @brief Updates the fcontact table
931 * @param array $arr The fcontact data
932 * @param bool $update Update or insert?
934 * @return string The id of the fcontact entry
936 private static function addFContact($arr, $update = false)
940 "UPDATE `fcontact` SET
954 WHERE `url` = '%s' AND `network` = '%s'",
956 dbesc($arr["photo"]),
957 dbesc($arr["request"]),
959 dbesc(strtolower($arr["addr"])),
961 dbesc($arr["batch"]),
962 dbesc($arr["notify"]),
964 dbesc($arr["confirm"]),
965 dbesc($arr["alias"]),
966 dbesc($arr["pubkey"]),
967 dbesc(DateTimeFormat::utcNow()),
969 dbesc($arr["network"])
973 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
974 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
975 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
978 dbesc($arr["photo"]),
979 dbesc($arr["request"]),
983 dbesc($arr["batch"]),
984 dbesc($arr["notify"]),
986 dbesc($arr["confirm"]),
987 dbesc($arr["network"]),
988 dbesc($arr["alias"]),
989 dbesc($arr["pubkey"]),
990 dbesc(DateTimeFormat::utcNow())
998 * @brief get a handle (user@domain.tld) from a given contact id
1000 * @param int $contact_id The id in the contact table
1001 * @param int $pcontact_id The id in the contact table (Used for the public contact)
1003 * @return string the handle
1005 private static function handleFromContact($contact_id, $pcontact_id = 0)
1009 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
1011 if ($pcontact_id != 0) {
1013 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
1014 intval($pcontact_id)
1017 if (DBM::is_result($r)) {
1018 return strtolower($r[0]["addr"]);
1023 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1027 if (DBM::is_result($r)) {
1030 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
1032 if ($contact['addr'] != "") {
1033 $handle = $contact['addr'];
1035 $baseurl_start = strpos($contact['url'], '://') + 3;
1036 // allows installations in a subdirectory--not sure how Diaspora will handle
1037 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1038 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1039 $handle = $contact['nick'].'@'.$baseurl;
1043 return strtolower($handle);
1047 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1050 * @param mixed $fcontact_guid Hexadecimal string guid
1052 * @return string the contact url or null
1054 public static function urlFromContactGuid($fcontact_guid)
1056 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1059 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1060 dbesc(NETWORK_DIASPORA),
1061 dbesc($fcontact_guid)
1064 if (DBM::is_result($r)) {
1065 return $r[0]['url'];
1072 * @brief Get a contact id for a given handle
1074 * @todo Move to Friendica\Model\Contact
1076 * @param int $uid The user id
1077 * @param string $handle The handle in the format user@domain.tld
1079 * @return int Contact id
1081 private static function contactByHandle($uid, $handle)
1083 // First do a direct search on the contact table
1085 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1090 if (DBM::is_result($r)) {
1094 * We haven't found it?
1095 * We use another function for it that will possibly create a contact entry.
1097 $cid = Contact::getIdForURL($handle, $uid);
1100 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1101 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1103 if (DBM::is_result($r)) {
1109 $handle_parts = explode("@", $handle);
1110 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1112 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1113 dbesc(NETWORK_DFRN),
1117 if (DBM::is_result($r)) {
1121 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1126 * @brief Check if posting is allowed for this contact
1128 * @param array $importer Array of the importer user
1129 * @param array $contact The contact that is checked
1130 * @param bool $is_comment Is the check for a comment?
1132 * @return bool is the contact allowed to post?
1134 private static function postAllow($importer, $contact, $is_comment = false)
1137 * Perhaps we were already sharing with this person. Now they're sharing with us.
1138 * That makes us friends.
1139 * Normally this should have handled by getting a request - but this could get lost
1141 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1142 // It is not removed by now. Possibly the code is needed?
1143 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1146 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1147 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1150 // $contact["rel"] = CONTACT_IS_FRIEND;
1151 // logger("defining user ".$contact["nick"]." as friend");
1154 // We don't seem to like that person
1155 if ($contact["blocked"] || $contact["readonly"]) {
1156 // Maybe blocked, don't accept.
1158 // We are following this person?
1159 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1160 // Yes, then it is fine.
1162 // Is it a post to a community?
1163 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1166 // Is the message a global user or a comment?
1167 } elseif (($importer["uid"] == 0) || $is_comment) {
1168 // Messages for the global users and comments are always accepted
1176 * @brief Fetches the contact id for a handle and checks if posting is allowed
1178 * @param array $importer Array of the importer user
1179 * @param string $handle The checked handle in the format user@domain.tld
1180 * @param bool $is_comment Is the check for a comment?
1182 * @return array The contact data
1184 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1186 $contact = self::contactByHandle($importer["uid"], $handle);
1188 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1189 // If a contact isn't found, we accept it anyway if it is a comment
1197 if (!self::postAllow($importer, $contact, $is_comment)) {
1198 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1205 * @brief Does the message already exists on the system?
1207 * @param int $uid The user id
1208 * @param string $guid The guid of the message
1210 * @return int|bool message id if the message already was stored into the system - or false.
1212 private static function messageExists($uid, $guid)
1215 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1220 if (DBM::is_result($r)) {
1221 logger("message ".$guid." already exists for user ".$uid);
1229 * @brief Checks for links to posts in a message
1231 * @param array $item The item array
1234 private static function fetchGuid($item)
1236 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1237 preg_replace_callback(
1239 function ($match) use ($item) {
1240 self::fetchGuidSub($match, $item);
1245 preg_replace_callback(
1246 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1247 function ($match) use ($item) {
1248 self::fetchGuidSub($match, $item);
1255 * @brief Checks for relative /people/* links in an item body to match local
1256 * contacts or prepends the remote host taken from the author link.
1258 * @param string $body The item body to replace links from
1259 * @param string $author_link The author link for missing local contact fallback
1261 * @return string the replaced string
1263 public static function replacePeopleGuid($body, $author_link)
1265 $return = preg_replace_callback(
1266 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1267 function ($match) use ($author_link) {
1269 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1270 // 1 => '0123456789abcdef'
1272 $handle = self::urlFromContactGuid($match[1]);
1275 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1277 // No local match, restoring absolute remote URL from author scheme and host
1278 $author_url = parse_url($author_link);
1279 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1291 * @brief sub function of "fetchGuid" which checks for links in messages
1293 * @param array $match array containing a link that has to be checked for a message link
1294 * @param array $item The item array
1297 private static function fetchGuidSub($match, $item)
1299 if (!self::storeByGuid($match[1], $item["author-link"])) {
1300 self::storeByGuid($match[1], $item["owner-link"]);
1305 * @brief Fetches an item with a given guid from a given server
1307 * @param string $guid the message guid
1308 * @param string $server The server address
1309 * @param int $uid The user id of the user
1311 * @return int the message id of the stored message or false
1313 private static function storeByGuid($guid, $server, $uid = 0)
1315 $serverparts = parse_url($server);
1316 $server = $serverparts["scheme"]."://".$serverparts["host"];
1318 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1320 $msg = self::message($guid, $server);
1326 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1328 // Now call the dispatcher
1329 return self::dispatchPublic($msg);
1333 * @brief Fetches a message from a server
1335 * @param string $guid message guid
1336 * @param string $server The url of the server
1337 * @param int $level Endless loop prevention
1340 * 'message' => The message XML
1341 * 'author' => The author handle
1342 * 'key' => The public key of the author
1344 private static function message($guid, $server, $level = 0)
1350 // This will work for new Diaspora servers and Friendica servers from 3.5
1351 $source_url = $server."/fetch/post/".urlencode($guid);
1353 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1355 $envelope = Network::fetchUrl($source_url);
1357 logger("Envelope was fetched.", LOGGER_DEBUG);
1358 $x = self::verifyMagicEnvelope($envelope);
1360 logger("Envelope could not be verified.", LOGGER_DEBUG);
1362 logger("Envelope was verified.", LOGGER_DEBUG);
1368 // This will work for older Diaspora and Friendica servers
1370 $source_url = $server."/p/".urlencode($guid).".xml";
1371 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1373 $x = Network::fetchUrl($source_url);
1379 $source_xml = XML::parseString($x);
1381 if (!is_object($source_xml)) {
1385 if ($source_xml->post->reshare) {
1386 // Reshare of a reshare - old Diaspora version
1387 logger("Message is a reshare", LOGGER_DEBUG);
1388 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1389 } elseif ($source_xml->getName() == "reshare") {
1390 // Reshare of a reshare - new Diaspora version
1391 logger("Message is a new reshare", LOGGER_DEBUG);
1392 return self::message($source_xml->root_guid, $server, ++$level);
1397 // Fetch the author - for the old and the new Diaspora version
1398 if ($source_xml->post->status_message->diaspora_handle) {
1399 $author = (string)$source_xml->post->status_message->diaspora_handle;
1400 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1401 $author = (string)$source_xml->author;
1404 // If this isn't a "status_message" then quit
1406 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1410 $msg = ["message" => $x, "author" => $author];
1412 $msg["key"] = self::key($msg["author"]);
1418 * @brief Fetches the item record of a given guid
1420 * @param int $uid The user id
1421 * @param string $guid message guid
1422 * @param string $author The handle of the item
1423 * @param array $contact The contact of the item owner
1425 * @return array the item record
1427 private static function parentItem($uid, $guid, $author, $contact)
1430 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1431 `author-name`, `author-link`, `author-avatar`,
1432 `owner-name`, `owner-link`, `owner-avatar`
1433 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1439 $result = self::storeByGuid($guid, $contact["url"], $uid);
1442 $person = self::personByHandle($author);
1443 $result = self::storeByGuid($guid, $person["url"], $uid);
1447 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1450 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1451 `author-name`, `author-link`, `author-avatar`,
1452 `owner-name`, `owner-link`, `owner-avatar`
1453 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1461 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1464 logger("parent item found: parent: ".$guid." - user: ".$uid);
1470 * @brief returns contact details
1472 * @param array $def_contact The default contact if the person isn't found
1473 * @param array $person The record of the person
1474 * @param int $uid The user id
1477 * 'cid' => contact id
1478 * 'network' => network type
1480 private static function authorContactByUrl($def_contact, $person, $uid)
1482 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1483 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1484 if (DBM::is_result($contact)) {
1485 $cid = $contact["id"];
1486 $network = $contact["network"];
1488 $cid = $def_contact["id"];
1489 $network = NETWORK_DIASPORA;
1492 return ["cid" => $cid, "network" => $network];
1496 * @brief Is the profile a hubzilla profile?
1498 * @param string $url The profile link
1500 * @return bool is it a hubzilla server?
1502 public static function isRedmatrix($url)
1504 return(strstr($url, "/channel/"));
1508 * @brief Generate a post link with a given handle and message guid
1510 * @param string $addr The user handle
1511 * @param string $guid message guid
1512 * @param string $parent_guid optional parent guid
1514 * @return string the post link
1516 private static function plink($addr, $guid, $parent_guid = '')
1518 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1521 if (!DBM::is_result($r)) {
1522 if ($parent_guid != '') {
1523 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1525 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1529 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1530 // So we try another way as well.
1531 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1532 if (DBM::is_result($s)) {
1533 $r[0]["network"] = $s[0]["network"];
1536 if ($r[0]["network"] == NETWORK_DFRN) {
1537 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1540 if (self::isRedmatrix($r[0]["url"])) {
1541 return $r[0]["url"]."/?f=&mid=".$guid;
1544 if ($parent_guid != '') {
1545 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1547 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1552 * @brief Receives account migration
1554 * @param array $importer Array of the importer user
1555 * @param object $data The message object
1557 * @return bool Success
1559 private static function receiveAccountMigration($importer, $data)
1561 $old_handle = notags(unxmlify($data->author));
1562 $new_handle = notags(unxmlify($data->profile->author));
1563 $signature = notags(unxmlify($data->signature));
1565 $contact = self::contactByHandle($importer["uid"], $old_handle);
1567 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1571 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1574 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1575 $key = self::key($old_handle);
1576 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1577 logger('No valid signature for migration.');
1581 // Update the profile
1582 self::receiveProfile($importer, $data->profile);
1584 // change the technical stuff in contact and gcontact
1585 $data = Probe::uri($new_handle);
1586 if ($data['network'] == NETWORK_PHANTOM) {
1587 logger('Account for '.$new_handle." couldn't be probed.");
1591 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1592 'name' => $data['name'], 'nick' => $data['nick'],
1593 'addr' => $data['addr'], 'batch' => $data['batch'],
1594 'notify' => $data['notify'], 'poll' => $data['poll'],
1595 'network' => $data['network']];
1597 dba::update('contact', $fields, ['addr' => $old_handle]);
1599 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1600 'name' => $data['name'], 'nick' => $data['nick'],
1601 'addr' => $data['addr'], 'connect' => $data['addr'],
1602 'notify' => $data['notify'], 'photo' => $data['photo'],
1603 'server_url' => $data['baseurl'], 'network' => $data['network']];
1605 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1607 logger('Contacts are updated.');
1610 /// @todo This is an extreme performance killer
1612 'owner-link' => [$contact["url"], $data["url"]],
1613 'author-link' => [$contact["url"], $data["url"]],
1615 foreach ($fields as $n => $f) {
1617 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1620 intval($importer["uid"])
1623 if (DBM::is_result($r)) {
1625 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1630 intval($importer["uid"])
1639 logger('Items are updated.');
1645 * @brief Processes an account deletion
1647 * @param array $importer Array of the importer user
1648 * @param object $data The message object
1650 * @return bool Success
1652 private static function receiveAccountDeletion($importer, $data)
1654 /// @todo Account deletion should remove the contact from the global contacts as well
1656 $author = notags(unxmlify($data->author));
1658 $contact = self::contactByHandle($importer["uid"], $author);
1660 logger("cannot find contact for author: ".$author);
1664 // We now remove the contact
1665 Contact::remove($contact["id"]);
1670 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1672 * @param string $author Author handle
1673 * @param string $guid Message guid
1674 * @param boolean $onlyfound Only return uri when found in the database
1676 * @return string The constructed uri or the one from our database
1678 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1680 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1681 if (DBM::is_result($r)) {
1682 return $r[0]["uri"];
1683 } elseif (!$onlyfound) {
1684 return $author.":".$guid;
1691 * @brief Fetch the guid from our database with a given uri
1693 * @param string $uri Message uri
1694 * @param string $uid Author handle
1696 * @return string The post guid
1698 private static function getGuidFromUri($uri, $uid)
1700 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1701 if (DBM::is_result($r)) {
1702 return $r[0]["guid"];
1709 * @brief Find the best importer for a comment, like, ...
1711 * @param string $guid The guid of the item
1713 * @return array|boolean the origin owner of that post - or false
1715 private static function importerForGuid($guid)
1717 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1719 if (DBM::is_result($item)) {
1720 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1721 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1722 if (DBM::is_result($contact)) {
1730 * @brief Processes an incoming comment
1732 * @param array $importer Array of the importer user
1733 * @param string $sender The sender of the message
1734 * @param object $data The message object
1735 * @param string $xml The original XML of the message
1737 * @return int The message id of the generated comment or "false" if there was an error
1739 private static function receiveComment($importer, $sender, $data, $xml)
1741 $author = notags(unxmlify($data->author));
1742 $guid = notags(unxmlify($data->guid));
1743 $parent_guid = notags(unxmlify($data->parent_guid));
1744 $text = unxmlify($data->text);
1746 if (isset($data->created_at)) {
1747 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1749 $created_at = DateTimeFormat::utcNow();
1752 if (isset($data->thread_parent_guid)) {
1753 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1754 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1759 $contact = self::allowedContactByHandle($importer, $sender, true);
1764 $message_id = self::messageExists($importer["uid"], $guid);
1769 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1770 if (!$parent_item) {
1774 $person = self::personByHandle($author);
1775 if (!is_array($person)) {
1776 logger("unable to find author details");
1780 // Fetch the contact id - if we know this contact
1781 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1785 $datarray["uid"] = $importer["uid"];
1786 $datarray["contact-id"] = $author_contact["cid"];
1787 $datarray["network"] = $author_contact["network"];
1789 $datarray["author-name"] = $person["name"];
1790 $datarray["author-link"] = $person["url"];
1791 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1793 $datarray["owner-name"] = $contact["name"];
1794 $datarray["owner-link"] = $contact["url"];
1795 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1797 $datarray["guid"] = $guid;
1798 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1800 $datarray["type"] = "remote-comment";
1801 $datarray["verb"] = ACTIVITY_POST;
1802 $datarray["gravity"] = GRAVITY_COMMENT;
1804 if ($thr_uri != "") {
1805 $datarray["parent-uri"] = $thr_uri;
1807 $datarray["parent-uri"] = $parent_item["uri"];
1810 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1812 $datarray["protocol"] = PROTOCOL_DIASPORA;
1813 $datarray["source"] = $xml;
1815 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1817 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1819 $body = Markdown::toBBCode($text);
1821 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1823 self::fetchGuid($datarray);
1825 $message_id = Item::insert($datarray);
1827 if ($message_id <= 0) {
1832 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1835 // If we are the origin of the parent we store the original data and notify our followers
1836 if ($message_id && $parent_item["origin"]) {
1837 // Formerly we stored the signed text, the signature and the author in different fields.
1838 // We now store the raw data so that we are more flexible.
1839 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1842 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1849 * @brief processes and stores private messages
1851 * @param array $importer Array of the importer user
1852 * @param array $contact The contact of the message
1853 * @param object $data The message object
1854 * @param array $msg Array of the processed message, author handle and key
1855 * @param object $mesg The private message
1856 * @param array $conversation The conversation record to which this message belongs
1858 * @return bool "true" if it was successful
1860 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1862 $author = notags(unxmlify($data->author));
1863 $guid = notags(unxmlify($data->guid));
1864 $subject = notags(unxmlify($data->subject));
1866 // "diaspora_handle" is the element name from the old version
1867 // "author" is the element name from the new version
1868 if ($mesg->author) {
1869 $msg_author = notags(unxmlify($mesg->author));
1870 } elseif ($mesg->diaspora_handle) {
1871 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1876 $msg_guid = notags(unxmlify($mesg->guid));
1877 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1878 $msg_text = unxmlify($mesg->text);
1879 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1881 if ($msg_conversation_guid != $guid) {
1882 logger("message conversation guid does not belong to the current conversation.");
1886 $body = Markdown::toBBCode($msg_text);
1887 $message_uri = $msg_author.":".$msg_guid;
1889 $person = self::personByHandle($msg_author);
1894 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1896 intval($importer["uid"])
1898 if (DBM::is_result($r)) {
1899 logger("duplicate message already delivered.", LOGGER_DEBUG);
1904 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1905 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1906 intval($importer["uid"]),
1908 intval($conversation["id"]),
1909 dbesc($person["name"]),
1910 dbesc($person["photo"]),
1911 dbesc($person["url"]),
1912 intval($contact["id"]),
1917 dbesc($message_uri),
1918 dbesc($author.":".$guid),
1919 dbesc($msg_created_at)
1924 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1928 "type" => NOTIFY_MAIL,
1929 "notify_flags" => $importer["notify-flags"],
1930 "language" => $importer["language"],
1931 "to_name" => $importer["username"],
1932 "to_email" => $importer["email"],
1933 "uid" =>$importer["uid"],
1934 "item" => ["subject" => $subject, "body" => $body],
1935 "source_name" => $person["name"],
1936 "source_link" => $person["url"],
1937 "source_photo" => $person["thumb"],
1938 "verb" => ACTIVITY_POST,
1945 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1947 * @param array $importer Array of the importer user
1948 * @param array $msg Array of the processed message, author handle and key
1949 * @param object $data The message object
1951 * @return bool Success
1953 private static function receiveConversation($importer, $msg, $data)
1955 $author = notags(unxmlify($data->author));
1956 $guid = notags(unxmlify($data->guid));
1957 $subject = notags(unxmlify($data->subject));
1958 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1959 $participants = notags(unxmlify($data->participants));
1961 $messages = $data->message;
1963 if (!count($messages)) {
1964 logger("empty conversation");
1968 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1973 $conversation = null;
1976 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1977 intval($importer["uid"]),
1981 $conversation = $c[0];
1984 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1985 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1986 intval($importer["uid"]),
1990 dbesc(DateTimeFormat::utcNow()),
1992 dbesc($participants)
1996 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1997 intval($importer["uid"]),
2003 $conversation = $c[0];
2006 if (!$conversation) {
2007 logger("unable to create conversation.");
2011 foreach ($messages as $mesg) {
2012 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
2019 * @brief Creates the body for a "like" message
2021 * @param array $contact The contact that send us the "like"
2022 * @param array $parent_item The item array of the parent item
2023 * @param string $guid message guid
2025 * @return string the body
2027 private static function constructLikeBody($contact, $parent_item, $guid)
2029 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2031 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2032 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
2033 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
2035 return sprintf($bodyverb, $ulink, $alink, $plink);
2039 * @brief Creates a XML object for a "like"
2041 * @param array $importer Array of the importer user
2042 * @param array $parent_item The item array of the parent item
2044 * @return string The XML
2046 private static function constructLikeObject($importer, $parent_item)
2048 $objtype = ACTIVITY_OBJ_NOTE;
2049 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
2050 $parent_body = $parent_item["body"];
2052 $xmldata = ["object" => ["type" => $objtype,
2054 "id" => $parent_item["uri"],
2057 "content" => $parent_body]];
2059 return XML::fromArray($xmldata, $xml, true);
2063 * @brief Processes "like" messages
2065 * @param array $importer Array of the importer user
2066 * @param string $sender The sender of the message
2067 * @param object $data The message object
2069 * @return int The message id of the generated like or "false" if there was an error
2071 private static function receiveLike($importer, $sender, $data)
2073 $author = notags(unxmlify($data->author));
2074 $guid = notags(unxmlify($data->guid));
2075 $parent_guid = notags(unxmlify($data->parent_guid));
2076 $parent_type = notags(unxmlify($data->parent_type));
2077 $positive = notags(unxmlify($data->positive));
2079 // likes on comments aren't supported by Diaspora - only on posts
2080 // But maybe this will be supported in the future, so we will accept it.
2081 if (!in_array($parent_type, ["Post", "Comment"])) {
2085 $contact = self::allowedContactByHandle($importer, $sender, true);
2090 $message_id = self::messageExists($importer["uid"], $guid);
2095 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2096 if (!$parent_item) {
2100 $person = self::personByHandle($author);
2101 if (!is_array($person)) {
2102 logger("unable to find author details");
2106 // Fetch the contact id - if we know this contact
2107 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2109 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2110 // We would accept this anyhow.
2111 if ($positive == "true") {
2112 $verb = ACTIVITY_LIKE;
2114 $verb = ACTIVITY_DISLIKE;
2119 $datarray["protocol"] = PROTOCOL_DIASPORA;
2121 $datarray["uid"] = $importer["uid"];
2122 $datarray["contact-id"] = $author_contact["cid"];
2123 $datarray["network"] = $author_contact["network"];
2125 $datarray["author-name"] = $person["name"];
2126 $datarray["author-link"] = $person["url"];
2127 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2129 $datarray["owner-name"] = $contact["name"];
2130 $datarray["owner-link"] = $contact["url"];
2131 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2133 $datarray["guid"] = $guid;
2134 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2136 $datarray["type"] = "activity";
2137 $datarray["verb"] = $verb;
2138 $datarray["gravity"] = GRAVITY_LIKE;
2139 $datarray["parent-uri"] = $parent_item["uri"];
2141 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2142 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2144 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2146 $message_id = Item::insert($datarray);
2148 if ($message_id <= 0) {
2153 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2156 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2157 if ($parent_item["id"] != $parent_item["parent"]) {
2158 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2159 $origin = $toplevel["origin"];
2161 $origin = $parent_item["origin"];
2164 // If we are the origin of the parent we store the original data and notify our followers
2165 if ($message_id && $origin) {
2166 // Formerly we stored the signed text, the signature and the author in different fields.
2167 // We now store the raw data so that we are more flexible.
2168 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2171 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2178 * @brief Processes private messages
2180 * @param array $importer Array of the importer user
2181 * @param object $data The message object
2183 * @return bool Success?
2185 private static function receiveMessage($importer, $data)
2187 $author = notags(unxmlify($data->author));
2188 $guid = notags(unxmlify($data->guid));
2189 $conversation_guid = notags(unxmlify($data->conversation_guid));
2190 $text = unxmlify($data->text);
2191 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2193 $contact = self::allowedContactByHandle($importer, $author, true);
2198 $conversation = null;
2201 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2202 intval($importer["uid"]),
2203 dbesc($conversation_guid)
2206 $conversation = $c[0];
2208 logger("conversation not available.");
2212 $message_uri = $author.":".$guid;
2214 $person = self::personByHandle($author);
2216 logger("unable to find author details");
2220 $body = Markdown::toBBCode($text);
2222 $body = self::replacePeopleGuid($body, $person["url"]);
2227 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2229 intval($importer["uid"])
2231 if (DBM::is_result($r)) {
2232 logger("duplicate message already delivered.", LOGGER_DEBUG);
2237 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2238 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2239 intval($importer["uid"]),
2241 intval($conversation["id"]),
2242 dbesc($person["name"]),
2243 dbesc($person["photo"]),
2244 dbesc($person["url"]),
2245 intval($contact["id"]),
2246 dbesc($conversation["subject"]),
2250 dbesc($message_uri),
2251 dbesc($author.":".$conversation["guid"]),
2257 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2262 * @brief Processes participations - unsupported by now
2264 * @param array $importer Array of the importer user
2265 * @param object $data The message object
2267 * @return bool always true
2269 private static function receiveParticipation($importer, $data)
2271 $author = strtolower(notags(unxmlify($data->author)));
2272 $parent_guid = notags(unxmlify($data->parent_guid));
2274 $contact_id = Contact::getIdForURL($author);
2276 logger('Contact not found: '.$author);
2280 $person = self::personByHandle($author);
2281 if (!is_array($person)) {
2282 logger("Person not found: ".$author);
2286 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2287 if (!DBM::is_result($item)) {
2288 logger('Item not found, no origin or private: '.$parent_guid);
2292 $author_parts = explode('@', $author);
2293 if (isset($author_parts[1])) {
2294 $server = $author_parts[1];
2296 // Should never happen
2300 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2302 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2303 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2306 // Send all existing comments and likes to the requesting server
2307 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2309 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2310 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2311 while ($comment = dba::fetch($comments)) {
2312 if ($comment['verb'] == ACTIVITY_POST) {
2313 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2315 $cmd = $comment['self'] ? 'like' : 'comment-import';
2317 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2318 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2320 dba::close($comments);
2326 * @brief Processes photos - unneeded
2328 * @param array $importer Array of the importer user
2329 * @param object $data The message object
2331 * @return bool always true
2333 private static function receivePhoto($importer, $data)
2335 // There doesn't seem to be a reason for this function,
2336 // since the photo data is transmitted in the status message as well
2341 * @brief Processes poll participations - unssupported
2343 * @param array $importer Array of the importer user
2344 * @param object $data The message object
2346 * @return bool always true
2348 private static function receivePollParticipation($importer, $data)
2350 // We don't support polls by now
2355 * @brief Processes incoming profile updates
2357 * @param array $importer Array of the importer user
2358 * @param object $data The message object
2360 * @return bool Success
2362 private static function receiveProfile($importer, $data)
2364 $author = strtolower(notags(unxmlify($data->author)));
2366 $contact = self::contactByHandle($importer["uid"], $author);
2371 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2372 $image_url = unxmlify($data->image_url);
2373 $birthday = unxmlify($data->birthday);
2374 $gender = unxmlify($data->gender);
2375 $about = Markdown::toBBCode(unxmlify($data->bio));
2376 $location = Markdown::toBBCode(unxmlify($data->location));
2377 $searchable = (unxmlify($data->searchable) == "true");
2378 $nsfw = (unxmlify($data->nsfw) == "true");
2379 $tags = unxmlify($data->tag_string);
2381 $tags = explode("#", $tags);
2384 foreach ($tags as $tag) {
2385 $tag = trim(strtolower($tag));
2391 $keywords = implode(", ", $keywords);
2393 $handle_parts = explode("@", $author);
2394 $nick = $handle_parts[0];
2397 $name = $handle_parts[0];
2400 if (preg_match("|^https?://|", $image_url) === 0) {
2401 $image_url = "http://".$handle_parts[1].$image_url;
2404 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2406 // Generic birthday. We don't know the timezone. The year is irrelevant.
2408 $birthday = str_replace("1000", "1901", $birthday);
2410 if ($birthday != "") {
2411 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2414 // this is to prevent multiple birthday notifications in a single year
2415 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2417 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2418 $birthday = $contact["bd"];
2422 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2423 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2427 dbesc(DateTimeFormat::utcNow()),
2433 intval($contact["id"]),
2434 intval($importer["uid"])
2437 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2438 "photo" => $image_url, "name" => $name, "location" => $location,
2439 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2440 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2441 "hide" => !$searchable, "nsfw" => $nsfw];
2443 $gcid = GContact::update($gcontact);
2445 GContact::link($gcid, $importer["uid"], $contact["id"]);
2447 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2453 * @brief Processes incoming friend requests
2455 * @param array $importer Array of the importer user
2456 * @param array $contact The contact that send the request
2459 private static function receiveRequestMakeFriend($importer, $contact)
2463 if ($contact["rel"] == CONTACT_IS_SHARING) {
2466 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2467 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2470 // send notification
2473 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2474 intval($importer["uid"])
2477 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2479 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2480 intval($importer["uid"])
2483 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2485 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2487 $arr["protocol"] = PROTOCOL_DIASPORA;
2488 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2489 $arr["uid"] = $importer["uid"];
2490 $arr["contact-id"] = $self[0]["id"];
2492 $arr["type"] = 'wall';
2493 $arr["gravity"] = 0;
2495 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2496 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2497 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2498 $arr["verb"] = ACTIVITY_FRIEND;
2499 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2501 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2502 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2503 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2504 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2506 $arr["object"] = self::constructNewFriendObject($contact);
2508 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2510 $arr["allow_cid"] = $user["allow_cid"];
2511 $arr["allow_gid"] = $user["allow_gid"];
2512 $arr["deny_cid"] = $user["deny_cid"];
2513 $arr["deny_gid"] = $user["deny_gid"];
2515 $i = Item::insert($arr);
2517 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2524 * @brief Creates a XML object for a "new friend" message
2526 * @param array $contact Array of the contact
2528 * @return string The XML
2530 private static function constructNewFriendObject($contact)
2532 $objtype = ACTIVITY_OBJ_PERSON;
2533 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2534 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2536 $xmldata = ["object" => ["type" => $objtype,
2537 "title" => $contact["name"],
2538 "id" => $contact["url"]."/".$contact["name"],
2541 return XML::fromArray($xmldata, $xml, true);
2545 * @brief Processes incoming sharing notification
2547 * @param array $importer Array of the importer user
2548 * @param object $data The message object
2550 * @return bool Success
2552 private static function receiveContactRequest($importer, $data)
2554 $author = unxmlify($data->author);
2555 $recipient = unxmlify($data->recipient);
2557 if (!$author || !$recipient) {
2561 // the current protocol version doesn't know these fields
2562 // That means that we will assume their existance
2563 if (isset($data->following)) {
2564 $following = (unxmlify($data->following) == "true");
2569 if (isset($data->sharing)) {
2570 $sharing = (unxmlify($data->sharing) == "true");
2575 $contact = self::contactByHandle($importer["uid"], $author);
2577 // perhaps we were already sharing with this person. Now they're sharing with us.
2578 // That makes us friends.
2581 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2582 self::receiveRequestMakeFriend($importer, $contact);
2584 // refetch the contact array
2585 $contact = self::contactByHandle($importer["uid"], $author);
2587 // If we are now friends, we are sending a share message.
2588 // Normally we needn't to do so, but the first message could have been vanished.
2589 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2590 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2592 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2593 $ret = self::sendShare($u[0], $contact);
2598 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2599 Contact::removeFollower($importer, $contact);
2604 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2605 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2607 } elseif (!$following && !$sharing) {
2608 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2610 } elseif (!$following && $sharing) {
2611 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2612 } elseif ($following && $sharing) {
2613 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2614 } elseif ($following && !$sharing) {
2615 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2618 $ret = self::personByHandle($author);
2620 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2621 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2625 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2628 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2629 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2630 intval($importer["uid"]),
2631 dbesc($ret["network"]),
2632 dbesc($ret["addr"]),
2633 DateTimeFormat::utcNow(),
2635 dbesc(normalise_link($ret["url"])),
2637 dbesc($ret["name"]),
2638 dbesc($ret["nick"]),
2639 dbesc($ret["photo"]),
2640 dbesc($ret["pubkey"]),
2641 dbesc($ret["notify"]),
2642 dbesc($ret["poll"]),
2647 // find the contact record we just created
2649 $contact_record = self::contactByHandle($importer["uid"], $author);
2651 if (!$contact_record) {
2652 logger("unable to locate newly created contact record.");
2656 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2658 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2660 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2662 if ($importer["page-flags"] == PAGE_NORMAL) {
2663 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2665 $hash = random_string().(string)time(); // Generate a confirm_key
2668 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2669 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2670 intval($importer["uid"]),
2671 intval($contact_record["id"]),
2674 dbesc(L10n::t("Sharing notification from Diaspora network")),
2676 dbesc(DateTimeFormat::utcNow())
2679 // automatic friend approval
2681 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2683 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2685 // technically they are sharing with us (CONTACT_IS_SHARING),
2686 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2687 // we are going to change the relationship and make them a follower.
2689 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2690 $new_relation = CONTACT_IS_FRIEND;
2691 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2692 $new_relation = CONTACT_IS_SHARING;
2694 $new_relation = CONTACT_IS_FOLLOWER;
2698 "UPDATE `contact` SET `rel` = %d,
2706 intval($new_relation),
2707 dbesc(DateTimeFormat::utcNow()),
2708 dbesc(DateTimeFormat::utcNow()),
2709 intval($contact_record["id"])
2712 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2714 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2715 $ret = self::sendShare($u[0], $contact_record);
2717 // Send the profile data, maybe it weren't transmitted before
2718 self::sendProfile($importer["uid"], [$contact_record]);
2726 * @brief Fetches a message with a given guid
2728 * @param string $guid message guid
2729 * @param string $orig_author handle of the original post
2730 * @param string $author handle of the sharer
2732 * @return array The fetched item
2734 private static function originalItem($guid, $orig_author, $author)
2736 // Do we already have this item?
2738 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2739 `author-name`, `author-link`, `author-avatar`
2740 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2744 if (DBM::is_result($r)) {
2745 logger("reshared message ".$guid." already exists on system.");
2747 // Maybe it is already a reshared item?
2748 // Then refetch the content, if it is a reshare from a reshare.
2749 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2750 if (self::isReshare($r[0]["body"], true)) {
2752 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2753 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2755 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2757 // Add OEmbed and other information to the body
2758 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2766 if (!DBM::is_result($r)) {
2767 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2768 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2769 $item_id = self::storeByGuid($guid, $server);
2772 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2773 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2774 $item_id = self::storeByGuid($guid, $server);
2779 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2780 `author-name`, `author-link`, `author-avatar`
2781 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2785 if (DBM::is_result($r)) {
2786 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2787 if (self::isReshare($r[0]["body"], false)) {
2788 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2789 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2800 * @brief Processes a reshare message
2802 * @param array $importer Array of the importer user
2803 * @param object $data The message object
2804 * @param string $xml The original XML of the message
2806 * @return int the message id
2808 private static function receiveReshare($importer, $data, $xml)
2810 $author = notags(unxmlify($data->author));
2811 $guid = notags(unxmlify($data->guid));
2812 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2813 $root_author = notags(unxmlify($data->root_author));
2814 $root_guid = notags(unxmlify($data->root_guid));
2815 /// @todo handle unprocessed property "provider_display_name"
2816 $public = notags(unxmlify($data->public));
2818 $contact = self::allowedContactByHandle($importer, $author, false);
2823 $message_id = self::messageExists($importer["uid"], $guid);
2828 $original_item = self::originalItem($root_guid, $root_author, $author);
2829 if (!$original_item) {
2833 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2837 $datarray["uid"] = $importer["uid"];
2838 $datarray["contact-id"] = $contact["id"];
2839 $datarray["network"] = NETWORK_DIASPORA;
2841 $datarray["author-name"] = $contact["name"];
2842 $datarray["author-link"] = $contact["url"];
2843 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2845 $datarray["owner-name"] = $datarray["author-name"];
2846 $datarray["owner-link"] = $datarray["author-link"];
2847 $datarray["owner-avatar"] = $datarray["author-avatar"];
2849 $datarray["guid"] = $guid;
2850 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2852 $datarray["verb"] = ACTIVITY_POST;
2853 $datarray["gravity"] = GRAVITY_PARENT;
2855 $datarray["protocol"] = PROTOCOL_DIASPORA;
2856 $datarray["source"] = $xml;
2858 $prefix = share_header(
2859 $original_item["author-name"],
2860 $original_item["author-link"],
2861 $original_item["author-avatar"],
2862 $original_item["guid"],
2863 $original_item["created"],
2866 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2868 $datarray["tag"] = $original_item["tag"];
2869 $datarray["app"] = $original_item["app"];
2871 $datarray["plink"] = self::plink($author, $guid);
2872 $datarray["private"] = (($public == "false") ? 1 : 0);
2873 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2875 $datarray["object-type"] = $original_item["object-type"];
2877 self::fetchGuid($datarray);
2878 $message_id = Item::insert($datarray);
2880 self::sendParticipation($contact, $datarray);
2883 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2891 * @brief Processes retractions
2893 * @param array $importer Array of the importer user
2894 * @param array $contact The contact of the item owner
2895 * @param object $data The message object
2897 * @return bool success
2899 private static function itemRetraction($importer, $contact, $data)
2901 $author = notags(unxmlify($data->author));
2902 $target_guid = notags(unxmlify($data->target_guid));
2903 $target_type = notags(unxmlify($data->target_type));
2905 $person = self::personByHandle($author);
2906 if (!is_array($person)) {
2907 logger("unable to find author detail for ".$author);
2911 if (empty($contact["url"])) {
2912 $contact["url"] = $person["url"];
2915 // Fetch items that are about to be deleted
2916 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2918 // When we receive a public retraction, we delete every item that we find.
2919 if ($importer['uid'] == 0) {
2920 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2922 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2924 $r = dba::select('item', $fields, $condition);
2925 if (!DBM::is_result($r)) {
2926 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2930 while ($item = dba::fetch($r)) {
2931 // Fetch the parent item
2932 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2934 // Only delete it if the parent author really fits
2935 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2936 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2940 Item::deleteById($item["id"]);
2942 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2944 // Now check if the retraction needs to be relayed by us
2945 if ($parent["origin"]) {
2947 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2955 * @brief Receives retraction messages
2957 * @param array $importer Array of the importer user
2958 * @param string $sender The sender of the message
2959 * @param object $data The message object
2961 * @return bool Success
2963 private static function receiveRetraction($importer, $sender, $data)
2965 $target_type = notags(unxmlify($data->target_type));
2967 $contact = self::contactByHandle($importer["uid"], $sender);
2968 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2969 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2973 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2975 switch ($target_type) {
2980 case "StatusMessage":
2981 return self::itemRetraction($importer, $contact, $data);
2985 /// @todo What should we do with an "unshare"?
2986 // Removing the contact isn't correct since we still can read the public items
2987 Contact::remove($contact["id"]);
2991 logger("Unknown target type ".$target_type);
2998 * @brief Receives status messages
3000 * @param array $importer Array of the importer user
3001 * @param object $data The message object
3002 * @param string $xml The original XML of the message
3004 * @return int The message id of the newly created item
3006 private static function receiveStatusMessage($importer, $data, $xml)
3008 $author = notags(unxmlify($data->author));
3009 $guid = notags(unxmlify($data->guid));
3010 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
3011 $public = notags(unxmlify($data->public));
3012 $text = unxmlify($data->text);
3013 $provider_display_name = notags(unxmlify($data->provider_display_name));
3015 $contact = self::allowedContactByHandle($importer, $author, false);
3020 $message_id = self::messageExists($importer["uid"], $guid);
3026 if ($data->location) {
3027 foreach ($data->location->children() as $fieldname => $data) {
3028 $address[$fieldname] = notags(unxmlify($data));
3032 $body = Markdown::toBBCode($text);
3036 // Attach embedded pictures to the body
3038 foreach ($data->photo as $photo) {
3039 $body = "[img]".unxmlify($photo->remote_photo_path).
3040 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
3043 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
3045 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
3047 // Add OEmbed and other information to the body
3048 if (!self::isRedmatrix($contact["url"])) {
3049 $body = add_page_info_to_body($body, false, true);
3053 /// @todo enable support for polls
3054 //if ($data->poll) {
3055 // foreach ($data->poll AS $poll)
3060 /// @todo enable support for events
3062 $datarray["uid"] = $importer["uid"];
3063 $datarray["contact-id"] = $contact["id"];
3064 $datarray["network"] = NETWORK_DIASPORA;
3066 $datarray["author-name"] = $contact["name"];
3067 $datarray["author-link"] = $contact["url"];
3068 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3070 $datarray["owner-name"] = $datarray["author-name"];
3071 $datarray["owner-link"] = $datarray["author-link"];
3072 $datarray["owner-avatar"] = $datarray["author-avatar"];
3074 $datarray["guid"] = $guid;
3075 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3077 $datarray["verb"] = ACTIVITY_POST;
3078 $datarray["gravity"] = GRAVITY_PARENT;
3080 $datarray["protocol"] = PROTOCOL_DIASPORA;
3081 $datarray["source"] = $xml;
3083 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3085 if ($provider_display_name != "") {
3086 $datarray["app"] = $provider_display_name;
3089 $datarray["plink"] = self::plink($author, $guid);
3090 $datarray["private"] = (($public == "false") ? 1 : 0);
3091 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3093 if (isset($address["address"])) {
3094 $datarray["location"] = $address["address"];
3097 if (isset($address["lat"]) && isset($address["lng"])) {
3098 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3101 self::fetchGuid($datarray);
3102 $message_id = Item::insert($datarray);
3104 self::sendParticipation($contact, $datarray);
3107 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3114 /* ************************************************************************************** *
3115 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3116 * ************************************************************************************** */
3119 * @brief returnes the handle of a contact
3121 * @param array $contact contact array
3123 * @return string the handle in the format user@domain.tld
3125 private static function myHandle($contact)
3127 if ($contact["addr"] != "") {
3128 return $contact["addr"];
3131 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3132 // So - just in case - we build the the address here.
3133 if ($contact["nickname"] != "") {
3134 $nick = $contact["nickname"];
3136 $nick = $contact["nick"];
3139 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3144 * @brief Creates the data for a private message in the new format
3146 * @param string $msg The message that is to be transmitted
3147 * @param array $user The record of the sender
3148 * @param array $contact Target of the communication
3149 * @param string $prvkey The private key of the sender
3150 * @param string $pubkey The public key of the receiver
3152 * @return string The encrypted data
3154 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3156 logger("Message: ".$msg, LOGGER_DATA);
3158 // without a public key nothing will work
3160 logger("pubkey missing: contact id: ".$contact["id"]);
3164 $aes_key = openssl_random_pseudo_bytes(32);
3165 $b_aes_key = base64_encode($aes_key);
3166 $iv = openssl_random_pseudo_bytes(16);
3167 $b_iv = base64_encode($iv);
3169 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3171 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3173 $encrypted_key_bundle = "";
3174 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3176 $json_object = json_encode(
3177 ["aes_key" => base64_encode($encrypted_key_bundle),
3178 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3181 return $json_object;
3185 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3187 * @param string $msg The message that is to be transmitted
3188 * @param array $user The record of the sender
3190 * @return string The envelope
3192 public static function buildMagicEnvelope($msg, $user)
3194 $b64url_data = base64url_encode($msg);
3195 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3197 $key_id = base64url_encode(self::myHandle($user));
3198 $type = "application/xml";
3199 $encoding = "base64url";
3200 $alg = "RSA-SHA256";
3201 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3203 // Fallback if the private key wasn't transmitted in the expected field
3204 if ($user['uprvkey'] == "") {
3205 $user['uprvkey'] = $user['prvkey'];
3208 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3209 $sig = base64url_encode($signature);
3211 $xmldata = ["me:env" => ["me:data" => $data,
3212 "@attributes" => ["type" => $type],
3213 "me:encoding" => $encoding,
3216 "@attributes2" => ["key_id" => $key_id]]];
3218 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3220 return XML::fromArray($xmldata, $xml, false, $namespaces);
3224 * @brief Create the envelope for a message
3226 * @param string $msg The message that is to be transmitted
3227 * @param array $user The record of the sender
3228 * @param array $contact Target of the communication
3229 * @param string $prvkey The private key of the sender
3230 * @param string $pubkey The public key of the receiver
3231 * @param bool $public Is the message public?
3233 * @return string The message that will be transmitted to other servers
3235 public static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3237 // The message is put into an envelope with the sender's signature
3238 $envelope = self::buildMagicEnvelope($msg, $user);
3240 // Private messages are put into a second envelope, encrypted with the receivers public key
3242 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3249 * @brief Creates a signature for a message
3251 * @param array $owner the array of the owner of the message
3252 * @param array $message The message that is to be signed
3254 * @return string The signature
3256 private static function signature($owner, $message)
3259 unset($sigmsg["author_signature"]);
3260 unset($sigmsg["parent_author_signature"]);
3262 $signed_text = implode(";", $sigmsg);
3264 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3268 * @brief Transmit a message to a target server
3270 * @param array $owner the array of the item owner
3271 * @param array $contact Target of the communication
3272 * @param string $envelope The message that is to be transmitted
3273 * @param bool $public_batch Is it a public post?
3274 * @param bool $queue_run Is the transmission called from the queue?
3275 * @param string $guid message guid
3277 * @return int Result of the transmission
3279 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3283 $enabled = intval(Config::get("system", "diaspora_enabled"));
3288 $logid = random_string(4);
3290 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3292 // We always try to use the data from the fcontact table.
3293 // This is important for transmitting data to Friendica servers.
3294 if (!empty($contact['addr'])) {
3295 $fcontact = self::personByHandle($contact['addr']);
3296 if (!empty($fcontact)) {
3297 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3302 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3306 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3308 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3311 if (!intval(Config::get("system", "diaspora_test"))) {
3312 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3314 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3315 $return_code = $a->get_curl_code();
3317 logger("test_mode");
3322 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3324 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3325 if (!$no_queue && ($contact['contact-type'] != ACCOUNT_TYPE_RELAY)) {
3326 logger("queue message");
3327 // queue message for redelivery
3328 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3331 // The message could not be delivered. We mark the contact as "dead"
3332 Contact::markForArchival($contact);
3333 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3334 // We successfully delivered a message, the contact is alive
3335 Contact::unmarkForArchival($contact);
3338 return $return_code ? $return_code : -1;
3343 * @brief Build the post xml
3345 * @param string $type The message type
3346 * @param array $message The message data
3348 * @return string The post XML
3350 public static function buildPostXml($type, $message)
3352 $data = [$type => $message];
3354 return XML::fromArray($data, $xml);
3358 * @brief Builds and transmit messages
3360 * @param array $owner the array of the item owner
3361 * @param array $contact Target of the communication
3362 * @param string $type The message type
3363 * @param array $message The message data
3364 * @param bool $public_batch Is it a public post?
3365 * @param string $guid message guid
3366 * @param bool $spool Should the transmission be spooled or transmitted?
3368 * @return int Result of the transmission
3370 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3372 $msg = self::buildPostXml($type, $message);
3374 logger('message: '.$msg, LOGGER_DATA);
3375 logger('send guid '.$guid, LOGGER_DEBUG);
3377 // Fallback if the private key wasn't transmitted in the expected field
3378 if ($owner['uprvkey'] == "") {
3379 $owner['uprvkey'] = $owner['prvkey'];
3382 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3385 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3388 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3391 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3393 return $return_code;
3397 * @brief sends a participation (Used to get all further updates)
3399 * @param array $contact Target of the communication
3400 * @param array $item Item array
3402 * @return int The result of the transmission
3404 private static function sendParticipation($contact, $item)
3406 // Don't send notifications for private postings
3407 if ($item['private']) {
3411 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3413 $result = Cache::get($cachekey);
3414 if (!is_null($result)) {
3418 // Fetch some user id to have a valid handle to transmit the participation.
3419 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3420 // If the item belongs to a user, we take this user id.
3421 if ($item['uid'] == 0) {
3422 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3423 $first_user = dba::selectFirst('user', ['uid'], $condition);
3424 $owner = User::getOwnerDataById($first_user['uid']);
3426 $owner = User::getOwnerDataById($item['uid']);
3429 $author = self::myHandle($owner);
3431 $message = ["author" => $author,
3432 "guid" => get_guid(32),
3433 "parent_type" => "Post",
3434 "parent_guid" => $item["guid"]];
3436 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3438 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3439 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3441 return self::buildAndTransmit($owner, $contact, "participation", $message);
3445 * @brief sends an account migration
3447 * @param array $owner the array of the item owner
3448 * @param array $contact Target of the communication
3449 * @param int $uid User ID
3451 * @return int The result of the transmission
3453 public static function sendAccountMigration($owner, $contact, $uid)
3455 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3456 $profile = self::createProfileData($uid);
3458 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3459 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3461 $message = ["author" => $old_handle,
3462 "profile" => $profile,
3463 "signature" => $signature];
3465 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3467 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3471 * @brief Sends a "share" message
3473 * @param array $owner the array of the item owner
3474 * @param array $contact Target of the communication
3476 * @return int The result of the transmission
3478 public static function sendShare($owner, $contact)
3481 * @todo support the different possible combinations of "following" and "sharing"
3482 * Currently, Diaspora only interprets the "sharing" field
3484 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3488 switch ($contact["rel"]) {
3489 case CONTACT_IS_FRIEND:
3492 case CONTACT_IS_SHARING:
3495 case CONTACT_IS_FOLLOWER:
3501 $message = ["author" => self::myHandle($owner),
3502 "recipient" => $contact["addr"],
3503 "following" => "true",
3504 "sharing" => "true"];
3506 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3508 return self::buildAndTransmit($owner, $contact, "contact", $message);
3512 * @brief sends an "unshare"
3514 * @param array $owner the array of the item owner
3515 * @param array $contact Target of the communication
3517 * @return int The result of the transmission
3519 public static function sendUnshare($owner, $contact)
3521 $message = ["author" => self::myHandle($owner),
3522 "recipient" => $contact["addr"],
3523 "following" => "false",
3524 "sharing" => "false"];
3526 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3528 return self::buildAndTransmit($owner, $contact, "contact", $message);
3532 * @brief Checks a message body if it is a reshare
3534 * @param string $body The message body that is to be check
3535 * @param bool $complete Should it be a complete check or a simple check?
3537 * @return array|bool Reshare details or "false" if no reshare
3539 public static function isReshare($body, $complete = true)
3541 $body = trim($body);
3543 // Skip if it isn't a pure repeated messages
3544 // Does it start with a share?
3545 if ((strpos($body, "[share") > 0) && $complete) {
3549 // Does it end with a share?
3550 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3554 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3555 // Skip if there is no shared message in there
3556 if ($body == $attributes) {
3560 // If we don't do the complete check we quit here
3566 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3567 if ($matches[1] != "") {
3568 $guid = $matches[1];
3571 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3572 if ($matches[1] != "") {
3573 $guid = $matches[1];
3578 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3585 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3586 $ret["root_guid"] = $guid;
3592 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3593 if ($matches[1] != "") {
3594 $profile = $matches[1];
3597 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3598 if ($matches[1] != "") {
3599 $profile = $matches[1];
3604 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3605 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3610 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3611 if ($matches[1] != "") {
3612 $link = $matches[1];
3615 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3616 if ($matches[1] != "") {
3617 $link = $matches[1];
3620 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3621 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3629 * @brief Create an event array
3631 * @param integer $event_id The id of the event
3633 * @return array with event data
3635 private static function buildEvent($event_id)
3637 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3638 if (!DBM::is_result($r)) {
3646 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3647 if (!DBM::is_result($r)) {
3653 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3654 if (!DBM::is_result($r)) {
3660 $eventdata['author'] = self::myHandle($owner);
3662 if ($event['guid']) {
3663 $eventdata['guid'] = $event['guid'];
3666 $mask = DateTimeFormat::ATOM;
3668 /// @todo - establish "all day" events in Friendica
3669 $eventdata["all_day"] = "false";
3671 if (!$event['adjust']) {
3672 $eventdata['timezone'] = $user['timezone'];
3674 if ($eventdata['timezone'] == "") {
3675 $eventdata['timezone'] = 'UTC';
3679 if ($event['start']) {
3680 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3682 if ($event['finish'] && !$event['nofinish']) {
3683 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3685 if ($event['summary']) {
3686 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3688 if ($event['desc']) {
3689 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3691 if ($event['location']) {
3692 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3693 $coord = Map::getCoordinates($event['location']);
3696 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3697 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3698 $location["lat"] = $coord['lat'];
3699 $location["lng"] = $coord['lon'];
3701 $location["lat"] = 0;
3702 $location["lng"] = 0;
3704 $eventdata['location'] = $location;
3711 * @brief Create a post (status message or reshare)
3713 * @param array $item The item that will be exported
3714 * @param array $owner the array of the item owner
3717 * 'type' -> Message type ("status_message" or "reshare")
3718 * 'message' -> Array of XML elements of the status
3720 public static function buildStatus($item, $owner)
3722 $cachekey = "diaspora:buildStatus:".$item['guid'];
3724 $result = Cache::get($cachekey);
3725 if (!is_null($result)) {
3729 $myaddr = self::myHandle($owner);
3731 $public = (($item["private"]) ? "false" : "true");
3733 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3735 // Detect a share element and do a reshare
3736 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3737 $message = ["author" => $myaddr,
3738 "guid" => $item["guid"],
3739 "created_at" => $created,
3740 "root_author" => $ret["root_handle"],
3741 "root_guid" => $ret["root_guid"],
3742 "provider_display_name" => $item["app"],
3743 "public" => $public];
3747 $title = $item["title"];
3748 $body = $item["body"];
3750 // convert to markdown
3751 $body = html_entity_decode(BBCode::toMarkdown($body));
3754 if (strlen($title)) {
3755 $body = "## ".html_entity_decode($title)."\n\n".$body;
3758 if ($item["attach"]) {
3759 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3761 $body .= "\n".L10n::t("Attachments:")."\n";
3762 foreach ($matches as $mtch) {
3763 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3770 if ($item["location"] != "")
3771 $location["address"] = $item["location"];
3773 if ($item["coord"] != "") {
3774 $coord = explode(" ", $item["coord"]);
3775 $location["lat"] = $coord[0];
3776 $location["lng"] = $coord[1];
3779 $message = ["author" => $myaddr,
3780 "guid" => $item["guid"],
3781 "created_at" => $created,
3782 "public" => $public,
3784 "provider_display_name" => $item["app"],
3785 "location" => $location];
3787 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3788 if (!isset($location["lat"]) || !isset($location["lng"])) {
3789 unset($message["location"]);
3792 if ($item['event-id'] > 0) {
3793 $event = self::buildEvent($item['event-id']);
3794 if (count($event)) {
3795 $message['event'] = $event;
3797 if (!empty($event['location']['address']) &&
3798 !empty($event['location']['lat']) &&
3799 !empty($event['location']['lng'])) {
3800 $message['location'] = $event['location'];
3803 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3804 // $message['text'] = '';
3808 $type = "status_message";
3811 $msg = ["type" => $type, "message" => $message];
3813 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3819 * @brief Sends a post
3821 * @param array $item The item that will be exported
3822 * @param array $owner the array of the item owner
3823 * @param array $contact Target of the communication
3824 * @param bool $public_batch Is it a public post?
3826 * @return int The result of the transmission
3828 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3830 $status = self::buildStatus($item, $owner);
3832 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3836 * @brief Creates a "like" object
3838 * @param array $item The item that will be exported
3839 * @param array $owner the array of the item owner
3841 * @return array The data for a "like"
3843 private static function constructLike($item, $owner)
3846 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3847 dbesc($item["thr-parent"])
3849 if (!DBM::is_result($p)) {
3855 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3857 if ($item['verb'] === ACTIVITY_LIKE) {
3859 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3860 $positive = "false";
3863 return(["author" => self::myHandle($owner),
3864 "guid" => $item["guid"],
3865 "parent_guid" => $parent["guid"],
3866 "parent_type" => $target_type,
3867 "positive" => $positive,
3868 "author_signature" => ""]);
3872 * @brief Creates an "EventParticipation" object
3874 * @param array $item The item that will be exported
3875 * @param array $owner the array of the item owner
3877 * @return array The data for an "EventParticipation"
3879 private static function constructAttend($item, $owner)
3882 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3883 dbesc($item["thr-parent"])
3885 if (!DBM::is_result($p)) {
3891 switch ($item['verb']) {
3892 case ACTIVITY_ATTEND:
3893 $attend_answer = 'accepted';
3895 case ACTIVITY_ATTENDNO:
3896 $attend_answer = 'declined';
3898 case ACTIVITY_ATTENDMAYBE:
3899 $attend_answer = 'tentative';
3902 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3906 return(["author" => self::myHandle($owner),
3907 "guid" => $item["guid"],
3908 "parent_guid" => $parent["guid"],
3909 "status" => $attend_answer,
3910 "author_signature" => ""]);
3914 * @brief Creates the object for a comment
3916 * @param array $item The item that will be exported
3917 * @param array $owner the array of the item owner
3919 * @return array The data for a comment
3921 private static function constructComment($item, $owner)
3923 $cachekey = "diaspora:constructComment:".$item['guid'];
3925 $result = Cache::get($cachekey);
3926 if (!is_null($result)) {
3931 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3932 intval($item["parent"]),
3933 intval($item["parent"])
3936 if (!DBM::is_result($p)) {
3942 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3943 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3945 $comment = ["author" => self::myHandle($owner),
3946 "guid" => $item["guid"],
3947 "created_at" => $created,
3948 "parent_guid" => $parent["guid"],
3950 "author_signature" => ""];
3952 // Send the thread parent guid only if it is a threaded comment
3953 if ($item['thr-parent'] != $item['parent-uri']) {
3954 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3957 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3963 * @brief Send a like or a comment
3965 * @param array $item The item that will be exported
3966 * @param array $owner the array of the item owner
3967 * @param array $contact Target of the communication
3968 * @param bool $public_batch Is it a public post?
3970 * @return int The result of the transmission
3972 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3974 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3975 $message = self::constructAttend($item, $owner);
3976 $type = "event_participation";
3977 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3978 $message = self::constructLike($item, $owner);
3981 $message = self::constructComment($item, $owner);
3989 $message["author_signature"] = self::signature($owner, $message);
3991 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3995 * @brief Creates a message from a signature record entry
3997 * @param array $item The item that will be exported
3998 * @param array $signature The entry of the "sign" record
4000 * @return string The message
4002 private static function messageFromSignature($item, $signature)
4004 // Split the signed text
4005 $signed_parts = explode(";", $signature['signed_text']);
4007 if ($item["deleted"]) {
4008 $message = ["author" => $signature['signer'],
4009 "target_guid" => $signed_parts[0],
4010 "target_type" => $signed_parts[1]];
4011 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4012 $message = ["author" => $signed_parts[4],
4013 "guid" => $signed_parts[1],
4014 "parent_guid" => $signed_parts[3],
4015 "parent_type" => $signed_parts[2],
4016 "positive" => $signed_parts[0],
4017 "author_signature" => $signature['signature'],
4018 "parent_author_signature" => ""];
4020 // Remove the comment guid
4021 $guid = array_shift($signed_parts);
4023 // Remove the parent guid
4024 $parent_guid = array_shift($signed_parts);
4026 // Remove the handle
4027 $handle = array_pop($signed_parts);
4029 // Glue the parts together
4030 $text = implode(";", $signed_parts);
4032 $message = ["author" => $handle,
4034 "parent_guid" => $parent_guid,
4035 "text" => implode(";", $signed_parts),
4036 "author_signature" => $signature['signature'],
4037 "parent_author_signature" => ""];
4043 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
4045 * @param array $item The item that will be exported
4046 * @param array $owner the array of the item owner
4047 * @param array $contact Target of the communication
4048 * @param bool $public_batch Is it a public post?
4050 * @return int The result of the transmission
4052 public static function sendRelay($item, $owner, $contact, $public_batch = false)
4054 if ($item["deleted"]) {
4055 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4056 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4062 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4064 // fetch the original signature
4067 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4072 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4078 // Old way - is used by the internal Friendica functions
4079 /// @todo Change all signatur storing functions to the new format
4080 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4081 $message = self::messageFromSignature($item, $signature);
4083 $msg = json_decode($signature['signed_text'], true);
4086 if (is_array($msg)) {
4087 foreach ($msg as $field => $data) {
4088 if (!$item["deleted"]) {
4089 if ($field == "diaspora_handle") {
4092 if ($field == "target_type") {
4093 $field = "parent_type";
4097 $message[$field] = $data;
4100 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4104 $message["parent_author_signature"] = self::signature($owner, $message);
4106 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4108 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4112 * @brief Sends a retraction (deletion) of a message, like or comment
4114 * @param array $item The item that will be exported
4115 * @param array $owner the array of the item owner
4116 * @param array $contact Target of the communication
4117 * @param bool $public_batch Is it a public post?
4118 * @param bool $relay Is the retraction transmitted from a relay?
4120 * @return int The result of the transmission
4122 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4124 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4126 $msg_type = "retraction";
4128 if ($item['id'] == $item['parent']) {
4129 $target_type = "Post";
4130 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4131 $target_type = "Like";
4133 $target_type = "Comment";
4136 $message = ["author" => $itemaddr,
4137 "target_guid" => $item['guid'],
4138 "target_type" => $target_type];
4140 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4142 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4146 * @brief Sends a mail
4148 * @param array $item The item that will be exported
4149 * @param array $owner The owner
4150 * @param array $contact Target of the communication
4152 * @return int The result of the transmission
4154 public static function sendMail($item, $owner, $contact)
4156 $myaddr = self::myHandle($owner);
4159 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4160 intval($item["convid"]),
4161 intval($item["uid"])
4164 if (!DBM::is_result($r)) {
4165 logger("conversation not found.");
4171 "author" => $cnv["creator"],
4172 "guid" => $cnv["guid"],
4173 "subject" => $cnv["subject"],
4174 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4175 "participants" => $cnv["recips"]
4178 $body = BBCode::toMarkdown($item["body"]);
4179 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4182 "author" => $myaddr,
4183 "guid" => $item["guid"],
4184 "conversation_guid" => $cnv["guid"],
4186 "created_at" => $created,
4189 if ($item["reply"]) {
4194 "author" => $cnv["creator"],
4195 "guid" => $cnv["guid"],
4196 "subject" => $cnv["subject"],
4197 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4198 "participants" => $cnv["recips"],
4201 $type = "conversation";
4204 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4208 * @brief Split a name into first name and last name
4210 * @param string $name The name
4212 * @return array The array with "first" and "last"
4214 public static function splitName($name) {
4215 $name = trim($name);
4217 // Is the name longer than 64 characters? Then cut the rest of it.
4218 if (strlen($name) > 64) {
4219 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4220 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4222 $name = substr($name, 0, 64);
4226 // Take the first word as first name
4227 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4228 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4229 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4230 return ['first' => $first, 'last' => $last];
4233 // Take the last word as last name
4234 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4235 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4237 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4238 return ['first' => $first, 'last' => $last];
4241 // Take the first 32 characters if there is no space in the first 32 characters
4242 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4243 $first = substr($name, 0, 32);
4244 $last = substr($name, 32);
4245 return ['first' => $first, 'last' => $last];
4248 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4249 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4251 // Check if the last name is longer than 32 characters
4252 if (strlen($last) > 32) {
4253 if (strpos($last, ' ') <= 32) {
4254 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4256 $last = substr($last, 0, 32);
4260 return ['first' => $first, 'last' => $last];
4264 * @brief Create profile data
4266 * @param int $uid The user id
4268 * @return array The profile data
4270 private static function createProfileData($uid)
4273 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4275 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4276 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4277 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4286 $handle = $profile["addr"];
4288 $split_name = self::splitName($profile['name']);
4289 $first = $split_name['first'];
4290 $last = $split_name['last'];
4292 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4293 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4294 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4295 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4301 if ($searchable === 'true') {
4304 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4305 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4309 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4312 $about = $profile['about'];
4313 $about = strip_tags(BBCode::convert($about));
4315 $location = Profile::formatLocation($profile);
4317 if ($profile['pub_keywords']) {
4318 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4319 $kw = str_replace(' ', ' ', $kw);
4320 $arr = explode(' ', $profile['pub_keywords']);
4322 for ($x = 0; $x < 5; $x ++) {
4323 if (trim($arr[$x])) {
4324 $tags .= '#'. trim($arr[$x]) .' ';
4329 $tags = trim($tags);
4332 return ["author" => $handle,
4333 "first_name" => $first,
4334 "last_name" => $last,
4335 "image_url" => $large,
4336 "image_url_medium" => $medium,
4337 "image_url_small" => $small,
4339 "gender" => $profile['gender'],
4341 "location" => $location,
4342 "searchable" => $searchable,
4344 "tag_string" => $tags];
4348 * @brief Sends profile data
4350 * @param int $uid The user id
4351 * @param bool $recips optional, default false
4354 public static function sendProfile($uid, $recips = false)
4360 $owner = User::getOwnerDataById($uid);
4367 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4368 AND `uid` = %d AND `rel` != %d",
4369 dbesc(NETWORK_DIASPORA),
4371 intval(CONTACT_IS_SHARING)
4379 $message = self::createProfileData($uid);
4381 foreach ($recips as $recip) {
4382 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4383 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4388 * @brief Stores the signature for likes that are created on our system
4390 * @param array $contact The contact array of the "like"
4391 * @param int $post_id The post id of the "like"
4393 * @return bool Success
4395 public static function storeLikeSignature($contact, $post_id)
4397 // Is the contact the owner? Then fetch the private key
4398 if (!$contact['self'] || ($contact['uid'] == 0)) {
4399 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4403 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4404 if (!DBM::is_result($r)) {
4408 $contact["uprvkey"] = $r[0]['prvkey'];
4410 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4411 if (!DBM::is_result($r)) {
4415 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4419 $message = self::constructLike($r[0], $contact);
4420 if ($message === false) {
4424 $message["author_signature"] = self::signature($contact, $message);
4427 * Now store the signature more flexible to dynamically support new fields.
4428 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4430 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4432 logger('Stored diaspora like signature');
4437 * @brief Stores the signature for comments that are created on our system
4439 * @param array $item The item array of the comment
4440 * @param array $contact The contact array of the item owner
4441 * @param string $uprvkey The private key of the sender
4442 * @param int $message_id The message id of the comment
4444 * @return bool Success
4446 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4448 if ($uprvkey == "") {
4449 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4453 $contact["uprvkey"] = $uprvkey;
4455 $message = self::constructComment($item, $contact);
4456 if ($message === false) {
4460 $message["author_signature"] = self::signature($contact, $message);
4463 * Now store the signature more flexible to dynamically support new fields.
4464 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4466 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4468 logger('Stored diaspora comment signature');