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 $tagserver = dba::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
86 while ($server = dba::fetch($tagserver)) {
87 $tagserverlist[] = $server['gserver-id'];
90 // All adresses with the given id
91 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
92 while ($server = dba::fetch($servers)) {
93 $serverlist[$server['url']] = $server['url'];
97 // Now we are collecting all relay contacts
99 foreach ($serverlist as $server_url) {
100 // We don't send messages to ourselves
101 if (!link_compare($server_url, System::baseUrl())) {
102 $contacts[] = self::getRelayContactId($server_url);
110 * @brief Return a contact for a given server address or creates a dummy entry
112 * @param string $server_url The url of the server
113 * @return array with the contact
115 private static function getRelayContactId($server_url)
117 $batch = $server_url . '/receive/public';
119 $fields = ['batch', 'id', 'name', 'network'];
120 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
121 'archive' => false, 'blocked' => false];
122 $contact = dba::selectFirst('contact', $fields, $condition);
123 if (DBM::is_result($contact)) {
126 $fields = ['uid' => 0, 'created' => DateTimeFormat::utcNow(),
127 'name' => 'relay', 'nick' => 'relay',
128 'url' => $server_url, 'nurl' => normalise_link($server_url),
129 'batch' => $batch, 'network' => NETWORK_DIASPORA,
130 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
131 'pending' => false, 'writable' => true];
132 dba::insert('contact', $fields);
134 $fields = ['batch', 'id', 'name', 'network'];
135 $contact = dba::selectFirst('contact', $fields, $condition);
136 if (DBM::is_result($contact)) {
142 // It should never happen that we arrive here
147 * @brief Return a list of participating contacts for a thread
149 * This is used for the participation feature.
150 * One of the parameters is a contact array.
151 * This is done to avoid duplicates.
153 * @param integer $thread The id of the thread
154 * @param array $contacts The previously fetched contacts
156 * @return array of relay servers
158 public static function participantsForThread($thread, $contacts)
160 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
161 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
162 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
163 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
164 WHERE `participation`.`iid` = ?", $thread);
166 while ($contact = dba::fetch($r)) {
167 if (!empty($contact['fnetwork'])) {
168 $contact['network'] = $contact['fnetwork'];
170 unset($contact['fnetwork']);
172 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
173 $contact['batch'] = $contact['fbatch'];
175 unset($contact['fbatch']);
178 foreach ($contacts as $entry) {
179 if ($entry['batch'] == $contact['batch']) {
185 $contacts[] = $contact;
194 * @brief repairs a signature that was double encoded
196 * The function is unused at the moment. It was copied from the old implementation.
198 * @param string $signature The signature
199 * @param string $handle The handle of the signature owner
200 * @param integer $level This value is only set inside this function to avoid endless loops
202 * @return string the repaired signature
204 private static function repairSignature($signature, $handle = "", $level = 1)
206 if ($signature == "") {
210 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
211 $signature = base64_decode($signature);
212 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
214 // Do a recursive call to be able to fix even multiple levels
216 $signature = self::repairSignature($signature, $handle, ++$level);
224 * @brief verify the envelope and return the verified data
226 * @param string $envelope The magic envelope
228 * @return string verified data
230 private static function verifyMagicEnvelope($envelope)
232 $basedom = XML::parseString($envelope);
234 if (!is_object($basedom)) {
235 logger("Envelope is no XML file");
239 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
241 if (sizeof($children) == 0) {
242 logger("XML has no children");
248 $data = base64url_decode($children->data);
249 $type = $children->data->attributes()->type[0];
251 $encoding = $children->encoding;
253 $alg = $children->alg;
255 $sig = base64url_decode($children->sig);
256 $key_id = $children->sig->attributes()->key_id[0];
258 $handle = base64url_decode($key_id);
261 $b64url_data = base64url_encode($data);
262 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
264 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
267 logger('No author could be decoded. Discarding. Message: ' . $envelope);
271 $key = self::key($handle);
273 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
277 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
279 logger('Message from ' . $handle . ' did not verify. Discarding.');
287 * @brief encrypts data via AES
289 * @param string $key The AES key
290 * @param string $iv The IV (is used for CBC encoding)
291 * @param string $data The data that is to be encrypted
293 * @return string encrypted data
295 private static function aesEncrypt($key, $iv, $data)
297 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
301 * @brief decrypts data via AES
303 * @param string $key The AES key
304 * @param string $iv The IV (is used for CBC encoding)
305 * @param string $encrypted The encrypted data
307 * @return string decrypted data
309 private static function aesDecrypt($key, $iv, $encrypted)
311 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
315 * @brief: Decodes incoming Diaspora message in the new format
317 * @param array $importer Array of the importer user
318 * @param string $raw raw post message
321 * 'message' -> decoded Diaspora XML message
322 * 'author' -> author diaspora handle
323 * 'key' -> author public key (converted to pkcs#8)
325 public static function decodeRaw($importer, $raw)
327 $data = json_decode($raw);
329 // Is it a private post? Then decrypt the outer Salmon
330 if (is_object($data)) {
331 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
332 $ciphertext = base64_decode($data->encrypted_magic_envelope);
334 $outer_key_bundle = '';
335 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
336 $j_outer_key_bundle = json_decode($outer_key_bundle);
338 if (!is_object($j_outer_key_bundle)) {
339 logger('Outer Salmon did not verify. Discarding.');
340 System::httpExit(400);
343 $outer_iv = base64_decode($j_outer_key_bundle->iv);
344 $outer_key = base64_decode($j_outer_key_bundle->key);
346 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
351 $basedom = XML::parseString($xml);
353 if (!is_object($basedom)) {
354 logger('Received data does not seem to be an XML. Discarding. '.$xml);
355 System::httpExit(400);
358 $base = $basedom->children(NAMESPACE_SALMON_ME);
360 // Not sure if this cleaning is needed
361 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
363 // Build the signed data
364 $type = $base->data[0]->attributes()->type[0];
365 $encoding = $base->encoding;
367 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
369 // This is the signature
370 $signature = base64url_decode($base->sig);
372 // Get the senders' public key
373 $key_id = $base->sig[0]->attributes()->key_id[0];
374 $author_addr = base64_decode($key_id);
375 if ($author_addr == '') {
376 logger('No author could be decoded. Discarding. Message: ' . $xml);
377 System::httpExit(400);
380 $key = self::key($author_addr);
382 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
383 System::httpExit(400);
386 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
388 logger('Message did not verify. Discarding.');
389 System::httpExit(400);
392 return ['message' => (string)base64url_decode($base->data),
393 'author' => unxmlify($author_addr),
394 'key' => (string)$key];
398 * @brief: Decodes incoming Diaspora message in the deprecated format
400 * @param array $importer Array of the importer user
401 * @param string $xml urldecoded Diaspora salmon
404 * 'message' -> decoded Diaspora XML message
405 * 'author' -> author diaspora handle
406 * 'key' -> author public key (converted to pkcs#8)
408 public static function decode($importer, $xml)
411 $basedom = XML::parseString($xml);
413 if (!is_object($basedom)) {
414 logger("XML is not parseable.");
417 $children = $basedom->children('https://joindiaspora.com/protocol');
419 $inner_aes_key = null;
422 if ($children->header) {
424 $author_link = str_replace('acct:', '', $children->header->author_id);
426 // This happens with posts from a relais
428 logger("This is no private post in the old format", LOGGER_DEBUG);
432 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
434 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
435 $ciphertext = base64_decode($encrypted_header->ciphertext);
437 $outer_key_bundle = '';
438 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
440 $j_outer_key_bundle = json_decode($outer_key_bundle);
442 $outer_iv = base64_decode($j_outer_key_bundle->iv);
443 $outer_key = base64_decode($j_outer_key_bundle->key);
445 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
447 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
448 $idom = XML::parseString($decrypted);
450 $inner_iv = base64_decode($idom->iv);
451 $inner_aes_key = base64_decode($idom->aes_key);
453 $author_link = str_replace('acct:', '', $idom->author_id);
456 $dom = $basedom->children(NAMESPACE_SALMON_ME);
458 // figure out where in the DOM tree our data is hiding
461 if ($dom->provenance->data) {
462 $base = $dom->provenance;
463 } elseif ($dom->env->data) {
465 } elseif ($dom->data) {
470 logger('unable to locate salmon data in xml');
471 System::httpExit(400);
475 // Stash the signature away for now. We have to find their key or it won't be good for anything.
476 $signature = base64url_decode($base->sig);
480 // strip whitespace so our data element will return to one big base64 blob
481 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
484 // stash away some other stuff for later
486 $type = $base->data[0]->attributes()->type[0];
487 $keyhash = $base->sig[0]->attributes()->keyhash[0];
488 $encoding = $base->encoding;
492 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
496 $data = base64url_decode($data);
500 $inner_decrypted = $data;
502 // Decode the encrypted blob
503 $inner_encrypted = base64_decode($data);
504 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
508 logger('Could not retrieve author URI.');
509 System::httpExit(400);
511 // Once we have the author URI, go to the web and try to find their public key
512 // (first this will look it up locally if it is in the fcontact cache)
513 // This will also convert diaspora public key from pkcs#1 to pkcs#8
515 logger('Fetching key for '.$author_link);
516 $key = self::key($author_link);
519 logger('Could not retrieve author key.');
520 System::httpExit(400);
523 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
526 logger('Message did not verify. Discarding.');
527 System::httpExit(400);
530 logger('Message verified.');
532 return ['message' => (string)$inner_decrypted,
533 'author' => unxmlify($author_link),
534 'key' => (string)$key];
539 * @brief Dispatches public messages and find the fitting receivers
541 * @param array $msg The post that will be dispatched
543 * @return int The message id of the generated message, "true" or "false" if there was an error
545 public static function dispatchPublic($msg)
547 $enabled = intval(Config::get("system", "diaspora_enabled"));
549 logger("diaspora is disabled");
553 if (!($postdata = self::validPosting($msg))) {
554 logger("Invalid posting");
558 $fields = $postdata['fields'];
560 // Is it a an action (comment, like, ...) for our own post?
561 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
562 $guid = notags(unxmlify($fields->parent_guid));
563 $importer = self::importerForGuid($guid);
564 if (is_array($importer)) {
565 logger("delivering to origin: ".$importer["name"]);
566 $message_id = self::dispatch($importer, $msg, $fields);
571 // Process item retractions. This has to be done separated from the other stuff,
572 // since retractions for comments could come even from non followers.
573 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
574 $target = notags(unxmlify($fields->target_type));
575 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
576 logger('processing retraction for '.$target, LOGGER_DEBUG);
577 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
578 $message_id = self::dispatch($importer, $msg, $fields);
583 // Now distribute it to the followers
585 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
586 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
587 AND NOT `account_expired` AND NOT `account_removed`",
588 dbesc(NETWORK_DIASPORA),
589 dbesc($msg["author"])
592 if (DBM::is_result($r)) {
593 foreach ($r as $rr) {
594 logger("delivering to: ".$rr["username"]);
595 self::dispatch($rr, $msg, $fields);
597 } elseif (!Config::get('system', 'relay_subscribe', false)) {
598 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
600 // Use a dummy importer to import the data for the public copy
601 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
602 $message_id = self::dispatch($importer, $msg, $fields);
609 * @brief Dispatches the different message types to the different functions
611 * @param array $importer Array of the importer user
612 * @param array $msg The post that will be dispatched
613 * @param object $fields SimpleXML object that contains the message
615 * @return int The message id of the generated message, "true" or "false" if there was an error
617 public static function dispatch($importer, $msg, $fields = null)
619 // The sender is the handle of the contact that sent the message.
620 // This will often be different with relayed messages (for example "like" and "comment")
621 $sender = $msg["author"];
623 // This is only needed for private postings since this is already done for public ones before
624 if (is_null($fields)) {
625 if (!($postdata = self::validPosting($msg))) {
626 logger("Invalid posting");
629 $fields = $postdata['fields'];
632 $type = $fields->getName();
634 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
637 case "account_migration":
638 return self::receiveAccountMigration($importer, $fields);
640 case "account_deletion":
641 return self::receiveAccountDeletion($importer, $fields);
644 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
647 return self::receiveContactRequest($importer, $fields);
650 return self::receiveConversation($importer, $msg, $fields);
653 return self::receiveLike($importer, $sender, $fields);
656 return self::receiveMessage($importer, $fields);
658 case "participation":
659 return self::receiveParticipation($importer, $fields);
661 case "photo": // Not implemented
662 return self::receivePhoto($importer, $fields);
664 case "poll_participation": // Not implemented
665 return self::receivePollParticipation($importer, $fields);
668 return self::receiveProfile($importer, $fields);
671 return self::receiveReshare($importer, $fields, $msg["message"]);
674 return self::receiveRetraction($importer, $sender, $fields);
676 case "status_message":
677 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
680 logger("Unknown message type ".$type);
688 * @brief Checks if a posting is valid and fetches the data fields.
690 * This function does not only check the signature.
691 * It also does the conversion between the old and the new diaspora format.
693 * @param array $msg Array with the XML, the sender handle and the sender signature
695 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
697 private static function validPosting($msg)
699 $data = XML::parseString($msg["message"]);
701 if (!is_object($data)) {
702 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
706 // Is this the new or the old version?
707 if ($data->getName() == "XML") {
709 foreach ($data->post->children() as $child) {
717 $type = $element->getName();
720 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
722 // All retractions are handled identically from now on.
723 // In the new version there will only be "retraction".
724 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
725 $type = "retraction";
727 if ($type == "request") {
731 $fields = new SimpleXMLElement("<".$type."/>");
734 $author_signature = null;
735 $parent_author_signature = null;
737 foreach ($element->children() as $fieldname => $entry) {
739 // Translation for the old XML structure
740 if ($fieldname == "diaspora_handle") {
741 $fieldname = "author";
743 if ($fieldname == "participant_handles") {
744 $fieldname = "participants";
746 if (in_array($type, ["like", "participation"])) {
747 if ($fieldname == "target_type") {
748 $fieldname = "parent_type";
751 if ($fieldname == "sender_handle") {
752 $fieldname = "author";
754 if ($fieldname == "recipient_handle") {
755 $fieldname = "recipient";
757 if ($fieldname == "root_diaspora_id") {
758 $fieldname = "root_author";
760 if ($type == "status_message") {
761 if ($fieldname == "raw_message") {
765 if ($type == "retraction") {
766 if ($fieldname == "post_guid") {
767 $fieldname = "target_guid";
769 if ($fieldname == "type") {
770 $fieldname = "target_type";
775 if (($fieldname == "author_signature") && ($entry != "")) {
776 $author_signature = base64_decode($entry);
777 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
778 $parent_author_signature = base64_decode($entry);
779 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
780 if ($signed_data != "") {
784 $signed_data .= $entry;
786 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
787 || ($orig_type == "relayable_retraction")
789 XML::copy($entry, $fields, $fieldname);
793 // This is something that shouldn't happen at all.
794 if (in_array($type, ["status_message", "reshare", "profile"])) {
795 if ($msg["author"] != $fields->author) {
796 logger("Message handle is not the same as envelope sender. Quitting this message.");
801 // Only some message types have signatures. So we quit here for the other types.
802 if (!in_array($type, ["comment", "like"])) {
803 return ["fields" => $fields, "relayed" => false];
805 // No author_signature? This is a must, so we quit.
806 if (!isset($author_signature)) {
807 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
811 if (isset($parent_author_signature)) {
814 $key = self::key($msg["author"]);
816 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
817 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);
824 $key = self::key($fields->author);
826 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
827 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
830 return ["fields" => $fields, "relayed" => $relayed];
835 * @brief Fetches the public key for a given handle
837 * @param string $handle The handle
839 * @return string The public key
841 private static function key($handle)
843 $handle = strval($handle);
845 logger("Fetching diaspora key for: ".$handle);
847 $r = self::personByHandle($handle);
856 * @brief Fetches data for a given handle
858 * @param string $handle The handle
860 * @return array the queried data
862 public static function personByHandle($handle)
866 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
867 if (DBM::is_result($person)) {
868 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
870 // update record occasionally so it doesn't get stale
871 $d = strtotime($person["updated"]." +00:00");
872 if ($d < strtotime("now - 14 days")) {
876 if ($person["guid"] == "") {
881 if (!DBM::is_result($person) || $update) {
882 logger("create or refresh", LOGGER_DEBUG);
883 $r = Probe::uri($handle, NETWORK_DIASPORA);
885 // Note that Friendica contacts will return a "Diaspora person"
886 // if Diaspora connectivity is enabled on their server
887 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
888 self::addFContact($r, $update);
890 // Fetch the updated or added contact
891 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
892 if (!DBM::is_result($person)) {
902 * @brief Updates the fcontact table
904 * @param array $arr The fcontact data
905 * @param bool $update Update or insert?
907 * @return string The id of the fcontact entry
909 private static function addFContact($arr, $update = false)
913 "UPDATE `fcontact` SET
927 WHERE `url` = '%s' AND `network` = '%s'",
929 dbesc($arr["photo"]),
930 dbesc($arr["request"]),
932 dbesc(strtolower($arr["addr"])),
934 dbesc($arr["batch"]),
935 dbesc($arr["notify"]),
937 dbesc($arr["confirm"]),
938 dbesc($arr["alias"]),
939 dbesc($arr["pubkey"]),
940 dbesc(DateTimeFormat::utcNow()),
942 dbesc($arr["network"])
946 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
947 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
948 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
951 dbesc($arr["photo"]),
952 dbesc($arr["request"]),
956 dbesc($arr["batch"]),
957 dbesc($arr["notify"]),
959 dbesc($arr["confirm"]),
960 dbesc($arr["network"]),
961 dbesc($arr["alias"]),
962 dbesc($arr["pubkey"]),
963 dbesc(DateTimeFormat::utcNow())
971 * @brief get a handle (user@domain.tld) from a given contact id
973 * @param int $contact_id The id in the contact table
974 * @param int $pcontact_id The id in the contact table (Used for the public contact)
976 * @return string the handle
978 private static function handleFromContact($contact_id, $pcontact_id = 0)
982 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
984 if ($pcontact_id != 0) {
986 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
990 if (DBM::is_result($r)) {
991 return strtolower($r[0]["addr"]);
996 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1000 if (DBM::is_result($r)) {
1003 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
1005 if ($contact['addr'] != "") {
1006 $handle = $contact['addr'];
1008 $baseurl_start = strpos($contact['url'], '://') + 3;
1009 // allows installations in a subdirectory--not sure how Diaspora will handle
1010 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1011 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1012 $handle = $contact['nick'].'@'.$baseurl;
1016 return strtolower($handle);
1020 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1023 * @param mixed $fcontact_guid Hexadecimal string guid
1025 * @return string the contact url or null
1027 public static function urlFromContactGuid($fcontact_guid)
1029 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1032 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1033 dbesc(NETWORK_DIASPORA),
1034 dbesc($fcontact_guid)
1037 if (DBM::is_result($r)) {
1038 return $r[0]['url'];
1045 * @brief Get a contact id for a given handle
1047 * @todo Move to Friendica\Model\Contact
1049 * @param int $uid The user id
1050 * @param string $handle The handle in the format user@domain.tld
1052 * @return int Contact id
1054 private static function contactByHandle($uid, $handle)
1056 // First do a direct search on the contact table
1058 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1063 if (DBM::is_result($r)) {
1067 * We haven't found it?
1068 * We use another function for it that will possibly create a contact entry.
1070 $cid = Contact::getIdForURL($handle, $uid);
1073 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1074 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1076 if (DBM::is_result($r)) {
1082 $handle_parts = explode("@", $handle);
1083 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1085 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1086 dbesc(NETWORK_DFRN),
1090 if (DBM::is_result($r)) {
1094 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1099 * @brief Check if posting is allowed for this contact
1101 * @param array $importer Array of the importer user
1102 * @param array $contact The contact that is checked
1103 * @param bool $is_comment Is the check for a comment?
1105 * @return bool is the contact allowed to post?
1107 private static function postAllow($importer, $contact, $is_comment = false)
1110 * Perhaps we were already sharing with this person. Now they're sharing with us.
1111 * That makes us friends.
1112 * Normally this should have handled by getting a request - but this could get lost
1114 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1115 // It is not removed by now. Possibly the code is needed?
1116 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1119 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1120 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1123 // $contact["rel"] = CONTACT_IS_FRIEND;
1124 // logger("defining user ".$contact["nick"]." as friend");
1127 // We don't seem to like that person
1128 if ($contact["blocked"] || $contact["readonly"]) {
1129 // Maybe blocked, don't accept.
1131 // We are following this person?
1132 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1133 // Yes, then it is fine.
1135 // Is it a post to a community?
1136 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1139 // Is the message a global user or a comment?
1140 } elseif (($importer["uid"] == 0) || $is_comment) {
1141 // Messages for the global users and comments are always accepted
1149 * @brief Fetches the contact id for a handle and checks if posting is allowed
1151 * @param array $importer Array of the importer user
1152 * @param string $handle The checked handle in the format user@domain.tld
1153 * @param bool $is_comment Is the check for a comment?
1155 * @return array The contact data
1157 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1159 $contact = self::contactByHandle($importer["uid"], $handle);
1161 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1162 // If a contact isn't found, we accept it anyway if it is a comment
1170 if (!self::postAllow($importer, $contact, $is_comment)) {
1171 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1178 * @brief Does the message already exists on the system?
1180 * @param int $uid The user id
1181 * @param string $guid The guid of the message
1183 * @return int|bool message id if the message already was stored into the system - or false.
1185 private static function messageExists($uid, $guid)
1188 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1193 if (DBM::is_result($r)) {
1194 logger("message ".$guid." already exists for user ".$uid);
1202 * @brief Checks for links to posts in a message
1204 * @param array $item The item array
1207 private static function fetchGuid($item)
1209 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1210 preg_replace_callback(
1212 function ($match) use ($item) {
1213 self::fetchGuidSub($match, $item);
1218 preg_replace_callback(
1219 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1220 function ($match) use ($item) {
1221 self::fetchGuidSub($match, $item);
1228 * @brief Checks for relative /people/* links in an item body to match local
1229 * contacts or prepends the remote host taken from the author link.
1231 * @param string $body The item body to replace links from
1232 * @param string $author_link The author link for missing local contact fallback
1234 * @return string the replaced string
1236 public static function replacePeopleGuid($body, $author_link)
1238 $return = preg_replace_callback(
1239 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1240 function ($match) use ($author_link) {
1242 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1243 // 1 => '0123456789abcdef'
1245 $handle = self::urlFromContactGuid($match[1]);
1248 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1250 // No local match, restoring absolute remote URL from author scheme and host
1251 $author_url = parse_url($author_link);
1252 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1264 * @brief sub function of "fetchGuid" which checks for links in messages
1266 * @param array $match array containing a link that has to be checked for a message link
1267 * @param array $item The item array
1270 private static function fetchGuidSub($match, $item)
1272 if (!self::storeByGuid($match[1], $item["author-link"])) {
1273 self::storeByGuid($match[1], $item["owner-link"]);
1278 * @brief Fetches an item with a given guid from a given server
1280 * @param string $guid the message guid
1281 * @param string $server The server address
1282 * @param int $uid The user id of the user
1284 * @return int the message id of the stored message or false
1286 private static function storeByGuid($guid, $server, $uid = 0)
1288 $serverparts = parse_url($server);
1289 $server = $serverparts["scheme"]."://".$serverparts["host"];
1291 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1293 $msg = self::message($guid, $server);
1299 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1301 // Now call the dispatcher
1302 return self::dispatchPublic($msg);
1306 * @brief Fetches a message from a server
1308 * @param string $guid message guid
1309 * @param string $server The url of the server
1310 * @param int $level Endless loop prevention
1313 * 'message' => The message XML
1314 * 'author' => The author handle
1315 * 'key' => The public key of the author
1317 private static function message($guid, $server, $level = 0)
1323 // This will work for new Diaspora servers and Friendica servers from 3.5
1324 $source_url = $server."/fetch/post/".urlencode($guid);
1326 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1328 $envelope = Network::fetchUrl($source_url);
1330 logger("Envelope was fetched.", LOGGER_DEBUG);
1331 $x = self::verifyMagicEnvelope($envelope);
1333 logger("Envelope could not be verified.", LOGGER_DEBUG);
1335 logger("Envelope was verified.", LOGGER_DEBUG);
1341 // This will work for older Diaspora and Friendica servers
1343 $source_url = $server."/p/".urlencode($guid).".xml";
1344 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1346 $x = Network::fetchUrl($source_url);
1352 $source_xml = XML::parseString($x);
1354 if (!is_object($source_xml)) {
1358 if ($source_xml->post->reshare) {
1359 // Reshare of a reshare - old Diaspora version
1360 logger("Message is a reshare", LOGGER_DEBUG);
1361 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1362 } elseif ($source_xml->getName() == "reshare") {
1363 // Reshare of a reshare - new Diaspora version
1364 logger("Message is a new reshare", LOGGER_DEBUG);
1365 return self::message($source_xml->root_guid, $server, ++$level);
1370 // Fetch the author - for the old and the new Diaspora version
1371 if ($source_xml->post->status_message->diaspora_handle) {
1372 $author = (string)$source_xml->post->status_message->diaspora_handle;
1373 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1374 $author = (string)$source_xml->author;
1377 // If this isn't a "status_message" then quit
1379 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1383 $msg = ["message" => $x, "author" => $author];
1385 $msg["key"] = self::key($msg["author"]);
1391 * @brief Fetches the item record of a given guid
1393 * @param int $uid The user id
1394 * @param string $guid message guid
1395 * @param string $author The handle of the item
1396 * @param array $contact The contact of the item owner
1398 * @return array the item record
1400 private static function parentItem($uid, $guid, $author, $contact)
1403 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1404 `author-name`, `author-link`, `author-avatar`,
1405 `owner-name`, `owner-link`, `owner-avatar`
1406 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1412 $result = self::storeByGuid($guid, $contact["url"], $uid);
1415 $person = self::personByHandle($author);
1416 $result = self::storeByGuid($guid, $person["url"], $uid);
1420 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1423 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1424 `author-name`, `author-link`, `author-avatar`,
1425 `owner-name`, `owner-link`, `owner-avatar`
1426 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1434 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1437 logger("parent item found: parent: ".$guid." - user: ".$uid);
1443 * @brief returns contact details
1445 * @param array $def_contact The default contact if the person isn't found
1446 * @param array $person The record of the person
1447 * @param int $uid The user id
1450 * 'cid' => contact id
1451 * 'network' => network type
1453 private static function authorContactByUrl($def_contact, $person, $uid)
1455 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1456 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1457 if (DBM::is_result($contact)) {
1458 $cid = $contact["id"];
1459 $network = $contact["network"];
1461 $cid = $def_contact["id"];
1462 $network = NETWORK_DIASPORA;
1465 return ["cid" => $cid, "network" => $network];
1469 * @brief Is the profile a hubzilla profile?
1471 * @param string $url The profile link
1473 * @return bool is it a hubzilla server?
1475 public static function isRedmatrix($url)
1477 return(strstr($url, "/channel/"));
1481 * @brief Generate a post link with a given handle and message guid
1483 * @param string $addr The user handle
1484 * @param string $guid message guid
1485 * @param string $parent_guid optional parent guid
1487 * @return string the post link
1489 private static function plink($addr, $guid, $parent_guid = '')
1491 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1494 if (!DBM::is_result($r)) {
1495 if ($parent_guid != '') {
1496 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1498 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1502 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1503 // So we try another way as well.
1504 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1505 if (DBM::is_result($s)) {
1506 $r[0]["network"] = $s[0]["network"];
1509 if ($r[0]["network"] == NETWORK_DFRN) {
1510 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1513 if (self::isRedmatrix($r[0]["url"])) {
1514 return $r[0]["url"]."/?f=&mid=".$guid;
1517 if ($parent_guid != '') {
1518 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1520 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1525 * @brief Receives account migration
1527 * @param array $importer Array of the importer user
1528 * @param object $data The message object
1530 * @return bool Success
1532 private static function receiveAccountMigration($importer, $data)
1534 $old_handle = notags(unxmlify($data->author));
1535 $new_handle = notags(unxmlify($data->profile->author));
1536 $signature = notags(unxmlify($data->signature));
1538 $contact = self::contactByHandle($importer["uid"], $old_handle);
1540 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1544 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1547 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1548 $key = self::key($old_handle);
1549 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1550 logger('No valid signature for migration.');
1554 // Update the profile
1555 self::receiveProfile($importer, $data->profile);
1557 // change the technical stuff in contact and gcontact
1558 $data = Probe::uri($new_handle);
1559 if ($data['network'] == NETWORK_PHANTOM) {
1560 logger('Account for '.$new_handle." couldn't be probed.");
1564 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1565 'name' => $data['name'], 'nick' => $data['nick'],
1566 'addr' => $data['addr'], 'batch' => $data['batch'],
1567 'notify' => $data['notify'], 'poll' => $data['poll'],
1568 'network' => $data['network']];
1570 dba::update('contact', $fields, ['addr' => $old_handle]);
1572 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1573 'name' => $data['name'], 'nick' => $data['nick'],
1574 'addr' => $data['addr'], 'connect' => $data['addr'],
1575 'notify' => $data['notify'], 'photo' => $data['photo'],
1576 'server_url' => $data['baseurl'], 'network' => $data['network']];
1578 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1580 logger('Contacts are updated.');
1583 /// @todo This is an extreme performance killer
1585 'owner-link' => [$contact["url"], $data["url"]],
1586 'author-link' => [$contact["url"], $data["url"]],
1588 foreach ($fields as $n => $f) {
1590 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1593 intval($importer["uid"])
1596 if (DBM::is_result($r)) {
1598 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1603 intval($importer["uid"])
1612 logger('Items are updated.');
1618 * @brief Processes an account deletion
1620 * @param array $importer Array of the importer user
1621 * @param object $data The message object
1623 * @return bool Success
1625 private static function receiveAccountDeletion($importer, $data)
1627 /// @todo Account deletion should remove the contact from the global contacts as well
1629 $author = notags(unxmlify($data->author));
1631 $contact = self::contactByHandle($importer["uid"], $author);
1633 logger("cannot find contact for author: ".$author);
1637 // We now remove the contact
1638 Contact::remove($contact["id"]);
1643 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1645 * @param string $author Author handle
1646 * @param string $guid Message guid
1647 * @param boolean $onlyfound Only return uri when found in the database
1649 * @return string The constructed uri or the one from our database
1651 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1653 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1654 if (DBM::is_result($r)) {
1655 return $r[0]["uri"];
1656 } elseif (!$onlyfound) {
1657 return $author.":".$guid;
1664 * @brief Fetch the guid from our database with a given uri
1666 * @param string $uri Message uri
1667 * @param string $uid Author handle
1669 * @return string The post guid
1671 private static function getGuidFromUri($uri, $uid)
1673 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1674 if (DBM::is_result($r)) {
1675 return $r[0]["guid"];
1682 * @brief Find the best importer for a comment, like, ...
1684 * @param string $guid The guid of the item
1686 * @return array|boolean the origin owner of that post - or false
1688 private static function importerForGuid($guid)
1690 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1692 if (DBM::is_result($item)) {
1693 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1694 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1695 if (DBM::is_result($contact)) {
1703 * @brief Processes an incoming comment
1705 * @param array $importer Array of the importer user
1706 * @param string $sender The sender of the message
1707 * @param object $data The message object
1708 * @param string $xml The original XML of the message
1710 * @return int The message id of the generated comment or "false" if there was an error
1712 private static function receiveComment($importer, $sender, $data, $xml)
1714 $author = notags(unxmlify($data->author));
1715 $guid = notags(unxmlify($data->guid));
1716 $parent_guid = notags(unxmlify($data->parent_guid));
1717 $text = unxmlify($data->text);
1719 if (isset($data->created_at)) {
1720 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1722 $created_at = DateTimeFormat::utcNow();
1725 if (isset($data->thread_parent_guid)) {
1726 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1727 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1732 $contact = self::allowedContactByHandle($importer, $sender, true);
1737 $message_id = self::messageExists($importer["uid"], $guid);
1742 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1743 if (!$parent_item) {
1747 $person = self::personByHandle($author);
1748 if (!is_array($person)) {
1749 logger("unable to find author details");
1753 // Fetch the contact id - if we know this contact
1754 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1758 $datarray["uid"] = $importer["uid"];
1759 $datarray["contact-id"] = $author_contact["cid"];
1760 $datarray["network"] = $author_contact["network"];
1762 $datarray["author-name"] = $person["name"];
1763 $datarray["author-link"] = $person["url"];
1764 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1766 $datarray["owner-name"] = $contact["name"];
1767 $datarray["owner-link"] = $contact["url"];
1768 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1770 $datarray["guid"] = $guid;
1771 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1773 $datarray["type"] = "remote-comment";
1774 $datarray["verb"] = ACTIVITY_POST;
1775 $datarray["gravity"] = GRAVITY_COMMENT;
1777 if ($thr_uri != "") {
1778 $datarray["parent-uri"] = $thr_uri;
1780 $datarray["parent-uri"] = $parent_item["uri"];
1783 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1785 $datarray["protocol"] = PROTOCOL_DIASPORA;
1786 $datarray["source"] = $xml;
1788 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1790 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1792 $body = Markdown::toBBCode($text);
1794 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1796 self::fetchGuid($datarray);
1798 $message_id = Item::insert($datarray);
1800 if ($message_id <= 0) {
1805 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1808 // If we are the origin of the parent we store the original data and notify our followers
1809 if ($message_id && $parent_item["origin"]) {
1810 // Formerly we stored the signed text, the signature and the author in different fields.
1811 // We now store the raw data so that we are more flexible.
1812 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1815 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1822 * @brief processes and stores private messages
1824 * @param array $importer Array of the importer user
1825 * @param array $contact The contact of the message
1826 * @param object $data The message object
1827 * @param array $msg Array of the processed message, author handle and key
1828 * @param object $mesg The private message
1829 * @param array $conversation The conversation record to which this message belongs
1831 * @return bool "true" if it was successful
1833 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1835 $author = notags(unxmlify($data->author));
1836 $guid = notags(unxmlify($data->guid));
1837 $subject = notags(unxmlify($data->subject));
1839 // "diaspora_handle" is the element name from the old version
1840 // "author" is the element name from the new version
1841 if ($mesg->author) {
1842 $msg_author = notags(unxmlify($mesg->author));
1843 } elseif ($mesg->diaspora_handle) {
1844 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1849 $msg_guid = notags(unxmlify($mesg->guid));
1850 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1851 $msg_text = unxmlify($mesg->text);
1852 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1854 if ($msg_conversation_guid != $guid) {
1855 logger("message conversation guid does not belong to the current conversation.");
1859 $body = Markdown::toBBCode($msg_text);
1860 $message_uri = $msg_author.":".$msg_guid;
1862 $person = self::personByHandle($msg_author);
1867 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1869 intval($importer["uid"])
1871 if (DBM::is_result($r)) {
1872 logger("duplicate message already delivered.", LOGGER_DEBUG);
1877 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1878 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1879 intval($importer["uid"]),
1881 intval($conversation["id"]),
1882 dbesc($person["name"]),
1883 dbesc($person["photo"]),
1884 dbesc($person["url"]),
1885 intval($contact["id"]),
1890 dbesc($message_uri),
1891 dbesc($author.":".$guid),
1892 dbesc($msg_created_at)
1897 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1901 "type" => NOTIFY_MAIL,
1902 "notify_flags" => $importer["notify-flags"],
1903 "language" => $importer["language"],
1904 "to_name" => $importer["username"],
1905 "to_email" => $importer["email"],
1906 "uid" =>$importer["uid"],
1907 "item" => ["subject" => $subject, "body" => $body],
1908 "source_name" => $person["name"],
1909 "source_link" => $person["url"],
1910 "source_photo" => $person["thumb"],
1911 "verb" => ACTIVITY_POST,
1918 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1920 * @param array $importer Array of the importer user
1921 * @param array $msg Array of the processed message, author handle and key
1922 * @param object $data The message object
1924 * @return bool Success
1926 private static function receiveConversation($importer, $msg, $data)
1928 $author = notags(unxmlify($data->author));
1929 $guid = notags(unxmlify($data->guid));
1930 $subject = notags(unxmlify($data->subject));
1931 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1932 $participants = notags(unxmlify($data->participants));
1934 $messages = $data->message;
1936 if (!count($messages)) {
1937 logger("empty conversation");
1941 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1946 $conversation = null;
1949 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1950 intval($importer["uid"]),
1954 $conversation = $c[0];
1957 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1958 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1959 intval($importer["uid"]),
1963 dbesc(DateTimeFormat::utcNow()),
1965 dbesc($participants)
1969 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1970 intval($importer["uid"]),
1976 $conversation = $c[0];
1979 if (!$conversation) {
1980 logger("unable to create conversation.");
1984 foreach ($messages as $mesg) {
1985 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1992 * @brief Creates the body for a "like" message
1994 * @param array $contact The contact that send us the "like"
1995 * @param array $parent_item The item array of the parent item
1996 * @param string $guid message guid
1998 * @return string the body
2000 private static function constructLikeBody($contact, $parent_item, $guid)
2002 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2004 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2005 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
2006 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
2008 return sprintf($bodyverb, $ulink, $alink, $plink);
2012 * @brief Creates a XML object for a "like"
2014 * @param array $importer Array of the importer user
2015 * @param array $parent_item The item array of the parent item
2017 * @return string The XML
2019 private static function constructLikeObject($importer, $parent_item)
2021 $objtype = ACTIVITY_OBJ_NOTE;
2022 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
2023 $parent_body = $parent_item["body"];
2025 $xmldata = ["object" => ["type" => $objtype,
2027 "id" => $parent_item["uri"],
2030 "content" => $parent_body]];
2032 return XML::fromArray($xmldata, $xml, true);
2036 * @brief Processes "like" messages
2038 * @param array $importer Array of the importer user
2039 * @param string $sender The sender of the message
2040 * @param object $data The message object
2042 * @return int The message id of the generated like or "false" if there was an error
2044 private static function receiveLike($importer, $sender, $data)
2046 $author = notags(unxmlify($data->author));
2047 $guid = notags(unxmlify($data->guid));
2048 $parent_guid = notags(unxmlify($data->parent_guid));
2049 $parent_type = notags(unxmlify($data->parent_type));
2050 $positive = notags(unxmlify($data->positive));
2052 // likes on comments aren't supported by Diaspora - only on posts
2053 // But maybe this will be supported in the future, so we will accept it.
2054 if (!in_array($parent_type, ["Post", "Comment"])) {
2058 $contact = self::allowedContactByHandle($importer, $sender, true);
2063 $message_id = self::messageExists($importer["uid"], $guid);
2068 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2069 if (!$parent_item) {
2073 $person = self::personByHandle($author);
2074 if (!is_array($person)) {
2075 logger("unable to find author details");
2079 // Fetch the contact id - if we know this contact
2080 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2082 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2083 // We would accept this anyhow.
2084 if ($positive == "true") {
2085 $verb = ACTIVITY_LIKE;
2087 $verb = ACTIVITY_DISLIKE;
2092 $datarray["protocol"] = PROTOCOL_DIASPORA;
2094 $datarray["uid"] = $importer["uid"];
2095 $datarray["contact-id"] = $author_contact["cid"];
2096 $datarray["network"] = $author_contact["network"];
2098 $datarray["author-name"] = $person["name"];
2099 $datarray["author-link"] = $person["url"];
2100 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2102 $datarray["owner-name"] = $contact["name"];
2103 $datarray["owner-link"] = $contact["url"];
2104 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2106 $datarray["guid"] = $guid;
2107 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2109 $datarray["type"] = "activity";
2110 $datarray["verb"] = $verb;
2111 $datarray["gravity"] = GRAVITY_LIKE;
2112 $datarray["parent-uri"] = $parent_item["uri"];
2114 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2115 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2117 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2119 $message_id = Item::insert($datarray);
2121 if ($message_id <= 0) {
2126 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2129 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2130 if ($parent_item["id"] != $parent_item["parent"]) {
2131 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2132 $origin = $toplevel["origin"];
2134 $origin = $parent_item["origin"];
2137 // If we are the origin of the parent we store the original data and notify our followers
2138 if ($message_id && $origin) {
2139 // Formerly we stored the signed text, the signature and the author in different fields.
2140 // We now store the raw data so that we are more flexible.
2141 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2144 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2151 * @brief Processes private messages
2153 * @param array $importer Array of the importer user
2154 * @param object $data The message object
2156 * @return bool Success?
2158 private static function receiveMessage($importer, $data)
2160 $author = notags(unxmlify($data->author));
2161 $guid = notags(unxmlify($data->guid));
2162 $conversation_guid = notags(unxmlify($data->conversation_guid));
2163 $text = unxmlify($data->text);
2164 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2166 $contact = self::allowedContactByHandle($importer, $author, true);
2171 $conversation = null;
2174 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2175 intval($importer["uid"]),
2176 dbesc($conversation_guid)
2179 $conversation = $c[0];
2181 logger("conversation not available.");
2185 $message_uri = $author.":".$guid;
2187 $person = self::personByHandle($author);
2189 logger("unable to find author details");
2193 $body = Markdown::toBBCode($text);
2195 $body = self::replacePeopleGuid($body, $person["url"]);
2200 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2202 intval($importer["uid"])
2204 if (DBM::is_result($r)) {
2205 logger("duplicate message already delivered.", LOGGER_DEBUG);
2210 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2211 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2212 intval($importer["uid"]),
2214 intval($conversation["id"]),
2215 dbesc($person["name"]),
2216 dbesc($person["photo"]),
2217 dbesc($person["url"]),
2218 intval($contact["id"]),
2219 dbesc($conversation["subject"]),
2223 dbesc($message_uri),
2224 dbesc($author.":".$conversation["guid"]),
2230 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2235 * @brief Processes participations - unsupported by now
2237 * @param array $importer Array of the importer user
2238 * @param object $data The message object
2240 * @return bool always true
2242 private static function receiveParticipation($importer, $data)
2244 $author = strtolower(notags(unxmlify($data->author)));
2245 $parent_guid = notags(unxmlify($data->parent_guid));
2247 $contact_id = Contact::getIdForURL($author);
2249 logger('Contact not found: '.$author);
2253 $person = self::personByHandle($author);
2254 if (!is_array($person)) {
2255 logger("Person not found: ".$author);
2259 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2260 if (!DBM::is_result($item)) {
2261 logger('Item not found, no origin or private: '.$parent_guid);
2265 $author_parts = explode('@', $author);
2266 if (isset($author_parts[1])) {
2267 $server = $author_parts[1];
2269 // Should never happen
2273 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2275 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2276 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2279 // Send all existing comments and likes to the requesting server
2280 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2282 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2283 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2284 while ($comment = dba::fetch($comments)) {
2285 if ($comment['verb'] == ACTIVITY_POST) {
2286 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2288 $cmd = $comment['self'] ? 'like' : 'comment-import';
2290 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2291 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2293 dba::close($comments);
2299 * @brief Processes photos - unneeded
2301 * @param array $importer Array of the importer user
2302 * @param object $data The message object
2304 * @return bool always true
2306 private static function receivePhoto($importer, $data)
2308 // There doesn't seem to be a reason for this function,
2309 // since the photo data is transmitted in the status message as well
2314 * @brief Processes poll participations - unssupported
2316 * @param array $importer Array of the importer user
2317 * @param object $data The message object
2319 * @return bool always true
2321 private static function receivePollParticipation($importer, $data)
2323 // We don't support polls by now
2328 * @brief Processes incoming profile updates
2330 * @param array $importer Array of the importer user
2331 * @param object $data The message object
2333 * @return bool Success
2335 private static function receiveProfile($importer, $data)
2337 $author = strtolower(notags(unxmlify($data->author)));
2339 $contact = self::contactByHandle($importer["uid"], $author);
2344 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2345 $image_url = unxmlify($data->image_url);
2346 $birthday = unxmlify($data->birthday);
2347 $gender = unxmlify($data->gender);
2348 $about = Markdown::toBBCode(unxmlify($data->bio));
2349 $location = Markdown::toBBCode(unxmlify($data->location));
2350 $searchable = (unxmlify($data->searchable) == "true");
2351 $nsfw = (unxmlify($data->nsfw) == "true");
2352 $tags = unxmlify($data->tag_string);
2354 $tags = explode("#", $tags);
2357 foreach ($tags as $tag) {
2358 $tag = trim(strtolower($tag));
2364 $keywords = implode(", ", $keywords);
2366 $handle_parts = explode("@", $author);
2367 $nick = $handle_parts[0];
2370 $name = $handle_parts[0];
2373 if (preg_match("|^https?://|", $image_url) === 0) {
2374 $image_url = "http://".$handle_parts[1].$image_url;
2377 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2379 // Generic birthday. We don't know the timezone. The year is irrelevant.
2381 $birthday = str_replace("1000", "1901", $birthday);
2383 if ($birthday != "") {
2384 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2387 // this is to prevent multiple birthday notifications in a single year
2388 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2390 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2391 $birthday = $contact["bd"];
2395 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2396 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2400 dbesc(DateTimeFormat::utcNow()),
2406 intval($contact["id"]),
2407 intval($importer["uid"])
2410 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2411 "photo" => $image_url, "name" => $name, "location" => $location,
2412 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2413 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2414 "hide" => !$searchable, "nsfw" => $nsfw];
2416 $gcid = GContact::update($gcontact);
2418 GContact::link($gcid, $importer["uid"], $contact["id"]);
2420 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2426 * @brief Processes incoming friend requests
2428 * @param array $importer Array of the importer user
2429 * @param array $contact The contact that send the request
2432 private static function receiveRequestMakeFriend($importer, $contact)
2436 if ($contact["rel"] == CONTACT_IS_SHARING) {
2439 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2440 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2443 // send notification
2446 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2447 intval($importer["uid"])
2450 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2452 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2453 intval($importer["uid"])
2456 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2458 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2460 $arr["protocol"] = PROTOCOL_DIASPORA;
2461 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2462 $arr["uid"] = $importer["uid"];
2463 $arr["contact-id"] = $self[0]["id"];
2465 $arr["type"] = 'wall';
2466 $arr["gravity"] = 0;
2468 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2469 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2470 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2471 $arr["verb"] = ACTIVITY_FRIEND;
2472 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2474 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2475 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2476 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2477 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2479 $arr["object"] = self::constructNewFriendObject($contact);
2481 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2483 $arr["allow_cid"] = $user["allow_cid"];
2484 $arr["allow_gid"] = $user["allow_gid"];
2485 $arr["deny_cid"] = $user["deny_cid"];
2486 $arr["deny_gid"] = $user["deny_gid"];
2488 $i = Item::insert($arr);
2490 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2497 * @brief Creates a XML object for a "new friend" message
2499 * @param array $contact Array of the contact
2501 * @return string The XML
2503 private static function constructNewFriendObject($contact)
2505 $objtype = ACTIVITY_OBJ_PERSON;
2506 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2507 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2509 $xmldata = ["object" => ["type" => $objtype,
2510 "title" => $contact["name"],
2511 "id" => $contact["url"]."/".$contact["name"],
2514 return XML::fromArray($xmldata, $xml, true);
2518 * @brief Processes incoming sharing notification
2520 * @param array $importer Array of the importer user
2521 * @param object $data The message object
2523 * @return bool Success
2525 private static function receiveContactRequest($importer, $data)
2527 $author = unxmlify($data->author);
2528 $recipient = unxmlify($data->recipient);
2530 if (!$author || !$recipient) {
2534 // the current protocol version doesn't know these fields
2535 // That means that we will assume their existance
2536 if (isset($data->following)) {
2537 $following = (unxmlify($data->following) == "true");
2542 if (isset($data->sharing)) {
2543 $sharing = (unxmlify($data->sharing) == "true");
2548 $contact = self::contactByHandle($importer["uid"], $author);
2550 // perhaps we were already sharing with this person. Now they're sharing with us.
2551 // That makes us friends.
2554 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2555 self::receiveRequestMakeFriend($importer, $contact);
2557 // refetch the contact array
2558 $contact = self::contactByHandle($importer["uid"], $author);
2560 // If we are now friends, we are sending a share message.
2561 // Normally we needn't to do so, but the first message could have been vanished.
2562 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2563 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2565 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2566 $ret = self::sendShare($u[0], $contact);
2571 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2572 Contact::removeFollower($importer, $contact);
2577 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2578 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2580 } elseif (!$following && !$sharing) {
2581 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2583 } elseif (!$following && $sharing) {
2584 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2585 } elseif ($following && $sharing) {
2586 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2587 } elseif ($following && !$sharing) {
2588 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2591 $ret = self::personByHandle($author);
2593 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2594 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2598 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2601 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2602 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2603 intval($importer["uid"]),
2604 dbesc($ret["network"]),
2605 dbesc($ret["addr"]),
2606 DateTimeFormat::utcNow(),
2608 dbesc(normalise_link($ret["url"])),
2610 dbesc($ret["name"]),
2611 dbesc($ret["nick"]),
2612 dbesc($ret["photo"]),
2613 dbesc($ret["pubkey"]),
2614 dbesc($ret["notify"]),
2615 dbesc($ret["poll"]),
2620 // find the contact record we just created
2622 $contact_record = self::contactByHandle($importer["uid"], $author);
2624 if (!$contact_record) {
2625 logger("unable to locate newly created contact record.");
2629 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2631 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2633 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2635 if ($importer["page-flags"] == PAGE_NORMAL) {
2636 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2638 $hash = random_string().(string)time(); // Generate a confirm_key
2641 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2642 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2643 intval($importer["uid"]),
2644 intval($contact_record["id"]),
2647 dbesc(L10n::t("Sharing notification from Diaspora network")),
2649 dbesc(DateTimeFormat::utcNow())
2652 // automatic friend approval
2654 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2656 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2658 // technically they are sharing with us (CONTACT_IS_SHARING),
2659 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2660 // we are going to change the relationship and make them a follower.
2662 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2663 $new_relation = CONTACT_IS_FRIEND;
2664 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2665 $new_relation = CONTACT_IS_SHARING;
2667 $new_relation = CONTACT_IS_FOLLOWER;
2671 "UPDATE `contact` SET `rel` = %d,
2679 intval($new_relation),
2680 dbesc(DateTimeFormat::utcNow()),
2681 dbesc(DateTimeFormat::utcNow()),
2682 intval($contact_record["id"])
2685 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2687 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2688 $ret = self::sendShare($u[0], $contact_record);
2690 // Send the profile data, maybe it weren't transmitted before
2691 self::sendProfile($importer["uid"], [$contact_record]);
2699 * @brief Fetches a message with a given guid
2701 * @param string $guid message guid
2702 * @param string $orig_author handle of the original post
2703 * @param string $author handle of the sharer
2705 * @return array The fetched item
2707 private static function originalItem($guid, $orig_author, $author)
2709 // Do we already have this item?
2711 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2712 `author-name`, `author-link`, `author-avatar`
2713 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2717 if (DBM::is_result($r)) {
2718 logger("reshared message ".$guid." already exists on system.");
2720 // Maybe it is already a reshared item?
2721 // Then refetch the content, if it is a reshare from a reshare.
2722 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2723 if (self::isReshare($r[0]["body"], true)) {
2725 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2726 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2728 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2730 // Add OEmbed and other information to the body
2731 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2739 if (!DBM::is_result($r)) {
2740 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2741 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2742 $item_id = self::storeByGuid($guid, $server);
2745 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2746 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2747 $item_id = self::storeByGuid($guid, $server);
2752 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2753 `author-name`, `author-link`, `author-avatar`
2754 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2758 if (DBM::is_result($r)) {
2759 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2760 if (self::isReshare($r[0]["body"], false)) {
2761 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2762 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2773 * @brief Processes a reshare message
2775 * @param array $importer Array of the importer user
2776 * @param object $data The message object
2777 * @param string $xml The original XML of the message
2779 * @return int the message id
2781 private static function receiveReshare($importer, $data, $xml)
2783 $author = notags(unxmlify($data->author));
2784 $guid = notags(unxmlify($data->guid));
2785 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2786 $root_author = notags(unxmlify($data->root_author));
2787 $root_guid = notags(unxmlify($data->root_guid));
2788 /// @todo handle unprocessed property "provider_display_name"
2789 $public = notags(unxmlify($data->public));
2791 $contact = self::allowedContactByHandle($importer, $author, false);
2796 $message_id = self::messageExists($importer["uid"], $guid);
2801 $original_item = self::originalItem($root_guid, $root_author, $author);
2802 if (!$original_item) {
2806 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2810 $datarray["uid"] = $importer["uid"];
2811 $datarray["contact-id"] = $contact["id"];
2812 $datarray["network"] = NETWORK_DIASPORA;
2814 $datarray["author-name"] = $contact["name"];
2815 $datarray["author-link"] = $contact["url"];
2816 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2818 $datarray["owner-name"] = $datarray["author-name"];
2819 $datarray["owner-link"] = $datarray["author-link"];
2820 $datarray["owner-avatar"] = $datarray["author-avatar"];
2822 $datarray["guid"] = $guid;
2823 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2825 $datarray["verb"] = ACTIVITY_POST;
2826 $datarray["gravity"] = GRAVITY_PARENT;
2828 $datarray["protocol"] = PROTOCOL_DIASPORA;
2829 $datarray["source"] = $xml;
2831 $prefix = share_header(
2832 $original_item["author-name"],
2833 $original_item["author-link"],
2834 $original_item["author-avatar"],
2835 $original_item["guid"],
2836 $original_item["created"],
2839 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2841 $datarray["tag"] = $original_item["tag"];
2842 $datarray["app"] = $original_item["app"];
2844 $datarray["plink"] = self::plink($author, $guid);
2845 $datarray["private"] = (($public == "false") ? 1 : 0);
2846 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2848 $datarray["object-type"] = $original_item["object-type"];
2850 self::fetchGuid($datarray);
2851 $message_id = Item::insert($datarray);
2853 self::sendParticipation($contact, $datarray);
2856 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2864 * @brief Processes retractions
2866 * @param array $importer Array of the importer user
2867 * @param array $contact The contact of the item owner
2868 * @param object $data The message object
2870 * @return bool success
2872 private static function itemRetraction($importer, $contact, $data)
2874 $author = notags(unxmlify($data->author));
2875 $target_guid = notags(unxmlify($data->target_guid));
2876 $target_type = notags(unxmlify($data->target_type));
2878 $person = self::personByHandle($author);
2879 if (!is_array($person)) {
2880 logger("unable to find author detail for ".$author);
2884 if (empty($contact["url"])) {
2885 $contact["url"] = $person["url"];
2888 // Fetch items that are about to be deleted
2889 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2891 // When we receive a public retraction, we delete every item that we find.
2892 if ($importer['uid'] == 0) {
2893 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2895 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2897 $r = dba::select('item', $fields, $condition);
2898 if (!DBM::is_result($r)) {
2899 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2903 while ($item = dba::fetch($r)) {
2904 // Fetch the parent item
2905 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2907 // Only delete it if the parent author really fits
2908 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2909 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2913 Item::deleteById($item["id"]);
2915 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2917 // Now check if the retraction needs to be relayed by us
2918 if ($parent["origin"]) {
2920 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2928 * @brief Receives retraction messages
2930 * @param array $importer Array of the importer user
2931 * @param string $sender The sender of the message
2932 * @param object $data The message object
2934 * @return bool Success
2936 private static function receiveRetraction($importer, $sender, $data)
2938 $target_type = notags(unxmlify($data->target_type));
2940 $contact = self::contactByHandle($importer["uid"], $sender);
2941 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2942 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2946 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2948 switch ($target_type) {
2953 case "StatusMessage":
2954 return self::itemRetraction($importer, $contact, $data);
2958 /// @todo What should we do with an "unshare"?
2959 // Removing the contact isn't correct since we still can read the public items
2960 Contact::remove($contact["id"]);
2964 logger("Unknown target type ".$target_type);
2971 * @brief Receives status messages
2973 * @param array $importer Array of the importer user
2974 * @param object $data The message object
2975 * @param string $xml The original XML of the message
2977 * @return int The message id of the newly created item
2979 private static function receiveStatusMessage($importer, $data, $xml)
2981 $author = notags(unxmlify($data->author));
2982 $guid = notags(unxmlify($data->guid));
2983 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2984 $public = notags(unxmlify($data->public));
2985 $text = unxmlify($data->text);
2986 $provider_display_name = notags(unxmlify($data->provider_display_name));
2988 $contact = self::allowedContactByHandle($importer, $author, false);
2993 $message_id = self::messageExists($importer["uid"], $guid);
2999 if ($data->location) {
3000 foreach ($data->location->children() as $fieldname => $data) {
3001 $address[$fieldname] = notags(unxmlify($data));
3005 $body = Markdown::toBBCode($text);
3009 // Attach embedded pictures to the body
3011 foreach ($data->photo as $photo) {
3012 $body = "[img]".unxmlify($photo->remote_photo_path).
3013 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
3016 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
3018 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
3020 // Add OEmbed and other information to the body
3021 if (!self::isRedmatrix($contact["url"])) {
3022 $body = add_page_info_to_body($body, false, true);
3026 /// @todo enable support for polls
3027 //if ($data->poll) {
3028 // foreach ($data->poll AS $poll)
3033 /// @todo enable support for events
3035 $datarray["uid"] = $importer["uid"];
3036 $datarray["contact-id"] = $contact["id"];
3037 $datarray["network"] = NETWORK_DIASPORA;
3039 $datarray["author-name"] = $contact["name"];
3040 $datarray["author-link"] = $contact["url"];
3041 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3043 $datarray["owner-name"] = $datarray["author-name"];
3044 $datarray["owner-link"] = $datarray["author-link"];
3045 $datarray["owner-avatar"] = $datarray["author-avatar"];
3047 $datarray["guid"] = $guid;
3048 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3050 $datarray["verb"] = ACTIVITY_POST;
3051 $datarray["gravity"] = GRAVITY_PARENT;
3053 $datarray["protocol"] = PROTOCOL_DIASPORA;
3054 $datarray["source"] = $xml;
3056 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3058 if ($provider_display_name != "") {
3059 $datarray["app"] = $provider_display_name;
3062 $datarray["plink"] = self::plink($author, $guid);
3063 $datarray["private"] = (($public == "false") ? 1 : 0);
3064 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3066 if (isset($address["address"])) {
3067 $datarray["location"] = $address["address"];
3070 if (isset($address["lat"]) && isset($address["lng"])) {
3071 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3074 self::fetchGuid($datarray);
3075 $message_id = Item::insert($datarray);
3077 self::sendParticipation($contact, $datarray);
3080 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3087 /* ************************************************************************************** *
3088 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3089 * ************************************************************************************** */
3092 * @brief returnes the handle of a contact
3094 * @param array $contact contact array
3096 * @return string the handle in the format user@domain.tld
3098 private static function myHandle($contact)
3100 if ($contact["addr"] != "") {
3101 return $contact["addr"];
3104 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3105 // So - just in case - we build the the address here.
3106 if ($contact["nickname"] != "") {
3107 $nick = $contact["nickname"];
3109 $nick = $contact["nick"];
3112 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3117 * @brief Creates the data for a private message in the new format
3119 * @param string $msg The message that is to be transmitted
3120 * @param array $user The record of the sender
3121 * @param array $contact Target of the communication
3122 * @param string $prvkey The private key of the sender
3123 * @param string $pubkey The public key of the receiver
3125 * @return string The encrypted data
3127 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3129 logger("Message: ".$msg, LOGGER_DATA);
3131 // without a public key nothing will work
3133 logger("pubkey missing: contact id: ".$contact["id"]);
3137 $aes_key = openssl_random_pseudo_bytes(32);
3138 $b_aes_key = base64_encode($aes_key);
3139 $iv = openssl_random_pseudo_bytes(16);
3140 $b_iv = base64_encode($iv);
3142 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3144 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3146 $encrypted_key_bundle = "";
3147 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3149 $json_object = json_encode(
3150 ["aes_key" => base64_encode($encrypted_key_bundle),
3151 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3154 return $json_object;
3158 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3160 * @param string $msg The message that is to be transmitted
3161 * @param array $user The record of the sender
3163 * @return string The envelope
3165 public static function buildMagicEnvelope($msg, $user)
3167 $b64url_data = base64url_encode($msg);
3168 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3170 $key_id = base64url_encode(self::myHandle($user));
3171 $type = "application/xml";
3172 $encoding = "base64url";
3173 $alg = "RSA-SHA256";
3174 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3176 // Fallback if the private key wasn't transmitted in the expected field
3177 if ($user['uprvkey'] == "") {
3178 $user['uprvkey'] = $user['prvkey'];
3181 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3182 $sig = base64url_encode($signature);
3184 $xmldata = ["me:env" => ["me:data" => $data,
3185 "@attributes" => ["type" => $type],
3186 "me:encoding" => $encoding,
3189 "@attributes2" => ["key_id" => $key_id]]];
3191 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3193 return XML::fromArray($xmldata, $xml, false, $namespaces);
3197 * @brief Create the envelope for a message
3199 * @param string $msg The message that is to be transmitted
3200 * @param array $user The record of the sender
3201 * @param array $contact Target of the communication
3202 * @param string $prvkey The private key of the sender
3203 * @param string $pubkey The public key of the receiver
3204 * @param bool $public Is the message public?
3206 * @return string The message that will be transmitted to other servers
3208 public static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3210 // The message is put into an envelope with the sender's signature
3211 $envelope = self::buildMagicEnvelope($msg, $user);
3213 // Private messages are put into a second envelope, encrypted with the receivers public key
3215 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3222 * @brief Creates a signature for a message
3224 * @param array $owner the array of the owner of the message
3225 * @param array $message The message that is to be signed
3227 * @return string The signature
3229 private static function signature($owner, $message)
3232 unset($sigmsg["author_signature"]);
3233 unset($sigmsg["parent_author_signature"]);
3235 $signed_text = implode(";", $sigmsg);
3237 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3241 * @brief Transmit a message to a target server
3243 * @param array $owner the array of the item owner
3244 * @param array $contact Target of the communication
3245 * @param string $envelope The message that is to be transmitted
3246 * @param bool $public_batch Is it a public post?
3247 * @param bool $queue_run Is the transmission called from the queue?
3248 * @param string $guid message guid
3250 * @return int Result of the transmission
3252 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3256 $enabled = intval(Config::get("system", "diaspora_enabled"));
3261 $logid = random_string(4);
3263 // We always try to use the data from the fcontact table.
3264 // This is important for transmitting data to Friendica servers.
3265 if (!empty($contact['addr']) && ($contact['network'] != NETWORK_DIASPORA)) {
3266 $fcontact = self::personByHandle($contact['addr']);
3267 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3269 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3273 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3277 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3279 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3282 if (!intval(Config::get("system", "diaspora_test"))) {
3283 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3285 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3286 $return_code = $a->get_curl_code();
3288 logger("test_mode");
3293 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3295 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3297 logger("queue message");
3298 // queue message for redelivery
3299 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3302 // The message could not be delivered. We mark the contact as "dead"
3303 Contact::markForArchival($contact);
3304 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3305 // We successfully delivered a message, the contact is alive
3306 Contact::unmarkForArchival($contact);
3309 return $return_code ? $return_code : -1;
3314 * @brief Build the post xml
3316 * @param string $type The message type
3317 * @param array $message The message data
3319 * @return string The post XML
3321 public static function buildPostXml($type, $message)
3323 $data = [$type => $message];
3325 return XML::fromArray($data, $xml);
3329 * @brief Builds and transmit messages
3331 * @param array $owner the array of the item owner
3332 * @param array $contact Target of the communication
3333 * @param string $type The message type
3334 * @param array $message The message data
3335 * @param bool $public_batch Is it a public post?
3336 * @param string $guid message guid
3337 * @param bool $spool Should the transmission be spooled or transmitted?
3339 * @return int Result of the transmission
3341 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3343 $msg = self::buildPostXml($type, $message);
3345 logger('message: '.$msg, LOGGER_DATA);
3346 logger('send guid '.$guid, LOGGER_DEBUG);
3348 // Fallback if the private key wasn't transmitted in the expected field
3349 if ($owner['uprvkey'] == "") {
3350 $owner['uprvkey'] = $owner['prvkey'];
3353 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3356 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3359 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3362 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3364 return $return_code;
3368 * @brief sends a participation (Used to get all further updates)
3370 * @param array $contact Target of the communication
3371 * @param array $item Item array
3373 * @return int The result of the transmission
3375 private static function sendParticipation($contact, $item)
3377 // Don't send notifications for private postings
3378 if ($item['private']) {
3382 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3384 $result = Cache::get($cachekey);
3385 if (!is_null($result)) {
3389 // Fetch some user id to have a valid handle to transmit the participation.
3390 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3391 // If the item belongs to a user, we take this user id.
3392 if ($item['uid'] == 0) {
3393 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3394 $first_user = dba::selectFirst('user', ['uid'], $condition);
3395 $owner = User::getOwnerDataById($first_user['uid']);
3397 $owner = User::getOwnerDataById($item['uid']);
3400 $author = self::myHandle($owner);
3402 $message = ["author" => $author,
3403 "guid" => get_guid(32),
3404 "parent_type" => "Post",
3405 "parent_guid" => $item["guid"]];
3407 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3409 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3410 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3412 return self::buildAndTransmit($owner, $contact, "participation", $message);
3416 * @brief sends an account migration
3418 * @param array $owner the array of the item owner
3419 * @param array $contact Target of the communication
3420 * @param int $uid User ID
3422 * @return int The result of the transmission
3424 public static function sendAccountMigration($owner, $contact, $uid)
3426 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3427 $profile = self::createProfileData($uid);
3429 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3430 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3432 $message = ["author" => $old_handle,
3433 "profile" => $profile,
3434 "signature" => $signature];
3436 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3438 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3442 * @brief Sends a "share" message
3444 * @param array $owner the array of the item owner
3445 * @param array $contact Target of the communication
3447 * @return int The result of the transmission
3449 public static function sendShare($owner, $contact)
3452 * @todo support the different possible combinations of "following" and "sharing"
3453 * Currently, Diaspora only interprets the "sharing" field
3455 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3459 switch ($contact["rel"]) {
3460 case CONTACT_IS_FRIEND:
3463 case CONTACT_IS_SHARING:
3466 case CONTACT_IS_FOLLOWER:
3472 $message = ["author" => self::myHandle($owner),
3473 "recipient" => $contact["addr"],
3474 "following" => "true",
3475 "sharing" => "true"];
3477 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3479 return self::buildAndTransmit($owner, $contact, "contact", $message);
3483 * @brief sends an "unshare"
3485 * @param array $owner the array of the item owner
3486 * @param array $contact Target of the communication
3488 * @return int The result of the transmission
3490 public static function sendUnshare($owner, $contact)
3492 $message = ["author" => self::myHandle($owner),
3493 "recipient" => $contact["addr"],
3494 "following" => "false",
3495 "sharing" => "false"];
3497 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3499 return self::buildAndTransmit($owner, $contact, "contact", $message);
3503 * @brief Checks a message body if it is a reshare
3505 * @param string $body The message body that is to be check
3506 * @param bool $complete Should it be a complete check or a simple check?
3508 * @return array|bool Reshare details or "false" if no reshare
3510 public static function isReshare($body, $complete = true)
3512 $body = trim($body);
3514 // Skip if it isn't a pure repeated messages
3515 // Does it start with a share?
3516 if ((strpos($body, "[share") > 0) && $complete) {
3520 // Does it end with a share?
3521 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3525 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3526 // Skip if there is no shared message in there
3527 if ($body == $attributes) {
3531 // If we don't do the complete check we quit here
3537 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3538 if ($matches[1] != "") {
3539 $guid = $matches[1];
3542 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3543 if ($matches[1] != "") {
3544 $guid = $matches[1];
3549 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3556 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3557 $ret["root_guid"] = $guid;
3563 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3564 if ($matches[1] != "") {
3565 $profile = $matches[1];
3568 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3569 if ($matches[1] != "") {
3570 $profile = $matches[1];
3575 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3576 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3581 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3582 if ($matches[1] != "") {
3583 $link = $matches[1];
3586 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3587 if ($matches[1] != "") {
3588 $link = $matches[1];
3591 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3592 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3600 * @brief Create an event array
3602 * @param integer $event_id The id of the event
3604 * @return array with event data
3606 private static function buildEvent($event_id)
3608 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3609 if (!DBM::is_result($r)) {
3617 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3618 if (!DBM::is_result($r)) {
3624 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3625 if (!DBM::is_result($r)) {
3631 $eventdata['author'] = self::myHandle($owner);
3633 if ($event['guid']) {
3634 $eventdata['guid'] = $event['guid'];
3637 $mask = DateTimeFormat::ATOM;
3639 /// @todo - establish "all day" events in Friendica
3640 $eventdata["all_day"] = "false";
3642 if (!$event['adjust']) {
3643 $eventdata['timezone'] = $user['timezone'];
3645 if ($eventdata['timezone'] == "") {
3646 $eventdata['timezone'] = 'UTC';
3650 if ($event['start']) {
3651 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3653 if ($event['finish'] && !$event['nofinish']) {
3654 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3656 if ($event['summary']) {
3657 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3659 if ($event['desc']) {
3660 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3662 if ($event['location']) {
3663 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3664 $coord = Map::getCoordinates($event['location']);
3667 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3668 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3669 $location["lat"] = $coord['lat'];
3670 $location["lng"] = $coord['lon'];
3672 $location["lat"] = 0;
3673 $location["lng"] = 0;
3675 $eventdata['location'] = $location;
3682 * @brief Create a post (status message or reshare)
3684 * @param array $item The item that will be exported
3685 * @param array $owner the array of the item owner
3688 * 'type' -> Message type ("status_message" or "reshare")
3689 * 'message' -> Array of XML elements of the status
3691 public static function buildStatus($item, $owner)
3693 $cachekey = "diaspora:buildStatus:".$item['guid'];
3695 $result = Cache::get($cachekey);
3696 if (!is_null($result)) {
3700 $myaddr = self::myHandle($owner);
3702 $public = (($item["private"]) ? "false" : "true");
3704 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3706 // Detect a share element and do a reshare
3707 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3708 $message = ["author" => $myaddr,
3709 "guid" => $item["guid"],
3710 "created_at" => $created,
3711 "root_author" => $ret["root_handle"],
3712 "root_guid" => $ret["root_guid"],
3713 "provider_display_name" => $item["app"],
3714 "public" => $public];
3718 $title = $item["title"];
3719 $body = $item["body"];
3721 // convert to markdown
3722 $body = html_entity_decode(BBCode::toMarkdown($body));
3725 if (strlen($title)) {
3726 $body = "## ".html_entity_decode($title)."\n\n".$body;
3729 if ($item["attach"]) {
3730 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3732 $body .= "\n".L10n::t("Attachments:")."\n";
3733 foreach ($matches as $mtch) {
3734 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3741 if ($item["location"] != "")
3742 $location["address"] = $item["location"];
3744 if ($item["coord"] != "") {
3745 $coord = explode(" ", $item["coord"]);
3746 $location["lat"] = $coord[0];
3747 $location["lng"] = $coord[1];
3750 $message = ["author" => $myaddr,
3751 "guid" => $item["guid"],
3752 "created_at" => $created,
3753 "public" => $public,
3755 "provider_display_name" => $item["app"],
3756 "location" => $location];
3758 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3759 if (!isset($location["lat"]) || !isset($location["lng"])) {
3760 unset($message["location"]);
3763 if ($item['event-id'] > 0) {
3764 $event = self::buildEvent($item['event-id']);
3765 if (count($event)) {
3766 $message['event'] = $event;
3768 if (!empty($event['location']['address']) &&
3769 !empty($event['location']['lat']) &&
3770 !empty($event['location']['lng'])) {
3771 $message['location'] = $event['location'];
3774 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3775 // $message['text'] = '';
3779 $type = "status_message";
3782 $msg = ["type" => $type, "message" => $message];
3784 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3790 * @brief Sends a post
3792 * @param array $item The item that will be exported
3793 * @param array $owner the array of the item owner
3794 * @param array $contact Target of the communication
3795 * @param bool $public_batch Is it a public post?
3797 * @return int The result of the transmission
3799 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3801 $status = self::buildStatus($item, $owner);
3803 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3807 * @brief Creates a "like" object
3809 * @param array $item The item that will be exported
3810 * @param array $owner the array of the item owner
3812 * @return array The data for a "like"
3814 private static function constructLike($item, $owner)
3817 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3818 dbesc($item["thr-parent"])
3820 if (!DBM::is_result($p)) {
3826 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3828 if ($item['verb'] === ACTIVITY_LIKE) {
3830 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3831 $positive = "false";
3834 return(["author" => self::myHandle($owner),
3835 "guid" => $item["guid"],
3836 "parent_guid" => $parent["guid"],
3837 "parent_type" => $target_type,
3838 "positive" => $positive,
3839 "author_signature" => ""]);
3843 * @brief Creates an "EventParticipation" object
3845 * @param array $item The item that will be exported
3846 * @param array $owner the array of the item owner
3848 * @return array The data for an "EventParticipation"
3850 private static function constructAttend($item, $owner)
3853 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3854 dbesc($item["thr-parent"])
3856 if (!DBM::is_result($p)) {
3862 switch ($item['verb']) {
3863 case ACTIVITY_ATTEND:
3864 $attend_answer = 'accepted';
3866 case ACTIVITY_ATTENDNO:
3867 $attend_answer = 'declined';
3869 case ACTIVITY_ATTENDMAYBE:
3870 $attend_answer = 'tentative';
3873 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3877 return(["author" => self::myHandle($owner),
3878 "guid" => $item["guid"],
3879 "parent_guid" => $parent["guid"],
3880 "status" => $attend_answer,
3881 "author_signature" => ""]);
3885 * @brief Creates the object for a comment
3887 * @param array $item The item that will be exported
3888 * @param array $owner the array of the item owner
3890 * @return array The data for a comment
3892 private static function constructComment($item, $owner)
3894 $cachekey = "diaspora:constructComment:".$item['guid'];
3896 $result = Cache::get($cachekey);
3897 if (!is_null($result)) {
3902 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3903 intval($item["parent"]),
3904 intval($item["parent"])
3907 if (!DBM::is_result($p)) {
3913 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3914 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3916 $comment = ["author" => self::myHandle($owner),
3917 "guid" => $item["guid"],
3918 "created_at" => $created,
3919 "parent_guid" => $parent["guid"],
3921 "author_signature" => ""];
3923 // Send the thread parent guid only if it is a threaded comment
3924 if ($item['thr-parent'] != $item['parent-uri']) {
3925 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3928 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3934 * @brief Send a like or a comment
3936 * @param array $item The item that will be exported
3937 * @param array $owner the array of the item owner
3938 * @param array $contact Target of the communication
3939 * @param bool $public_batch Is it a public post?
3941 * @return int The result of the transmission
3943 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3945 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3946 $message = self::constructAttend($item, $owner);
3947 $type = "event_participation";
3948 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3949 $message = self::constructLike($item, $owner);
3952 $message = self::constructComment($item, $owner);
3960 $message["author_signature"] = self::signature($owner, $message);
3962 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3966 * @brief Creates a message from a signature record entry
3968 * @param array $item The item that will be exported
3969 * @param array $signature The entry of the "sign" record
3971 * @return string The message
3973 private static function messageFromSignature($item, $signature)
3975 // Split the signed text
3976 $signed_parts = explode(";", $signature['signed_text']);
3978 if ($item["deleted"]) {
3979 $message = ["author" => $signature['signer'],
3980 "target_guid" => $signed_parts[0],
3981 "target_type" => $signed_parts[1]];
3982 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3983 $message = ["author" => $signed_parts[4],
3984 "guid" => $signed_parts[1],
3985 "parent_guid" => $signed_parts[3],
3986 "parent_type" => $signed_parts[2],
3987 "positive" => $signed_parts[0],
3988 "author_signature" => $signature['signature'],
3989 "parent_author_signature" => ""];
3991 // Remove the comment guid
3992 $guid = array_shift($signed_parts);
3994 // Remove the parent guid
3995 $parent_guid = array_shift($signed_parts);
3997 // Remove the handle
3998 $handle = array_pop($signed_parts);
4000 // Glue the parts together
4001 $text = implode(";", $signed_parts);
4003 $message = ["author" => $handle,
4005 "parent_guid" => $parent_guid,
4006 "text" => implode(";", $signed_parts),
4007 "author_signature" => $signature['signature'],
4008 "parent_author_signature" => ""];
4014 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
4016 * @param array $item The item that will be exported
4017 * @param array $owner the array of the item owner
4018 * @param array $contact Target of the communication
4019 * @param bool $public_batch Is it a public post?
4021 * @return int The result of the transmission
4023 public static function sendRelay($item, $owner, $contact, $public_batch = false)
4025 if ($item["deleted"]) {
4026 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4027 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4033 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4035 // fetch the original signature
4038 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4043 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4049 // Old way - is used by the internal Friendica functions
4050 /// @todo Change all signatur storing functions to the new format
4051 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4052 $message = self::messageFromSignature($item, $signature);
4054 $msg = json_decode($signature['signed_text'], true);
4057 if (is_array($msg)) {
4058 foreach ($msg as $field => $data) {
4059 if (!$item["deleted"]) {
4060 if ($field == "diaspora_handle") {
4063 if ($field == "target_type") {
4064 $field = "parent_type";
4068 $message[$field] = $data;
4071 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4075 $message["parent_author_signature"] = self::signature($owner, $message);
4077 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4079 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4083 * @brief Sends a retraction (deletion) of a message, like or comment
4085 * @param array $item The item that will be exported
4086 * @param array $owner the array of the item owner
4087 * @param array $contact Target of the communication
4088 * @param bool $public_batch Is it a public post?
4089 * @param bool $relay Is the retraction transmitted from a relay?
4091 * @return int The result of the transmission
4093 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4095 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4097 $msg_type = "retraction";
4099 if ($item['id'] == $item['parent']) {
4100 $target_type = "Post";
4101 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4102 $target_type = "Like";
4104 $target_type = "Comment";
4107 $message = ["author" => $itemaddr,
4108 "target_guid" => $item['guid'],
4109 "target_type" => $target_type];
4111 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4113 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4117 * @brief Sends a mail
4119 * @param array $item The item that will be exported
4120 * @param array $owner The owner
4121 * @param array $contact Target of the communication
4123 * @return int The result of the transmission
4125 public static function sendMail($item, $owner, $contact)
4127 $myaddr = self::myHandle($owner);
4130 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4131 intval($item["convid"]),
4132 intval($item["uid"])
4135 if (!DBM::is_result($r)) {
4136 logger("conversation not found.");
4142 "author" => $cnv["creator"],
4143 "guid" => $cnv["guid"],
4144 "subject" => $cnv["subject"],
4145 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4146 "participants" => $cnv["recips"]
4149 $body = BBCode::toMarkdown($item["body"]);
4150 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4153 "author" => $myaddr,
4154 "guid" => $item["guid"],
4155 "conversation_guid" => $cnv["guid"],
4157 "created_at" => $created,
4160 if ($item["reply"]) {
4165 "author" => $cnv["creator"],
4166 "guid" => $cnv["guid"],
4167 "subject" => $cnv["subject"],
4168 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4169 "participants" => $cnv["recips"],
4172 $type = "conversation";
4175 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4179 * @brief Split a name into first name and last name
4181 * @param string $name The name
4183 * @return array The array with "first" and "last"
4185 public static function splitName($name) {
4186 $name = trim($name);
4188 // Is the name longer than 64 characters? Then cut the rest of it.
4189 if (strlen($name) > 64) {
4190 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4191 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4193 $name = substr($name, 0, 64);
4197 // Take the first word as first name
4198 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4199 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4200 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4201 return ['first' => $first, 'last' => $last];
4204 // Take the last word as last name
4205 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4206 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4208 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4209 return ['first' => $first, 'last' => $last];
4212 // Take the first 32 characters if there is no space in the first 32 characters
4213 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4214 $first = substr($name, 0, 32);
4215 $last = substr($name, 32);
4216 return ['first' => $first, 'last' => $last];
4219 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4220 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4222 // Check if the last name is longer than 32 characters
4223 if (strlen($last) > 32) {
4224 if (strpos($last, ' ') <= 32) {
4225 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4227 $last = substr($last, 0, 32);
4231 return ['first' => $first, 'last' => $last];
4235 * @brief Create profile data
4237 * @param int $uid The user id
4239 * @return array The profile data
4241 private static function createProfileData($uid)
4244 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4246 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4247 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4248 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4257 $handle = $profile["addr"];
4259 $split_name = self::splitName($profile['name']);
4260 $first = $split_name['first'];
4261 $last = $split_name['last'];
4263 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4264 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4265 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4266 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4272 if ($searchable === 'true') {
4275 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4276 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4280 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4283 $about = $profile['about'];
4284 $about = strip_tags(BBCode::convert($about));
4286 $location = Profile::formatLocation($profile);
4288 if ($profile['pub_keywords']) {
4289 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4290 $kw = str_replace(' ', ' ', $kw);
4291 $arr = explode(' ', $profile['pub_keywords']);
4293 for ($x = 0; $x < 5; $x ++) {
4294 if (trim($arr[$x])) {
4295 $tags .= '#'. trim($arr[$x]) .' ';
4300 $tags = trim($tags);
4303 return ["author" => $handle,
4304 "first_name" => $first,
4305 "last_name" => $last,
4306 "image_url" => $large,
4307 "image_url_medium" => $medium,
4308 "image_url_small" => $small,
4310 "gender" => $profile['gender'],
4312 "location" => $location,
4313 "searchable" => $searchable,
4315 "tag_string" => $tags];
4319 * @brief Sends profile data
4321 * @param int $uid The user id
4322 * @param bool $recips optional, default false
4325 public static function sendProfile($uid, $recips = false)
4331 $owner = User::getOwnerDataById($uid);
4338 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4339 AND `uid` = %d AND `rel` != %d",
4340 dbesc(NETWORK_DIASPORA),
4342 intval(CONTACT_IS_SHARING)
4350 $message = self::createProfileData($uid);
4352 foreach ($recips as $recip) {
4353 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4354 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4359 * @brief Stores the signature for likes that are created on our system
4361 * @param array $contact The contact array of the "like"
4362 * @param int $post_id The post id of the "like"
4364 * @return bool Success
4366 public static function storeLikeSignature($contact, $post_id)
4368 // Is the contact the owner? Then fetch the private key
4369 if (!$contact['self'] || ($contact['uid'] == 0)) {
4370 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4374 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4375 if (!DBM::is_result($r)) {
4379 $contact["uprvkey"] = $r[0]['prvkey'];
4381 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4382 if (!DBM::is_result($r)) {
4386 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4390 $message = self::constructLike($r[0], $contact);
4391 if ($message === false) {
4395 $message["author_signature"] = self::signature($contact, $message);
4398 * Now store the signature more flexible to dynamically support new fields.
4399 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4401 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4403 logger('Stored diaspora like signature');
4408 * @brief Stores the signature for comments that are created on our system
4410 * @param array $item The item array of the comment
4411 * @param array $contact The contact array of the item owner
4412 * @param string $uprvkey The private key of the sender
4413 * @param int $message_id The message id of the comment
4415 * @return bool Success
4417 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4419 if ($uprvkey == "") {
4420 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4424 $contact["uprvkey"] = $uprvkey;
4426 $message = self::constructComment($item, $contact);
4427 if ($message === false) {
4431 $message["author_signature"] = self::signature($contact, $message);
4434 * Now store the signature more flexible to dynamically support new fields.
4435 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4437 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4439 logger('Stored diaspora comment signature');