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