]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
DFRN: Bugfix for not storing mails
[friendica.git] / src / Protocol / Diaspora.php
1 <?php
2 /**
3  * @file src/Protocol/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  *
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.
9  */
10 namespace Friendica\Protocol;
11
12 use Friendica\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Item;
23 use Friendica\Model\Profile;
24 use Friendica\Model\Queue;
25 use Friendica\Model\User;
26 use Friendica\Network\Probe;
27 use Friendica\Util\Crypto;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\Network;
30 use Friendica\Util\XML;
31 use dba;
32 use SimpleXMLElement;
33
34 require_once 'include/dba.php';
35 require_once 'include/items.php';
36 require_once 'include/bb2diaspora.php';
37
38 /**
39  * @brief This class contain functions to create and send Diaspora XML files
40  *
41  */
42 class Diaspora
43 {
44         /**
45          * @brief Return a list of relay servers
46          *
47          * This is an experimental Diaspora feature.
48          *
49          * @return array of relay servers
50          */
51         public static function relayList()
52         {
53                 $serverdata = Config::get("system", "relay_server");
54                 if ($serverdata == "") {
55                         return [];
56                 }
57
58                 $relay = [];
59
60                 $servers = explode(",", $serverdata);
61
62                 foreach ($servers as $server) {
63                         $server = trim($server);
64                         $addr = "relay@".str_replace("http://", "", normalise_link($server));
65                         $batch = $server."/receive/public";
66
67                         $relais = q(
68                                 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
69                                 dbesc($batch),
70                                 dbesc($addr),
71                                 dbesc(normalise_link($server))
72                         );
73
74                         if (!$relais) {
75                                 $r = q(
76                                         "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
77                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
78                                         DateTimeFormat::utcNow(),
79                                         dbesc($addr),
80                                         dbesc($addr),
81                                         dbesc($server),
82                                         dbesc(normalise_link($server)),
83                                         dbesc($batch),
84                                         dbesc(NETWORK_DIASPORA),
85                                         intval(CONTACT_IS_FOLLOWER),
86                                         dbesc(DateTimeFormat::utcNow()),
87                                         dbesc(DateTimeFormat::utcNow()),
88                                         dbesc(DateTimeFormat::utcNow())
89                                 );
90
91                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
92                                 if ($relais) {
93                                         $relay[] = $relais[0];
94                                 }
95                         } else {
96                                 $relay[] = $relais[0];
97                         }
98                 }
99
100                 return $relay;
101         }
102
103         /**
104          * @brief Return a list of participating contacts for a thread
105          *
106          * This is used for the participation feature.
107          * One of the parameters is a contact array.
108          * This is done to avoid duplicates.
109          *
110          * @param integer $thread   The id of the thread
111          * @param array   $contacts The previously fetched contacts
112          *
113          * @return array of relay servers
114          */
115         public static function participantsForThread($thread, $contacts)
116         {
117                 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
118                                 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
119                                 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
120                                 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
121                                 WHERE `participation`.`iid` = ?", $thread);
122
123                 while ($contact = dba::fetch($r)) {
124                         if (!empty($contact['fnetwork'])) {
125                                 $contact['network'] = $contact['fnetwork'];
126                         }
127                         unset($contact['fnetwork']);
128
129                         if (empty($contact['batch']) && !empty($contact['fbatch'])) {
130                                 $contact['batch'] = $contact['fbatch'];
131                         }
132                         unset($contact['fbatch']);
133
134                         $exists = false;
135                         foreach ($contacts as $entry) {
136                                 if ($entry['batch'] == $contact['batch']) {
137                                         $exists = true;
138                                 }
139                         }
140
141                         if (!$exists) {
142                                 $contacts[] = $contact;
143                         }
144                 }
145                 dba::close($r);
146
147                 return $contacts;
148         }
149
150         /**
151          * @brief repairs a signature that was double encoded
152          *
153          * The function is unused at the moment. It was copied from the old implementation.
154          *
155          * @param string  $signature The signature
156          * @param string  $handle    The handle of the signature owner
157          * @param integer $level     This value is only set inside this function to avoid endless loops
158          *
159          * @return string the repaired signature
160          */
161         private static function repairSignature($signature, $handle = "", $level = 1)
162         {
163                 if ($signature == "") {
164                         return ($signature);
165                 }
166
167                 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
168                         $signature = base64_decode($signature);
169                         logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
170
171                         // Do a recursive call to be able to fix even multiple levels
172                         if ($level < 10) {
173                                 $signature = self::repairSignature($signature, $handle, ++$level);
174                         }
175                 }
176
177                 return($signature);
178         }
179
180         /**
181          * @brief verify the envelope and return the verified data
182          *
183          * @param string $envelope The magic envelope
184          *
185          * @return string verified data
186          */
187         private static function verifyMagicEnvelope($envelope)
188         {
189                 $basedom = XML::parseString($envelope);
190
191                 if (!is_object($basedom)) {
192                         logger("Envelope is no XML file");
193                         return false;
194                 }
195
196                 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
197
198                 if (sizeof($children) == 0) {
199                         logger("XML has no children");
200                         return false;
201                 }
202
203                 $handle = "";
204
205                 $data = base64url_decode($children->data);
206                 $type = $children->data->attributes()->type[0];
207
208                 $encoding = $children->encoding;
209
210                 $alg = $children->alg;
211
212                 $sig = base64url_decode($children->sig);
213                 $key_id = $children->sig->attributes()->key_id[0];
214                 if ($key_id != "") {
215                         $handle = base64url_decode($key_id);
216                 }
217
218                 $b64url_data = base64url_encode($data);
219                 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
220
221                 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
222
223                 $key = self::key($handle);
224
225                 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
226                 if (!$verify) {
227                         logger('Message did not verify. Discarding.');
228                         return false;
229                 }
230
231                 return $data;
232         }
233
234         /**
235          * @brief encrypts data via AES
236          *
237          * @param string $key  The AES key
238          * @param string $iv   The IV (is used for CBC encoding)
239          * @param string $data The data that is to be encrypted
240          *
241          * @return string encrypted data
242          */
243         private static function aesEncrypt($key, $iv, $data)
244         {
245                 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
246         }
247
248         /**
249          * @brief decrypts data via AES
250          *
251          * @param string $key       The AES key
252          * @param string $iv        The IV (is used for CBC encoding)
253          * @param string $encrypted The encrypted data
254          *
255          * @return string decrypted data
256          */
257         private static function aesDecrypt($key, $iv, $encrypted)
258         {
259                 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
260         }
261
262         /**
263          * @brief: Decodes incoming Diaspora message in the new format
264          *
265          * @param array  $importer Array of the importer user
266          * @param string $raw      raw post message
267          *
268          * @return array
269          * 'message' -> decoded Diaspora XML message
270          * 'author' -> author diaspora handle
271          * 'key' -> author public key (converted to pkcs#8)
272          */
273         public static function decodeRaw($importer, $raw)
274         {
275                 $data = json_decode($raw);
276
277                 // Is it a private post? Then decrypt the outer Salmon
278                 if (is_object($data)) {
279                         $encrypted_aes_key_bundle = base64_decode($data->aes_key);
280                         $ciphertext = base64_decode($data->encrypted_magic_envelope);
281
282                         $outer_key_bundle = '';
283                         @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
284                         $j_outer_key_bundle = json_decode($outer_key_bundle);
285
286                         if (!is_object($j_outer_key_bundle)) {
287                                 logger('Outer Salmon did not verify. Discarding.');
288                                 System::httpExit(400);
289                         }
290
291                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
292                         $outer_key = base64_decode($j_outer_key_bundle->key);
293
294                         $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
295                 } else {
296                         $xml = $raw;
297                 }
298
299                 $basedom = XML::parseString($xml);
300
301                 if (!is_object($basedom)) {
302                         logger('Received data does not seem to be an XML. Discarding. '.$xml);
303                         System::httpExit(400);
304                 }
305
306                 $base = $basedom->children(NAMESPACE_SALMON_ME);
307
308                 // Not sure if this cleaning is needed
309                 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
310
311                 // Build the signed data
312                 $type = $base->data[0]->attributes()->type[0];
313                 $encoding = $base->encoding;
314                 $alg = $base->alg;
315                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
316
317                 // This is the signature
318                 $signature = base64url_decode($base->sig);
319
320                 // Get the senders' public key
321                 $key_id = $base->sig[0]->attributes()->key_id[0];
322                 $author_addr = base64_decode($key_id);
323                 $key = self::key($author_addr);
324
325                 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
326                 if (!$verify) {
327                         logger('Message did not verify. Discarding.');
328                         System::httpExit(400);
329                 }
330
331                 return ['message' => (string)base64url_decode($base->data),
332                                 'author' => unxmlify($author_addr),
333                                 'key' => (string)$key];
334         }
335
336         /**
337          * @brief: Decodes incoming Diaspora message in the deprecated format
338          *
339          * @param array  $importer Array of the importer user
340          * @param string $xml      urldecoded Diaspora salmon
341          *
342          * @return array
343          * 'message' -> decoded Diaspora XML message
344          * 'author' -> author diaspora handle
345          * 'key' -> author public key (converted to pkcs#8)
346          */
347         public static function decode($importer, $xml)
348         {
349                 $public = false;
350                 $basedom = XML::parseString($xml);
351
352                 if (!is_object($basedom)) {
353                         logger("XML is not parseable.");
354                         return false;
355                 }
356                 $children = $basedom->children('https://joindiaspora.com/protocol');
357
358                 $inner_aes_key = null;
359                 $inner_iv = null;
360
361                 if ($children->header) {
362                         $public = true;
363                         $author_link = str_replace('acct:', '', $children->header->author_id);
364                 } else {
365                         // This happens with posts from a relais
366                         if (!$importer) {
367                                 logger("This is no private post in the old format", LOGGER_DEBUG);
368                                 return false;
369                         }
370
371                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
372
373                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
374                         $ciphertext = base64_decode($encrypted_header->ciphertext);
375
376                         $outer_key_bundle = '';
377                         openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
378
379                         $j_outer_key_bundle = json_decode($outer_key_bundle);
380
381                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
382                         $outer_key = base64_decode($j_outer_key_bundle->key);
383
384                         $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
385
386                         logger('decrypted: '.$decrypted, LOGGER_DEBUG);
387                         $idom = XML::parseString($decrypted);
388
389                         $inner_iv = base64_decode($idom->iv);
390                         $inner_aes_key = base64_decode($idom->aes_key);
391
392                         $author_link = str_replace('acct:', '', $idom->author_id);
393                 }
394
395                 $dom = $basedom->children(NAMESPACE_SALMON_ME);
396
397                 // figure out where in the DOM tree our data is hiding
398
399                 $base = null;
400                 if ($dom->provenance->data) {
401                         $base = $dom->provenance;
402                 } elseif ($dom->env->data) {
403                         $base = $dom->env;
404                 } elseif ($dom->data) {
405                         $base = $dom;
406                 }
407
408                 if (!$base) {
409                         logger('unable to locate salmon data in xml');
410                         System::httpExit(400);
411                 }
412
413
414                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
415                 $signature = base64url_decode($base->sig);
416
417                 // unpack the  data
418
419                 // strip whitespace so our data element will return to one big base64 blob
420                 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
421
422
423                 // stash away some other stuff for later
424
425                 $type = $base->data[0]->attributes()->type[0];
426                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
427                 $encoding = $base->encoding;
428                 $alg = $base->alg;
429
430
431                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
432
433
434                 // decode the data
435                 $data = base64url_decode($data);
436
437
438                 if ($public) {
439                         $inner_decrypted = $data;
440                 } else {
441                         // Decode the encrypted blob
442                         $inner_encrypted = base64_decode($data);
443                         $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
444                 }
445
446                 if (!$author_link) {
447                         logger('Could not retrieve author URI.');
448                         System::httpExit(400);
449                 }
450                 // Once we have the author URI, go to the web and try to find their public key
451                 // (first this will look it up locally if it is in the fcontact cache)
452                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
453
454                 logger('Fetching key for '.$author_link);
455                 $key = self::key($author_link);
456
457                 if (!$key) {
458                         logger('Could not retrieve author key.');
459                         System::httpExit(400);
460                 }
461
462                 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
463
464                 if (!$verify) {
465                         logger('Message did not verify. Discarding.');
466                         System::httpExit(400);
467                 }
468
469                 logger('Message verified.');
470
471                 return ['message' => (string)$inner_decrypted,
472                                 'author' => unxmlify($author_link),
473                                 'key' => (string)$key];
474         }
475
476
477         /**
478          * @brief Dispatches public messages and find the fitting receivers
479          *
480          * @param array $msg The post that will be dispatched
481          *
482          * @return int The message id of the generated message, "true" or "false" if there was an error
483          */
484         public static function dispatchPublic($msg)
485         {
486                 $enabled = intval(Config::get("system", "diaspora_enabled"));
487                 if (!$enabled) {
488                         logger("diaspora is disabled");
489                         return false;
490                 }
491
492                 if (!($postdata = self::validPosting($msg))) {
493                         logger("Invalid posting");
494                         return false;
495                 }
496
497                 $fields = $postdata['fields'];
498
499                 // Is it a an action (comment, like, ...) for our own post?
500                 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
501                         $guid = notags(unxmlify($fields->parent_guid));
502                         $importer = self::importerForGuid($guid);
503                         if (is_array($importer)) {
504                                 logger("delivering to origin: ".$importer["name"]);
505                                 $message_id = self::dispatch($importer, $msg, $fields);
506                                 return $message_id;
507                         }
508                 }
509
510                 // Process item retractions. This has to be done separated from the other stuff,
511                 // since retractions for comments could come even from non followers.
512                 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
513                         $target = notags(unxmlify($fields->target_type));
514                         if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
515                                 logger('processing retraction for '.$target, LOGGER_DEBUG);
516                                 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
517                                 $message_id = self::dispatch($importer, $msg, $fields);
518                                 return $message_id;
519                         }
520                 }
521
522                 // Now distribute it to the followers
523                 $r = q(
524                         "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
525                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
526                         AND NOT `account_expired` AND NOT `account_removed`",
527                         dbesc(NETWORK_DIASPORA),
528                         dbesc($msg["author"])
529                 );
530
531                 if (DBM::is_result($r)) {
532                         foreach ($r as $rr) {
533                                 logger("delivering to: ".$rr["username"]);
534                                 self::dispatch($rr, $msg, $fields);
535                         }
536                 } elseif (!Config::get('system', 'relay_subscribe', false)) {
537                         logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
538                 } else {
539                         // Use a dummy importer to import the data for the public copy
540                         $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
541                         $message_id = self::dispatch($importer, $msg, $fields);
542                 }
543
544                 return $message_id;
545         }
546
547         /**
548          * @brief Dispatches the different message types to the different functions
549          *
550          * @param array  $importer Array of the importer user
551          * @param array  $msg      The post that will be dispatched
552          * @param object $fields   SimpleXML object that contains the message
553          *
554          * @return int The message id of the generated message, "true" or "false" if there was an error
555          */
556         public static function dispatch($importer, $msg, $fields = null)
557         {
558                 // The sender is the handle of the contact that sent the message.
559                 // This will often be different with relayed messages (for example "like" and "comment")
560                 $sender = $msg["author"];
561
562                 // This is only needed for private postings since this is already done for public ones before
563                 if (is_null($fields)) {
564                         if (!($postdata = self::validPosting($msg))) {
565                                 logger("Invalid posting");
566                                 return false;
567                         }
568                         $fields = $postdata['fields'];
569                 }
570
571                 $type = $fields->getName();
572
573                 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
574
575                 switch ($type) {
576                         case "account_migration":
577                                 return self::receiveAccountMigration($importer, $fields);
578
579                         case "account_deletion":
580                                 return self::receiveAccountDeletion($importer, $fields);
581
582                         case "comment":
583                                 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
584
585                         case "contact":
586                                 return self::receiveContactRequest($importer, $fields);
587
588                         case "conversation":
589                                 return self::receiveConversation($importer, $msg, $fields);
590
591                         case "like":
592                                 return self::receiveLike($importer, $sender, $fields);
593
594                         case "message":
595                                 return self::receiveMessage($importer, $fields);
596
597                         case "participation":
598                                 return self::receiveParticipation($importer, $fields);
599
600                         case "photo": // Not implemented
601                                 return self::receivePhoto($importer, $fields);
602
603                         case "poll_participation": // Not implemented
604                                 return self::receivePollParticipation($importer, $fields);
605
606                         case "profile":
607                                 return self::receiveProfile($importer, $fields);
608
609                         case "reshare":
610                                 return self::receiveReshare($importer, $fields, $msg["message"]);
611
612                         case "retraction":
613                                 return self::receiveRetraction($importer, $sender, $fields);
614
615                         case "status_message":
616                                 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
617
618                         default:
619                                 logger("Unknown message type ".$type);
620                                 return false;
621                 }
622
623                 return true;
624         }
625
626         /**
627          * @brief Checks if a posting is valid and fetches the data fields.
628          *
629          * This function does not only check the signature.
630          * It also does the conversion between the old and the new diaspora format.
631          *
632          * @param array $msg Array with the XML, the sender handle and the sender signature
633          *
634          * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
635          */
636         private static function validPosting($msg)
637         {
638                 $data = XML::parseString($msg["message"]);
639
640                 if (!is_object($data)) {
641                         logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
642                         return false;
643                 }
644
645                 // Is this the new or the old version?
646                 if ($data->getName() == "XML") {
647                         $oldXML = true;
648                         foreach ($data->post->children() as $child) {
649                                 $element = $child;
650                         }
651                 } else {
652                         $oldXML = false;
653                         $element = $data;
654                 }
655
656                 $type = $element->getName();
657                 $orig_type = $type;
658
659                 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
660
661                 // All retractions are handled identically from now on.
662                 // In the new version there will only be "retraction".
663                 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
664                         $type = "retraction";
665
666                 if ($type == "request") {
667                         $type = "contact";
668                 }
669
670                 $fields = new SimpleXMLElement("<".$type."/>");
671
672                 $signed_data = "";
673                 $author_signature = null;
674                 $parent_author_signature = null;
675
676                 foreach ($element->children() as $fieldname => $entry) {
677                         if ($oldXML) {
678                                 // Translation for the old XML structure
679                                 if ($fieldname == "diaspora_handle") {
680                                         $fieldname = "author";
681                                 }
682                                 if ($fieldname == "participant_handles") {
683                                         $fieldname = "participants";
684                                 }
685                                 if (in_array($type, ["like", "participation"])) {
686                                         if ($fieldname == "target_type") {
687                                                 $fieldname = "parent_type";
688                                         }
689                                 }
690                                 if ($fieldname == "sender_handle") {
691                                         $fieldname = "author";
692                                 }
693                                 if ($fieldname == "recipient_handle") {
694                                         $fieldname = "recipient";
695                                 }
696                                 if ($fieldname == "root_diaspora_id") {
697                                         $fieldname = "root_author";
698                                 }
699                                 if ($type == "status_message") {
700                                         if ($fieldname == "raw_message") {
701                                                 $fieldname = "text";
702                                         }
703                                 }
704                                 if ($type == "retraction") {
705                                         if ($fieldname == "post_guid") {
706                                                 $fieldname = "target_guid";
707                                         }
708                                         if ($fieldname == "type") {
709                                                 $fieldname = "target_type";
710                                         }
711                                 }
712                         }
713
714                         if (($fieldname == "author_signature") && ($entry != "")) {
715                                 $author_signature = base64_decode($entry);
716                         } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
717                                 $parent_author_signature = base64_decode($entry);
718                         } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
719                                 if ($signed_data != "") {
720                                         $signed_data .= ";";
721                                 }
722
723                                 $signed_data .= $entry;
724                         }
725                         if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
726                                 || ($orig_type == "relayable_retraction")
727                         ) {
728                                 XML::copy($entry, $fields, $fieldname);
729                         }
730                 }
731
732                 // This is something that shouldn't happen at all.
733                 if (in_array($type, ["status_message", "reshare", "profile"])) {
734                         if ($msg["author"] != $fields->author) {
735                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
736                                 return false;
737                         }
738                 }
739
740                 // Only some message types have signatures. So we quit here for the other types.
741                 if (!in_array($type, ["comment", "like"])) {
742                         return ["fields" => $fields, "relayed" => false];
743                 }
744                 // No author_signature? This is a must, so we quit.
745                 if (!isset($author_signature)) {
746                         logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
747                         return false;
748                 }
749
750                 if (isset($parent_author_signature)) {
751                         $relayed = true;
752
753                         $key = self::key($msg["author"]);
754
755                         if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
756                                 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);
757                                 return false;
758                         }
759                 } else {
760                         $relayed = false;
761                 }
762
763                 $key = self::key($fields->author);
764
765                 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
766                         logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
767                         return false;
768                 } else {
769                         return ["fields" => $fields, "relayed" => $relayed];
770                 }
771         }
772
773         /**
774          * @brief Fetches the public key for a given handle
775          *
776          * @param string $handle The handle
777          *
778          * @return string The public key
779          */
780         private static function key($handle)
781         {
782                 $handle = strval($handle);
783
784                 logger("Fetching diaspora key for: ".$handle);
785
786                 $r = self::personByHandle($handle);
787                 if ($r) {
788                         return $r["pubkey"];
789                 }
790
791                 return "";
792         }
793
794         /**
795          * @brief Fetches data for a given handle
796          *
797          * @param string $handle The handle
798          *
799          * @return array the queried data
800          */
801         public static function personByHandle($handle)
802         {
803                 $update = false;
804
805                 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
806                 if (DBM::is_result($person)) {
807                         logger("In cache " . print_r($person, true), LOGGER_DEBUG);
808
809                         // update record occasionally so it doesn't get stale
810                         $d = strtotime($person["updated"]." +00:00");
811                         if ($d < strtotime("now - 14 days")) {
812                                 $update = true;
813                         }
814
815                         if ($person["guid"] == "") {
816                                 $update = true;
817                         }
818                 }
819
820                 if (!DBM::is_result($person) || $update) {
821                         logger("create or refresh", LOGGER_DEBUG);
822                         $r = Probe::uri($handle, NETWORK_DIASPORA);
823
824                         // Note that Friendica contacts will return a "Diaspora person"
825                         // if Diaspora connectivity is enabled on their server
826                         if ($r && ($r["network"] === NETWORK_DIASPORA)) {
827                                 self::addFContact($r, $update);
828                                 $person = $r;
829                         }
830                 }
831
832                 return $person;
833         }
834
835         /**
836          * @brief Updates the fcontact table
837          *
838          * @param array $arr    The fcontact data
839          * @param bool  $update Update or insert?
840          *
841          * @return string The id of the fcontact entry
842          */
843         private static function addFContact($arr, $update = false)
844         {
845                 if ($update) {
846                         $r = q(
847                                 "UPDATE `fcontact` SET
848                                         `name` = '%s',
849                                         `photo` = '%s',
850                                         `request` = '%s',
851                                         `nick` = '%s',
852                                         `addr` = '%s',
853                                         `guid` = '%s',
854                                         `batch` = '%s',
855                                         `notify` = '%s',
856                                         `poll` = '%s',
857                                         `confirm` = '%s',
858                                         `alias` = '%s',
859                                         `pubkey` = '%s',
860                                         `updated` = '%s'
861                                 WHERE `url` = '%s' AND `network` = '%s'",
862                                 dbesc($arr["name"]),
863                                 dbesc($arr["photo"]),
864                                 dbesc($arr["request"]),
865                                 dbesc($arr["nick"]),
866                                 dbesc(strtolower($arr["addr"])),
867                                 dbesc($arr["guid"]),
868                                 dbesc($arr["batch"]),
869                                 dbesc($arr["notify"]),
870                                 dbesc($arr["poll"]),
871                                 dbesc($arr["confirm"]),
872                                 dbesc($arr["alias"]),
873                                 dbesc($arr["pubkey"]),
874                                 dbesc(DateTimeFormat::utcNow()),
875                                 dbesc($arr["url"]),
876                                 dbesc($arr["network"])
877                         );
878                 } else {
879                         $r = q(
880                                 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
881                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
882                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
883                                 dbesc($arr["url"]),
884                                 dbesc($arr["name"]),
885                                 dbesc($arr["photo"]),
886                                 dbesc($arr["request"]),
887                                 dbesc($arr["nick"]),
888                                 dbesc($arr["addr"]),
889                                 dbesc($arr["guid"]),
890                                 dbesc($arr["batch"]),
891                                 dbesc($arr["notify"]),
892                                 dbesc($arr["poll"]),
893                                 dbesc($arr["confirm"]),
894                                 dbesc($arr["network"]),
895                                 dbesc($arr["alias"]),
896                                 dbesc($arr["pubkey"]),
897                                 dbesc(DateTimeFormat::utcNow())
898                         );
899                 }
900
901                 return $r;
902         }
903
904         /**
905          * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
906          *
907          * @param int $contact_id  The id in the contact table
908          * @param int $gcontact_id The id in the gcontact table
909          *
910          * @return string the handle
911          */
912         public static function handleFromContact($contact_id, $gcontact_id = 0)
913         {
914                 $handle = false;
915
916                 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
917
918                 if ($gcontact_id != 0) {
919                         $r = q(
920                                 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
921                                 intval($gcontact_id)
922                         );
923
924                         if (DBM::is_result($r)) {
925                                 return strtolower($r[0]["addr"]);
926                         }
927                 }
928
929                 $r = q(
930                         "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
931                         intval($contact_id)
932                 );
933
934                 if (DBM::is_result($r)) {
935                         $contact = $r[0];
936
937                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
938
939                         if ($contact['addr'] != "") {
940                                 $handle = $contact['addr'];
941                         } else {
942                                 $baseurl_start = strpos($contact['url'], '://') + 3;
943                                 // allows installations in a subdirectory--not sure how Diaspora will handle
944                                 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
945                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
946                                 $handle = $contact['nick'].'@'.$baseurl;
947                         }
948                 }
949
950                 return strtolower($handle);
951         }
952
953         /**
954          * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
955          * fcontact guid
956          *
957          * @param mixed $fcontact_guid Hexadecimal string guid
958          *
959          * @return string the contact url or null
960          */
961         public static function urlFromContactGuid($fcontact_guid)
962         {
963                 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
964
965                 $r = q(
966                         "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
967                         dbesc(NETWORK_DIASPORA),
968                         dbesc($fcontact_guid)
969                 );
970
971                 if (DBM::is_result($r)) {
972                         return $r[0]['url'];
973                 }
974
975                 return null;
976         }
977
978         /**
979          * @brief Get a contact id for a given handle
980          *
981          * @todo Move to Friendica\Model\Contact
982          *
983          * @param int    $uid    The user id
984          * @param string $handle The handle in the format user@domain.tld
985          *
986          * @return int Contact id
987          */
988         private static function contactByHandle($uid, $handle)
989         {
990                 // First do a direct search on the contact table
991                 $r = q(
992                         "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
993                         intval($uid),
994                         dbesc($handle)
995                 );
996
997                 if (DBM::is_result($r)) {
998                         return $r[0];
999                 } else {
1000                         /*
1001                          * We haven't found it?
1002                          * We use another function for it that will possibly create a contact entry.
1003                          */
1004                         $cid = Contact::getIdForURL($handle, $uid);
1005
1006                         if ($cid > 0) {
1007                                 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1008                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1009
1010                                 if (DBM::is_result($r)) {
1011                                         return $r[0];
1012                                 }
1013                         }
1014                 }
1015
1016                 $handle_parts = explode("@", $handle);
1017                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1018                 $r = q(
1019                         "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1020                         dbesc(NETWORK_DFRN),
1021                         intval($uid),
1022                         dbesc($nurl_sql)
1023                 );
1024                 if (DBM::is_result($r)) {
1025                         return $r[0];
1026                 }
1027
1028                 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1029                 return false;
1030         }
1031
1032         /**
1033          * @brief Check if posting is allowed for this contact
1034          *
1035          * @param array $importer   Array of the importer user
1036          * @param array $contact    The contact that is checked
1037          * @param bool  $is_comment Is the check for a comment?
1038          *
1039          * @return bool is the contact allowed to post?
1040          */
1041         private static function postAllow($importer, $contact, $is_comment = false)
1042         {
1043                 /*
1044                  * Perhaps we were already sharing with this person. Now they're sharing with us.
1045                  * That makes us friends.
1046                  * Normally this should have handled by getting a request - but this could get lost
1047                  */
1048                 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1049                 // It is not removed by now. Possibly the code is needed?
1050                 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1051                 //      dba::update(
1052                 //              'contact',
1053                 //              array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1054                 //              array('id' => $contact["id"], 'uid' => $contact["uid"])
1055                 //      );
1056                 //
1057                 //      $contact["rel"] = CONTACT_IS_FRIEND;
1058                 //      logger("defining user ".$contact["nick"]." as friend");
1059                 //}
1060
1061                 // We don't seem to like that person
1062                 if ($contact["blocked"] || $contact["readonly"]) {
1063                         // Maybe blocked, don't accept.
1064                         return false;
1065                         // We are following this person?
1066                 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1067                         // Yes, then it is fine.
1068                         return true;
1069                         // Is it a post to a community?
1070                 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1071                         // That's good
1072                         return true;
1073                         // Is the message a global user or a comment?
1074                 } elseif (($importer["uid"] == 0) || $is_comment) {
1075                         // Messages for the global users and comments are always accepted
1076                         return true;
1077                 }
1078
1079                 return false;
1080         }
1081
1082         /**
1083          * @brief Fetches the contact id for a handle and checks if posting is allowed
1084          *
1085          * @param array  $importer   Array of the importer user
1086          * @param string $handle     The checked handle in the format user@domain.tld
1087          * @param bool   $is_comment Is the check for a comment?
1088          *
1089          * @return array The contact data
1090          */
1091         private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1092         {
1093                 $contact = self::contactByHandle($importer["uid"], $handle);
1094                 if (!$contact) {
1095                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1096                         // If a contact isn't found, we accept it anyway if it is a comment
1097                         if ($is_comment) {
1098                                 return $importer;
1099                         } else {
1100                                 return false;
1101                         }
1102                 }
1103
1104                 if (!self::postAllow($importer, $contact, $is_comment)) {
1105                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1106                         return false;
1107                 }
1108                 return $contact;
1109         }
1110
1111         /**
1112          * @brief Does the message already exists on the system?
1113          *
1114          * @param int    $uid  The user id
1115          * @param string $guid The guid of the message
1116          *
1117          * @return int|bool message id if the message already was stored into the system - or false.
1118          */
1119         private static function messageExists($uid, $guid)
1120         {
1121                 $r = q(
1122                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1123                         intval($uid),
1124                         dbesc($guid)
1125                 );
1126
1127                 if (DBM::is_result($r)) {
1128                         logger("message ".$guid." already exists for user ".$uid);
1129                         return $r[0]["id"];
1130                 }
1131
1132                 return false;
1133         }
1134
1135         /**
1136          * @brief Checks for links to posts in a message
1137          *
1138          * @param array $item The item array
1139          * @return void
1140          */
1141         private static function fetchGuid($item)
1142         {
1143                 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1144                 preg_replace_callback(
1145                         $expression,
1146                         function ($match) use ($item) {
1147                                 self::fetchGuidSub($match, $item);
1148                         },
1149                         $item["body"]
1150                 );
1151
1152                 preg_replace_callback(
1153                         "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1154                         function ($match) use ($item) {
1155                                 self::fetchGuidSub($match, $item);
1156                         },
1157                         $item["body"]
1158                 );
1159         }
1160
1161         /**
1162          * @brief Checks for relative /people/* links in an item body to match local
1163          * contacts or prepends the remote host taken from the author link.
1164          *
1165          * @param string $body        The item body to replace links from
1166          * @param string $author_link The author link for missing local contact fallback
1167          *
1168          * @return string the replaced string
1169          */
1170         public static function replacePeopleGuid($body, $author_link)
1171         {
1172                 $return = preg_replace_callback(
1173                         "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1174                         function ($match) use ($author_link) {
1175                                 // $match
1176                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1177                                 // 1 => '0123456789abcdef'
1178                                 // 2 => 'Foo Bar'
1179                                 $handle = self::urlFromContactGuid($match[1]);
1180
1181                                 if ($handle) {
1182                                         $return = '@[url='.$handle.']'.$match[2].'[/url]';
1183                                 } else {
1184                                         // No local match, restoring absolute remote URL from author scheme and host
1185                                         $author_url = parse_url($author_link);
1186                                         $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1187                                 }
1188
1189                                 return $return;
1190                         },
1191                         $body
1192                 );
1193
1194                 return $return;
1195         }
1196
1197         /**
1198          * @brief sub function of "fetchGuid" which checks for links in messages
1199          *
1200          * @param array $match array containing a link that has to be checked for a message link
1201          * @param array $item  The item array
1202          * @return void
1203          */
1204         private static function fetchGuidSub($match, $item)
1205         {
1206                 if (!self::storeByGuid($match[1], $item["author-link"])) {
1207                         self::storeByGuid($match[1], $item["owner-link"]);
1208                 }
1209         }
1210
1211         /**
1212          * @brief Fetches an item with a given guid from a given server
1213          *
1214          * @param string $guid   the message guid
1215          * @param string $server The server address
1216          * @param int    $uid    The user id of the user
1217          *
1218          * @return int the message id of the stored message or false
1219          */
1220         private static function storeByGuid($guid, $server, $uid = 0)
1221         {
1222                 $serverparts = parse_url($server);
1223                 $server = $serverparts["scheme"]."://".$serverparts["host"];
1224
1225                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1226
1227                 $msg = self::message($guid, $server);
1228
1229                 if (!$msg) {
1230                         return false;
1231                 }
1232
1233                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1234
1235                 // Now call the dispatcher
1236                 return self::dispatchPublic($msg);
1237         }
1238
1239         /**
1240          * @brief Fetches a message from a server
1241          *
1242          * @param string $guid   message guid
1243          * @param string $server The url of the server
1244          * @param int    $level  Endless loop prevention
1245          *
1246          * @return array
1247          *      'message' => The message XML
1248          *      'author' => The author handle
1249          *      'key' => The public key of the author
1250          */
1251         private static function message($guid, $server, $level = 0)
1252         {
1253                 if ($level > 5) {
1254                         return false;
1255                 }
1256
1257                 // This will work for new Diaspora servers and Friendica servers from 3.5
1258                 $source_url = $server."/fetch/post/".urlencode($guid);
1259
1260                 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1261
1262                 $envelope = Network::fetchUrl($source_url);
1263                 if ($envelope) {
1264                         logger("Envelope was fetched.", LOGGER_DEBUG);
1265                         $x = self::verifyMagicEnvelope($envelope);
1266                         if (!$x) {
1267                                 logger("Envelope could not be verified.", LOGGER_DEBUG);
1268                         } else {
1269                                 logger("Envelope was verified.", LOGGER_DEBUG);
1270                         }
1271                 } else {
1272                         $x = false;
1273                 }
1274
1275                 // This will work for older Diaspora and Friendica servers
1276                 if (!$x) {
1277                         $source_url = $server."/p/".urlencode($guid).".xml";
1278                         logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1279
1280                         $x = Network::fetchUrl($source_url);
1281                         if (!$x) {
1282                                 return false;
1283                         }
1284                 }
1285
1286                 $source_xml = XML::parseString($x);
1287
1288                 if (!is_object($source_xml)) {
1289                         return false;
1290                 }
1291
1292                 if ($source_xml->post->reshare) {
1293                         // Reshare of a reshare - old Diaspora version
1294                         logger("Message is a reshare", LOGGER_DEBUG);
1295                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1296                 } elseif ($source_xml->getName() == "reshare") {
1297                         // Reshare of a reshare - new Diaspora version
1298                         logger("Message is a new reshare", LOGGER_DEBUG);
1299                         return self::message($source_xml->root_guid, $server, ++$level);
1300                 }
1301
1302                 $author = "";
1303
1304                 // Fetch the author - for the old and the new Diaspora version
1305                 if ($source_xml->post->status_message->diaspora_handle) {
1306                         $author = (string)$source_xml->post->status_message->diaspora_handle;
1307                 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1308                         $author = (string)$source_xml->author;
1309                 }
1310
1311                 // If this isn't a "status_message" then quit
1312                 if (!$author) {
1313                         logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1314                         return false;
1315                 }
1316
1317                 $msg = ["message" => $x, "author" => $author];
1318
1319                 $msg["key"] = self::key($msg["author"]);
1320
1321                 return $msg;
1322         }
1323
1324         /**
1325          * @brief Fetches the item record of a given guid
1326          *
1327          * @param int    $uid     The user id
1328          * @param string $guid    message guid
1329          * @param string $author  The handle of the item
1330          * @param array  $contact The contact of the item owner
1331          *
1332          * @return array the item record
1333          */
1334         private static function parentItem($uid, $guid, $author, $contact)
1335         {
1336                 $r = q(
1337                         "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1338                                 `author-name`, `author-link`, `author-avatar`,
1339                                 `owner-name`, `owner-link`, `owner-avatar`
1340                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1341                         intval($uid),
1342                         dbesc($guid)
1343                 );
1344
1345                 if (!$r) {
1346                         $result = self::storeByGuid($guid, $contact["url"], $uid);
1347
1348                         if (!$result) {
1349                                 $person = self::personByHandle($author);
1350                                 $result = self::storeByGuid($guid, $person["url"], $uid);
1351                         }
1352
1353                         if ($result) {
1354                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1355
1356                                 $r = q(
1357                                         "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1358                                                 `author-name`, `author-link`, `author-avatar`,
1359                                                 `owner-name`, `owner-link`, `owner-avatar`
1360                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1361                                         intval($uid),
1362                                         dbesc($guid)
1363                                 );
1364                         }
1365                 }
1366
1367                 if (!$r) {
1368                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
1369                         return false;
1370                 } else {
1371                         logger("parent item found: parent: ".$guid." - user: ".$uid);
1372                         return $r[0];
1373                 }
1374         }
1375
1376         /**
1377          * @brief returns contact details
1378          *
1379          * @param array $def_contact The default contact if the person isn't found
1380          * @param array $person      The record of the person
1381          * @param int   $uid         The user id
1382          *
1383          * @return array
1384          *      'cid' => contact id
1385          *      'network' => network type
1386          */
1387         private static function authorContactByUrl($def_contact, $person, $uid)
1388         {
1389                 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1390                 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1391                 if (DBM::is_result($contact)) {
1392                         $cid = $contact["id"];
1393                         $network = $contact["network"];
1394                 } else {
1395                         $cid = $def_contact["id"];
1396                         $network = NETWORK_DIASPORA;
1397                 }
1398
1399                 return ["cid" => $cid, "network" => $network];
1400         }
1401
1402         /**
1403          * @brief Is the profile a hubzilla profile?
1404          *
1405          * @param string $url The profile link
1406          *
1407          * @return bool is it a hubzilla server?
1408          */
1409         public static function isRedmatrix($url)
1410         {
1411                 return(strstr($url, "/channel/"));
1412         }
1413
1414         /**
1415          * @brief Generate a post link with a given handle and message guid
1416          *
1417          * @param string $addr        The user handle
1418          * @param string $guid        message guid
1419          * @param string $parent_guid optional parent guid
1420          *
1421          * @return string the post link
1422          */
1423         private static function plink($addr, $guid, $parent_guid = '')
1424         {
1425                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1426
1427                 // Fallback
1428                 if (!DBM::is_result($r)) {
1429                         if ($parent_guid != '') {
1430                                 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1431                         } else {
1432                                 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1433                         }
1434                 }
1435
1436                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1437                 // So we try another way as well.
1438                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1439                 if (DBM::is_result($s)) {
1440                         $r[0]["network"] = $s[0]["network"];
1441                 }
1442
1443                 if ($r[0]["network"] == NETWORK_DFRN) {
1444                         return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1445                 }
1446
1447                 if (self::isRedmatrix($r[0]["url"])) {
1448                         return $r[0]["url"]."/?f=&mid=".$guid;
1449                 }
1450
1451                 if ($parent_guid != '') {
1452                         return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1453                 } else {
1454                         return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1455                 }
1456         }
1457
1458         /**
1459          * @brief Receives account migration
1460          *
1461          * @param array  $importer Array of the importer user
1462          * @param object $data     The message object
1463          *
1464          * @return bool Success
1465          */
1466         private static function receiveAccountMigration($importer, $data)
1467         {
1468                 $old_handle = notags(unxmlify($data->author));
1469                 $new_handle = notags(unxmlify($data->profile->author));
1470                 $signature = notags(unxmlify($data->signature));
1471
1472                 $contact = self::contactByHandle($importer["uid"], $old_handle);
1473                 if (!$contact) {
1474                         logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1475                         return false;
1476                 }
1477
1478                 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1479
1480                 // Check signature
1481                 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1482                 $key = self::key($old_handle);
1483                 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1484                         logger('No valid signature for migration.');
1485                         return false;
1486                 }
1487
1488                 // Update the profile
1489                 self::receiveProfile($importer, $data->profile);
1490
1491                 // change the technical stuff in contact and gcontact
1492                 $data = Probe::uri($new_handle);
1493                 if ($data['network'] == NETWORK_PHANTOM) {
1494                         logger('Account for '.$new_handle." couldn't be probed.");
1495                         return false;
1496                 }
1497
1498                 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1499                                 'name' => $data['name'], 'nick' => $data['nick'],
1500                                 'addr' => $data['addr'], 'batch' => $data['batch'],
1501                                 'notify' => $data['notify'], 'poll' => $data['poll'],
1502                                 'network' => $data['network']];
1503
1504                 dba::update('contact', $fields, ['addr' => $old_handle]);
1505
1506                 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1507                                 'name' => $data['name'], 'nick' => $data['nick'],
1508                                 'addr' => $data['addr'], 'connect' => $data['addr'],
1509                                 'notify' => $data['notify'], 'photo' => $data['photo'],
1510                                 'server_url' => $data['baseurl'], 'network' => $data['network']];
1511
1512                 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1513
1514                 logger('Contacts are updated.');
1515
1516                 // update items
1517                 /// @todo This is an extreme performance killer
1518                 $fields = [
1519                         'owner-link' => [$contact["url"], $data["url"]],
1520                         'author-link' => [$contact["url"], $data["url"]],
1521                 ];
1522                 foreach ($fields as $n => $f) {
1523                         $r = q(
1524                                 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1525                                 $n,
1526                                 dbesc($f[0]),
1527                                 intval($importer["uid"])
1528                         );
1529
1530                         if (DBM::is_result($r)) {
1531                                 $x = q(
1532                                         "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1533                                         $n,
1534                                         dbesc($f[1]),
1535                                         $n,
1536                                         dbesc($f[0]),
1537                                         intval($importer["uid"])
1538                                 );
1539
1540                                 if ($x === false) {
1541                                         return false;
1542                                 }
1543                         }
1544                 }
1545
1546                 logger('Items are updated.');
1547
1548                 return true;
1549         }
1550
1551         /**
1552          * @brief Processes an account deletion
1553          *
1554          * @param array  $importer Array of the importer user
1555          * @param object $data     The message object
1556          *
1557          * @return bool Success
1558          */
1559         private static function receiveAccountDeletion($importer, $data)
1560         {
1561                 /// @todo Account deletion should remove the contact from the global contacts as well
1562
1563                 $author = notags(unxmlify($data->author));
1564
1565                 $contact = self::contactByHandle($importer["uid"], $author);
1566                 if (!$contact) {
1567                         logger("cannot find contact for author: ".$author);
1568                         return false;
1569                 }
1570
1571                 // We now remove the contact
1572                 Contact::remove($contact["id"]);
1573                 return true;
1574         }
1575
1576         /**
1577          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1578          *
1579          * @param string  $author    Author handle
1580          * @param string  $guid      Message guid
1581          * @param boolean $onlyfound Only return uri when found in the database
1582          *
1583          * @return string The constructed uri or the one from our database
1584          */
1585         private static function getUriFromGuid($author, $guid, $onlyfound = false)
1586         {
1587                 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1588                 if (DBM::is_result($r)) {
1589                         return $r[0]["uri"];
1590                 } elseif (!$onlyfound) {
1591                         return $author.":".$guid;
1592                 }
1593
1594                 return "";
1595         }
1596
1597         /**
1598          * @brief Fetch the guid from our database with a given uri
1599          *
1600          * @param string $uri Message uri
1601          * @param string $uid Author handle
1602          *
1603          * @return string The post guid
1604          */
1605         private static function getGuidFromUri($uri, $uid)
1606         {
1607                 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1608                 if (DBM::is_result($r)) {
1609                         return $r[0]["guid"];
1610                 } else {
1611                         return false;
1612                 }
1613         }
1614
1615         /**
1616          * @brief Find the best importer for a comment, like, ...
1617          *
1618          * @param string $guid The guid of the item
1619          *
1620          * @return array|boolean the origin owner of that post - or false
1621          */
1622         private static function importerForGuid($guid)
1623         {
1624                 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1625
1626                 if (DBM::is_result($item)) {
1627                         logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1628                         $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1629                         if (DBM::is_result($contact)) {
1630                                 return $contact;
1631                         }
1632                 }
1633                 return false;
1634         }
1635
1636         /**
1637          * @brief Processes an incoming comment
1638          *
1639          * @param array  $importer Array of the importer user
1640          * @param string $sender   The sender of the message
1641          * @param object $data     The message object
1642          * @param string $xml      The original XML of the message
1643          *
1644          * @return int The message id of the generated comment or "false" if there was an error
1645          */
1646         private static function receiveComment($importer, $sender, $data, $xml)
1647         {
1648                 $author = notags(unxmlify($data->author));
1649                 $guid = notags(unxmlify($data->guid));
1650                 $parent_guid = notags(unxmlify($data->parent_guid));
1651                 $text = unxmlify($data->text);
1652
1653                 if (isset($data->created_at)) {
1654                         $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1655                 } else {
1656                         $created_at = DateTimeFormat::utcNow();
1657                 }
1658
1659                 if (isset($data->thread_parent_guid)) {
1660                         $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1661                         $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1662                 } else {
1663                         $thr_uri = "";
1664                 }
1665
1666                 $contact = self::allowedContactByHandle($importer, $sender, true);
1667                 if (!$contact) {
1668                         return false;
1669                 }
1670
1671                 $message_id = self::messageExists($importer["uid"], $guid);
1672                 if ($message_id) {
1673                         return true;
1674                 }
1675
1676                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1677                 if (!$parent_item) {
1678                         return false;
1679                 }
1680
1681                 $person = self::personByHandle($author);
1682                 if (!is_array($person)) {
1683                         logger("unable to find author details");
1684                         return false;
1685                 }
1686
1687                 // Fetch the contact id - if we know this contact
1688                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1689
1690                 $datarray = [];
1691
1692                 $datarray["uid"] = $importer["uid"];
1693                 $datarray["contact-id"] = $author_contact["cid"];
1694                 $datarray["network"]  = $author_contact["network"];
1695
1696                 $datarray["author-name"] = $person["name"];
1697                 $datarray["author-link"] = $person["url"];
1698                 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1699
1700                 $datarray["owner-name"] = $contact["name"];
1701                 $datarray["owner-link"] = $contact["url"];
1702                 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1703
1704                 $datarray["guid"] = $guid;
1705                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1706
1707                 $datarray["type"] = "remote-comment";
1708                 $datarray["verb"] = ACTIVITY_POST;
1709                 $datarray["gravity"] = GRAVITY_COMMENT;
1710
1711                 if ($thr_uri != "") {
1712                         $datarray["parent-uri"] = $thr_uri;
1713                 } else {
1714                         $datarray["parent-uri"] = $parent_item["uri"];
1715                 }
1716
1717                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1718
1719                 $datarray["protocol"] = PROTOCOL_DIASPORA;
1720                 $datarray["source"] = $xml;
1721
1722                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1723
1724                 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1725
1726                 $body = diaspora2bb($text);
1727
1728                 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1729
1730                 self::fetchGuid($datarray);
1731
1732                 $message_id = Item::insert($datarray);
1733
1734                 if ($message_id <= 0) {
1735                         return false;
1736                 }
1737
1738                 if ($message_id) {
1739                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1740                 }
1741
1742                 // If we are the origin of the parent we store the original data and notify our followers
1743                 if ($message_id && $parent_item["origin"]) {
1744                         // Formerly we stored the signed text, the signature and the author in different fields.
1745                         // We now store the raw data so that we are more flexible.
1746                         dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1747
1748                         // notify others
1749                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1750                 }
1751
1752                 return true;
1753         }
1754
1755         /**
1756          * @brief processes and stores private messages
1757          *
1758          * @param array  $importer     Array of the importer user
1759          * @param array  $contact      The contact of the message
1760          * @param object $data         The message object
1761          * @param array  $msg          Array of the processed message, author handle and key
1762          * @param object $mesg         The private message
1763          * @param array  $conversation The conversation record to which this message belongs
1764          *
1765          * @return bool "true" if it was successful
1766          */
1767         private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1768         {
1769                 $author = notags(unxmlify($data->author));
1770                 $guid = notags(unxmlify($data->guid));
1771                 $subject = notags(unxmlify($data->subject));
1772
1773                 // "diaspora_handle" is the element name from the old version
1774                 // "author" is the element name from the new version
1775                 if ($mesg->author) {
1776                         $msg_author = notags(unxmlify($mesg->author));
1777                 } elseif ($mesg->diaspora_handle) {
1778                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1779                 } else {
1780                         return false;
1781                 }
1782
1783                 $msg_guid = notags(unxmlify($mesg->guid));
1784                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1785                 $msg_text = unxmlify($mesg->text);
1786                 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1787
1788                 if ($msg_conversation_guid != $guid) {
1789                         logger("message conversation guid does not belong to the current conversation.");
1790                         return false;
1791                 }
1792
1793                 $body = diaspora2bb($msg_text);
1794                 $message_uri = $msg_author.":".$msg_guid;
1795
1796                 $person = self::personByHandle($msg_author);
1797
1798                 dba::lock('mail');
1799
1800                 $r = q(
1801                         "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1802                         dbesc($msg_guid),
1803                         intval($importer["uid"])
1804                 );
1805                 if (DBM::is_result($r)) {
1806                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1807                         return false;
1808                 }
1809
1810                 q(
1811                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1812                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1813                         intval($importer["uid"]),
1814                         dbesc($msg_guid),
1815                         intval($conversation["id"]),
1816                         dbesc($person["name"]),
1817                         dbesc($person["photo"]),
1818                         dbesc($person["url"]),
1819                         intval($contact["id"]),
1820                         dbesc($subject),
1821                         dbesc($body),
1822                         0,
1823                         0,
1824                         dbesc($message_uri),
1825                         dbesc($author.":".$guid),
1826                         dbesc($msg_created_at)
1827                 );
1828
1829                 dba::unlock();
1830
1831                 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1832
1833                 notification(
1834                         [
1835                         "type" => NOTIFY_MAIL,
1836                         "notify_flags" => $importer["notify-flags"],
1837                         "language" => $importer["language"],
1838                         "to_name" => $importer["username"],
1839                         "to_email" => $importer["email"],
1840                         "uid" =>$importer["uid"],
1841                         "item" => ["subject" => $subject, "body" => $body],
1842                         "source_name" => $person["name"],
1843                         "source_link" => $person["url"],
1844                         "source_photo" => $person["thumb"],
1845                         "verb" => ACTIVITY_POST,
1846                         "otype" => "mail"]
1847                 );
1848                 return true;
1849         }
1850
1851         /**
1852          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1853          *
1854          * @param array  $importer Array of the importer user
1855          * @param array  $msg      Array of the processed message, author handle and key
1856          * @param object $data     The message object
1857          *
1858          * @return bool Success
1859          */
1860         private static function receiveConversation($importer, $msg, $data)
1861         {
1862                 $author = notags(unxmlify($data->author));
1863                 $guid = notags(unxmlify($data->guid));
1864                 $subject = notags(unxmlify($data->subject));
1865                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1866                 $participants = notags(unxmlify($data->participants));
1867
1868                 $messages = $data->message;
1869
1870                 if (!count($messages)) {
1871                         logger("empty conversation");
1872                         return false;
1873                 }
1874
1875                 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1876                 if (!$contact) {
1877                         return false;
1878                 }
1879
1880                 $conversation = null;
1881
1882                 $c = q(
1883                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1884                         intval($importer["uid"]),
1885                         dbesc($guid)
1886                 );
1887                 if ($c)
1888                         $conversation = $c[0];
1889                 else {
1890                         $r = q(
1891                                 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1892                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1893                                 intval($importer["uid"]),
1894                                 dbesc($guid),
1895                                 dbesc($author),
1896                                 dbesc($created_at),
1897                                 dbesc(DateTimeFormat::utcNow()),
1898                                 dbesc($subject),
1899                                 dbesc($participants)
1900                         );
1901                         if ($r) {
1902                                 $c = q(
1903                                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1904                                         intval($importer["uid"]),
1905                                         dbesc($guid)
1906                                 );
1907                         }
1908
1909                         if ($c) {
1910                                 $conversation = $c[0];
1911                         }
1912                 }
1913                 if (!$conversation) {
1914                         logger("unable to create conversation.");
1915                         return false;
1916                 }
1917
1918                 foreach ($messages as $mesg) {
1919                         self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1920                 }
1921
1922                 return true;
1923         }
1924
1925         /**
1926          * @brief Creates the body for a "like" message
1927          *
1928          * @param array  $contact     The contact that send us the "like"
1929          * @param array  $parent_item The item array of the parent item
1930          * @param string $guid        message guid
1931          *
1932          * @return string the body
1933          */
1934         private static function constructLikeBody($contact, $parent_item, $guid)
1935         {
1936                 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1937
1938                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1939                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1940                 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1941
1942                 return sprintf($bodyverb, $ulink, $alink, $plink);
1943         }
1944
1945         /**
1946          * @brief Creates a XML object for a "like"
1947          *
1948          * @param array $importer    Array of the importer user
1949          * @param array $parent_item The item array of the parent item
1950          *
1951          * @return string The XML
1952          */
1953         private static function constructLikeObject($importer, $parent_item)
1954         {
1955                 $objtype = ACTIVITY_OBJ_NOTE;
1956                 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1957                 $parent_body = $parent_item["body"];
1958
1959                 $xmldata = ["object" => ["type" => $objtype,
1960                                                 "local" => "1",
1961                                                 "id" => $parent_item["uri"],
1962                                                 "link" => $link,
1963                                                 "title" => "",
1964                                                 "content" => $parent_body]];
1965
1966                 return XML::fromArray($xmldata, $xml, true);
1967         }
1968
1969         /**
1970          * @brief Processes "like" messages
1971          *
1972          * @param array  $importer Array of the importer user
1973          * @param string $sender   The sender of the message
1974          * @param object $data     The message object
1975          *
1976          * @return int The message id of the generated like or "false" if there was an error
1977          */
1978         private static function receiveLike($importer, $sender, $data)
1979         {
1980                 $author = notags(unxmlify($data->author));
1981                 $guid = notags(unxmlify($data->guid));
1982                 $parent_guid = notags(unxmlify($data->parent_guid));
1983                 $parent_type = notags(unxmlify($data->parent_type));
1984                 $positive = notags(unxmlify($data->positive));
1985
1986                 // likes on comments aren't supported by Diaspora - only on posts
1987                 // But maybe this will be supported in the future, so we will accept it.
1988                 if (!in_array($parent_type, ["Post", "Comment"])) {
1989                         return false;
1990                 }
1991
1992                 $contact = self::allowedContactByHandle($importer, $sender, true);
1993                 if (!$contact) {
1994                         return false;
1995                 }
1996
1997                 $message_id = self::messageExists($importer["uid"], $guid);
1998                 if ($message_id) {
1999                         return true;
2000                 }
2001
2002                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2003                 if (!$parent_item) {
2004                         return false;
2005                 }
2006
2007                 $person = self::personByHandle($author);
2008                 if (!is_array($person)) {
2009                         logger("unable to find author details");
2010                         return false;
2011                 }
2012
2013                 // Fetch the contact id - if we know this contact
2014                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2015
2016                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2017                 // We would accept this anyhow.
2018                 if ($positive == "true") {
2019                         $verb = ACTIVITY_LIKE;
2020                 } else {
2021                         $verb = ACTIVITY_DISLIKE;
2022                 }
2023
2024                 $datarray = [];
2025
2026                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2027
2028                 $datarray["uid"] = $importer["uid"];
2029                 $datarray["contact-id"] = $author_contact["cid"];
2030                 $datarray["network"]  = $author_contact["network"];
2031
2032                 $datarray["author-name"] = $person["name"];
2033                 $datarray["author-link"] = $person["url"];
2034                 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2035
2036                 $datarray["owner-name"] = $contact["name"];
2037                 $datarray["owner-link"] = $contact["url"];
2038                 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2039
2040                 $datarray["guid"] = $guid;
2041                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2042
2043                 $datarray["type"] = "activity";
2044                 $datarray["verb"] = $verb;
2045                 $datarray["gravity"] = GRAVITY_LIKE;
2046                 $datarray["parent-uri"] = $parent_item["uri"];
2047
2048                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2049                 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2050
2051                 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2052
2053                 $message_id = Item::insert($datarray);
2054
2055                 if ($message_id <= 0) {
2056                         return false;
2057                 }
2058
2059                 if ($message_id) {
2060                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2061                 }
2062
2063                 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2064                 if ($parent_item["id"] != $parent_item["parent"]) {
2065                         $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2066                         $origin = $toplevel["origin"];
2067                 } else {
2068                         $origin = $parent_item["origin"];
2069                 }
2070
2071                 // If we are the origin of the parent we store the original data and notify our followers
2072                 if ($message_id && $origin) {
2073                         // Formerly we stored the signed text, the signature and the author in different fields.
2074                         // We now store the raw data so that we are more flexible.
2075                         dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2076
2077                         // notify others
2078                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2079                 }
2080
2081                 return true;
2082         }
2083
2084         /**
2085          * @brief Processes private messages
2086          *
2087          * @param array  $importer Array of the importer user
2088          * @param object $data     The message object
2089          *
2090          * @return bool Success?
2091          */
2092         private static function receiveMessage($importer, $data)
2093         {
2094                 $author = notags(unxmlify($data->author));
2095                 $guid = notags(unxmlify($data->guid));
2096                 $conversation_guid = notags(unxmlify($data->conversation_guid));
2097                 $text = unxmlify($data->text);
2098                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2099
2100                 $contact = self::allowedContactByHandle($importer, $author, true);
2101                 if (!$contact) {
2102                         return false;
2103                 }
2104
2105                 $conversation = null;
2106
2107                 $c = q(
2108                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2109                         intval($importer["uid"]),
2110                         dbesc($conversation_guid)
2111                 );
2112                 if ($c) {
2113                         $conversation = $c[0];
2114                 } else {
2115                         logger("conversation not available.");
2116                         return false;
2117                 }
2118
2119                 $message_uri = $author.":".$guid;
2120
2121                 $person = self::personByHandle($author);
2122                 if (!$person) {
2123                         logger("unable to find author details");
2124                         return false;
2125                 }
2126
2127                 $body = diaspora2bb($text);
2128
2129                 $body = self::replacePeopleGuid($body, $person["url"]);
2130
2131                 dba::lock('mail');
2132
2133                 $r = q(
2134                         "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2135                         dbesc($guid),
2136                         intval($importer["uid"])
2137                 );
2138                 if (DBM::is_result($r)) {
2139                         logger("duplicate message already delivered.", LOGGER_DEBUG);
2140                         return false;
2141                 }
2142
2143                 q(
2144                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2145                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2146                         intval($importer["uid"]),
2147                         dbesc($guid),
2148                         intval($conversation["id"]),
2149                         dbesc($person["name"]),
2150                         dbesc($person["photo"]),
2151                         dbesc($person["url"]),
2152                         intval($contact["id"]),
2153                         dbesc($conversation["subject"]),
2154                         dbesc($body),
2155                         0,
2156                         1,
2157                         dbesc($message_uri),
2158                         dbesc($author.":".$conversation["guid"]),
2159                         dbesc($created_at)
2160                 );
2161
2162                 dba::unlock();
2163
2164                 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2165                 return true;
2166         }
2167
2168         /**
2169          * @brief Processes participations - unsupported by now
2170          *
2171          * @param array  $importer Array of the importer user
2172          * @param object $data     The message object
2173          *
2174          * @return bool always true
2175          */
2176         private static function receiveParticipation($importer, $data)
2177         {
2178                 $author = strtolower(notags(unxmlify($data->author)));
2179                 $parent_guid = notags(unxmlify($data->parent_guid));
2180
2181                 $contact_id = Contact::getIdForURL($author);
2182                 if (!$contact_id) {
2183                         logger('Contact not found: '.$author);
2184                         return false;
2185                 }
2186
2187                 $person = self::personByHandle($author);
2188                 if (!is_array($person)) {
2189                         logger("Person not found: ".$author);
2190                         return false;
2191                 }
2192
2193                 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2194                 if (!DBM::is_result($item)) {
2195                         logger('Item not found, no origin or private: '.$parent_guid);
2196                         return false;
2197                 }
2198
2199                 $author_parts = explode('@', $author);
2200                 if (isset($author_parts[1])) {
2201                         $server = $author_parts[1];
2202                 } else {
2203                         // Should never happen
2204                         $server = $author;
2205                 }
2206
2207                 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2208                 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2209
2210                 // Send all existing comments and likes to the requesting server
2211                 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2212                                 FROM `item`
2213                                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2214                                 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2215                 while ($comment = dba::fetch($comments)) {
2216                         if ($comment['verb'] == ACTIVITY_POST) {
2217                                 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2218                         } else {
2219                                 $cmd = $comment['self'] ? 'like' : 'comment-import';
2220                         }
2221                         logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2222                         Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2223                 }
2224                 dba::close($comments);
2225
2226                 return true;
2227         }
2228
2229         /**
2230          * @brief Processes photos - unneeded
2231          *
2232          * @param array  $importer Array of the importer user
2233          * @param object $data     The message object
2234          *
2235          * @return bool always true
2236          */
2237         private static function receivePhoto($importer, $data)
2238         {
2239                 // There doesn't seem to be a reason for this function,
2240                 // since the photo data is transmitted in the status message as well
2241                 return true;
2242         }
2243
2244         /**
2245          * @brief Processes poll participations - unssupported
2246          *
2247          * @param array  $importer Array of the importer user
2248          * @param object $data     The message object
2249          *
2250          * @return bool always true
2251          */
2252         private static function receivePollParticipation($importer, $data)
2253         {
2254                 // We don't support polls by now
2255                 return true;
2256         }
2257
2258         /**
2259          * @brief Processes incoming profile updates
2260          *
2261          * @param array  $importer Array of the importer user
2262          * @param object $data     The message object
2263          *
2264          * @return bool Success
2265          */
2266         private static function receiveProfile($importer, $data)
2267         {
2268                 $author = strtolower(notags(unxmlify($data->author)));
2269
2270                 $contact = self::contactByHandle($importer["uid"], $author);
2271                 if (!$contact) {
2272                         return false;
2273                 }
2274
2275                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2276                 $image_url = unxmlify($data->image_url);
2277                 $birthday = unxmlify($data->birthday);
2278                 $gender = unxmlify($data->gender);
2279                 $about = diaspora2bb(unxmlify($data->bio));
2280                 $location = diaspora2bb(unxmlify($data->location));
2281                 $searchable = (unxmlify($data->searchable) == "true");
2282                 $nsfw = (unxmlify($data->nsfw) == "true");
2283                 $tags = unxmlify($data->tag_string);
2284
2285                 $tags = explode("#", $tags);
2286
2287                 $keywords = [];
2288                 foreach ($tags as $tag) {
2289                         $tag = trim(strtolower($tag));
2290                         if ($tag != "") {
2291                                 $keywords[] = $tag;
2292                         }
2293                 }
2294
2295                 $keywords = implode(", ", $keywords);
2296
2297                 $handle_parts = explode("@", $author);
2298                 $nick = $handle_parts[0];
2299
2300                 if ($name === "") {
2301                         $name = $handle_parts[0];
2302                 }
2303
2304                 if (preg_match("|^https?://|", $image_url) === 0) {
2305                         $image_url = "http://".$handle_parts[1].$image_url;
2306                 }
2307
2308                 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2309
2310                 // Generic birthday. We don't know the timezone. The year is irrelevant.
2311
2312                 $birthday = str_replace("1000", "1901", $birthday);
2313
2314                 if ($birthday != "") {
2315                         $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2316                 }
2317
2318                 // this is to prevent multiple birthday notifications in a single year
2319                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2320
2321                 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2322                         $birthday = $contact["bd"];
2323                 }
2324
2325                 $r = q(
2326                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2327                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2328                         dbesc($name),
2329                         dbesc($nick),
2330                         dbesc($author),
2331                         dbesc(DateTimeFormat::utcNow()),
2332                         dbesc($birthday),
2333                         dbesc($location),
2334                         dbesc($about),
2335                         dbesc($keywords),
2336                         dbesc($gender),
2337                         intval($contact["id"]),
2338                         intval($importer["uid"])
2339                 );
2340
2341                 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2342                                         "photo" => $image_url, "name" => $name, "location" => $location,
2343                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
2344                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2345                                         "hide" => !$searchable, "nsfw" => $nsfw];
2346
2347                 $gcid = GContact::update($gcontact);
2348
2349                 GContact::link($gcid, $importer["uid"], $contact["id"]);
2350
2351                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2352
2353                 return true;
2354         }
2355
2356         /**
2357          * @brief Processes incoming friend requests
2358          *
2359          * @param array $importer Array of the importer user
2360          * @param array $contact  The contact that send the request
2361          * @return void
2362          */
2363         private static function receiveRequestMakeFriend($importer, $contact)
2364         {
2365                 $a = get_app();
2366
2367                 if ($contact["rel"] == CONTACT_IS_SHARING) {
2368                         dba::update(
2369                                 'contact',
2370                                 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2371                                 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2372                         );
2373                 }
2374                 // send notification
2375
2376                 $r = q(
2377                         "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2378                         intval($importer["uid"])
2379                 );
2380
2381                 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2382                         $self = q(
2383                                 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2384                                 intval($importer["uid"])
2385                         );
2386
2387                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2388
2389                         if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2390                                 $arr = [];
2391                                 $arr["protocol"] = PROTOCOL_DIASPORA;
2392                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2393                                 $arr["uid"] = $importer["uid"];
2394                                 $arr["contact-id"] = $self[0]["id"];
2395                                 $arr["wall"] = 1;
2396                                 $arr["type"] = 'wall';
2397                                 $arr["gravity"] = 0;
2398                                 $arr["origin"] = 1;
2399                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2400                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2401                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2402                                 $arr["verb"] = ACTIVITY_FRIEND;
2403                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2404
2405                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2406                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2407                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2408                                 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2409
2410                                 $arr["object"] = self::constructNewFriendObject($contact);
2411
2412                                 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2413
2414                                 $arr["allow_cid"] = $user["allow_cid"];
2415                                 $arr["allow_gid"] = $user["allow_gid"];
2416                                 $arr["deny_cid"]  = $user["deny_cid"];
2417                                 $arr["deny_gid"]  = $user["deny_gid"];
2418
2419                                 $i = Item::insert($arr);
2420                                 if ($i) {
2421                                         Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2422                                 }
2423                         }
2424                 }
2425         }
2426
2427         /**
2428          * @brief Creates a XML object for a "new friend" message
2429          *
2430          * @param array $contact Array of the contact
2431          *
2432          * @return string The XML
2433          */
2434         private static function constructNewFriendObject($contact)
2435         {
2436                 $objtype = ACTIVITY_OBJ_PERSON;
2437                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2438                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2439
2440                 $xmldata = ["object" => ["type" => $objtype,
2441                                                 "title" => $contact["name"],
2442                                                 "id" => $contact["url"]."/".$contact["name"],
2443                                                 "link" => $link]];
2444
2445                 return XML::fromArray($xmldata, $xml, true);
2446         }
2447
2448         /**
2449          * @brief Processes incoming sharing notification
2450          *
2451          * @param array  $importer Array of the importer user
2452          * @param object $data     The message object
2453          *
2454          * @return bool Success
2455          */
2456         private static function receiveContactRequest($importer, $data)
2457         {
2458                 $author = unxmlify($data->author);
2459                 $recipient = unxmlify($data->recipient);
2460
2461                 if (!$author || !$recipient) {
2462                         return false;
2463                 }
2464
2465                 // the current protocol version doesn't know these fields
2466                 // That means that we will assume their existance
2467                 if (isset($data->following)) {
2468                         $following = (unxmlify($data->following) == "true");
2469                 } else {
2470                         $following = true;
2471                 }
2472
2473                 if (isset($data->sharing)) {
2474                         $sharing = (unxmlify($data->sharing) == "true");
2475                 } else {
2476                         $sharing = true;
2477                 }
2478
2479                 $contact = self::contactByHandle($importer["uid"], $author);
2480
2481                 // perhaps we were already sharing with this person. Now they're sharing with us.
2482                 // That makes us friends.
2483                 if ($contact) {
2484                         if ($following) {
2485                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2486                                 self::receiveRequestMakeFriend($importer, $contact);
2487
2488                                 // refetch the contact array
2489                                 $contact = self::contactByHandle($importer["uid"], $author);
2490
2491                                 // If we are now friends, we are sending a share message.
2492                                 // Normally we needn't to do so, but the first message could have been vanished.
2493                                 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2494                                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2495                                         if ($u) {
2496                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2497                                                 $ret = self::sendShare($u[0], $contact);
2498                                         }
2499                                 }
2500                                 return true;
2501                         } else {
2502                                 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2503                                 Contact::removeFollower($importer, $contact);
2504                                 return true;
2505                         }
2506                 }
2507
2508                 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2509                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2510                         return false;
2511                 } elseif (!$following && !$sharing) {
2512                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2513                         return false;
2514                 } elseif (!$following && $sharing) {
2515                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2516                 } elseif ($following && $sharing) {
2517                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2518                 } elseif ($following && !$sharing) {
2519                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2520                 }
2521
2522                 $ret = self::personByHandle($author);
2523
2524                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2525                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2526                         return false;
2527                 }
2528
2529                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2530
2531                 $r = q(
2532                         "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2533                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2534                         intval($importer["uid"]),
2535                         dbesc($ret["network"]),
2536                         dbesc($ret["addr"]),
2537                         DateTimeFormat::utcNow(),
2538                         dbesc($ret["url"]),
2539                         dbesc(normalise_link($ret["url"])),
2540                         dbesc($batch),
2541                         dbesc($ret["name"]),
2542                         dbesc($ret["nick"]),
2543                         dbesc($ret["photo"]),
2544                         dbesc($ret["pubkey"]),
2545                         dbesc($ret["notify"]),
2546                         dbesc($ret["poll"]),
2547                         1,
2548                         2
2549                 );
2550
2551                 // find the contact record we just created
2552
2553                 $contact_record = self::contactByHandle($importer["uid"], $author);
2554
2555                 if (!$contact_record) {
2556                         logger("unable to locate newly created contact record.");
2557                         return;
2558                 }
2559
2560                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2561
2562                 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2563
2564                 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2565
2566                 if ($importer["page-flags"] == PAGE_NORMAL) {
2567                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2568
2569                         $hash = random_string().(string)time();   // Generate a confirm_key
2570
2571                         $ret = q(
2572                                 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2573                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2574                                 intval($importer["uid"]),
2575                                 intval($contact_record["id"]),
2576                                 0,
2577                                 0,
2578                                 dbesc(L10n::t("Sharing notification from Diaspora network")),
2579                                 dbesc($hash),
2580                                 dbesc(DateTimeFormat::utcNow())
2581                         );
2582                 } else {
2583                         // automatic friend approval
2584
2585                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2586
2587                         Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2588
2589                         // technically they are sharing with us (CONTACT_IS_SHARING),
2590                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2591                         // we are going to change the relationship and make them a follower.
2592
2593                         if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2594                                 $new_relation = CONTACT_IS_FRIEND;
2595                         } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2596                                 $new_relation = CONTACT_IS_SHARING;
2597                         } else {
2598                                 $new_relation = CONTACT_IS_FOLLOWER;
2599                         }
2600
2601                         $r = q(
2602                                 "UPDATE `contact` SET `rel` = %d,
2603                                 `name-date` = '%s',
2604                                 `uri-date` = '%s',
2605                                 `blocked` = 0,
2606                                 `pending` = 0,
2607                                 `writable` = 1
2608                                 WHERE `id` = %d
2609                                 ",
2610                                 intval($new_relation),
2611                                 dbesc(DateTimeFormat::utcNow()),
2612                                 dbesc(DateTimeFormat::utcNow()),
2613                                 intval($contact_record["id"])
2614                         );
2615
2616                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2617                         if ($u) {
2618                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2619                                 $ret = self::sendShare($u[0], $contact_record);
2620
2621                                 // Send the profile data, maybe it weren't transmitted before
2622                                 self::sendProfile($importer["uid"], [$contact_record]);
2623                         }
2624                 }
2625
2626                 return true;
2627         }
2628
2629         /**
2630          * @brief Fetches a message with a given guid
2631          *
2632          * @param string $guid        message guid
2633          * @param string $orig_author handle of the original post
2634          * @param string $author      handle of the sharer
2635          *
2636          * @return array The fetched item
2637          */
2638         private static function originalItem($guid, $orig_author, $author)
2639         {
2640                 // Do we already have this item?
2641                 $r = q(
2642                         "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2643                                 `author-name`, `author-link`, `author-avatar`
2644                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2645                         dbesc($guid)
2646                 );
2647
2648                 if (DBM::is_result($r)) {
2649                         logger("reshared message ".$guid." already exists on system.");
2650
2651                         // Maybe it is already a reshared item?
2652                         // Then refetch the content, if it is a reshare from a reshare.
2653                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2654                         if (self::isReshare($r[0]["body"], true)) {
2655                                 $r = [];
2656                         } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2657                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2658
2659                                 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2660
2661                                 // Add OEmbed and other information to the body
2662                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2663
2664                                 return $r[0];
2665                         } else {
2666                                 return $r[0];
2667                         }
2668                 }
2669
2670                 if (!DBM::is_result($r)) {
2671                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2672                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2673                         $item_id = self::storeByGuid($guid, $server);
2674
2675                         if (!$item_id) {
2676                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2677                                 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2678                                 $item_id = self::storeByGuid($guid, $server);
2679                         }
2680
2681                         if ($item_id) {
2682                                 $r = q(
2683                                         "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2684                                                 `author-name`, `author-link`, `author-avatar`
2685                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2686                                         intval($item_id)
2687                                 );
2688
2689                                 if (DBM::is_result($r)) {
2690                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2691                                         if (self::isReshare($r[0]["body"], false)) {
2692                                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2693                                                 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2694                                         }
2695
2696                                         return $r[0];
2697                                 }
2698                         }
2699                 }
2700                 return false;
2701         }
2702
2703         /**
2704          * @brief Processes a reshare message
2705          *
2706          * @param array  $importer Array of the importer user
2707          * @param object $data     The message object
2708          * @param string $xml      The original XML of the message
2709          *
2710          * @return int the message id
2711          */
2712         private static function receiveReshare($importer, $data, $xml)
2713         {
2714                 $author = notags(unxmlify($data->author));
2715                 $guid = notags(unxmlify($data->guid));
2716                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2717                 $root_author = notags(unxmlify($data->root_author));
2718                 $root_guid = notags(unxmlify($data->root_guid));
2719                 /// @todo handle unprocessed property "provider_display_name"
2720                 $public = notags(unxmlify($data->public));
2721
2722                 $contact = self::allowedContactByHandle($importer, $author, false);
2723                 if (!$contact) {
2724                         return false;
2725                 }
2726
2727                 $message_id = self::messageExists($importer["uid"], $guid);
2728                 if ($message_id) {
2729                         return true;
2730                 }
2731
2732                 $original_item = self::originalItem($root_guid, $root_author, $author);
2733                 if (!$original_item) {
2734                         return false;
2735                 }
2736
2737                 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2738
2739                 $datarray = [];
2740
2741                 $datarray["uid"] = $importer["uid"];
2742                 $datarray["contact-id"] = $contact["id"];
2743                 $datarray["network"]  = NETWORK_DIASPORA;
2744
2745                 $datarray["author-name"] = $contact["name"];
2746                 $datarray["author-link"] = $contact["url"];
2747                 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2748
2749                 $datarray["owner-name"] = $datarray["author-name"];
2750                 $datarray["owner-link"] = $datarray["author-link"];
2751                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2752
2753                 $datarray["guid"] = $guid;
2754                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2755
2756                 $datarray["verb"] = ACTIVITY_POST;
2757                 $datarray["gravity"] = GRAVITY_PARENT;
2758
2759                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2760                 $datarray["source"] = $xml;
2761
2762                 $prefix = share_header(
2763                         $original_item["author-name"],
2764                         $original_item["author-link"],
2765                         $original_item["author-avatar"],
2766                         $original_item["guid"],
2767                         $original_item["created"],
2768                         $orig_url
2769                 );
2770                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2771
2772                 $datarray["tag"] = $original_item["tag"];
2773                 $datarray["app"]  = $original_item["app"];
2774
2775                 $datarray["plink"] = self::plink($author, $guid);
2776                 $datarray["private"] = (($public == "false") ? 1 : 0);
2777                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2778
2779                 $datarray["object-type"] = $original_item["object-type"];
2780
2781                 self::fetchGuid($datarray);
2782                 $message_id = Item::insert($datarray);
2783
2784                 self::sendParticipation($contact, $datarray);
2785
2786                 if ($message_id) {
2787                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2788                         return true;
2789                 } else {
2790                         return false;
2791                 }
2792         }
2793
2794         /**
2795          * @brief Processes retractions
2796          *
2797          * @param array  $importer Array of the importer user
2798          * @param array  $contact  The contact of the item owner
2799          * @param object $data     The message object
2800          *
2801          * @return bool success
2802          */
2803         private static function itemRetraction($importer, $contact, $data)
2804         {
2805                 $author = notags(unxmlify($data->author));
2806                 $target_guid = notags(unxmlify($data->target_guid));
2807                 $target_type = notags(unxmlify($data->target_type));
2808
2809                 $person = self::personByHandle($author);
2810                 if (!is_array($person)) {
2811                         logger("unable to find author detail for ".$author);
2812                         return false;
2813                 }
2814
2815                 if (empty($contact["url"])) {
2816                         $contact["url"] = $person["url"];
2817                 }
2818
2819                 // Fetch items that are about to be deleted
2820                 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2821
2822                 // When we receive a public retraction, we delete every item that we find.
2823                 if ($importer['uid'] == 0) {
2824                         $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2825                 } else {
2826                         $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2827                 }
2828                 $r = dba::select('item', $fields, $condition);
2829                 if (!DBM::is_result($r)) {
2830                         logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2831                         return false;
2832                 }
2833
2834                 while ($item = dba::fetch($r)) {
2835                         // Fetch the parent item
2836                         $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2837
2838                         // Only delete it if the parent author really fits
2839                         if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2840                                 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2841                                 continue;
2842                         }
2843
2844                         Item::deleteById($item["id"]);
2845
2846                         logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2847
2848                         // Now check if the retraction needs to be relayed by us
2849                         if ($parent["origin"]) {
2850                                 // notify others
2851                                 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2852                         }
2853                 }
2854
2855                 return true;
2856         }
2857
2858         /**
2859          * @brief Receives retraction messages
2860          *
2861          * @param array  $importer Array of the importer user
2862          * @param string $sender   The sender of the message
2863          * @param object $data     The message object
2864          *
2865          * @return bool Success
2866          */
2867         private static function receiveRetraction($importer, $sender, $data)
2868         {
2869                 $target_type = notags(unxmlify($data->target_type));
2870
2871                 $contact = self::contactByHandle($importer["uid"], $sender);
2872                 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2873                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2874                         return false;
2875                 }
2876
2877                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2878
2879                 switch ($target_type) {
2880                         case "Comment":
2881                         case "Like":
2882                         case "Post":
2883                         case "Reshare":
2884                         case "StatusMessage":
2885                                 return self::itemRetraction($importer, $contact, $data);
2886
2887                         case "Contact":
2888                         case "Person":
2889                                 /// @todo What should we do with an "unshare"?
2890                                 // Removing the contact isn't correct since we still can read the public items
2891                                 Contact::remove($contact["id"]);
2892                                 return true;
2893
2894                         default:
2895                                 logger("Unknown target type ".$target_type);
2896                                 return false;
2897                 }
2898                 return true;
2899         }
2900
2901         /**
2902          * @brief Receives status messages
2903          *
2904          * @param array  $importer Array of the importer user
2905          * @param object $data     The message object
2906          * @param string $xml      The original XML of the message
2907          *
2908          * @return int The message id of the newly created item
2909          */
2910         private static function receiveStatusMessage($importer, $data, $xml)
2911         {
2912                 $author = notags(unxmlify($data->author));
2913                 $guid = notags(unxmlify($data->guid));
2914                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2915                 $public = notags(unxmlify($data->public));
2916                 $text = unxmlify($data->text);
2917                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2918
2919                 $contact = self::allowedContactByHandle($importer, $author, false);
2920                 if (!$contact) {
2921                         return false;
2922                 }
2923
2924                 $message_id = self::messageExists($importer["uid"], $guid);
2925                 if ($message_id) {
2926                         return true;
2927                 }
2928
2929                 $address = [];
2930                 if ($data->location) {
2931                         foreach ($data->location->children() as $fieldname => $data) {
2932                                 $address[$fieldname] = notags(unxmlify($data));
2933                         }
2934                 }
2935
2936                 $body = diaspora2bb($text);
2937
2938                 $datarray = [];
2939
2940                 // Attach embedded pictures to the body
2941                 if ($data->photo) {
2942                         foreach ($data->photo as $photo) {
2943                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2944                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2945                         }
2946
2947                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2948                 } else {
2949                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2950
2951                         // Add OEmbed and other information to the body
2952                         if (!self::isRedmatrix($contact["url"])) {
2953                                 $body = add_page_info_to_body($body, false, true);
2954                         }
2955                 }
2956
2957                 /// @todo enable support for polls
2958                 //if ($data->poll) {
2959                 //      foreach ($data->poll AS $poll)
2960                 //              print_r($poll);
2961                 //      die("poll!\n");
2962                 //}
2963
2964                 /// @todo enable support for events
2965
2966                 $datarray["uid"] = $importer["uid"];
2967                 $datarray["contact-id"] = $contact["id"];
2968                 $datarray["network"] = NETWORK_DIASPORA;
2969
2970                 $datarray["author-name"] = $contact["name"];
2971                 $datarray["author-link"] = $contact["url"];
2972                 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2973
2974                 $datarray["owner-name"] = $datarray["author-name"];
2975                 $datarray["owner-link"] = $datarray["author-link"];
2976                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2977
2978                 $datarray["guid"] = $guid;
2979                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2980
2981                 $datarray["verb"] = ACTIVITY_POST;
2982                 $datarray["gravity"] = GRAVITY_PARENT;
2983
2984                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2985                 $datarray["source"] = $xml;
2986
2987                 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2988
2989                 if ($provider_display_name != "") {
2990                         $datarray["app"] = $provider_display_name;
2991                 }
2992
2993                 $datarray["plink"] = self::plink($author, $guid);
2994                 $datarray["private"] = (($public == "false") ? 1 : 0);
2995                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2996
2997                 if (isset($address["address"])) {
2998                         $datarray["location"] = $address["address"];
2999                 }
3000
3001                 if (isset($address["lat"]) && isset($address["lng"])) {
3002                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
3003                 }
3004
3005                 self::fetchGuid($datarray);
3006                 $message_id = Item::insert($datarray);
3007
3008                 self::sendParticipation($contact, $datarray);
3009
3010                 if ($message_id) {
3011                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3012                         return true;
3013                 } else {
3014                         return false;
3015                 }
3016         }
3017
3018         /* ************************************************************************************** *
3019          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3020          * ************************************************************************************** */
3021
3022         /**
3023          * @brief returnes the handle of a contact
3024          *
3025          * @param array $contact contact array
3026          *
3027          * @return string the handle in the format user@domain.tld
3028          */
3029         private static function myHandle($contact)
3030         {
3031                 if ($contact["addr"] != "") {
3032                         return $contact["addr"];
3033                 }
3034
3035                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3036                 // So - just in case - we build the the address here.
3037                 if ($contact["nickname"] != "") {
3038                         $nick = $contact["nickname"];
3039                 } else {
3040                         $nick = $contact["nick"];
3041                 }
3042
3043                 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3044         }
3045
3046
3047         /**
3048          * @brief Creates the data for a private message in the new format
3049          *
3050          * @param string $msg     The message that is to be transmitted
3051          * @param array  $user    The record of the sender
3052          * @param array  $contact Target of the communication
3053          * @param string $prvkey  The private key of the sender
3054          * @param string $pubkey  The public key of the receiver
3055          *
3056          * @return string The encrypted data
3057          */
3058         public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3059         {
3060                 logger("Message: ".$msg, LOGGER_DATA);
3061
3062                 // without a public key nothing will work
3063                 if (!$pubkey) {
3064                         logger("pubkey missing: contact id: ".$contact["id"]);
3065                         return false;
3066                 }
3067
3068                 $aes_key = openssl_random_pseudo_bytes(32);
3069                 $b_aes_key = base64_encode($aes_key);
3070                 $iv = openssl_random_pseudo_bytes(16);
3071                 $b_iv = base64_encode($iv);
3072
3073                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3074
3075                 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3076
3077                 $encrypted_key_bundle = "";
3078                 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3079
3080                 $json_object = json_encode(
3081                         ["aes_key" => base64_encode($encrypted_key_bundle),
3082                                         "encrypted_magic_envelope" => base64_encode($ciphertext)]
3083                 );
3084
3085                 return $json_object;
3086         }
3087
3088         /**
3089          * @brief Creates the envelope for the "fetch" endpoint and for the new format
3090          *
3091          * @param string $msg  The message that is to be transmitted
3092          * @param array  $user The record of the sender
3093          *
3094          * @return string The envelope
3095          */
3096         public static function buildMagicEnvelope($msg, $user)
3097         {
3098                 $b64url_data = base64url_encode($msg);
3099                 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3100
3101                 $key_id = base64url_encode(self::myHandle($user));
3102                 $type = "application/xml";
3103                 $encoding = "base64url";
3104                 $alg = "RSA-SHA256";
3105                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3106
3107                 // Fallback if the private key wasn't transmitted in the expected field
3108                 if ($user['uprvkey'] == "") {
3109                         $user['uprvkey'] = $user['prvkey'];
3110                 }
3111
3112                 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3113                 $sig = base64url_encode($signature);
3114
3115                 $xmldata = ["me:env" => ["me:data" => $data,
3116                                                         "@attributes" => ["type" => $type],
3117                                                         "me:encoding" => $encoding,
3118                                                         "me:alg" => $alg,
3119                                                         "me:sig" => $sig,
3120                                                         "@attributes2" => ["key_id" => $key_id]]];
3121
3122                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3123
3124                 return XML::fromArray($xmldata, $xml, false, $namespaces);
3125         }
3126
3127         /**
3128          * @brief Create the envelope for a message
3129          *
3130          * @param string $msg     The message that is to be transmitted
3131          * @param array  $user    The record of the sender
3132          * @param array  $contact Target of the communication
3133          * @param string $prvkey  The private key of the sender
3134          * @param string $pubkey  The public key of the receiver
3135          * @param bool   $public  Is the message public?
3136          *
3137          * @return string The message that will be transmitted to other servers
3138          */
3139         private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3140         {
3141                 // The message is put into an envelope with the sender's signature
3142                 $envelope = self::buildMagicEnvelope($msg, $user);
3143
3144                 // Private messages are put into a second envelope, encrypted with the receivers public key
3145                 if (!$public) {
3146                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3147                 }
3148
3149                 return $envelope;
3150         }
3151
3152         /**
3153          * @brief Creates a signature for a message
3154          *
3155          * @param array $owner   the array of the owner of the message
3156          * @param array $message The message that is to be signed
3157          *
3158          * @return string The signature
3159          */
3160         private static function signature($owner, $message)
3161         {
3162                 $sigmsg = $message;
3163                 unset($sigmsg["author_signature"]);
3164                 unset($sigmsg["parent_author_signature"]);
3165
3166                 $signed_text = implode(";", $sigmsg);
3167
3168                 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3169         }
3170
3171         /**
3172          * @brief Transmit a message to a target server
3173          *
3174          * @param array  $owner        the array of the item owner
3175          * @param array  $contact      Target of the communication
3176          * @param string $envelope     The message that is to be transmitted
3177          * @param bool   $public_batch Is it a public post?
3178          * @param bool   $queue_run    Is the transmission called from the queue?
3179          * @param string $guid         message guid
3180          *
3181          * @return int Result of the transmission
3182          */
3183         public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3184         {
3185                 $a = get_app();
3186
3187                 $enabled = intval(Config::get("system", "diaspora_enabled"));
3188                 if (!$enabled) {
3189                         return 200;
3190                 }
3191
3192                 $logid = random_string(4);
3193                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3194
3195                 // Fetch the fcontact entry when there is missing data
3196                 // Will possibly happen when data is transmitted to a DFRN contact
3197                 if (empty($dest_url) && !empty($contact['addr'])) {
3198                         $fcontact = self::personByHandle($contact['addr']);
3199                         $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3200                 }
3201
3202                 if (!$dest_url) {
3203                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3204                         return 0;
3205                 }
3206
3207                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3208
3209                 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3210                         $return_code = 0;
3211                 } else {
3212                         if (!intval(Config::get("system", "diaspora_test"))) {
3213                                 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3214
3215                                 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3216                                 $return_code = $a->get_curl_code();
3217                         } else {
3218                                 logger("test_mode");
3219                                 return 200;
3220                         }
3221                 }
3222
3223                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3224
3225                 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3226                         if (!$no_queue) {
3227                                 logger("queue message");
3228                                 // queue message for redelivery
3229                                 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3230                         }
3231
3232                         // The message could not be delivered. We mark the contact as "dead"
3233                         Contact::markForArchival($contact);
3234                 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3235                         // We successfully delivered a message, the contact is alive
3236                         Contact::unmarkForArchival($contact);
3237                 }
3238
3239                 return $return_code ? $return_code : -1;
3240         }
3241
3242
3243         /**
3244          * @brief Build the post xml
3245          *
3246          * @param string $type    The message type
3247          * @param array  $message The message data
3248          *
3249          * @return string The post XML
3250          */
3251         public static function buildPostXml($type, $message)
3252         {
3253                 $data = [$type => $message];
3254
3255                 return XML::fromArray($data, $xml);
3256         }
3257
3258         /**
3259          * @brief Builds and transmit messages
3260          *
3261          * @param array  $owner        the array of the item owner
3262          * @param array  $contact      Target of the communication
3263          * @param string $type         The message type
3264          * @param array  $message      The message data
3265          * @param bool   $public_batch Is it a public post?
3266          * @param string $guid         message guid
3267          * @param bool   $spool        Should the transmission be spooled or transmitted?
3268          *
3269          * @return int Result of the transmission
3270          */
3271         private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3272         {
3273                 $msg = self::buildPostXml($type, $message);
3274
3275                 logger('message: '.$msg, LOGGER_DATA);
3276                 logger('send guid '.$guid, LOGGER_DEBUG);
3277
3278                 // Fallback if the private key wasn't transmitted in the expected field
3279                 if ($owner['uprvkey'] == "") {
3280                         $owner['uprvkey'] = $owner['prvkey'];
3281                 }
3282
3283                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3284
3285                 if ($spool) {
3286                         Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3287                         return true;
3288                 } else {
3289                         $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3290                 }
3291
3292                 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3293
3294                 return $return_code;
3295         }
3296
3297         /**
3298          * @brief sends a participation (Used to get all further updates)
3299          *
3300          * @param array $contact Target of the communication
3301          * @param array $item    Item array
3302          *
3303          * @return int The result of the transmission
3304          */
3305         private static function sendParticipation($contact, $item)
3306         {
3307                 // Don't send notifications for private postings
3308                 if ($item['private']) {
3309                         return;
3310                 }
3311
3312                 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3313
3314                 $result = Cache::get($cachekey);
3315                 if (!is_null($result)) {
3316                         return;
3317                 }
3318
3319                 // Fetch some user id to have a valid handle to transmit the participation.
3320                 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3321                 // If the item belongs to a user, we take this user id.
3322                 if ($item['uid'] == 0) {
3323                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3324                         $first_user = dba::selectFirst('user', ['uid'], $condition);
3325                         $owner = User::getOwnerDataById($first_user['uid']);
3326                 } else {
3327                         $owner = User::getOwnerDataById($item['uid']);
3328                 }
3329
3330                 $author = self::myHandle($owner);
3331
3332                 $message = ["author" => $author,
3333                                 "guid" => get_guid(32),
3334                                 "parent_type" => "Post",
3335                                 "parent_guid" => $item["guid"]];
3336
3337                 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3338
3339                 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3340                 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3341
3342                 return self::buildAndTransmit($owner, $contact, "participation", $message);
3343         }
3344
3345         /**
3346          * @brief sends an account migration
3347          *
3348          * @param array $owner   the array of the item owner
3349          * @param array $contact Target of the communication
3350          * @param int   $uid     User ID
3351          *
3352          * @return int The result of the transmission
3353          */
3354         public static function sendAccountMigration($owner, $contact, $uid)
3355         {
3356                 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3357                 $profile = self::createProfileData($uid);
3358
3359                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3360                 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3361
3362                 $message = ["author" => $old_handle,
3363                                 "profile" => $profile,
3364                                 "signature" => $signature];
3365
3366                 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3367
3368                 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3369         }
3370
3371         /**
3372          * @brief Sends a "share" message
3373          *
3374          * @param array $owner   the array of the item owner
3375          * @param array $contact Target of the communication
3376          *
3377          * @return int The result of the transmission
3378          */
3379         public static function sendShare($owner, $contact)
3380         {
3381                 /**
3382                  * @todo support the different possible combinations of "following" and "sharing"
3383                  * Currently, Diaspora only interprets the "sharing" field
3384                  *
3385                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3386                  */
3387
3388                 /*
3389                 switch ($contact["rel"]) {
3390                         case CONTACT_IS_FRIEND:
3391                                 $following = true;
3392                                 $sharing = true;
3393                         case CONTACT_IS_SHARING:
3394                                 $following = false;
3395                                 $sharing = true;
3396                         case CONTACT_IS_FOLLOWER:
3397                                 $following = true;
3398                                 $sharing = false;
3399                 }
3400                 */
3401
3402                 $message = ["author" => self::myHandle($owner),
3403                                 "recipient" => $contact["addr"],
3404                                 "following" => "true",
3405                                 "sharing" => "true"];
3406
3407                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3408
3409                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3410         }
3411
3412         /**
3413          * @brief sends an "unshare"
3414          *
3415          * @param array $owner   the array of the item owner
3416          * @param array $contact Target of the communication
3417          *
3418          * @return int The result of the transmission
3419          */
3420         public static function sendUnshare($owner, $contact)
3421         {
3422                 $message = ["author" => self::myHandle($owner),
3423                                 "recipient" => $contact["addr"],
3424                                 "following" => "false",
3425                                 "sharing" => "false"];
3426
3427                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3428
3429                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3430         }
3431
3432         /**
3433          * @brief Checks a message body if it is a reshare
3434          *
3435          * @param string $body     The message body that is to be check
3436          * @param bool   $complete Should it be a complete check or a simple check?
3437          *
3438          * @return array|bool Reshare details or "false" if no reshare
3439          */
3440         public static function isReshare($body, $complete = true)
3441         {
3442                 $body = trim($body);
3443
3444                 // Skip if it isn't a pure repeated messages
3445                 // Does it start with a share?
3446                 if ((strpos($body, "[share") > 0) && $complete) {
3447                         return(false);
3448                 }
3449
3450                 // Does it end with a share?
3451                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3452                         return(false);
3453                 }
3454
3455                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3456                 // Skip if there is no shared message in there
3457                 if ($body == $attributes) {
3458                         return(false);
3459                 }
3460
3461                 // If we don't do the complete check we quit here
3462                 if (!$complete) {
3463                         return true;
3464                 }
3465
3466                 $guid = "";
3467                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3468                 if ($matches[1] != "") {
3469                         $guid = $matches[1];
3470                 }
3471
3472                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3473                 if ($matches[1] != "") {
3474                         $guid = $matches[1];
3475                 }
3476
3477                 if ($guid != "") {
3478                         $r = q(
3479                                 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3480                                 dbesc($guid),
3481                                 NETWORK_DFRN,
3482                                 NETWORK_DIASPORA
3483                         );
3484                         if ($r) {
3485                                 $ret= [];
3486                                 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3487                                 $ret["root_guid"] = $guid;
3488                                 return($ret);
3489                         }
3490                 }
3491
3492                 $profile = "";
3493                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3494                 if ($matches[1] != "") {
3495                         $profile = $matches[1];
3496                 }
3497
3498                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3499                 if ($matches[1] != "") {
3500                         $profile = $matches[1];
3501                 }
3502
3503                 $ret= [];
3504
3505                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3506                 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3507                         return(false);
3508                 }
3509
3510                 $link = "";
3511                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3512                 if ($matches[1] != "") {
3513                         $link = $matches[1];
3514                 }
3515
3516                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3517                 if ($matches[1] != "") {
3518                         $link = $matches[1];
3519                 }
3520
3521                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3522                 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3523                         return(false);
3524                 }
3525
3526                 return($ret);
3527         }
3528
3529         /**
3530          * @brief Create an event array
3531          *
3532          * @param integer $event_id The id of the event
3533          *
3534          * @return array with event data
3535          */
3536         private static function buildEvent($event_id)
3537         {
3538                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3539                 if (!DBM::is_result($r)) {
3540                         return [];
3541                 }
3542
3543                 $event = $r[0];
3544
3545                 $eventdata = [];
3546
3547                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3548                 if (!DBM::is_result($r)) {
3549                         return [];
3550                 }
3551
3552                 $user = $r[0];
3553
3554                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3555                 if (!DBM::is_result($r)) {
3556                         return [];
3557                 }
3558
3559                 $owner = $r[0];
3560
3561                 $eventdata['author'] = self::myHandle($owner);
3562
3563                 if ($event['guid']) {
3564                         $eventdata['guid'] = $event['guid'];
3565                 }
3566
3567                 $mask = DateTimeFormat::ATOM;
3568
3569                 /// @todo - establish "all day" events in Friendica
3570                 $eventdata["all_day"] = "false";
3571
3572                 if (!$event['adjust']) {
3573                         $eventdata['timezone'] = $user['timezone'];
3574
3575                         if ($eventdata['timezone'] == "") {
3576                                 $eventdata['timezone'] = 'UTC';
3577                         }
3578                 }
3579
3580                 if ($event['start']) {
3581                         $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3582                 }
3583                 if ($event['finish'] && !$event['nofinish']) {
3584                         $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3585                 }
3586                 if ($event['summary']) {
3587                         $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3588                 }
3589                 if ($event['desc']) {
3590                         $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3591                 }
3592                 if ($event['location']) {
3593                         $location = [];
3594                         $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3595                         $location["lat"] = 0;
3596                         $location["lng"] = 0;
3597                         $eventdata['location'] = $location;
3598                 }
3599
3600                 return $eventdata;
3601         }
3602
3603         /**
3604          * @brief Create a post (status message or reshare)
3605          *
3606          * @param array $item  The item that will be exported
3607          * @param array $owner the array of the item owner
3608          *
3609          * @return array
3610          * 'type' -> Message type ("status_message" or "reshare")
3611          * 'message' -> Array of XML elements of the status
3612          */
3613         public static function buildStatus($item, $owner)
3614         {
3615                 $cachekey = "diaspora:buildStatus:".$item['guid'];
3616
3617                 $result = Cache::get($cachekey);
3618                 if (!is_null($result)) {
3619                         return $result;
3620                 }
3621
3622                 $myaddr = self::myHandle($owner);
3623
3624                 $public = (($item["private"]) ? "false" : "true");
3625
3626                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3627
3628                 // Detect a share element and do a reshare
3629                 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3630                         $message = ["author" => $myaddr,
3631                                         "guid" => $item["guid"],
3632                                         "created_at" => $created,
3633                                         "root_author" => $ret["root_handle"],
3634                                         "root_guid" => $ret["root_guid"],
3635                                         "provider_display_name" => $item["app"],
3636                                         "public" => $public];
3637
3638                         $type = "reshare";
3639                 } else {
3640                         $title = $item["title"];
3641                         $body = $item["body"];
3642
3643                         // convert to markdown
3644                         $body = html_entity_decode(bb2diaspora($body));
3645
3646                         // Adding the title
3647                         if (strlen($title)) {
3648                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3649                         }
3650
3651                         if ($item["attach"]) {
3652                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3653                                 if (cnt) {
3654                                         $body .= "\n".L10n::t("Attachments:")."\n";
3655                                         foreach ($matches as $mtch) {
3656                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3657                                         }
3658                                 }
3659                         }
3660
3661                         $location = [];
3662
3663                         if ($item["location"] != "")
3664                                 $location["address"] = $item["location"];
3665
3666                         if ($item["coord"] != "") {
3667                                 $coord = explode(" ", $item["coord"]);
3668                                 $location["lat"] = $coord[0];
3669                                 $location["lng"] = $coord[1];
3670                         }
3671
3672                         $message = ["author" => $myaddr,
3673                                         "guid" => $item["guid"],
3674                                         "created_at" => $created,
3675                                         "public" => $public,
3676                                         "text" => $body,
3677                                         "provider_display_name" => $item["app"],
3678                                         "location" => $location];
3679
3680                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3681                         if (!isset($location["lat"]) || !isset($location["lng"])) {
3682                                 unset($message["location"]);
3683                         }
3684
3685                         if ($item['event-id'] > 0) {
3686                                 $event = self::buildEvent($item['event-id']);
3687                                 if (count($event)) {
3688                                         $message['event'] = $event;
3689
3690                                         /// @todo Once Diaspora supports it, we will remove the body
3691                                         // $message['text'] = '';
3692                                 }
3693                         }
3694
3695                         $type = "status_message";
3696                 }
3697
3698                 $msg = ["type" => $type, "message" => $message];
3699
3700                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3701
3702                 return $msg;
3703         }
3704
3705         /**
3706          * @brief Sends a post
3707          *
3708          * @param array $item         The item that will be exported
3709          * @param array $owner        the array of the item owner
3710          * @param array $contact      Target of the communication
3711          * @param bool  $public_batch Is it a public post?
3712          *
3713          * @return int The result of the transmission
3714          */
3715         public static function sendStatus($item, $owner, $contact, $public_batch = false)
3716         {
3717                 $status = self::buildStatus($item, $owner);
3718
3719                 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3720         }
3721
3722         /**
3723          * @brief Creates a "like" object
3724          *
3725          * @param array $item  The item that will be exported
3726          * @param array $owner the array of the item owner
3727          *
3728          * @return array The data for a "like"
3729          */
3730         private static function constructLike($item, $owner)
3731         {
3732                 $p = q(
3733                         "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3734                         dbesc($item["thr-parent"])
3735                 );
3736                 if (!DBM::is_result($p)) {
3737                         return false;
3738                 }
3739
3740                 $parent = $p[0];
3741
3742                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3743                 $positive = null;
3744                 if ($item['verb'] === ACTIVITY_LIKE) {
3745                         $positive = "true";
3746                 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3747                         $positive = "false";
3748                 }
3749
3750                 return(["author" => self::myHandle($owner),
3751                                 "guid" => $item["guid"],
3752                                 "parent_guid" => $parent["guid"],
3753                                 "parent_type" => $target_type,
3754                                 "positive" => $positive,
3755                                 "author_signature" => ""]);
3756         }
3757
3758         /**
3759          * @brief Creates an "EventParticipation" object
3760          *
3761          * @param array $item  The item that will be exported
3762          * @param array $owner the array of the item owner
3763          *
3764          * @return array The data for an "EventParticipation"
3765          */
3766         private static function constructAttend($item, $owner)
3767         {
3768                 $p = q(
3769                         "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3770                         dbesc($item["thr-parent"])
3771                 );
3772                 if (!DBM::is_result($p)) {
3773                         return false;
3774                 }
3775
3776                 $parent = $p[0];
3777
3778                 switch ($item['verb']) {
3779                         case ACTIVITY_ATTEND:
3780                                 $attend_answer = 'accepted';
3781                                 break;
3782                         case ACTIVITY_ATTENDNO:
3783                                 $attend_answer = 'declined';
3784                                 break;
3785                         case ACTIVITY_ATTENDMAYBE:
3786                                 $attend_answer = 'tentative';
3787                                 break;
3788                         default:
3789                                 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3790                                 return false;
3791                 }
3792
3793                 return(["author" => self::myHandle($owner),
3794                                 "guid" => $item["guid"],
3795                                 "parent_guid" => $parent["guid"],
3796                                 "status" => $attend_answer,
3797                                 "author_signature" => ""]);
3798         }
3799
3800         /**
3801          * @brief Creates the object for a comment
3802          *
3803          * @param array $item  The item that will be exported
3804          * @param array $owner the array of the item owner
3805          *
3806          * @return array The data for a comment
3807          */
3808         private static function constructComment($item, $owner)
3809         {
3810                 $cachekey = "diaspora:constructComment:".$item['guid'];
3811
3812                 $result = Cache::get($cachekey);
3813                 if (!is_null($result)) {
3814                         return $result;
3815                 }
3816
3817                 $p = q(
3818                         "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3819                         intval($item["parent"]),
3820                         intval($item["parent"])
3821                 );
3822
3823                 if (!DBM::is_result($p)) {
3824                         return false;
3825                 }
3826
3827                 $parent = $p[0];
3828
3829                 $text = html_entity_decode(bb2diaspora($item["body"]));
3830                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3831
3832                 $comment = ["author" => self::myHandle($owner),
3833                                 "guid" => $item["guid"],
3834                                 "created_at" => $created,
3835                                 "parent_guid" => $parent["guid"],
3836                                 "text" => $text,
3837                                 "author_signature" => ""];
3838
3839                 // Send the thread parent guid only if it is a threaded comment
3840                 if ($item['thr-parent'] != $item['parent-uri']) {
3841                         $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3842                 }
3843
3844                 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3845
3846                 return($comment);
3847         }
3848
3849         /**
3850          * @brief Send a like or a comment
3851          *
3852          * @param array $item         The item that will be exported
3853          * @param array $owner        the array of the item owner
3854          * @param array $contact      Target of the communication
3855          * @param bool  $public_batch Is it a public post?
3856          *
3857          * @return int The result of the transmission
3858          */
3859         public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3860         {
3861                 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3862                         $message = self::constructAttend($item, $owner);
3863                         $type = "event_participation";
3864                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3865                         $message = self::constructLike($item, $owner);
3866                         $type = "like";
3867                 } else {
3868                         $message = self::constructComment($item, $owner);
3869                         $type = "comment";
3870                 }
3871
3872                 if (!$message) {
3873                         return false;
3874                 }
3875
3876                 $message["author_signature"] = self::signature($owner, $message);
3877
3878                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3879         }
3880
3881         /**
3882          * @brief Creates a message from a signature record entry
3883          *
3884          * @param array $item      The item that will be exported
3885          * @param array $signature The entry of the "sign" record
3886          *
3887          * @return string The message
3888          */
3889         private static function messageFromSignature($item, $signature)
3890         {
3891                 // Split the signed text
3892                 $signed_parts = explode(";", $signature['signed_text']);
3893
3894                 if ($item["deleted"]) {
3895                         $message = ["author" => $signature['signer'],
3896                                         "target_guid" => $signed_parts[0],
3897                                         "target_type" => $signed_parts[1]];
3898                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3899                         $message = ["author" => $signed_parts[4],
3900                                         "guid" => $signed_parts[1],
3901                                         "parent_guid" => $signed_parts[3],
3902                                         "parent_type" => $signed_parts[2],
3903                                         "positive" => $signed_parts[0],
3904                                         "author_signature" => $signature['signature'],
3905                                         "parent_author_signature" => ""];
3906                 } else {
3907                         // Remove the comment guid
3908                         $guid = array_shift($signed_parts);
3909
3910                         // Remove the parent guid
3911                         $parent_guid = array_shift($signed_parts);
3912
3913                         // Remove the handle
3914                         $handle = array_pop($signed_parts);
3915
3916                         // Glue the parts together
3917                         $text = implode(";", $signed_parts);
3918
3919                         $message = ["author" => $handle,
3920                                         "guid" => $guid,
3921                                         "parent_guid" => $parent_guid,
3922                                         "text" => implode(";", $signed_parts),
3923                                         "author_signature" => $signature['signature'],
3924                                         "parent_author_signature" => ""];
3925                 }
3926                 return $message;
3927         }
3928
3929         /**
3930          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3931          *
3932          * @param array $item         The item that will be exported
3933          * @param array $owner        the array of the item owner
3934          * @param array $contact      Target of the communication
3935          * @param bool  $public_batch Is it a public post?
3936          *
3937          * @return int The result of the transmission
3938          */
3939         public static function sendRelay($item, $owner, $contact, $public_batch = false)
3940         {
3941                 if ($item["deleted"]) {
3942                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3943                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3944                         $type = "like";
3945                 } else {
3946                         $type = "comment";
3947                 }
3948
3949                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3950
3951                 // fetch the original signature
3952
3953                 $r = q(
3954                         "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3955                         intval($item["id"])
3956                 );
3957
3958                 if (!$r) {
3959                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3960                         return false;
3961                 }
3962
3963                 $signature = $r[0];
3964
3965                 // Old way - is used by the internal Friendica functions
3966                 /// @todo Change all signatur storing functions to the new format
3967                 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3968                         $message = self::messageFromSignature($item, $signature);
3969                 } else {// New way
3970                         $msg = json_decode($signature['signed_text'], true);
3971
3972                         $message = [];
3973                         if (is_array($msg)) {
3974                                 foreach ($msg as $field => $data) {
3975                                         if (!$item["deleted"]) {
3976                                                 if ($field == "diaspora_handle") {
3977                                                         $field = "author";
3978                                                 }
3979                                                 if ($field == "target_type") {
3980                                                         $field = "parent_type";
3981                                                 }
3982                                         }
3983
3984                                         $message[$field] = $data;
3985                                 }
3986                         } else {
3987                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3988                         }
3989                 }
3990
3991                 $message["parent_author_signature"] = self::signature($owner, $message);
3992
3993                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3994
3995                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3996         }
3997
3998         /**
3999          * @brief Sends a retraction (deletion) of a message, like or comment
4000          *
4001          * @param array $item         The item that will be exported
4002          * @param array $owner        the array of the item owner
4003          * @param array $contact      Target of the communication
4004          * @param bool  $public_batch Is it a public post?
4005          * @param bool  $relay        Is the retraction transmitted from a relay?
4006          *
4007          * @return int The result of the transmission
4008          */
4009         public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4010         {
4011                 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
4012
4013                 $msg_type = "retraction";
4014
4015                 if ($item['id'] == $item['parent']) {
4016                         $target_type = "Post";
4017                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4018                         $target_type = "Like";
4019                 } else {
4020                         $target_type = "Comment";
4021                 }
4022
4023                 $message = ["author" => $itemaddr,
4024                                 "target_guid" => $item['guid'],
4025                                 "target_type" => $target_type];
4026
4027                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4028
4029                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4030         }
4031
4032         /**
4033          * @brief Sends a mail
4034          *
4035          * @param array $item    The item that will be exported
4036          * @param array $owner   The owner
4037          * @param array $contact Target of the communication
4038          *
4039          * @return int The result of the transmission
4040          */
4041         public static function sendMail($item, $owner, $contact)
4042         {
4043                 $myaddr = self::myHandle($owner);
4044
4045                 $r = q(
4046                         "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4047                         intval($item["convid"]),
4048                         intval($item["uid"])
4049                 );
4050
4051                 if (!DBM::is_result($r)) {
4052                         logger("conversation not found.");
4053                         return;
4054                 }
4055                 $cnv = $r[0];
4056
4057                 $conv = [
4058                         "author" => $cnv["creator"],
4059                         "guid" => $cnv["guid"],
4060                         "subject" => $cnv["subject"],
4061                         "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4062                         "participants" => $cnv["recips"]
4063                 ];
4064
4065                 $body = bb2diaspora($item["body"]);
4066                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4067
4068                 $msg = [
4069                         "author" => $myaddr,
4070                         "guid" => $item["guid"],
4071                         "conversation_guid" => $cnv["guid"],
4072                         "text" => $body,
4073                         "created_at" => $created,
4074                 ];
4075
4076                 if ($item["reply"]) {
4077                         $message = $msg;
4078                         $type = "message";
4079                 } else {
4080                         $message = [
4081                                         "author" => $cnv["creator"],
4082                                         "guid" => $cnv["guid"],
4083                                         "subject" => $cnv["subject"],
4084                                         "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4085                                         "participants" => $cnv["recips"],
4086                                         "message" => $msg];
4087
4088                         $type = "conversation";
4089                 }
4090
4091                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4092         }
4093
4094         /**
4095          * @brief Split a name into first name and last name
4096          *
4097          * @param string $name The name
4098          *
4099          * @return array The array with "first" and "last"
4100          */
4101         public static function splitName($name) {
4102                 $name = trim($name);
4103
4104                 // Is the name longer than 64 characters? Then cut the rest of it.
4105                 if (strlen($name) > 64) {
4106                         if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4107                                 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4108                         } else {
4109                                 $name = substr($name, 0, 64);
4110                         }
4111                 }
4112
4113                 // Take the first word as first name
4114                 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4115                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4116                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4117                         return ['first' => $first, 'last' => $last];
4118                 }
4119
4120                 // Take the last word as last name
4121                 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4122                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4123
4124                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4125                         return ['first' => $first, 'last' => $last];
4126                 }
4127
4128                 // Take the first 32 characters if there is no space in the first 32 characters
4129                 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4130                         $first = substr($name, 0, 32);
4131                         $last = substr($name, 32);
4132                         return ['first' => $first, 'last' => $last];
4133                 }
4134
4135                 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4136                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4137
4138                 // Check if the last name is longer than 32 characters
4139                 if (strlen($last) > 32) {
4140                         if (strpos($last, ' ') <= 32) {
4141                                 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4142                         } else {
4143                                 $last = substr($last, 0, 32);
4144                         }
4145                 }
4146
4147                 return ['first' => $first, 'last' => $last];
4148         }
4149
4150         /**
4151          * @brief Create profile data
4152          *
4153          * @param int $uid The user id
4154          *
4155          * @return array The profile data
4156          */
4157         private static function createProfileData($uid)
4158         {
4159                 $r = q(
4160                         "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4161                         FROM `profile`
4162                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4163                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4164                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4165                         intval($uid)
4166                 );
4167
4168                 if (!$r) {
4169                         return [];
4170                 }
4171
4172                 $profile = $r[0];
4173                 $handle = $profile["addr"];
4174
4175                 $split_name = self::splitName($profile['name']);
4176                 $first = $split_name['first'];
4177                 $last = $split_name['last'];
4178
4179                 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4180                 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4181                 $small = System::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
4182                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4183
4184                 $dob = null;
4185                 $about = null;
4186                 $location = null;
4187                 $tags = null;
4188                 if ($searchable === 'true') {
4189                         $dob = '';
4190
4191                         if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4192                                 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4193                                 if ($year < 1004) {
4194                                         $year = 1004;
4195                                 }
4196                                 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4197                         }
4198
4199                         $about = $profile['about'];
4200                         $about = strip_tags(bbcode($about));
4201
4202                         $location = Profile::formatLocation($profile);
4203                         $tags = '';
4204                         if ($profile['pub_keywords']) {
4205                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4206                                 $kw = str_replace('  ', ' ', $kw);
4207                                 $arr = explode(' ', $profile['pub_keywords']);
4208                                 if (count($arr)) {
4209                                         for ($x = 0; $x < 5; $x ++) {
4210                                                 if (trim($arr[$x])) {
4211                                                         $tags .= '#'. trim($arr[$x]) .' ';
4212                                                 }
4213                                         }
4214                                 }
4215                         }
4216                         $tags = trim($tags);
4217                 }
4218
4219                 return ["author" => $handle,
4220                                 "first_name" => $first,
4221                                 "last_name" => $last,
4222                                 "image_url" => $large,
4223                                 "image_url_medium" => $medium,
4224                                 "image_url_small" => $small,
4225                                 "birthday" => $dob,
4226                                 "gender" => $profile['gender'],
4227                                 "bio" => $about,
4228                                 "location" => $location,
4229                                 "searchable" => $searchable,
4230                                 "nsfw" => "false",
4231                                 "tag_string" => $tags];
4232         }
4233
4234         /**
4235          * @brief Sends profile data
4236          *
4237          * @param int  $uid    The user id
4238          * @param bool $recips optional, default false
4239          * @return void
4240          */
4241         public static function sendProfile($uid, $recips = false)
4242         {
4243                 if (!$uid) {
4244                         return;
4245                 }
4246
4247                 $owner = User::getOwnerDataById($uid);
4248                 if (!$owner) {
4249                         return;
4250                 }
4251
4252                 if (!$recips) {
4253                         $recips = q(
4254                                 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4255                                 AND `uid` = %d AND `rel` != %d",
4256                                 dbesc(NETWORK_DIASPORA),
4257                                 intval($uid),
4258                                 intval(CONTACT_IS_SHARING)
4259                         );
4260                 }
4261
4262                 if (!$recips) {
4263                         return;
4264                 }
4265
4266                 $message = self::createProfileData($uid);
4267
4268                 foreach ($recips as $recip) {
4269                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4270                         self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4271                 }
4272         }
4273
4274         /**
4275          * @brief Stores the signature for likes that are created on our system
4276          *
4277          * @param array $contact The contact array of the "like"
4278          * @param int   $post_id The post id of the "like"
4279          *
4280          * @return bool Success
4281          */
4282         public static function storeLikeSignature($contact, $post_id)
4283         {
4284                 // Is the contact the owner? Then fetch the private key
4285                 if (!$contact['self'] || ($contact['uid'] == 0)) {
4286                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
4287                         return false;
4288                 }
4289
4290                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4291                 if (!DBM::is_result($r)) {
4292                         return false;
4293                 }
4294
4295                 $contact["uprvkey"] = $r[0]['prvkey'];
4296
4297                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4298                 if (!DBM::is_result($r)) {
4299                         return false;
4300                 }
4301
4302                 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4303                         return false;
4304                 }
4305
4306                 $message = self::constructLike($r[0], $contact);
4307                 if ($message === false) {
4308                         return false;
4309                 }
4310
4311                 $message["author_signature"] = self::signature($contact, $message);
4312
4313                 /*
4314                  * Now store the signature more flexible to dynamically support new fields.
4315                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4316                  */
4317                 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4318
4319                 logger('Stored diaspora like signature');
4320                 return true;
4321         }
4322
4323         /**
4324          * @brief Stores the signature for comments that are created on our system
4325          *
4326          * @param array  $item       The item array of the comment
4327          * @param array  $contact    The contact array of the item owner
4328          * @param string $uprvkey    The private key of the sender
4329          * @param int    $message_id The message id of the comment
4330          *
4331          * @return bool Success
4332          */
4333         public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4334         {
4335                 if ($uprvkey == "") {
4336                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4337                         return false;
4338                 }
4339
4340                 $contact["uprvkey"] = $uprvkey;
4341
4342                 $message = self::constructComment($item, $contact);
4343                 if ($message === false) {
4344                         return false;
4345                 }
4346
4347                 $message["author_signature"] = self::signature($contact, $message);
4348
4349                 /*
4350                  * Now store the signature more flexible to dynamically support new fields.
4351                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4352                  */
4353                 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4354
4355                 logger('Stored diaspora comment signature');
4356                 return true;
4357         }
4358 }