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