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