3 * @file src/Protocol/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\Markdown;
15 use Friendica\Core\Cache;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\Queue;
28 use Friendica\Model\User;
29 use Friendica\Network\Probe;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
34 use Friendica\Util\Map;
38 require_once 'include/dba.php';
39 require_once 'include/items.php';
42 * @brief This class contain functions to create and send Diaspora XML files
48 * @brief Return a list of relay servers
50 * The list contains not only the official relays but also servers that we serve directly
52 * @param integer $item_id The id of the item that is sent
53 * @return array of relay servers
55 public static function relayList($item_id)
59 // Fetching relay servers
60 $serverdata = Config::get("system", "relay_server");
61 if ($serverdata != "") {
62 $servers = explode(",", $serverdata);
63 foreach ($servers as $server) {
64 $serverlist[$server] = trim($server);
68 if (Config::get("system", "relay_directly", false)) {
69 // Servers that want to get all content
70 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
71 while ($server = dba::fetch($servers)) {
72 $serverlist[$server['url']] = $server['url'];
75 // All tags of the current post
76 $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $item_id];
77 $tags = dba::select('term', ['term'], $condition);
79 while ($tag = dba::fetch($tags)) {
80 $taglist[] = $tag['term'];
83 // All servers who wants content with this tag
85 if (!empty($taglist)) {
86 $tagserver = dba::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
87 while ($server = dba::fetch($tagserver)) {
88 $tagserverlist[] = $server['gserver-id'];
92 // All adresses with the given id
93 if (!empty($tagserverlist)) {
94 $servers = dba::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
95 while ($server = dba::fetch($servers)) {
96 $serverlist[$server['url']] = $server['url'];
101 // Now we are collecting all relay contacts
103 foreach ($serverlist as $server_url) {
104 // We don't send messages to ourselves
105 if (!link_compare($server_url, System::baseUrl())) {
106 $contacts[] = self::getRelayContactId($server_url);
114 * @brief Return a contact for a given server address or creates a dummy entry
116 * @param string $server_url The url of the server
117 * @return array with the contact
119 private static function getRelayContactId($server_url)
121 $batch = $server_url . '/receive/public';
123 $fields = ['batch', 'id', 'name', 'network'];
124 $condition = ['uid' => 0, 'network' => NETWORK_DIASPORA, 'batch' => $batch,
125 'archive' => false, 'blocked' => false];
126 $contact = dba::selectFirst('contact', $fields, $condition);
127 if (DBM::is_result($contact)) {
130 $fields = ['uid' => 0, 'created' => DateTimeFormat::utcNow(),
131 'name' => 'relay', 'nick' => 'relay',
132 'url' => $server_url, 'nurl' => normalise_link($server_url),
133 'batch' => $batch, 'network' => NETWORK_DIASPORA,
134 'rel' => CONTACT_IS_FOLLOWER, 'blocked' => false,
135 'pending' => false, 'writable' => true];
136 dba::insert('contact', $fields);
138 $fields = ['batch', 'id', 'name', 'network'];
139 $contact = dba::selectFirst('contact', $fields, $condition);
140 if (DBM::is_result($contact)) {
146 // It should never happen that we arrive here
151 * @brief Return a list of participating contacts for a thread
153 * This is used for the participation feature.
154 * One of the parameters is a contact array.
155 * This is done to avoid duplicates.
157 * @param integer $thread The id of the thread
158 * @param array $contacts The previously fetched contacts
160 * @return array of relay servers
162 public static function participantsForThread($thread, $contacts)
164 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
165 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
166 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
167 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
168 WHERE `participation`.`iid` = ?", $thread);
170 while ($contact = dba::fetch($r)) {
171 if (!empty($contact['fnetwork'])) {
172 $contact['network'] = $contact['fnetwork'];
174 unset($contact['fnetwork']);
176 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
177 $contact['batch'] = $contact['fbatch'];
179 unset($contact['fbatch']);
182 foreach ($contacts as $entry) {
183 if ($entry['batch'] == $contact['batch']) {
189 $contacts[] = $contact;
198 * @brief repairs a signature that was double encoded
200 * The function is unused at the moment. It was copied from the old implementation.
202 * @param string $signature The signature
203 * @param string $handle The handle of the signature owner
204 * @param integer $level This value is only set inside this function to avoid endless loops
206 * @return string the repaired signature
208 private static function repairSignature($signature, $handle = "", $level = 1)
210 if ($signature == "") {
214 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
215 $signature = base64_decode($signature);
216 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
218 // Do a recursive call to be able to fix even multiple levels
220 $signature = self::repairSignature($signature, $handle, ++$level);
228 * @brief verify the envelope and return the verified data
230 * @param string $envelope The magic envelope
232 * @return string verified data
234 private static function verifyMagicEnvelope($envelope)
236 $basedom = XML::parseString($envelope);
238 if (!is_object($basedom)) {
239 logger("Envelope is no XML file");
243 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
245 if (sizeof($children) == 0) {
246 logger("XML has no children");
252 $data = base64url_decode($children->data);
253 $type = $children->data->attributes()->type[0];
255 $encoding = $children->encoding;
257 $alg = $children->alg;
259 $sig = base64url_decode($children->sig);
260 $key_id = $children->sig->attributes()->key_id[0];
262 $handle = base64url_decode($key_id);
265 $b64url_data = base64url_encode($data);
266 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
268 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
271 logger('No author could be decoded. Discarding. Message: ' . $envelope);
275 $key = self::key($handle);
277 logger("Couldn't get a key for handle " . $handle . ". Discarding.");
281 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
283 logger('Message from ' . $handle . ' did not verify. Discarding.');
291 * @brief encrypts data via AES
293 * @param string $key The AES key
294 * @param string $iv The IV (is used for CBC encoding)
295 * @param string $data The data that is to be encrypted
297 * @return string encrypted data
299 private static function aesEncrypt($key, $iv, $data)
301 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
305 * @brief decrypts data via AES
307 * @param string $key The AES key
308 * @param string $iv The IV (is used for CBC encoding)
309 * @param string $encrypted The encrypted data
311 * @return string decrypted data
313 private static function aesDecrypt($key, $iv, $encrypted)
315 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
319 * @brief: Decodes incoming Diaspora message in the new format
321 * @param array $importer Array of the importer user
322 * @param string $raw raw post message
325 * 'message' -> decoded Diaspora XML message
326 * 'author' -> author diaspora handle
327 * 'key' -> author public key (converted to pkcs#8)
329 public static function decodeRaw($importer, $raw)
331 $data = json_decode($raw);
333 // Is it a private post? Then decrypt the outer Salmon
334 if (is_object($data)) {
335 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
336 $ciphertext = base64_decode($data->encrypted_magic_envelope);
338 $outer_key_bundle = '';
339 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
340 $j_outer_key_bundle = json_decode($outer_key_bundle);
342 if (!is_object($j_outer_key_bundle)) {
343 logger('Outer Salmon did not verify. Discarding.');
344 System::httpExit(400);
347 $outer_iv = base64_decode($j_outer_key_bundle->iv);
348 $outer_key = base64_decode($j_outer_key_bundle->key);
350 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
355 $basedom = XML::parseString($xml);
357 if (!is_object($basedom)) {
358 logger('Received data does not seem to be an XML. Discarding. '.$xml);
359 System::httpExit(400);
362 $base = $basedom->children(NAMESPACE_SALMON_ME);
364 // Not sure if this cleaning is needed
365 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
367 // Build the signed data
368 $type = $base->data[0]->attributes()->type[0];
369 $encoding = $base->encoding;
371 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
373 // This is the signature
374 $signature = base64url_decode($base->sig);
376 // Get the senders' public key
377 $key_id = $base->sig[0]->attributes()->key_id[0];
378 $author_addr = base64_decode($key_id);
379 if ($author_addr == '') {
380 logger('No author could be decoded. Discarding. Message: ' . $xml);
381 System::httpExit(400);
384 $key = self::key($author_addr);
386 logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
387 System::httpExit(400);
390 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
392 logger('Message did not verify. Discarding.');
393 System::httpExit(400);
396 return ['message' => (string)base64url_decode($base->data),
397 'author' => unxmlify($author_addr),
398 'key' => (string)$key];
402 * @brief: Decodes incoming Diaspora message in the deprecated format
404 * @param array $importer Array of the importer user
405 * @param string $xml urldecoded Diaspora salmon
408 * 'message' -> decoded Diaspora XML message
409 * 'author' -> author diaspora handle
410 * 'key' -> author public key (converted to pkcs#8)
412 public static function decode($importer, $xml)
415 $basedom = XML::parseString($xml);
417 if (!is_object($basedom)) {
418 logger("XML is not parseable.");
421 $children = $basedom->children('https://joindiaspora.com/protocol');
423 $inner_aes_key = null;
426 if ($children->header) {
428 $author_link = str_replace('acct:', '', $children->header->author_id);
430 // This happens with posts from a relais
432 logger("This is no private post in the old format", LOGGER_DEBUG);
436 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
438 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
439 $ciphertext = base64_decode($encrypted_header->ciphertext);
441 $outer_key_bundle = '';
442 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
444 $j_outer_key_bundle = json_decode($outer_key_bundle);
446 $outer_iv = base64_decode($j_outer_key_bundle->iv);
447 $outer_key = base64_decode($j_outer_key_bundle->key);
449 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
451 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
452 $idom = XML::parseString($decrypted);
454 $inner_iv = base64_decode($idom->iv);
455 $inner_aes_key = base64_decode($idom->aes_key);
457 $author_link = str_replace('acct:', '', $idom->author_id);
460 $dom = $basedom->children(NAMESPACE_SALMON_ME);
462 // figure out where in the DOM tree our data is hiding
465 if ($dom->provenance->data) {
466 $base = $dom->provenance;
467 } elseif ($dom->env->data) {
469 } elseif ($dom->data) {
474 logger('unable to locate salmon data in xml');
475 System::httpExit(400);
479 // Stash the signature away for now. We have to find their key or it won't be good for anything.
480 $signature = base64url_decode($base->sig);
484 // strip whitespace so our data element will return to one big base64 blob
485 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
488 // stash away some other stuff for later
490 $type = $base->data[0]->attributes()->type[0];
491 $keyhash = $base->sig[0]->attributes()->keyhash[0];
492 $encoding = $base->encoding;
496 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
500 $data = base64url_decode($data);
504 $inner_decrypted = $data;
506 // Decode the encrypted blob
507 $inner_encrypted = base64_decode($data);
508 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
512 logger('Could not retrieve author URI.');
513 System::httpExit(400);
515 // Once we have the author URI, go to the web and try to find their public key
516 // (first this will look it up locally if it is in the fcontact cache)
517 // This will also convert diaspora public key from pkcs#1 to pkcs#8
519 logger('Fetching key for '.$author_link);
520 $key = self::key($author_link);
523 logger('Could not retrieve author key.');
524 System::httpExit(400);
527 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
530 logger('Message did not verify. Discarding.');
531 System::httpExit(400);
534 logger('Message verified.');
536 return ['message' => (string)$inner_decrypted,
537 'author' => unxmlify($author_link),
538 'key' => (string)$key];
543 * @brief Dispatches public messages and find the fitting receivers
545 * @param array $msg The post that will be dispatched
547 * @return int The message id of the generated message, "true" or "false" if there was an error
549 public static function dispatchPublic($msg)
551 $enabled = intval(Config::get("system", "diaspora_enabled"));
553 logger("diaspora is disabled");
557 if (!($postdata = self::validPosting($msg))) {
558 logger("Invalid posting");
562 $fields = $postdata['fields'];
564 // Is it a an action (comment, like, ...) for our own post?
565 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
566 $guid = notags(unxmlify($fields->parent_guid));
567 $importer = self::importerForGuid($guid);
568 if (is_array($importer)) {
569 logger("delivering to origin: ".$importer["name"]);
570 $message_id = self::dispatch($importer, $msg, $fields);
575 // Process item retractions. This has to be done separated from the other stuff,
576 // since retractions for comments could come even from non followers.
577 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
578 $target = notags(unxmlify($fields->target_type));
579 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
580 logger('processing retraction for '.$target, LOGGER_DEBUG);
581 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
582 $message_id = self::dispatch($importer, $msg, $fields);
587 // Now distribute it to the followers
589 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
590 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
591 AND NOT `account_expired` AND NOT `account_removed`",
592 dbesc(NETWORK_DIASPORA),
593 dbesc($msg["author"])
596 if (DBM::is_result($r)) {
597 foreach ($r as $rr) {
598 logger("delivering to: ".$rr["username"]);
599 self::dispatch($rr, $msg, $fields);
601 } elseif (!Config::get('system', 'relay_subscribe', false)) {
602 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
604 // Use a dummy importer to import the data for the public copy
605 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
606 $message_id = self::dispatch($importer, $msg, $fields);
613 * @brief Dispatches the different message types to the different functions
615 * @param array $importer Array of the importer user
616 * @param array $msg The post that will be dispatched
617 * @param object $fields SimpleXML object that contains the message
619 * @return int The message id of the generated message, "true" or "false" if there was an error
621 public static function dispatch($importer, $msg, $fields = null)
623 // The sender is the handle of the contact that sent the message.
624 // This will often be different with relayed messages (for example "like" and "comment")
625 $sender = $msg["author"];
627 // This is only needed for private postings since this is already done for public ones before
628 if (is_null($fields)) {
629 if (!($postdata = self::validPosting($msg))) {
630 logger("Invalid posting");
633 $fields = $postdata['fields'];
636 $type = $fields->getName();
638 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
641 case "account_migration":
642 return self::receiveAccountMigration($importer, $fields);
644 case "account_deletion":
645 return self::receiveAccountDeletion($importer, $fields);
648 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
651 return self::receiveContactRequest($importer, $fields);
654 return self::receiveConversation($importer, $msg, $fields);
657 return self::receiveLike($importer, $sender, $fields);
660 return self::receiveMessage($importer, $fields);
662 case "participation":
663 return self::receiveParticipation($importer, $fields);
665 case "photo": // Not implemented
666 return self::receivePhoto($importer, $fields);
668 case "poll_participation": // Not implemented
669 return self::receivePollParticipation($importer, $fields);
672 return self::receiveProfile($importer, $fields);
675 return self::receiveReshare($importer, $fields, $msg["message"]);
678 return self::receiveRetraction($importer, $sender, $fields);
680 case "status_message":
681 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
684 logger("Unknown message type ".$type);
692 * @brief Checks if a posting is valid and fetches the data fields.
694 * This function does not only check the signature.
695 * It also does the conversion between the old and the new diaspora format.
697 * @param array $msg Array with the XML, the sender handle and the sender signature
699 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
701 private static function validPosting($msg)
703 $data = XML::parseString($msg["message"]);
705 if (!is_object($data)) {
706 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
710 // Is this the new or the old version?
711 if ($data->getName() == "XML") {
713 foreach ($data->post->children() as $child) {
721 $type = $element->getName();
724 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
726 // All retractions are handled identically from now on.
727 // In the new version there will only be "retraction".
728 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
729 $type = "retraction";
731 if ($type == "request") {
735 $fields = new SimpleXMLElement("<".$type."/>");
738 $author_signature = null;
739 $parent_author_signature = null;
741 foreach ($element->children() as $fieldname => $entry) {
743 // Translation for the old XML structure
744 if ($fieldname == "diaspora_handle") {
745 $fieldname = "author";
747 if ($fieldname == "participant_handles") {
748 $fieldname = "participants";
750 if (in_array($type, ["like", "participation"])) {
751 if ($fieldname == "target_type") {
752 $fieldname = "parent_type";
755 if ($fieldname == "sender_handle") {
756 $fieldname = "author";
758 if ($fieldname == "recipient_handle") {
759 $fieldname = "recipient";
761 if ($fieldname == "root_diaspora_id") {
762 $fieldname = "root_author";
764 if ($type == "status_message") {
765 if ($fieldname == "raw_message") {
769 if ($type == "retraction") {
770 if ($fieldname == "post_guid") {
771 $fieldname = "target_guid";
773 if ($fieldname == "type") {
774 $fieldname = "target_type";
779 if (($fieldname == "author_signature") && ($entry != "")) {
780 $author_signature = base64_decode($entry);
781 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
782 $parent_author_signature = base64_decode($entry);
783 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
784 if ($signed_data != "") {
788 $signed_data .= $entry;
790 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
791 || ($orig_type == "relayable_retraction")
793 XML::copy($entry, $fields, $fieldname);
797 // This is something that shouldn't happen at all.
798 if (in_array($type, ["status_message", "reshare", "profile"])) {
799 if ($msg["author"] != $fields->author) {
800 logger("Message handle is not the same as envelope sender. Quitting this message.");
805 // Only some message types have signatures. So we quit here for the other types.
806 if (!in_array($type, ["comment", "like"])) {
807 return ["fields" => $fields, "relayed" => false];
809 // No author_signature? This is a must, so we quit.
810 if (!isset($author_signature)) {
811 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
815 if (isset($parent_author_signature)) {
818 $key = self::key($msg["author"]);
820 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
821 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);
828 $key = self::key($fields->author);
830 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
831 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
834 return ["fields" => $fields, "relayed" => $relayed];
839 * @brief Fetches the public key for a given handle
841 * @param string $handle The handle
843 * @return string The public key
845 private static function key($handle)
847 $handle = strval($handle);
849 logger("Fetching diaspora key for: ".$handle);
851 $r = self::personByHandle($handle);
860 * @brief Fetches data for a given handle
862 * @param string $handle The handle
864 * @return array the queried data
866 public static function personByHandle($handle)
870 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
871 if (DBM::is_result($person)) {
872 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
874 // update record occasionally so it doesn't get stale
875 $d = strtotime($person["updated"]." +00:00");
876 if ($d < strtotime("now - 14 days")) {
880 if ($person["guid"] == "") {
885 if (!DBM::is_result($person) || $update) {
886 logger("create or refresh", LOGGER_DEBUG);
887 $r = Probe::uri($handle, NETWORK_DIASPORA);
889 // Note that Friendica contacts will return a "Diaspora person"
890 // if Diaspora connectivity is enabled on their server
891 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
892 self::addFContact($r, $update);
894 // Fetch the updated or added contact
895 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
896 if (!DBM::is_result($person)) {
906 * @brief Updates the fcontact table
908 * @param array $arr The fcontact data
909 * @param bool $update Update or insert?
911 * @return string The id of the fcontact entry
913 private static function addFContact($arr, $update = false)
917 "UPDATE `fcontact` SET
931 WHERE `url` = '%s' AND `network` = '%s'",
933 dbesc($arr["photo"]),
934 dbesc($arr["request"]),
936 dbesc(strtolower($arr["addr"])),
938 dbesc($arr["batch"]),
939 dbesc($arr["notify"]),
941 dbesc($arr["confirm"]),
942 dbesc($arr["alias"]),
943 dbesc($arr["pubkey"]),
944 dbesc(DateTimeFormat::utcNow()),
946 dbesc($arr["network"])
950 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
951 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
952 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
955 dbesc($arr["photo"]),
956 dbesc($arr["request"]),
960 dbesc($arr["batch"]),
961 dbesc($arr["notify"]),
963 dbesc($arr["confirm"]),
964 dbesc($arr["network"]),
965 dbesc($arr["alias"]),
966 dbesc($arr["pubkey"]),
967 dbesc(DateTimeFormat::utcNow())
975 * @brief get a handle (user@domain.tld) from a given contact id
977 * @param int $contact_id The id in the contact table
978 * @param int $pcontact_id The id in the contact table (Used for the public contact)
980 * @return string the handle
982 private static function handleFromContact($contact_id, $pcontact_id = 0)
986 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
988 if ($pcontact_id != 0) {
990 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
994 if (DBM::is_result($r)) {
995 return strtolower($r[0]["addr"]);
1000 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1004 if (DBM::is_result($r)) {
1007 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
1009 if ($contact['addr'] != "") {
1010 $handle = $contact['addr'];
1012 $baseurl_start = strpos($contact['url'], '://') + 3;
1013 // allows installations in a subdirectory--not sure how Diaspora will handle
1014 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1015 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1016 $handle = $contact['nick'].'@'.$baseurl;
1020 return strtolower($handle);
1024 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1027 * @param mixed $fcontact_guid Hexadecimal string guid
1029 * @return string the contact url or null
1031 public static function urlFromContactGuid($fcontact_guid)
1033 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1036 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1037 dbesc(NETWORK_DIASPORA),
1038 dbesc($fcontact_guid)
1041 if (DBM::is_result($r)) {
1042 return $r[0]['url'];
1049 * @brief Get a contact id for a given handle
1051 * @todo Move to Friendica\Model\Contact
1053 * @param int $uid The user id
1054 * @param string $handle The handle in the format user@domain.tld
1056 * @return int Contact id
1058 private static function contactByHandle($uid, $handle)
1060 // First do a direct search on the contact table
1062 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1067 if (DBM::is_result($r)) {
1071 * We haven't found it?
1072 * We use another function for it that will possibly create a contact entry.
1074 $cid = Contact::getIdForURL($handle, $uid);
1077 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1078 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1080 if (DBM::is_result($r)) {
1086 $handle_parts = explode("@", $handle);
1087 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1089 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1090 dbesc(NETWORK_DFRN),
1094 if (DBM::is_result($r)) {
1098 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1103 * @brief Check if posting is allowed for this contact
1105 * @param array $importer Array of the importer user
1106 * @param array $contact The contact that is checked
1107 * @param bool $is_comment Is the check for a comment?
1109 * @return bool is the contact allowed to post?
1111 private static function postAllow($importer, $contact, $is_comment = false)
1114 * Perhaps we were already sharing with this person. Now they're sharing with us.
1115 * That makes us friends.
1116 * Normally this should have handled by getting a request - but this could get lost
1118 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1119 // It is not removed by now. Possibly the code is needed?
1120 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1123 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1124 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1127 // $contact["rel"] = CONTACT_IS_FRIEND;
1128 // logger("defining user ".$contact["nick"]." as friend");
1131 // We don't seem to like that person
1132 if ($contact["blocked"] || $contact["readonly"]) {
1133 // Maybe blocked, don't accept.
1135 // We are following this person?
1136 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1137 // Yes, then it is fine.
1139 // Is it a post to a community?
1140 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1143 // Is the message a global user or a comment?
1144 } elseif (($importer["uid"] == 0) || $is_comment) {
1145 // Messages for the global users and comments are always accepted
1153 * @brief Fetches the contact id for a handle and checks if posting is allowed
1155 * @param array $importer Array of the importer user
1156 * @param string $handle The checked handle in the format user@domain.tld
1157 * @param bool $is_comment Is the check for a comment?
1159 * @return array The contact data
1161 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1163 $contact = self::contactByHandle($importer["uid"], $handle);
1165 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1166 // If a contact isn't found, we accept it anyway if it is a comment
1174 if (!self::postAllow($importer, $contact, $is_comment)) {
1175 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1182 * @brief Does the message already exists on the system?
1184 * @param int $uid The user id
1185 * @param string $guid The guid of the message
1187 * @return int|bool message id if the message already was stored into the system - or false.
1189 private static function messageExists($uid, $guid)
1192 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1197 if (DBM::is_result($r)) {
1198 logger("message ".$guid." already exists for user ".$uid);
1206 * @brief Checks for links to posts in a message
1208 * @param array $item The item array
1211 private static function fetchGuid($item)
1213 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1214 preg_replace_callback(
1216 function ($match) use ($item) {
1217 self::fetchGuidSub($match, $item);
1222 preg_replace_callback(
1223 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1224 function ($match) use ($item) {
1225 self::fetchGuidSub($match, $item);
1232 * @brief Checks for relative /people/* links in an item body to match local
1233 * contacts or prepends the remote host taken from the author link.
1235 * @param string $body The item body to replace links from
1236 * @param string $author_link The author link for missing local contact fallback
1238 * @return string the replaced string
1240 public static function replacePeopleGuid($body, $author_link)
1242 $return = preg_replace_callback(
1243 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1244 function ($match) use ($author_link) {
1246 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1247 // 1 => '0123456789abcdef'
1249 $handle = self::urlFromContactGuid($match[1]);
1252 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1254 // No local match, restoring absolute remote URL from author scheme and host
1255 $author_url = parse_url($author_link);
1256 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1268 * @brief sub function of "fetchGuid" which checks for links in messages
1270 * @param array $match array containing a link that has to be checked for a message link
1271 * @param array $item The item array
1274 private static function fetchGuidSub($match, $item)
1276 if (!self::storeByGuid($match[1], $item["author-link"])) {
1277 self::storeByGuid($match[1], $item["owner-link"]);
1282 * @brief Fetches an item with a given guid from a given server
1284 * @param string $guid the message guid
1285 * @param string $server The server address
1286 * @param int $uid The user id of the user
1288 * @return int the message id of the stored message or false
1290 private static function storeByGuid($guid, $server, $uid = 0)
1292 $serverparts = parse_url($server);
1293 $server = $serverparts["scheme"]."://".$serverparts["host"];
1295 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1297 $msg = self::message($guid, $server);
1303 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1305 // Now call the dispatcher
1306 return self::dispatchPublic($msg);
1310 * @brief Fetches a message from a server
1312 * @param string $guid message guid
1313 * @param string $server The url of the server
1314 * @param int $level Endless loop prevention
1317 * 'message' => The message XML
1318 * 'author' => The author handle
1319 * 'key' => The public key of the author
1321 private static function message($guid, $server, $level = 0)
1327 // This will work for new Diaspora servers and Friendica servers from 3.5
1328 $source_url = $server."/fetch/post/".urlencode($guid);
1330 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1332 $envelope = Network::fetchUrl($source_url);
1334 logger("Envelope was fetched.", LOGGER_DEBUG);
1335 $x = self::verifyMagicEnvelope($envelope);
1337 logger("Envelope could not be verified.", LOGGER_DEBUG);
1339 logger("Envelope was verified.", LOGGER_DEBUG);
1345 // This will work for older Diaspora and Friendica servers
1347 $source_url = $server."/p/".urlencode($guid).".xml";
1348 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1350 $x = Network::fetchUrl($source_url);
1356 $source_xml = XML::parseString($x);
1358 if (!is_object($source_xml)) {
1362 if ($source_xml->post->reshare) {
1363 // Reshare of a reshare - old Diaspora version
1364 logger("Message is a reshare", LOGGER_DEBUG);
1365 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1366 } elseif ($source_xml->getName() == "reshare") {
1367 // Reshare of a reshare - new Diaspora version
1368 logger("Message is a new reshare", LOGGER_DEBUG);
1369 return self::message($source_xml->root_guid, $server, ++$level);
1374 // Fetch the author - for the old and the new Diaspora version
1375 if ($source_xml->post->status_message->diaspora_handle) {
1376 $author = (string)$source_xml->post->status_message->diaspora_handle;
1377 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1378 $author = (string)$source_xml->author;
1381 // If this isn't a "status_message" then quit
1383 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1387 $msg = ["message" => $x, "author" => $author];
1389 $msg["key"] = self::key($msg["author"]);
1395 * @brief Fetches the item record of a given guid
1397 * @param int $uid The user id
1398 * @param string $guid message guid
1399 * @param string $author The handle of the item
1400 * @param array $contact The contact of the item owner
1402 * @return array the item record
1404 private static function parentItem($uid, $guid, $author, $contact)
1407 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1408 `author-name`, `author-link`, `author-avatar`,
1409 `owner-name`, `owner-link`, `owner-avatar`
1410 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1416 $result = self::storeByGuid($guid, $contact["url"], $uid);
1419 $person = self::personByHandle($author);
1420 $result = self::storeByGuid($guid, $person["url"], $uid);
1424 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1427 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1428 `author-name`, `author-link`, `author-avatar`,
1429 `owner-name`, `owner-link`, `owner-avatar`
1430 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1438 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1441 logger("parent item found: parent: ".$guid." - user: ".$uid);
1447 * @brief returns contact details
1449 * @param array $def_contact The default contact if the person isn't found
1450 * @param array $person The record of the person
1451 * @param int $uid The user id
1454 * 'cid' => contact id
1455 * 'network' => network type
1457 private static function authorContactByUrl($def_contact, $person, $uid)
1459 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1460 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1461 if (DBM::is_result($contact)) {
1462 $cid = $contact["id"];
1463 $network = $contact["network"];
1465 $cid = $def_contact["id"];
1466 $network = NETWORK_DIASPORA;
1469 return ["cid" => $cid, "network" => $network];
1473 * @brief Is the profile a hubzilla profile?
1475 * @param string $url The profile link
1477 * @return bool is it a hubzilla server?
1479 public static function isRedmatrix($url)
1481 return(strstr($url, "/channel/"));
1485 * @brief Generate a post link with a given handle and message guid
1487 * @param string $addr The user handle
1488 * @param string $guid message guid
1489 * @param string $parent_guid optional parent guid
1491 * @return string the post link
1493 private static function plink($addr, $guid, $parent_guid = '')
1495 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1498 if (!DBM::is_result($r)) {
1499 if ($parent_guid != '') {
1500 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1502 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1506 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1507 // So we try another way as well.
1508 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1509 if (DBM::is_result($s)) {
1510 $r[0]["network"] = $s[0]["network"];
1513 if ($r[0]["network"] == NETWORK_DFRN) {
1514 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1517 if (self::isRedmatrix($r[0]["url"])) {
1518 return $r[0]["url"]."/?f=&mid=".$guid;
1521 if ($parent_guid != '') {
1522 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1524 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1529 * @brief Receives account migration
1531 * @param array $importer Array of the importer user
1532 * @param object $data The message object
1534 * @return bool Success
1536 private static function receiveAccountMigration($importer, $data)
1538 $old_handle = notags(unxmlify($data->author));
1539 $new_handle = notags(unxmlify($data->profile->author));
1540 $signature = notags(unxmlify($data->signature));
1542 $contact = self::contactByHandle($importer["uid"], $old_handle);
1544 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1548 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1551 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1552 $key = self::key($old_handle);
1553 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1554 logger('No valid signature for migration.');
1558 // Update the profile
1559 self::receiveProfile($importer, $data->profile);
1561 // change the technical stuff in contact and gcontact
1562 $data = Probe::uri($new_handle);
1563 if ($data['network'] == NETWORK_PHANTOM) {
1564 logger('Account for '.$new_handle." couldn't be probed.");
1568 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1569 'name' => $data['name'], 'nick' => $data['nick'],
1570 'addr' => $data['addr'], 'batch' => $data['batch'],
1571 'notify' => $data['notify'], 'poll' => $data['poll'],
1572 'network' => $data['network']];
1574 dba::update('contact', $fields, ['addr' => $old_handle]);
1576 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1577 'name' => $data['name'], 'nick' => $data['nick'],
1578 'addr' => $data['addr'], 'connect' => $data['addr'],
1579 'notify' => $data['notify'], 'photo' => $data['photo'],
1580 'server_url' => $data['baseurl'], 'network' => $data['network']];
1582 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1584 logger('Contacts are updated.');
1587 /// @todo This is an extreme performance killer
1589 'owner-link' => [$contact["url"], $data["url"]],
1590 'author-link' => [$contact["url"], $data["url"]],
1592 foreach ($fields as $n => $f) {
1594 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1597 intval($importer["uid"])
1600 if (DBM::is_result($r)) {
1602 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1607 intval($importer["uid"])
1616 logger('Items are updated.');
1622 * @brief Processes an account deletion
1624 * @param array $importer Array of the importer user
1625 * @param object $data The message object
1627 * @return bool Success
1629 private static function receiveAccountDeletion($importer, $data)
1631 /// @todo Account deletion should remove the contact from the global contacts as well
1633 $author = notags(unxmlify($data->author));
1635 $contact = self::contactByHandle($importer["uid"], $author);
1637 logger("cannot find contact for author: ".$author);
1641 // We now remove the contact
1642 Contact::remove($contact["id"]);
1647 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1649 * @param string $author Author handle
1650 * @param string $guid Message guid
1651 * @param boolean $onlyfound Only return uri when found in the database
1653 * @return string The constructed uri or the one from our database
1655 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1657 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1658 if (DBM::is_result($r)) {
1659 return $r[0]["uri"];
1660 } elseif (!$onlyfound) {
1661 return $author.":".$guid;
1668 * @brief Fetch the guid from our database with a given uri
1670 * @param string $uri Message uri
1671 * @param string $uid Author handle
1673 * @return string The post guid
1675 private static function getGuidFromUri($uri, $uid)
1677 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1678 if (DBM::is_result($r)) {
1679 return $r[0]["guid"];
1686 * @brief Find the best importer for a comment, like, ...
1688 * @param string $guid The guid of the item
1690 * @return array|boolean the origin owner of that post - or false
1692 private static function importerForGuid($guid)
1694 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1696 if (DBM::is_result($item)) {
1697 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1698 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1699 if (DBM::is_result($contact)) {
1707 * @brief Processes an incoming comment
1709 * @param array $importer Array of the importer user
1710 * @param string $sender The sender of the message
1711 * @param object $data The message object
1712 * @param string $xml The original XML of the message
1714 * @return int The message id of the generated comment or "false" if there was an error
1716 private static function receiveComment($importer, $sender, $data, $xml)
1718 $author = notags(unxmlify($data->author));
1719 $guid = notags(unxmlify($data->guid));
1720 $parent_guid = notags(unxmlify($data->parent_guid));
1721 $text = unxmlify($data->text);
1723 if (isset($data->created_at)) {
1724 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1726 $created_at = DateTimeFormat::utcNow();
1729 if (isset($data->thread_parent_guid)) {
1730 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1731 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1736 $contact = self::allowedContactByHandle($importer, $sender, true);
1741 $message_id = self::messageExists($importer["uid"], $guid);
1746 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1747 if (!$parent_item) {
1751 $person = self::personByHandle($author);
1752 if (!is_array($person)) {
1753 logger("unable to find author details");
1757 // Fetch the contact id - if we know this contact
1758 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1762 $datarray["uid"] = $importer["uid"];
1763 $datarray["contact-id"] = $author_contact["cid"];
1764 $datarray["network"] = $author_contact["network"];
1766 $datarray["author-name"] = $person["name"];
1767 $datarray["author-link"] = $person["url"];
1768 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1770 $datarray["owner-name"] = $contact["name"];
1771 $datarray["owner-link"] = $contact["url"];
1772 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1774 $datarray["guid"] = $guid;
1775 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1777 $datarray["type"] = "remote-comment";
1778 $datarray["verb"] = ACTIVITY_POST;
1779 $datarray["gravity"] = GRAVITY_COMMENT;
1781 if ($thr_uri != "") {
1782 $datarray["parent-uri"] = $thr_uri;
1784 $datarray["parent-uri"] = $parent_item["uri"];
1787 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1789 $datarray["protocol"] = PROTOCOL_DIASPORA;
1790 $datarray["source"] = $xml;
1792 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1794 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1796 $body = Markdown::toBBCode($text);
1798 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1800 self::fetchGuid($datarray);
1802 $message_id = Item::insert($datarray);
1804 if ($message_id <= 0) {
1809 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1812 // If we are the origin of the parent we store the original data and notify our followers
1813 if ($message_id && $parent_item["origin"]) {
1814 // Formerly we stored the signed text, the signature and the author in different fields.
1815 // We now store the raw data so that we are more flexible.
1816 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1819 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1826 * @brief processes and stores private messages
1828 * @param array $importer Array of the importer user
1829 * @param array $contact The contact of the message
1830 * @param object $data The message object
1831 * @param array $msg Array of the processed message, author handle and key
1832 * @param object $mesg The private message
1833 * @param array $conversation The conversation record to which this message belongs
1835 * @return bool "true" if it was successful
1837 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1839 $author = notags(unxmlify($data->author));
1840 $guid = notags(unxmlify($data->guid));
1841 $subject = notags(unxmlify($data->subject));
1843 // "diaspora_handle" is the element name from the old version
1844 // "author" is the element name from the new version
1845 if ($mesg->author) {
1846 $msg_author = notags(unxmlify($mesg->author));
1847 } elseif ($mesg->diaspora_handle) {
1848 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1853 $msg_guid = notags(unxmlify($mesg->guid));
1854 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1855 $msg_text = unxmlify($mesg->text);
1856 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1858 if ($msg_conversation_guid != $guid) {
1859 logger("message conversation guid does not belong to the current conversation.");
1863 $body = Markdown::toBBCode($msg_text);
1864 $message_uri = $msg_author.":".$msg_guid;
1866 $person = self::personByHandle($msg_author);
1871 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1873 intval($importer["uid"])
1875 if (DBM::is_result($r)) {
1876 logger("duplicate message already delivered.", LOGGER_DEBUG);
1881 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1882 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1883 intval($importer["uid"]),
1885 intval($conversation["id"]),
1886 dbesc($person["name"]),
1887 dbesc($person["photo"]),
1888 dbesc($person["url"]),
1889 intval($contact["id"]),
1894 dbesc($message_uri),
1895 dbesc($author.":".$guid),
1896 dbesc($msg_created_at)
1901 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1905 "type" => NOTIFY_MAIL,
1906 "notify_flags" => $importer["notify-flags"],
1907 "language" => $importer["language"],
1908 "to_name" => $importer["username"],
1909 "to_email" => $importer["email"],
1910 "uid" =>$importer["uid"],
1911 "item" => ["subject" => $subject, "body" => $body],
1912 "source_name" => $person["name"],
1913 "source_link" => $person["url"],
1914 "source_photo" => $person["thumb"],
1915 "verb" => ACTIVITY_POST,
1922 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1924 * @param array $importer Array of the importer user
1925 * @param array $msg Array of the processed message, author handle and key
1926 * @param object $data The message object
1928 * @return bool Success
1930 private static function receiveConversation($importer, $msg, $data)
1932 $author = notags(unxmlify($data->author));
1933 $guid = notags(unxmlify($data->guid));
1934 $subject = notags(unxmlify($data->subject));
1935 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1936 $participants = notags(unxmlify($data->participants));
1938 $messages = $data->message;
1940 if (!count($messages)) {
1941 logger("empty conversation");
1945 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1950 $conversation = null;
1953 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1954 intval($importer["uid"]),
1958 $conversation = $c[0];
1961 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1962 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1963 intval($importer["uid"]),
1967 dbesc(DateTimeFormat::utcNow()),
1969 dbesc($participants)
1973 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1974 intval($importer["uid"]),
1980 $conversation = $c[0];
1983 if (!$conversation) {
1984 logger("unable to create conversation.");
1988 foreach ($messages as $mesg) {
1989 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1996 * @brief Creates the body for a "like" message
1998 * @param array $contact The contact that send us the "like"
1999 * @param array $parent_item The item array of the parent item
2000 * @param string $guid message guid
2002 * @return string the body
2004 private static function constructLikeBody($contact, $parent_item, $guid)
2006 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
2008 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2009 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
2010 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
2012 return sprintf($bodyverb, $ulink, $alink, $plink);
2016 * @brief Creates a XML object for a "like"
2018 * @param array $importer Array of the importer user
2019 * @param array $parent_item The item array of the parent item
2021 * @return string The XML
2023 private static function constructLikeObject($importer, $parent_item)
2025 $objtype = ACTIVITY_OBJ_NOTE;
2026 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
2027 $parent_body = $parent_item["body"];
2029 $xmldata = ["object" => ["type" => $objtype,
2031 "id" => $parent_item["uri"],
2034 "content" => $parent_body]];
2036 return XML::fromArray($xmldata, $xml, true);
2040 * @brief Processes "like" messages
2042 * @param array $importer Array of the importer user
2043 * @param string $sender The sender of the message
2044 * @param object $data The message object
2046 * @return int The message id of the generated like or "false" if there was an error
2048 private static function receiveLike($importer, $sender, $data)
2050 $author = notags(unxmlify($data->author));
2051 $guid = notags(unxmlify($data->guid));
2052 $parent_guid = notags(unxmlify($data->parent_guid));
2053 $parent_type = notags(unxmlify($data->parent_type));
2054 $positive = notags(unxmlify($data->positive));
2056 // likes on comments aren't supported by Diaspora - only on posts
2057 // But maybe this will be supported in the future, so we will accept it.
2058 if (!in_array($parent_type, ["Post", "Comment"])) {
2062 $contact = self::allowedContactByHandle($importer, $sender, true);
2067 $message_id = self::messageExists($importer["uid"], $guid);
2072 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2073 if (!$parent_item) {
2077 $person = self::personByHandle($author);
2078 if (!is_array($person)) {
2079 logger("unable to find author details");
2083 // Fetch the contact id - if we know this contact
2084 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2086 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2087 // We would accept this anyhow.
2088 if ($positive == "true") {
2089 $verb = ACTIVITY_LIKE;
2091 $verb = ACTIVITY_DISLIKE;
2096 $datarray["protocol"] = PROTOCOL_DIASPORA;
2098 $datarray["uid"] = $importer["uid"];
2099 $datarray["contact-id"] = $author_contact["cid"];
2100 $datarray["network"] = $author_contact["network"];
2102 $datarray["author-name"] = $person["name"];
2103 $datarray["author-link"] = $person["url"];
2104 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2106 $datarray["owner-name"] = $contact["name"];
2107 $datarray["owner-link"] = $contact["url"];
2108 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2110 $datarray["guid"] = $guid;
2111 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2113 $datarray["type"] = "activity";
2114 $datarray["verb"] = $verb;
2115 $datarray["gravity"] = GRAVITY_LIKE;
2116 $datarray["parent-uri"] = $parent_item["uri"];
2118 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2119 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2121 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2123 $message_id = Item::insert($datarray);
2125 if ($message_id <= 0) {
2130 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2133 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2134 if ($parent_item["id"] != $parent_item["parent"]) {
2135 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2136 $origin = $toplevel["origin"];
2138 $origin = $parent_item["origin"];
2141 // If we are the origin of the parent we store the original data and notify our followers
2142 if ($message_id && $origin) {
2143 // Formerly we stored the signed text, the signature and the author in different fields.
2144 // We now store the raw data so that we are more flexible.
2145 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2148 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2155 * @brief Processes private messages
2157 * @param array $importer Array of the importer user
2158 * @param object $data The message object
2160 * @return bool Success?
2162 private static function receiveMessage($importer, $data)
2164 $author = notags(unxmlify($data->author));
2165 $guid = notags(unxmlify($data->guid));
2166 $conversation_guid = notags(unxmlify($data->conversation_guid));
2167 $text = unxmlify($data->text);
2168 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2170 $contact = self::allowedContactByHandle($importer, $author, true);
2175 $conversation = null;
2178 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2179 intval($importer["uid"]),
2180 dbesc($conversation_guid)
2183 $conversation = $c[0];
2185 logger("conversation not available.");
2189 $message_uri = $author.":".$guid;
2191 $person = self::personByHandle($author);
2193 logger("unable to find author details");
2197 $body = Markdown::toBBCode($text);
2199 $body = self::replacePeopleGuid($body, $person["url"]);
2204 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2206 intval($importer["uid"])
2208 if (DBM::is_result($r)) {
2209 logger("duplicate message already delivered.", LOGGER_DEBUG);
2214 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2215 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2216 intval($importer["uid"]),
2218 intval($conversation["id"]),
2219 dbesc($person["name"]),
2220 dbesc($person["photo"]),
2221 dbesc($person["url"]),
2222 intval($contact["id"]),
2223 dbesc($conversation["subject"]),
2227 dbesc($message_uri),
2228 dbesc($author.":".$conversation["guid"]),
2234 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2239 * @brief Processes participations - unsupported by now
2241 * @param array $importer Array of the importer user
2242 * @param object $data The message object
2244 * @return bool always true
2246 private static function receiveParticipation($importer, $data)
2248 $author = strtolower(notags(unxmlify($data->author)));
2249 $parent_guid = notags(unxmlify($data->parent_guid));
2251 $contact_id = Contact::getIdForURL($author);
2253 logger('Contact not found: '.$author);
2257 $person = self::personByHandle($author);
2258 if (!is_array($person)) {
2259 logger("Person not found: ".$author);
2263 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2264 if (!DBM::is_result($item)) {
2265 logger('Item not found, no origin or private: '.$parent_guid);
2269 $author_parts = explode('@', $author);
2270 if (isset($author_parts[1])) {
2271 $server = $author_parts[1];
2273 // Should never happen
2277 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2279 if (!dba::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2280 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2283 // Send all existing comments and likes to the requesting server
2284 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2286 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2287 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2288 while ($comment = dba::fetch($comments)) {
2289 if ($comment['verb'] == ACTIVITY_POST) {
2290 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2292 $cmd = $comment['self'] ? 'like' : 'comment-import';
2294 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2295 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2297 dba::close($comments);
2303 * @brief Processes photos - unneeded
2305 * @param array $importer Array of the importer user
2306 * @param object $data The message object
2308 * @return bool always true
2310 private static function receivePhoto($importer, $data)
2312 // There doesn't seem to be a reason for this function,
2313 // since the photo data is transmitted in the status message as well
2318 * @brief Processes poll participations - unssupported
2320 * @param array $importer Array of the importer user
2321 * @param object $data The message object
2323 * @return bool always true
2325 private static function receivePollParticipation($importer, $data)
2327 // We don't support polls by now
2332 * @brief Processes incoming profile updates
2334 * @param array $importer Array of the importer user
2335 * @param object $data The message object
2337 * @return bool Success
2339 private static function receiveProfile($importer, $data)
2341 $author = strtolower(notags(unxmlify($data->author)));
2343 $contact = self::contactByHandle($importer["uid"], $author);
2348 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2349 $image_url = unxmlify($data->image_url);
2350 $birthday = unxmlify($data->birthday);
2351 $gender = unxmlify($data->gender);
2352 $about = Markdown::toBBCode(unxmlify($data->bio));
2353 $location = Markdown::toBBCode(unxmlify($data->location));
2354 $searchable = (unxmlify($data->searchable) == "true");
2355 $nsfw = (unxmlify($data->nsfw) == "true");
2356 $tags = unxmlify($data->tag_string);
2358 $tags = explode("#", $tags);
2361 foreach ($tags as $tag) {
2362 $tag = trim(strtolower($tag));
2368 $keywords = implode(", ", $keywords);
2370 $handle_parts = explode("@", $author);
2371 $nick = $handle_parts[0];
2374 $name = $handle_parts[0];
2377 if (preg_match("|^https?://|", $image_url) === 0) {
2378 $image_url = "http://".$handle_parts[1].$image_url;
2381 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2383 // Generic birthday. We don't know the timezone. The year is irrelevant.
2385 $birthday = str_replace("1000", "1901", $birthday);
2387 if ($birthday != "") {
2388 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2391 // this is to prevent multiple birthday notifications in a single year
2392 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2394 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2395 $birthday = $contact["bd"];
2399 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2400 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2404 dbesc(DateTimeFormat::utcNow()),
2410 intval($contact["id"]),
2411 intval($importer["uid"])
2414 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2415 "photo" => $image_url, "name" => $name, "location" => $location,
2416 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2417 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2418 "hide" => !$searchable, "nsfw" => $nsfw];
2420 $gcid = GContact::update($gcontact);
2422 GContact::link($gcid, $importer["uid"], $contact["id"]);
2424 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2430 * @brief Processes incoming friend requests
2432 * @param array $importer Array of the importer user
2433 * @param array $contact The contact that send the request
2436 private static function receiveRequestMakeFriend($importer, $contact)
2440 if ($contact["rel"] == CONTACT_IS_SHARING) {
2443 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2444 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2447 // send notification
2450 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2451 intval($importer["uid"])
2454 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2456 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2457 intval($importer["uid"])
2460 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2462 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2464 $arr["protocol"] = PROTOCOL_DIASPORA;
2465 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2466 $arr["uid"] = $importer["uid"];
2467 $arr["contact-id"] = $self[0]["id"];
2469 $arr["type"] = 'wall';
2470 $arr["gravity"] = 0;
2472 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2473 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2474 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2475 $arr["verb"] = ACTIVITY_FRIEND;
2476 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2478 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2479 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2480 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2481 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2483 $arr["object"] = self::constructNewFriendObject($contact);
2485 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2487 $arr["allow_cid"] = $user["allow_cid"];
2488 $arr["allow_gid"] = $user["allow_gid"];
2489 $arr["deny_cid"] = $user["deny_cid"];
2490 $arr["deny_gid"] = $user["deny_gid"];
2492 $i = Item::insert($arr);
2494 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2501 * @brief Creates a XML object for a "new friend" message
2503 * @param array $contact Array of the contact
2505 * @return string The XML
2507 private static function constructNewFriendObject($contact)
2509 $objtype = ACTIVITY_OBJ_PERSON;
2510 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2511 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2513 $xmldata = ["object" => ["type" => $objtype,
2514 "title" => $contact["name"],
2515 "id" => $contact["url"]."/".$contact["name"],
2518 return XML::fromArray($xmldata, $xml, true);
2522 * @brief Processes incoming sharing notification
2524 * @param array $importer Array of the importer user
2525 * @param object $data The message object
2527 * @return bool Success
2529 private static function receiveContactRequest($importer, $data)
2531 $author = unxmlify($data->author);
2532 $recipient = unxmlify($data->recipient);
2534 if (!$author || !$recipient) {
2538 // the current protocol version doesn't know these fields
2539 // That means that we will assume their existance
2540 if (isset($data->following)) {
2541 $following = (unxmlify($data->following) == "true");
2546 if (isset($data->sharing)) {
2547 $sharing = (unxmlify($data->sharing) == "true");
2552 $contact = self::contactByHandle($importer["uid"], $author);
2554 // perhaps we were already sharing with this person. Now they're sharing with us.
2555 // That makes us friends.
2558 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2559 self::receiveRequestMakeFriend($importer, $contact);
2561 // refetch the contact array
2562 $contact = self::contactByHandle($importer["uid"], $author);
2564 // If we are now friends, we are sending a share message.
2565 // Normally we needn't to do so, but the first message could have been vanished.
2566 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2567 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2569 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2570 $ret = self::sendShare($u[0], $contact);
2575 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2576 Contact::removeFollower($importer, $contact);
2581 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2582 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2584 } elseif (!$following && !$sharing) {
2585 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2587 } elseif (!$following && $sharing) {
2588 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2589 } elseif ($following && $sharing) {
2590 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2591 } elseif ($following && !$sharing) {
2592 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2595 $ret = self::personByHandle($author);
2597 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2598 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2602 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2605 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2606 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2607 intval($importer["uid"]),
2608 dbesc($ret["network"]),
2609 dbesc($ret["addr"]),
2610 DateTimeFormat::utcNow(),
2612 dbesc(normalise_link($ret["url"])),
2614 dbesc($ret["name"]),
2615 dbesc($ret["nick"]),
2616 dbesc($ret["photo"]),
2617 dbesc($ret["pubkey"]),
2618 dbesc($ret["notify"]),
2619 dbesc($ret["poll"]),
2624 // find the contact record we just created
2626 $contact_record = self::contactByHandle($importer["uid"], $author);
2628 if (!$contact_record) {
2629 logger("unable to locate newly created contact record.");
2633 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2635 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2637 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2639 if ($importer["page-flags"] == PAGE_NORMAL) {
2640 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2642 $hash = random_string().(string)time(); // Generate a confirm_key
2645 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2646 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2647 intval($importer["uid"]),
2648 intval($contact_record["id"]),
2651 dbesc(L10n::t("Sharing notification from Diaspora network")),
2653 dbesc(DateTimeFormat::utcNow())
2656 // automatic friend approval
2658 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2660 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2662 // technically they are sharing with us (CONTACT_IS_SHARING),
2663 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2664 // we are going to change the relationship and make them a follower.
2666 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2667 $new_relation = CONTACT_IS_FRIEND;
2668 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2669 $new_relation = CONTACT_IS_SHARING;
2671 $new_relation = CONTACT_IS_FOLLOWER;
2675 "UPDATE `contact` SET `rel` = %d,
2683 intval($new_relation),
2684 dbesc(DateTimeFormat::utcNow()),
2685 dbesc(DateTimeFormat::utcNow()),
2686 intval($contact_record["id"])
2689 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2691 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2692 $ret = self::sendShare($u[0], $contact_record);
2694 // Send the profile data, maybe it weren't transmitted before
2695 self::sendProfile($importer["uid"], [$contact_record]);
2703 * @brief Fetches a message with a given guid
2705 * @param string $guid message guid
2706 * @param string $orig_author handle of the original post
2707 * @param string $author handle of the sharer
2709 * @return array The fetched item
2711 private static function originalItem($guid, $orig_author, $author)
2713 // Do we already have this item?
2715 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2716 `author-name`, `author-link`, `author-avatar`
2717 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2721 if (DBM::is_result($r)) {
2722 logger("reshared message ".$guid." already exists on system.");
2724 // Maybe it is already a reshared item?
2725 // Then refetch the content, if it is a reshare from a reshare.
2726 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2727 if (self::isReshare($r[0]["body"], true)) {
2729 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2730 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2732 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2734 // Add OEmbed and other information to the body
2735 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2743 if (!DBM::is_result($r)) {
2744 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2745 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2746 $item_id = self::storeByGuid($guid, $server);
2749 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2750 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2751 $item_id = self::storeByGuid($guid, $server);
2756 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2757 `author-name`, `author-link`, `author-avatar`
2758 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2762 if (DBM::is_result($r)) {
2763 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2764 if (self::isReshare($r[0]["body"], false)) {
2765 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2766 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2777 * @brief Processes a reshare message
2779 * @param array $importer Array of the importer user
2780 * @param object $data The message object
2781 * @param string $xml The original XML of the message
2783 * @return int the message id
2785 private static function receiveReshare($importer, $data, $xml)
2787 $author = notags(unxmlify($data->author));
2788 $guid = notags(unxmlify($data->guid));
2789 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2790 $root_author = notags(unxmlify($data->root_author));
2791 $root_guid = notags(unxmlify($data->root_guid));
2792 /// @todo handle unprocessed property "provider_display_name"
2793 $public = notags(unxmlify($data->public));
2795 $contact = self::allowedContactByHandle($importer, $author, false);
2800 $message_id = self::messageExists($importer["uid"], $guid);
2805 $original_item = self::originalItem($root_guid, $root_author, $author);
2806 if (!$original_item) {
2810 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2814 $datarray["uid"] = $importer["uid"];
2815 $datarray["contact-id"] = $contact["id"];
2816 $datarray["network"] = NETWORK_DIASPORA;
2818 $datarray["author-name"] = $contact["name"];
2819 $datarray["author-link"] = $contact["url"];
2820 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2822 $datarray["owner-name"] = $datarray["author-name"];
2823 $datarray["owner-link"] = $datarray["author-link"];
2824 $datarray["owner-avatar"] = $datarray["author-avatar"];
2826 $datarray["guid"] = $guid;
2827 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2829 $datarray["verb"] = ACTIVITY_POST;
2830 $datarray["gravity"] = GRAVITY_PARENT;
2832 $datarray["protocol"] = PROTOCOL_DIASPORA;
2833 $datarray["source"] = $xml;
2835 $prefix = share_header(
2836 $original_item["author-name"],
2837 $original_item["author-link"],
2838 $original_item["author-avatar"],
2839 $original_item["guid"],
2840 $original_item["created"],
2843 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2845 $datarray["tag"] = $original_item["tag"];
2846 $datarray["app"] = $original_item["app"];
2848 $datarray["plink"] = self::plink($author, $guid);
2849 $datarray["private"] = (($public == "false") ? 1 : 0);
2850 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2852 $datarray["object-type"] = $original_item["object-type"];
2854 self::fetchGuid($datarray);
2855 $message_id = Item::insert($datarray);
2857 self::sendParticipation($contact, $datarray);
2860 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2868 * @brief Processes retractions
2870 * @param array $importer Array of the importer user
2871 * @param array $contact The contact of the item owner
2872 * @param object $data The message object
2874 * @return bool success
2876 private static function itemRetraction($importer, $contact, $data)
2878 $author = notags(unxmlify($data->author));
2879 $target_guid = notags(unxmlify($data->target_guid));
2880 $target_type = notags(unxmlify($data->target_type));
2882 $person = self::personByHandle($author);
2883 if (!is_array($person)) {
2884 logger("unable to find author detail for ".$author);
2888 if (empty($contact["url"])) {
2889 $contact["url"] = $person["url"];
2892 // Fetch items that are about to be deleted
2893 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2895 // When we receive a public retraction, we delete every item that we find.
2896 if ($importer['uid'] == 0) {
2897 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2899 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2901 $r = dba::select('item', $fields, $condition);
2902 if (!DBM::is_result($r)) {
2903 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2907 while ($item = dba::fetch($r)) {
2908 // Fetch the parent item
2909 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2911 // Only delete it if the parent author really fits
2912 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2913 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2917 Item::deleteById($item["id"]);
2919 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2921 // Now check if the retraction needs to be relayed by us
2922 if ($parent["origin"]) {
2924 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2932 * @brief Receives retraction messages
2934 * @param array $importer Array of the importer user
2935 * @param string $sender The sender of the message
2936 * @param object $data The message object
2938 * @return bool Success
2940 private static function receiveRetraction($importer, $sender, $data)
2942 $target_type = notags(unxmlify($data->target_type));
2944 $contact = self::contactByHandle($importer["uid"], $sender);
2945 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2946 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2950 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2952 switch ($target_type) {
2957 case "StatusMessage":
2958 return self::itemRetraction($importer, $contact, $data);
2962 /// @todo What should we do with an "unshare"?
2963 // Removing the contact isn't correct since we still can read the public items
2964 Contact::remove($contact["id"]);
2968 logger("Unknown target type ".$target_type);
2975 * @brief Receives status messages
2977 * @param array $importer Array of the importer user
2978 * @param object $data The message object
2979 * @param string $xml The original XML of the message
2981 * @return int The message id of the newly created item
2983 private static function receiveStatusMessage($importer, $data, $xml)
2985 $author = notags(unxmlify($data->author));
2986 $guid = notags(unxmlify($data->guid));
2987 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2988 $public = notags(unxmlify($data->public));
2989 $text = unxmlify($data->text);
2990 $provider_display_name = notags(unxmlify($data->provider_display_name));
2992 $contact = self::allowedContactByHandle($importer, $author, false);
2997 $message_id = self::messageExists($importer["uid"], $guid);
3003 if ($data->location) {
3004 foreach ($data->location->children() as $fieldname => $data) {
3005 $address[$fieldname] = notags(unxmlify($data));
3009 $body = Markdown::toBBCode($text);
3013 // Attach embedded pictures to the body
3015 foreach ($data->photo as $photo) {
3016 $body = "[img]".unxmlify($photo->remote_photo_path).
3017 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
3020 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
3022 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
3024 // Add OEmbed and other information to the body
3025 if (!self::isRedmatrix($contact["url"])) {
3026 $body = add_page_info_to_body($body, false, true);
3030 /// @todo enable support for polls
3031 //if ($data->poll) {
3032 // foreach ($data->poll AS $poll)
3037 /// @todo enable support for events
3039 $datarray["uid"] = $importer["uid"];
3040 $datarray["contact-id"] = $contact["id"];
3041 $datarray["network"] = NETWORK_DIASPORA;
3043 $datarray["author-name"] = $contact["name"];
3044 $datarray["author-link"] = $contact["url"];
3045 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
3047 $datarray["owner-name"] = $datarray["author-name"];
3048 $datarray["owner-link"] = $datarray["author-link"];
3049 $datarray["owner-avatar"] = $datarray["author-avatar"];
3051 $datarray["guid"] = $guid;
3052 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3054 $datarray["verb"] = ACTIVITY_POST;
3055 $datarray["gravity"] = GRAVITY_PARENT;
3057 $datarray["protocol"] = PROTOCOL_DIASPORA;
3058 $datarray["source"] = $xml;
3060 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3062 if ($provider_display_name != "") {
3063 $datarray["app"] = $provider_display_name;
3066 $datarray["plink"] = self::plink($author, $guid);
3067 $datarray["private"] = (($public == "false") ? 1 : 0);
3068 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3070 if (isset($address["address"])) {
3071 $datarray["location"] = $address["address"];
3074 if (isset($address["lat"]) && isset($address["lng"])) {
3075 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3078 self::fetchGuid($datarray);
3079 $message_id = Item::insert($datarray);
3081 self::sendParticipation($contact, $datarray);
3084 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3091 /* ************************************************************************************** *
3092 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3093 * ************************************************************************************** */
3096 * @brief returnes the handle of a contact
3098 * @param array $contact contact array
3100 * @return string the handle in the format user@domain.tld
3102 private static function myHandle($contact)
3104 if ($contact["addr"] != "") {
3105 return $contact["addr"];
3108 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3109 // So - just in case - we build the the address here.
3110 if ($contact["nickname"] != "") {
3111 $nick = $contact["nickname"];
3113 $nick = $contact["nick"];
3116 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3121 * @brief Creates the data for a private message in the new format
3123 * @param string $msg The message that is to be transmitted
3124 * @param array $user The record of the sender
3125 * @param array $contact Target of the communication
3126 * @param string $prvkey The private key of the sender
3127 * @param string $pubkey The public key of the receiver
3129 * @return string The encrypted data
3131 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3133 logger("Message: ".$msg, LOGGER_DATA);
3135 // without a public key nothing will work
3137 logger("pubkey missing: contact id: ".$contact["id"]);
3141 $aes_key = openssl_random_pseudo_bytes(32);
3142 $b_aes_key = base64_encode($aes_key);
3143 $iv = openssl_random_pseudo_bytes(16);
3144 $b_iv = base64_encode($iv);
3146 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3148 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3150 $encrypted_key_bundle = "";
3151 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3153 $json_object = json_encode(
3154 ["aes_key" => base64_encode($encrypted_key_bundle),
3155 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3158 return $json_object;
3162 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3164 * @param string $msg The message that is to be transmitted
3165 * @param array $user The record of the sender
3167 * @return string The envelope
3169 public static function buildMagicEnvelope($msg, $user)
3171 $b64url_data = base64url_encode($msg);
3172 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3174 $key_id = base64url_encode(self::myHandle($user));
3175 $type = "application/xml";
3176 $encoding = "base64url";
3177 $alg = "RSA-SHA256";
3178 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3180 // Fallback if the private key wasn't transmitted in the expected field
3181 if ($user['uprvkey'] == "") {
3182 $user['uprvkey'] = $user['prvkey'];
3185 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3186 $sig = base64url_encode($signature);
3188 $xmldata = ["me:env" => ["me:data" => $data,
3189 "@attributes" => ["type" => $type],
3190 "me:encoding" => $encoding,
3193 "@attributes2" => ["key_id" => $key_id]]];
3195 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3197 return XML::fromArray($xmldata, $xml, false, $namespaces);
3201 * @brief Create the envelope for a message
3203 * @param string $msg The message that is to be transmitted
3204 * @param array $user The record of the sender
3205 * @param array $contact Target of the communication
3206 * @param string $prvkey The private key of the sender
3207 * @param string $pubkey The public key of the receiver
3208 * @param bool $public Is the message public?
3210 * @return string The message that will be transmitted to other servers
3212 public static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3214 // The message is put into an envelope with the sender's signature
3215 $envelope = self::buildMagicEnvelope($msg, $user);
3217 // Private messages are put into a second envelope, encrypted with the receivers public key
3219 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3226 * @brief Creates a signature for a message
3228 * @param array $owner the array of the owner of the message
3229 * @param array $message The message that is to be signed
3231 * @return string The signature
3233 private static function signature($owner, $message)
3236 unset($sigmsg["author_signature"]);
3237 unset($sigmsg["parent_author_signature"]);
3239 $signed_text = implode(";", $sigmsg);
3241 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3245 * @brief Transmit a message to a target server
3247 * @param array $owner the array of the item owner
3248 * @param array $contact Target of the communication
3249 * @param string $envelope The message that is to be transmitted
3250 * @param bool $public_batch Is it a public post?
3251 * @param bool $queue_run Is the transmission called from the queue?
3252 * @param string $guid message guid
3254 * @return int Result of the transmission
3256 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3260 $enabled = intval(Config::get("system", "diaspora_enabled"));
3265 $logid = random_string(4);
3267 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3269 // We always try to use the data from the fcontact table.
3270 // This is important for transmitting data to Friendica servers.
3271 if (!empty($contact['addr'])) {
3272 $fcontact = self::personByHandle($contact['addr']);
3273 if (!empty($fcontact)) {
3274 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3279 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3283 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3285 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3288 if (!intval(Config::get("system", "diaspora_test"))) {
3289 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3291 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3292 $return_code = $a->get_curl_code();
3294 logger("test_mode");
3299 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3301 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3303 logger("queue message");
3304 // queue message for redelivery
3305 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3308 // The message could not be delivered. We mark the contact as "dead"
3309 Contact::markForArchival($contact);
3310 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3311 // We successfully delivered a message, the contact is alive
3312 Contact::unmarkForArchival($contact);
3315 return $return_code ? $return_code : -1;
3320 * @brief Build the post xml
3322 * @param string $type The message type
3323 * @param array $message The message data
3325 * @return string The post XML
3327 public static function buildPostXml($type, $message)
3329 $data = [$type => $message];
3331 return XML::fromArray($data, $xml);
3335 * @brief Builds and transmit messages
3337 * @param array $owner the array of the item owner
3338 * @param array $contact Target of the communication
3339 * @param string $type The message type
3340 * @param array $message The message data
3341 * @param bool $public_batch Is it a public post?
3342 * @param string $guid message guid
3343 * @param bool $spool Should the transmission be spooled or transmitted?
3345 * @return int Result of the transmission
3347 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3349 $msg = self::buildPostXml($type, $message);
3351 logger('message: '.$msg, LOGGER_DATA);
3352 logger('send guid '.$guid, LOGGER_DEBUG);
3354 // Fallback if the private key wasn't transmitted in the expected field
3355 if ($owner['uprvkey'] == "") {
3356 $owner['uprvkey'] = $owner['prvkey'];
3359 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3362 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3365 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3368 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3370 return $return_code;
3374 * @brief sends a participation (Used to get all further updates)
3376 * @param array $contact Target of the communication
3377 * @param array $item Item array
3379 * @return int The result of the transmission
3381 private static function sendParticipation($contact, $item)
3383 // Don't send notifications for private postings
3384 if ($item['private']) {
3388 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3390 $result = Cache::get($cachekey);
3391 if (!is_null($result)) {
3395 // Fetch some user id to have a valid handle to transmit the participation.
3396 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3397 // If the item belongs to a user, we take this user id.
3398 if ($item['uid'] == 0) {
3399 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3400 $first_user = dba::selectFirst('user', ['uid'], $condition);
3401 $owner = User::getOwnerDataById($first_user['uid']);
3403 $owner = User::getOwnerDataById($item['uid']);
3406 $author = self::myHandle($owner);
3408 $message = ["author" => $author,
3409 "guid" => get_guid(32),
3410 "parent_type" => "Post",
3411 "parent_guid" => $item["guid"]];
3413 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3415 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3416 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3418 return self::buildAndTransmit($owner, $contact, "participation", $message);
3422 * @brief sends an account migration
3424 * @param array $owner the array of the item owner
3425 * @param array $contact Target of the communication
3426 * @param int $uid User ID
3428 * @return int The result of the transmission
3430 public static function sendAccountMigration($owner, $contact, $uid)
3432 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3433 $profile = self::createProfileData($uid);
3435 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3436 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3438 $message = ["author" => $old_handle,
3439 "profile" => $profile,
3440 "signature" => $signature];
3442 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3444 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3448 * @brief Sends a "share" message
3450 * @param array $owner the array of the item owner
3451 * @param array $contact Target of the communication
3453 * @return int The result of the transmission
3455 public static function sendShare($owner, $contact)
3458 * @todo support the different possible combinations of "following" and "sharing"
3459 * Currently, Diaspora only interprets the "sharing" field
3461 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3465 switch ($contact["rel"]) {
3466 case CONTACT_IS_FRIEND:
3469 case CONTACT_IS_SHARING:
3472 case CONTACT_IS_FOLLOWER:
3478 $message = ["author" => self::myHandle($owner),
3479 "recipient" => $contact["addr"],
3480 "following" => "true",
3481 "sharing" => "true"];
3483 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3485 return self::buildAndTransmit($owner, $contact, "contact", $message);
3489 * @brief sends an "unshare"
3491 * @param array $owner the array of the item owner
3492 * @param array $contact Target of the communication
3494 * @return int The result of the transmission
3496 public static function sendUnshare($owner, $contact)
3498 $message = ["author" => self::myHandle($owner),
3499 "recipient" => $contact["addr"],
3500 "following" => "false",
3501 "sharing" => "false"];
3503 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3505 return self::buildAndTransmit($owner, $contact, "contact", $message);
3509 * @brief Checks a message body if it is a reshare
3511 * @param string $body The message body that is to be check
3512 * @param bool $complete Should it be a complete check or a simple check?
3514 * @return array|bool Reshare details or "false" if no reshare
3516 public static function isReshare($body, $complete = true)
3518 $body = trim($body);
3520 // Skip if it isn't a pure repeated messages
3521 // Does it start with a share?
3522 if ((strpos($body, "[share") > 0) && $complete) {
3526 // Does it end with a share?
3527 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3531 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3532 // Skip if there is no shared message in there
3533 if ($body == $attributes) {
3537 // If we don't do the complete check we quit here
3543 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3544 if ($matches[1] != "") {
3545 $guid = $matches[1];
3548 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3549 if ($matches[1] != "") {
3550 $guid = $matches[1];
3555 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3562 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3563 $ret["root_guid"] = $guid;
3569 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3570 if ($matches[1] != "") {
3571 $profile = $matches[1];
3574 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3575 if ($matches[1] != "") {
3576 $profile = $matches[1];
3581 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3582 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3587 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3588 if ($matches[1] != "") {
3589 $link = $matches[1];
3592 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3593 if ($matches[1] != "") {
3594 $link = $matches[1];
3597 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3598 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3606 * @brief Create an event array
3608 * @param integer $event_id The id of the event
3610 * @return array with event data
3612 private static function buildEvent($event_id)
3614 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3615 if (!DBM::is_result($r)) {
3623 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3624 if (!DBM::is_result($r)) {
3630 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3631 if (!DBM::is_result($r)) {
3637 $eventdata['author'] = self::myHandle($owner);
3639 if ($event['guid']) {
3640 $eventdata['guid'] = $event['guid'];
3643 $mask = DateTimeFormat::ATOM;
3645 /// @todo - establish "all day" events in Friendica
3646 $eventdata["all_day"] = "false";
3648 if (!$event['adjust']) {
3649 $eventdata['timezone'] = $user['timezone'];
3651 if ($eventdata['timezone'] == "") {
3652 $eventdata['timezone'] = 'UTC';
3656 if ($event['start']) {
3657 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3659 if ($event['finish'] && !$event['nofinish']) {
3660 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3662 if ($event['summary']) {
3663 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3665 if ($event['desc']) {
3666 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3668 if ($event['location']) {
3669 $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3670 $coord = Map::getCoordinates($event['location']);
3673 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3674 if (!empty($coord['lat']) && !empty($coord['lon'])) {
3675 $location["lat"] = $coord['lat'];
3676 $location["lng"] = $coord['lon'];
3678 $location["lat"] = 0;
3679 $location["lng"] = 0;
3681 $eventdata['location'] = $location;
3688 * @brief Create a post (status message or reshare)
3690 * @param array $item The item that will be exported
3691 * @param array $owner the array of the item owner
3694 * 'type' -> Message type ("status_message" or "reshare")
3695 * 'message' -> Array of XML elements of the status
3697 public static function buildStatus($item, $owner)
3699 $cachekey = "diaspora:buildStatus:".$item['guid'];
3701 $result = Cache::get($cachekey);
3702 if (!is_null($result)) {
3706 $myaddr = self::myHandle($owner);
3708 $public = (($item["private"]) ? "false" : "true");
3710 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3712 // Detect a share element and do a reshare
3713 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3714 $message = ["author" => $myaddr,
3715 "guid" => $item["guid"],
3716 "created_at" => $created,
3717 "root_author" => $ret["root_handle"],
3718 "root_guid" => $ret["root_guid"],
3719 "provider_display_name" => $item["app"],
3720 "public" => $public];
3724 $title = $item["title"];
3725 $body = $item["body"];
3727 // convert to markdown
3728 $body = html_entity_decode(BBCode::toMarkdown($body));
3731 if (strlen($title)) {
3732 $body = "## ".html_entity_decode($title)."\n\n".$body;
3735 if ($item["attach"]) {
3736 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3738 $body .= "\n".L10n::t("Attachments:")."\n";
3739 foreach ($matches as $mtch) {
3740 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3747 if ($item["location"] != "")
3748 $location["address"] = $item["location"];
3750 if ($item["coord"] != "") {
3751 $coord = explode(" ", $item["coord"]);
3752 $location["lat"] = $coord[0];
3753 $location["lng"] = $coord[1];
3756 $message = ["author" => $myaddr,
3757 "guid" => $item["guid"],
3758 "created_at" => $created,
3759 "public" => $public,
3761 "provider_display_name" => $item["app"],
3762 "location" => $location];
3764 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3765 if (!isset($location["lat"]) || !isset($location["lng"])) {
3766 unset($message["location"]);
3769 if ($item['event-id'] > 0) {
3770 $event = self::buildEvent($item['event-id']);
3771 if (count($event)) {
3772 $message['event'] = $event;
3774 if (!empty($event['location']['address']) &&
3775 !empty($event['location']['lat']) &&
3776 !empty($event['location']['lng'])) {
3777 $message['location'] = $event['location'];
3780 /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3781 // $message['text'] = '';
3785 $type = "status_message";
3788 $msg = ["type" => $type, "message" => $message];
3790 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3796 * @brief Sends a post
3798 * @param array $item The item that will be exported
3799 * @param array $owner the array of the item owner
3800 * @param array $contact Target of the communication
3801 * @param bool $public_batch Is it a public post?
3803 * @return int The result of the transmission
3805 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3807 $status = self::buildStatus($item, $owner);
3809 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3813 * @brief Creates a "like" object
3815 * @param array $item The item that will be exported
3816 * @param array $owner the array of the item owner
3818 * @return array The data for a "like"
3820 private static function constructLike($item, $owner)
3823 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3824 dbesc($item["thr-parent"])
3826 if (!DBM::is_result($p)) {
3832 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3834 if ($item['verb'] === ACTIVITY_LIKE) {
3836 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3837 $positive = "false";
3840 return(["author" => self::myHandle($owner),
3841 "guid" => $item["guid"],
3842 "parent_guid" => $parent["guid"],
3843 "parent_type" => $target_type,
3844 "positive" => $positive,
3845 "author_signature" => ""]);
3849 * @brief Creates an "EventParticipation" object
3851 * @param array $item The item that will be exported
3852 * @param array $owner the array of the item owner
3854 * @return array The data for an "EventParticipation"
3856 private static function constructAttend($item, $owner)
3859 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3860 dbesc($item["thr-parent"])
3862 if (!DBM::is_result($p)) {
3868 switch ($item['verb']) {
3869 case ACTIVITY_ATTEND:
3870 $attend_answer = 'accepted';
3872 case ACTIVITY_ATTENDNO:
3873 $attend_answer = 'declined';
3875 case ACTIVITY_ATTENDMAYBE:
3876 $attend_answer = 'tentative';
3879 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3883 return(["author" => self::myHandle($owner),
3884 "guid" => $item["guid"],
3885 "parent_guid" => $parent["guid"],
3886 "status" => $attend_answer,
3887 "author_signature" => ""]);
3891 * @brief Creates the object for a comment
3893 * @param array $item The item that will be exported
3894 * @param array $owner the array of the item owner
3896 * @return array The data for a comment
3898 private static function constructComment($item, $owner)
3900 $cachekey = "diaspora:constructComment:".$item['guid'];
3902 $result = Cache::get($cachekey);
3903 if (!is_null($result)) {
3908 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3909 intval($item["parent"]),
3910 intval($item["parent"])
3913 if (!DBM::is_result($p)) {
3919 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3920 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3922 $comment = ["author" => self::myHandle($owner),
3923 "guid" => $item["guid"],
3924 "created_at" => $created,
3925 "parent_guid" => $parent["guid"],
3927 "author_signature" => ""];
3929 // Send the thread parent guid only if it is a threaded comment
3930 if ($item['thr-parent'] != $item['parent-uri']) {
3931 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3934 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3940 * @brief Send a like or a comment
3942 * @param array $item The item that will be exported
3943 * @param array $owner the array of the item owner
3944 * @param array $contact Target of the communication
3945 * @param bool $public_batch Is it a public post?
3947 * @return int The result of the transmission
3949 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3951 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3952 $message = self::constructAttend($item, $owner);
3953 $type = "event_participation";
3954 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3955 $message = self::constructLike($item, $owner);
3958 $message = self::constructComment($item, $owner);
3966 $message["author_signature"] = self::signature($owner, $message);
3968 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3972 * @brief Creates a message from a signature record entry
3974 * @param array $item The item that will be exported
3975 * @param array $signature The entry of the "sign" record
3977 * @return string The message
3979 private static function messageFromSignature($item, $signature)
3981 // Split the signed text
3982 $signed_parts = explode(";", $signature['signed_text']);
3984 if ($item["deleted"]) {
3985 $message = ["author" => $signature['signer'],
3986 "target_guid" => $signed_parts[0],
3987 "target_type" => $signed_parts[1]];
3988 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3989 $message = ["author" => $signed_parts[4],
3990 "guid" => $signed_parts[1],
3991 "parent_guid" => $signed_parts[3],
3992 "parent_type" => $signed_parts[2],
3993 "positive" => $signed_parts[0],
3994 "author_signature" => $signature['signature'],
3995 "parent_author_signature" => ""];
3997 // Remove the comment guid
3998 $guid = array_shift($signed_parts);
4000 // Remove the parent guid
4001 $parent_guid = array_shift($signed_parts);
4003 // Remove the handle
4004 $handle = array_pop($signed_parts);
4006 // Glue the parts together
4007 $text = implode(";", $signed_parts);
4009 $message = ["author" => $handle,
4011 "parent_guid" => $parent_guid,
4012 "text" => implode(";", $signed_parts),
4013 "author_signature" => $signature['signature'],
4014 "parent_author_signature" => ""];
4020 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
4022 * @param array $item The item that will be exported
4023 * @param array $owner the array of the item owner
4024 * @param array $contact Target of the communication
4025 * @param bool $public_batch Is it a public post?
4027 * @return int The result of the transmission
4029 public static function sendRelay($item, $owner, $contact, $public_batch = false)
4031 if ($item["deleted"]) {
4032 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
4033 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4039 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4041 // fetch the original signature
4044 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
4049 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
4055 // Old way - is used by the internal Friendica functions
4056 /// @todo Change all signatur storing functions to the new format
4057 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
4058 $message = self::messageFromSignature($item, $signature);
4060 $msg = json_decode($signature['signed_text'], true);
4063 if (is_array($msg)) {
4064 foreach ($msg as $field => $data) {
4065 if (!$item["deleted"]) {
4066 if ($field == "diaspora_handle") {
4069 if ($field == "target_type") {
4070 $field = "parent_type";
4074 $message[$field] = $data;
4077 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4081 $message["parent_author_signature"] = self::signature($owner, $message);
4083 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4085 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4089 * @brief Sends a retraction (deletion) of a message, like or comment
4091 * @param array $item The item that will be exported
4092 * @param array $owner the array of the item owner
4093 * @param array $contact Target of the communication
4094 * @param bool $public_batch Is it a public post?
4095 * @param bool $relay Is the retraction transmitted from a relay?
4097 * @return int The result of the transmission
4099 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4101 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4103 $msg_type = "retraction";
4105 if ($item['id'] == $item['parent']) {
4106 $target_type = "Post";
4107 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4108 $target_type = "Like";
4110 $target_type = "Comment";
4113 $message = ["author" => $itemaddr,
4114 "target_guid" => $item['guid'],
4115 "target_type" => $target_type];
4117 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4119 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4123 * @brief Sends a mail
4125 * @param array $item The item that will be exported
4126 * @param array $owner The owner
4127 * @param array $contact Target of the communication
4129 * @return int The result of the transmission
4131 public static function sendMail($item, $owner, $contact)
4133 $myaddr = self::myHandle($owner);
4136 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4137 intval($item["convid"]),
4138 intval($item["uid"])
4141 if (!DBM::is_result($r)) {
4142 logger("conversation not found.");
4148 "author" => $cnv["creator"],
4149 "guid" => $cnv["guid"],
4150 "subject" => $cnv["subject"],
4151 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4152 "participants" => $cnv["recips"]
4155 $body = BBCode::toMarkdown($item["body"]);
4156 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4159 "author" => $myaddr,
4160 "guid" => $item["guid"],
4161 "conversation_guid" => $cnv["guid"],
4163 "created_at" => $created,
4166 if ($item["reply"]) {
4171 "author" => $cnv["creator"],
4172 "guid" => $cnv["guid"],
4173 "subject" => $cnv["subject"],
4174 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4175 "participants" => $cnv["recips"],
4178 $type = "conversation";
4181 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4185 * @brief Split a name into first name and last name
4187 * @param string $name The name
4189 * @return array The array with "first" and "last"
4191 public static function splitName($name) {
4192 $name = trim($name);
4194 // Is the name longer than 64 characters? Then cut the rest of it.
4195 if (strlen($name) > 64) {
4196 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4197 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4199 $name = substr($name, 0, 64);
4203 // Take the first word as first name
4204 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4205 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4206 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4207 return ['first' => $first, 'last' => $last];
4210 // Take the last word as last name
4211 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4212 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4214 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4215 return ['first' => $first, 'last' => $last];
4218 // Take the first 32 characters if there is no space in the first 32 characters
4219 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4220 $first = substr($name, 0, 32);
4221 $last = substr($name, 32);
4222 return ['first' => $first, 'last' => $last];
4225 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4226 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4228 // Check if the last name is longer than 32 characters
4229 if (strlen($last) > 32) {
4230 if (strpos($last, ' ') <= 32) {
4231 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4233 $last = substr($last, 0, 32);
4237 return ['first' => $first, 'last' => $last];
4241 * @brief Create profile data
4243 * @param int $uid The user id
4245 * @return array The profile data
4247 private static function createProfileData($uid)
4250 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4252 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4253 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4254 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4263 $handle = $profile["addr"];
4265 $split_name = self::splitName($profile['name']);
4266 $first = $split_name['first'];
4267 $last = $split_name['last'];
4269 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4270 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4271 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4272 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4278 if ($searchable === 'true') {
4281 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4282 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4286 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4289 $about = $profile['about'];
4290 $about = strip_tags(BBCode::convert($about));
4292 $location = Profile::formatLocation($profile);
4294 if ($profile['pub_keywords']) {
4295 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4296 $kw = str_replace(' ', ' ', $kw);
4297 $arr = explode(' ', $profile['pub_keywords']);
4299 for ($x = 0; $x < 5; $x ++) {
4300 if (trim($arr[$x])) {
4301 $tags .= '#'. trim($arr[$x]) .' ';
4306 $tags = trim($tags);
4309 return ["author" => $handle,
4310 "first_name" => $first,
4311 "last_name" => $last,
4312 "image_url" => $large,
4313 "image_url_medium" => $medium,
4314 "image_url_small" => $small,
4316 "gender" => $profile['gender'],
4318 "location" => $location,
4319 "searchable" => $searchable,
4321 "tag_string" => $tags];
4325 * @brief Sends profile data
4327 * @param int $uid The user id
4328 * @param bool $recips optional, default false
4331 public static function sendProfile($uid, $recips = false)
4337 $owner = User::getOwnerDataById($uid);
4344 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4345 AND `uid` = %d AND `rel` != %d",
4346 dbesc(NETWORK_DIASPORA),
4348 intval(CONTACT_IS_SHARING)
4356 $message = self::createProfileData($uid);
4358 foreach ($recips as $recip) {
4359 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4360 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4365 * @brief Stores the signature for likes that are created on our system
4367 * @param array $contact The contact array of the "like"
4368 * @param int $post_id The post id of the "like"
4370 * @return bool Success
4372 public static function storeLikeSignature($contact, $post_id)
4374 // Is the contact the owner? Then fetch the private key
4375 if (!$contact['self'] || ($contact['uid'] == 0)) {
4376 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4380 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4381 if (!DBM::is_result($r)) {
4385 $contact["uprvkey"] = $r[0]['prvkey'];
4387 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4388 if (!DBM::is_result($r)) {
4392 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4396 $message = self::constructLike($r[0], $contact);
4397 if ($message === false) {
4401 $message["author_signature"] = self::signature($contact, $message);
4404 * Now store the signature more flexible to dynamically support new fields.
4405 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4407 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4409 logger('Stored diaspora like signature');
4414 * @brief Stores the signature for comments that are created on our system
4416 * @param array $item The item array of the comment
4417 * @param array $contact The contact array of the item owner
4418 * @param string $uprvkey The private key of the sender
4419 * @param int $message_id The message id of the comment
4421 * @return bool Success
4423 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4425 if ($uprvkey == "") {
4426 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4430 $contact["uprvkey"] = $uprvkey;
4432 $message = self::constructComment($item, $contact);
4433 if ($message === false) {
4437 $message["author_signature"] = self::signature($contact, $message);
4440 * Now store the signature more flexible to dynamically support new fields.
4441 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4443 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4445 logger('Stored diaspora comment signature');