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