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