]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
Merge remote-tracking branch 'upstream/develop' into write-tags
[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', 'tag', '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', 'tag', '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["tag"] = $original_item["tag"];
2776                 $datarray["attach"] = $original_item["attach"];
2777                 $datarray["app"]  = $original_item["app"];
2778
2779                 $datarray["plink"] = self::plink($author, $guid);
2780                 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2781                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2782
2783                 $datarray["object-type"] = $original_item["object-type"];
2784
2785                 self::fetchGuid($datarray);
2786                 $message_id = Item::insert($datarray);
2787
2788                 self::sendParticipation($contact, $datarray);
2789
2790                 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2791                 if ($root_message_id) {
2792                         self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2793                 }
2794
2795                 if ($message_id) {
2796                         Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2797                         if ($datarray['uid'] == 0) {
2798                                 Item::distribute($message_id);
2799                         }
2800                         return true;
2801                 } else {
2802                         return false;
2803                 }
2804         }
2805
2806         /**
2807          * Processes retractions
2808          *
2809          * @param array  $importer Array of the importer user
2810          * @param array  $contact  The contact of the item owner
2811          * @param object $data     The message object
2812          *
2813          * @return bool success
2814          * @throws \Exception
2815          */
2816         private static function itemRetraction(array $importer, array $contact, $data)
2817         {
2818                 $author = Strings::escapeTags(XML::unescape($data->author));
2819                 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2820                 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2821
2822                 $person = self::personByHandle($author);
2823                 if (!is_array($person)) {
2824                         Logger::log("unable to find author detail for ".$author);
2825                         return false;
2826                 }
2827
2828                 if (empty($contact["url"])) {
2829                         $contact["url"] = $person["url"];
2830                 }
2831
2832                 // Fetch items that are about to be deleted
2833                 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2834
2835                 // When we receive a public retraction, we delete every item that we find.
2836                 if ($importer['uid'] == 0) {
2837                         $condition = ['guid' => $target_guid, 'deleted' => false];
2838                 } else {
2839                         $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2840                 }
2841
2842                 $r = Item::select($fields, $condition);
2843                 if (!DBA::isResult($r)) {
2844                         Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2845                         return false;
2846                 }
2847
2848                 while ($item = Item::fetch($r)) {
2849                         if (strstr($item['file'], '[')) {
2850                                 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2851                                 continue;
2852                         }
2853
2854                         // Fetch the parent item
2855                         $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2856
2857                         // Only delete it if the parent author really fits
2858                         if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2859                                 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2860                                 continue;
2861                         }
2862
2863                         Item::markForDeletion(['id' => $item['id']]);
2864
2865                         Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], Logger::DEBUG);
2866                 }
2867
2868                 return true;
2869         }
2870
2871         /**
2872          * Receives retraction messages
2873          *
2874          * @param array  $importer Array of the importer user
2875          * @param string $sender   The sender of the message
2876          * @param object $data     The message object
2877          *
2878          * @return bool Success
2879          * @throws \Exception
2880          */
2881         private static function receiveRetraction(array $importer, $sender, $data)
2882         {
2883                 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2884
2885                 $contact = self::contactByHandle($importer["uid"], $sender);
2886                 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2887                         Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2888                         return false;
2889                 }
2890
2891                 if (!$contact) {
2892                         $contact = [];
2893                 }
2894
2895                 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2896
2897                 switch ($target_type) {
2898                         case "Comment":
2899                         case "Like":
2900                         case "Post":
2901                         case "Reshare":
2902                         case "StatusMessage":
2903                                 return self::itemRetraction($importer, $contact, $data);
2904
2905                         case "PollParticipation":
2906                         case "Photo":
2907                                 // Currently unsupported
2908                                 break;
2909
2910                         default:
2911                                 Logger::log("Unknown target type ".$target_type);
2912                                 return false;
2913                 }
2914                 return true;
2915         }
2916
2917         /**
2918          * Receives status messages
2919          *
2920          * @param array            $importer Array of the importer user
2921          * @param SimpleXMLElement $data     The message object
2922          * @param string           $xml      The original XML of the message
2923          *
2924          * @return int The message id of the newly created item
2925          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2926          * @throws \ImagickException
2927          */
2928         private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2929         {
2930                 $author = Strings::escapeTags(XML::unescape($data->author));
2931                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2932                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2933                 $public = Strings::escapeTags(XML::unescape($data->public));
2934                 $text = XML::unescape($data->text);
2935                 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2936
2937                 $contact = self::allowedContactByHandle($importer, $author, false);
2938                 if (!$contact) {
2939                         return false;
2940                 }
2941
2942                 $message_id = self::messageExists($importer["uid"], $guid);
2943                 if ($message_id) {
2944                         return true;
2945                 }
2946
2947                 $address = [];
2948                 if ($data->location) {
2949                         foreach ($data->location->children() as $fieldname => $data) {
2950                                 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2951                         }
2952                 }
2953
2954                 $body = Markdown::toBBCode($text);
2955
2956                 $datarray = [];
2957
2958                 // Attach embedded pictures to the body
2959                 if ($data->photo) {
2960                         foreach ($data->photo as $photo) {
2961                                 $body = "[img]".XML::unescape($photo->remote_photo_path).
2962                                         XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2963                         }
2964
2965                         $datarray["object-type"] = Activity\ObjectType::IMAGE;
2966                 } else {
2967                         $datarray["object-type"] = Activity\ObjectType::NOTE;
2968
2969                         // Add OEmbed and other information to the body
2970                         if (!self::isHubzilla($contact["url"])) {
2971                                 $body = add_page_info_to_body($body, false, true);
2972                         }
2973                 }
2974
2975                 /// @todo enable support for polls
2976                 //if ($data->poll) {
2977                 //      foreach ($data->poll AS $poll)
2978                 //              print_r($poll);
2979                 //      die("poll!\n");
2980                 //}
2981
2982                 /// @todo enable support for events
2983
2984                 $datarray["uid"] = $importer["uid"];
2985                 $datarray["contact-id"] = $contact["id"];
2986                 $datarray["network"] = Protocol::DIASPORA;
2987
2988                 $datarray["author-link"] = $contact["url"];
2989                 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2990
2991                 $datarray["owner-link"] = $datarray["author-link"];
2992                 $datarray["owner-id"] = $datarray["author-id"];
2993
2994                 $datarray["guid"] = $guid;
2995                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2996                 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2997
2998                 $datarray["verb"] = Activity::POST;
2999                 $datarray["gravity"] = GRAVITY_PARENT;
3000
3001                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
3002                 $datarray["source"] = $xml;
3003
3004                 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3005
3006                 self::storeMentions($datarray['uri-id'], $text);
3007                 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
3008
3009                 if ($provider_display_name != "") {
3010                         $datarray["app"] = $provider_display_name;
3011                 }
3012
3013                 $datarray["plink"] = self::plink($author, $guid);
3014                 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
3015                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3016
3017                 if (isset($address["address"])) {
3018                         $datarray["location"] = $address["address"];
3019                 }
3020
3021                 if (isset($address["lat"]) && isset($address["lng"])) {
3022                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
3023                 }
3024
3025                 self::fetchGuid($datarray);
3026                 $message_id = Item::insert($datarray);
3027
3028                 self::sendParticipation($contact, $datarray);
3029
3030                 if ($message_id) {
3031                         Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
3032                         if ($datarray['uid'] == 0) {
3033                                 Item::distribute($message_id);
3034                         }
3035                         return true;
3036                 } else {
3037                         return false;
3038                 }
3039         }
3040
3041         /* ************************************************************************************** *
3042          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3043          * ************************************************************************************** */
3044
3045         /**
3046          * returnes the handle of a contact
3047          *
3048          * @param array $contact contact array
3049          *
3050          * @return string the handle in the format user@domain.tld
3051          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3052          */
3053         private static function myHandle(array $contact)
3054         {
3055                 if (!empty($contact["addr"])) {
3056                         return $contact["addr"];
3057                 }
3058
3059                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3060                 // So - just in case - we build the the address here.
3061                 if ($contact["nickname"] != "") {
3062                         $nick = $contact["nickname"];
3063                 } else {
3064                         $nick = $contact["nick"];
3065                 }
3066
3067                 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
3068         }
3069
3070
3071         /**
3072          * Creates the data for a private message in the new format
3073          *
3074          * @param string $msg     The message that is to be transmitted
3075          * @param array  $user    The record of the sender
3076          * @param array  $contact Target of the communication
3077          * @param string $prvkey  The private key of the sender
3078          * @param string $pubkey  The public key of the receiver
3079          *
3080          * @return string The encrypted data
3081          * @throws \Exception
3082          */
3083         public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
3084         {
3085                 Logger::log("Message: ".$msg, Logger::DATA);
3086
3087                 // without a public key nothing will work
3088                 if (!$pubkey) {
3089                         Logger::log("pubkey missing: contact id: ".$contact["id"]);
3090                         return false;
3091                 }
3092
3093                 $aes_key = openssl_random_pseudo_bytes(32);
3094                 $b_aes_key = base64_encode($aes_key);
3095                 $iv = openssl_random_pseudo_bytes(16);
3096                 $b_iv = base64_encode($iv);
3097
3098                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3099
3100                 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3101
3102                 $encrypted_key_bundle = "";
3103                 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3104
3105                 $json_object = json_encode(
3106                         ["aes_key" => base64_encode($encrypted_key_bundle),
3107                                         "encrypted_magic_envelope" => base64_encode($ciphertext)]
3108                 );
3109
3110                 return $json_object;
3111         }
3112
3113         /**
3114          * Creates the envelope for the "fetch" endpoint and for the new format
3115          *
3116          * @param string $msg  The message that is to be transmitted
3117          * @param array  $user The record of the sender
3118          *
3119          * @return string The envelope
3120          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3121          */
3122         public static function buildMagicEnvelope($msg, array $user)
3123         {
3124                 $b64url_data = Strings::base64UrlEncode($msg);
3125                 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3126
3127                 $key_id = Strings::base64UrlEncode(self::myHandle($user));
3128                 $type = "application/xml";
3129                 $encoding = "base64url";
3130                 $alg = "RSA-SHA256";
3131                 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
3132
3133                 // Fallback if the private key wasn't transmitted in the expected field
3134                 if ($user['uprvkey'] == "") {
3135                         $user['uprvkey'] = $user['prvkey'];
3136                 }
3137
3138                 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3139                 $sig = Strings::base64UrlEncode($signature);
3140
3141                 $xmldata = ["me:env" => ["me:data" => $data,
3142                                                         "@attributes" => ["type" => $type],
3143                                                         "me:encoding" => $encoding,
3144                                                         "me:alg" => $alg,
3145                                                         "me:sig" => $sig,
3146                                                         "@attributes2" => ["key_id" => $key_id]]];
3147
3148                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3149
3150                 return XML::fromArray($xmldata, $xml, false, $namespaces);
3151         }
3152
3153         /**
3154          * Create the envelope for a message
3155          *
3156          * @param string $msg     The message that is to be transmitted
3157          * @param array  $user    The record of the sender
3158          * @param array  $contact Target of the communication
3159          * @param string $prvkey  The private key of the sender
3160          * @param string $pubkey  The public key of the receiver
3161          * @param bool   $public  Is the message public?
3162          *
3163          * @return string The message that will be transmitted to other servers
3164          * @throws \Exception
3165          */
3166         public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3167         {
3168                 // The message is put into an envelope with the sender's signature
3169                 $envelope = self::buildMagicEnvelope($msg, $user);
3170
3171                 // Private messages are put into a second envelope, encrypted with the receivers public key
3172                 if (!$public) {
3173                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3174                 }
3175
3176                 return $envelope;
3177         }
3178
3179         /**
3180          * Creates a signature for a message
3181          *
3182          * @param array $owner   the array of the owner of the message
3183          * @param array $message The message that is to be signed
3184          *
3185          * @return string The signature
3186          */
3187         private static function signature($owner, $message)
3188         {
3189                 $sigmsg = $message;
3190                 unset($sigmsg["author_signature"]);
3191                 unset($sigmsg["parent_author_signature"]);
3192
3193                 $signed_text = implode(";", $sigmsg);
3194
3195                 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3196         }
3197
3198         /**
3199          * Transmit a message to a target server
3200          *
3201          * @param array  $owner        the array of the item owner
3202          * @param array  $contact      Target of the communication
3203          * @param string $envelope     The message that is to be transmitted
3204          * @param bool   $public_batch Is it a public post?
3205          * @param string $guid         message guid
3206          *
3207          * @return int Result of the transmission
3208          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3209          * @throws \ImagickException
3210          */
3211         private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3212         {
3213                 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3214                 if (!$enabled) {
3215                         return 200;
3216                 }
3217
3218                 $logid = Strings::getRandomHex(4);
3219
3220                 // We always try to use the data from the fcontact table.
3221                 // This is important for transmitting data to Friendica servers.
3222                 if (!empty($contact['addr'])) {
3223                         $fcontact = self::personByHandle($contact['addr']);
3224                         if (!empty($fcontact)) {
3225                                 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3226                         }
3227                 }
3228
3229                 if (empty($dest_url)) {
3230                         $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3231                 }
3232
3233                 if (!$dest_url) {
3234                         Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3235                         return 0;
3236                 }
3237
3238                 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3239
3240                 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3241                         $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3242
3243                         $postResult = Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3244                         $return_code = $postResult->getReturnCode();
3245                 } else {
3246                         Logger::log("test_mode");
3247                         return 200;
3248                 }
3249
3250                 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3251
3252                 return $return_code ? $return_code : -1;
3253         }
3254
3255
3256         /**
3257          * Build the post xml
3258          *
3259          * @param string $type    The message type
3260          * @param array  $message The message data
3261          *
3262          * @return string The post XML
3263          */
3264         public static function buildPostXml($type, $message)
3265         {
3266                 $data = [$type => $message];
3267
3268                 return XML::fromArray($data, $xml);
3269         }
3270
3271         /**
3272          * Builds and transmit messages
3273          *
3274          * @param array  $owner        the array of the item owner
3275          * @param array  $contact      Target of the communication
3276          * @param string $type         The message type
3277          * @param array  $message      The message data
3278          * @param bool   $public_batch Is it a public post?
3279          * @param string $guid         message guid
3280          *
3281          * @return int Result of the transmission
3282          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3283          * @throws \ImagickException
3284          */
3285         private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3286         {
3287                 $msg = self::buildPostXml($type, $message);
3288
3289                 Logger::log('message: '.$msg, Logger::DATA);
3290                 Logger::log('send guid '.$guid, Logger::DEBUG);
3291
3292                 // Fallback if the private key wasn't transmitted in the expected field
3293                 if (empty($owner['uprvkey'])) {
3294                         $owner['uprvkey'] = $owner['prvkey'];
3295                 }
3296
3297                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3298
3299                 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3300
3301                 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3302
3303                 return $return_code;
3304         }
3305
3306         /**
3307          * sends a participation (Used to get all further updates)
3308          *
3309          * @param array $contact Target of the communication
3310          * @param array $item    Item array
3311          *
3312          * @return int The result of the transmission
3313          * @throws \Exception
3314          */
3315         private static function sendParticipation(array $contact, array $item)
3316         {
3317                 // Don't send notifications for private postings
3318                 if ($item['private'] == Item::PRIVATE) {
3319                         return;
3320                 }
3321
3322                 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3323
3324                 $result = DI::cache()->get($cachekey);
3325                 if (!is_null($result)) {
3326                         return;
3327                 }
3328
3329                 // Fetch some user id to have a valid handle to transmit the participation.
3330                 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3331                 // If the item belongs to a user, we take this user id.
3332                 if ($item['uid'] == 0) {
3333                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3334                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
3335                         $owner = User::getOwnerDataById($first_user['uid']);
3336                 } else {
3337                         $owner = User::getOwnerDataById($item['uid']);
3338                 }
3339
3340                 $author = self::myHandle($owner);
3341
3342                 $message = ["author" => $author,
3343                                 "guid" => System::createUUID(),
3344                                 "parent_type" => "Post",
3345                                 "parent_guid" => $item["guid"]];
3346
3347                 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3348
3349                 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3350                 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3351
3352                 return self::buildAndTransmit($owner, $contact, "participation", $message);
3353         }
3354
3355         /**
3356          * sends an account migration
3357          *
3358          * @param array $owner   the array of the item owner
3359          * @param array $contact Target of the communication
3360          * @param int   $uid     User ID
3361          *
3362          * @return int The result of the transmission
3363          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3364          * @throws \ImagickException
3365          */
3366         public static function sendAccountMigration(array $owner, array $contact, $uid)
3367         {
3368                 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3369                 $profile = self::createProfileData($uid);
3370
3371                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3372                 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3373
3374                 $message = ["author" => $old_handle,
3375                                 "profile" => $profile,
3376                                 "signature" => $signature];
3377
3378                 Logger::log("Send account migration ".print_r($message, true), Logger::DEBUG);
3379
3380                 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3381         }
3382
3383         /**
3384          * Sends a "share" message
3385          *
3386          * @param array $owner   the array of the item owner
3387          * @param array $contact Target of the communication
3388          *
3389          * @return int The result of the transmission
3390          * @throws \Exception
3391          */
3392         public static function sendShare(array $owner, array $contact)
3393         {
3394                 /**
3395                  * @todo support the different possible combinations of "following" and "sharing"
3396                  * Currently, Diaspora only interprets the "sharing" field
3397                  *
3398                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3399                  */
3400
3401                 /*
3402                 switch ($contact["rel"]) {
3403                         case Contact::FRIEND:
3404                                 $following = true;
3405                                 $sharing = true;
3406
3407                         case Contact::SHARING:
3408                                 $following = false;
3409                                 $sharing = true;
3410
3411                         case Contact::FOLLOWER:
3412                                 $following = true;
3413                                 $sharing = false;
3414                 }
3415                 */
3416
3417                 $message = ["author" => self::myHandle($owner),
3418                                 "recipient" => $contact["addr"],
3419                                 "following" => "true",
3420                                 "sharing" => "true"];
3421
3422                 Logger::log("Send share ".print_r($message, true), Logger::DEBUG);
3423
3424                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3425         }
3426
3427         /**
3428          * sends an "unshare"
3429          *
3430          * @param array $owner   the array of the item owner
3431          * @param array $contact Target of the communication
3432          *
3433          * @return int The result of the transmission
3434          * @throws \Exception
3435          */
3436         public static function sendUnshare(array $owner, array $contact)
3437         {
3438                 $message = ["author" => self::myHandle($owner),
3439                                 "recipient" => $contact["addr"],
3440                                 "following" => "false",
3441                                 "sharing" => "false"];
3442
3443                 Logger::log("Send unshare ".print_r($message, true), Logger::DEBUG);
3444
3445                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3446         }
3447
3448         /**
3449          * Checks a message body if it is a reshare
3450          *
3451          * @param string $body     The message body that is to be check
3452          * @param bool   $complete Should it be a complete check or a simple check?
3453          *
3454          * @return array|bool Reshare details or "false" if no reshare
3455          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3456          * @throws \ImagickException
3457          */
3458         public static function isReshare($body, $complete = true)
3459         {
3460                 $body = trim($body);
3461
3462                 $reshared = Item::getShareArray(['body' => $body]);
3463                 if (empty($reshared)) {
3464                         return false;
3465                 }
3466
3467                 // Skip if it isn't a pure repeated messages
3468                 // Does it start with a share?
3469                 if (!empty($reshared['comment']) && $complete) {
3470                         return false;
3471                 }
3472
3473                 if (!empty($reshared['guid']) && $complete) {
3474                         $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3475                         $item = Item::selectFirst(['contact-id'], $condition);
3476                         if (DBA::isResult($item)) {
3477                                 $ret = [];
3478                                 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3479                                 $ret["root_guid"] = $reshared['guid'];
3480                                 return $ret;
3481                         } elseif ($complete) {
3482                                 // We are resharing something that isn't a DFRN or Diaspora post.
3483                                 // So we have to return "false" on "$complete" to not trigger a reshare.
3484                                 return false;
3485                         }
3486                 } elseif (empty($reshared['guid']) && $complete) {
3487                         return false;
3488                 }
3489
3490                 $ret = [];
3491
3492                 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3493                         $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3494                         if (!empty($contact['addr'])) {
3495                                 $ret['root_handle'] = $contact['addr'];
3496                         }
3497                 }
3498
3499                 if (empty($ret) && !$complete) {
3500                         return true;
3501                 }
3502
3503                 return $ret;
3504         }
3505
3506         /**
3507          * Create an event array
3508          *
3509          * @param integer $event_id The id of the event
3510          *
3511          * @return array with event data
3512          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3513          */
3514         private static function buildEvent($event_id)
3515         {
3516                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3517                 if (!DBA::isResult($r)) {
3518                         return [];
3519                 }
3520
3521                 $event = $r[0];
3522
3523                 $eventdata = [];
3524
3525                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3526                 if (!DBA::isResult($r)) {
3527                         return [];
3528                 }
3529
3530                 $user = $r[0];
3531
3532                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3533                 if (!DBA::isResult($r)) {
3534                         return [];
3535                 }
3536
3537                 $owner = $r[0];
3538
3539                 $eventdata['author'] = self::myHandle($owner);
3540
3541                 if ($event['guid']) {
3542                         $eventdata['guid'] = $event['guid'];
3543                 }
3544
3545                 $mask = DateTimeFormat::ATOM;
3546
3547                 /// @todo - establish "all day" events in Friendica
3548                 $eventdata["all_day"] = "false";
3549
3550                 $eventdata['timezone'] = 'UTC';
3551                 if (!$event['adjust'] && $user['timezone']) {
3552                         $eventdata['timezone'] = $user['timezone'];
3553                 }
3554
3555                 if ($event['start']) {
3556                         $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3557                 }
3558                 if ($event['finish'] && !$event['nofinish']) {
3559                         $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3560                 }
3561                 if ($event['summary']) {
3562                         $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3563                 }
3564                 if ($event['desc']) {
3565                         $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3566                 }
3567                 if ($event['location']) {
3568                         $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3569                         $coord = Map::getCoordinates($event['location']);
3570
3571                         $location = [];
3572                         $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3573                         if (!empty($coord['lat']) && !empty($coord['lon'])) {
3574                                 $location["lat"] = $coord['lat'];
3575                                 $location["lng"] = $coord['lon'];
3576                         } else {
3577                                 $location["lat"] = 0;
3578                                 $location["lng"] = 0;
3579                         }
3580                         $eventdata['location'] = $location;
3581                 }
3582
3583                 return $eventdata;
3584         }
3585
3586         /**
3587          * Create a post (status message or reshare)
3588          *
3589          * @param array $item  The item that will be exported
3590          * @param array $owner the array of the item owner
3591          *
3592          * @return array
3593          * 'type' -> Message type ("status_message" or "reshare")
3594          * 'message' -> Array of XML elements of the status
3595          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3596          * @throws \ImagickException
3597          */
3598         public static function buildStatus(array $item, array $owner)
3599         {
3600                 $cachekey = "diaspora:buildStatus:".$item['guid'];
3601
3602                 $result = DI::cache()->get($cachekey);
3603                 if (!is_null($result)) {
3604                         return $result;
3605                 }
3606
3607                 $myaddr = self::myHandle($owner);
3608
3609                 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3610                 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3611                 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3612
3613                 // Detect a share element and do a reshare
3614                 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3615                         $message = ["author" => $myaddr,
3616                                         "guid" => $item["guid"],
3617                                         "created_at" => $created,
3618                                         "root_author" => $ret["root_handle"],
3619                                         "root_guid" => $ret["root_guid"],
3620                                         "provider_display_name" => $item["app"],
3621                                         "public" => $public];
3622
3623                         $type = "reshare";
3624                 } else {
3625                         $title = $item["title"];
3626                         $body = $item["body"];
3627
3628                         // Fetch the title from an attached link - if there is one
3629                         if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3630                                 $page_data = BBCode::getAttachmentData($item['body']);
3631                                 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3632                                         $title = $page_data['title'];
3633                                 }
3634                         }
3635
3636                         if ($item['author-link'] != $item['owner-link']) {
3637                                 require_once 'mod/share.php';
3638                                 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3639                                         "", $item['created'], $item['plink']) . $body . '[/share]';
3640                         }
3641
3642                         // convert to markdown
3643                         $body = html_entity_decode(BBCode::toMarkdown($body));
3644
3645                         // Adding the title
3646                         if (strlen($title)) {
3647                                 $body = "### ".html_entity_decode($title)."\n\n".$body;
3648                         }
3649
3650                         if ($item["attach"]) {
3651                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3652                                 if ($cnt) {
3653                                         $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3654                                         foreach ($matches as $mtch) {
3655                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3656                                         }
3657                                 }
3658                         }
3659
3660                         $location = [];
3661
3662                         if ($item["location"] != "")
3663                                 $location["address"] = $item["location"];
3664
3665                         if ($item["coord"] != "") {
3666                                 $coord = explode(" ", $item["coord"]);
3667                                 $location["lat"] = $coord[0];
3668                                 $location["lng"] = $coord[1];
3669                         }
3670
3671                         $message = ["author" => $myaddr,
3672                                         "guid" => $item["guid"],
3673                                         "created_at" => $created,
3674                                         "edited_at" => $edited,
3675                                         "public" => $public,
3676                                         "text" => $body,
3677                                         "provider_display_name" => $item["app"],
3678                                         "location" => $location];
3679
3680                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3681                         if (!isset($location["lat"]) || !isset($location["lng"])) {
3682                                 unset($message["location"]);
3683                         }
3684
3685                         if ($item['event-id'] > 0) {
3686                                 $event = self::buildEvent($item['event-id']);
3687                                 if (count($event)) {
3688                                         $message['event'] = $event;
3689
3690                                         if (!empty($event['location']['address']) &&
3691                                                 !empty($event['location']['lat']) &&
3692                                                 !empty($event['location']['lng'])) {
3693                                                 $message['location'] = $event['location'];
3694                                         }
3695
3696                                         /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3697                                         // $message['text'] = '';
3698                                 }
3699                         }
3700
3701                         $type = "status_message";
3702                 }
3703
3704                 $msg = ["type" => $type, "message" => $message];
3705
3706                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3707
3708                 return $msg;
3709         }
3710
3711         private static function prependParentAuthorMention($body, $profile_url)
3712         {
3713                 $profile = Contact::getDetailsByURL($profile_url);
3714                 if (!empty($profile['addr'])
3715                         && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3716                         && !strstr($body, $profile['addr'])
3717                         && !strstr($body, $profile_url)
3718                 ) {
3719                         $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3720                 }
3721
3722                 return $body;
3723         }
3724
3725         /**
3726          * Sends a post
3727          *
3728          * @param array $item         The item that will be exported
3729          * @param array $owner        the array of the item owner
3730          * @param array $contact      Target of the communication
3731          * @param bool  $public_batch Is it a public post?
3732          *
3733          * @return int The result of the transmission
3734          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3735          * @throws \ImagickException
3736          */
3737         public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3738         {
3739                 $status = self::buildStatus($item, $owner);
3740
3741                 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3742         }
3743
3744         /**
3745          * Creates a "like" object
3746          *
3747          * @param array $item  The item that will be exported
3748          * @param array $owner the array of the item owner
3749          *
3750          * @return array The data for a "like"
3751          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3752          */
3753         private static function constructLike(array $item, array $owner)
3754         {
3755                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3756                 if (!DBA::isResult($parent)) {
3757                         return false;
3758                 }
3759
3760                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3761                 $positive = null;
3762                 if ($item['verb'] === Activity::LIKE) {
3763                         $positive = "true";
3764                 } elseif ($item['verb'] === Activity::DISLIKE) {
3765                         $positive = "false";
3766                 }
3767
3768                 return(["author" => self::myHandle($owner),
3769                                 "guid" => $item["guid"],
3770                                 "parent_guid" => $parent["guid"],
3771                                 "parent_type" => $target_type,
3772                                 "positive" => $positive,
3773                                 "author_signature" => ""]);
3774         }
3775
3776         /**
3777          * Creates an "EventParticipation" object
3778          *
3779          * @param array $item  The item that will be exported
3780          * @param array $owner the array of the item owner
3781          *
3782          * @return array The data for an "EventParticipation"
3783          * @throws \Exception
3784          */
3785         private static function constructAttend(array $item, array $owner)
3786         {
3787                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3788                 if (!DBA::isResult($parent)) {
3789                         return false;
3790                 }
3791
3792                 switch ($item['verb']) {
3793                         case Activity::ATTEND:
3794                                 $attend_answer = 'accepted';
3795                                 break;
3796                         case Activity::ATTENDNO:
3797                                 $attend_answer = 'declined';
3798                                 break;
3799                         case Activity::ATTENDMAYBE:
3800                                 $attend_answer = 'tentative';
3801                                 break;
3802                         default:
3803                                 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3804                                 return false;
3805                 }
3806
3807                 return(["author" => self::myHandle($owner),
3808                                 "guid" => $item["guid"],
3809                                 "parent_guid" => $parent["guid"],
3810                                 "status" => $attend_answer,
3811                                 "author_signature" => ""]);
3812         }
3813
3814         /**
3815          * Creates the object for a comment
3816          *
3817          * @param array $item  The item that will be exported
3818          * @param array $owner the array of the item owner
3819          *
3820          * @return array|false The data for a comment
3821          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3822          */
3823         private static function constructComment(array $item, array $owner)
3824         {
3825                 $cachekey = "diaspora:constructComment:".$item['guid'];
3826
3827                 $result = DI::cache()->get($cachekey);
3828                 if (!is_null($result)) {
3829                         return $result;
3830                 }
3831
3832                 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3833                 if (!DBA::isResult($toplevel_item)) {
3834                         Logger::error('Missing parent conversation item', ['parent' => $item["parent"]]);
3835                         return false;
3836                 }
3837
3838                 $thread_parent_item = $toplevel_item;
3839                 if ($item['thr-parent'] != $item['parent-uri']) {
3840                         $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3841                 }
3842
3843                 $body = $item["body"];
3844
3845                 // The replied to autor mention is prepended for clarity if:
3846                 // - Item replied isn't yours
3847                 // - Item is public or explicit mentions are disabled
3848                 // - Implicit mentions are enabled
3849                 if (
3850                         $item['author-id'] != $thread_parent_item['author-id']
3851                         && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3852                         && !DI::config()->get('system', 'disable_implicit_mentions')
3853                 ) {
3854                         $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3855                 }
3856
3857                 $text = html_entity_decode(BBCode::toMarkdown($body));
3858                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3859                 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3860
3861                 $comment = [
3862                         "author"      => self::myHandle($owner),
3863                         "guid"        => $item["guid"],
3864                         "created_at"  => $created,
3865                         "edited_at"   => $edited,
3866                         "parent_guid" => $toplevel_item["guid"],
3867                         "text"        => $text,
3868                         "author_signature" => ""
3869                 ];
3870
3871                 // Send the thread parent guid only if it is a threaded comment
3872                 if ($item['thr-parent'] != $item['parent-uri']) {
3873                         $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3874                 }
3875
3876                 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3877
3878                 return($comment);
3879         }
3880
3881         /**
3882          * Send a like or a comment
3883          *
3884          * @param array $item         The item that will be exported
3885          * @param array $owner        the array of the item owner
3886          * @param array $contact      Target of the communication
3887          * @param bool  $public_batch Is it a public post?
3888          *
3889          * @return int The result of the transmission
3890          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3891          * @throws \ImagickException
3892          */
3893         public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3894         {
3895                 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3896                         $message = self::constructAttend($item, $owner);
3897                         $type = "event_participation";
3898                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3899                         $message = self::constructLike($item, $owner);
3900                         $type = "like";
3901                 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3902                         $message = self::constructComment($item, $owner);
3903                         $type = "comment";
3904                 }
3905
3906                 if (empty($message)) {
3907                         return false;
3908                 }
3909
3910                 $message["author_signature"] = self::signature($owner, $message);
3911
3912                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3913         }
3914
3915         /**
3916          * Creates a message from a signature record entry
3917          *
3918          * @param array $item The item that will be exported
3919          * @return array The message
3920          */
3921         private static function messageFromSignature(array $item)
3922         {
3923                 // Split the signed text
3924                 $signed_parts = explode(";", $item['signed_text']);
3925
3926                 if ($item["deleted"]) {
3927                         $message = ["author" => $item['signer'],
3928                                         "target_guid" => $signed_parts[0],
3929                                         "target_type" => $signed_parts[1]];
3930                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3931                         $message = ["author" => $signed_parts[4],
3932                                         "guid" => $signed_parts[1],
3933                                         "parent_guid" => $signed_parts[3],
3934                                         "parent_type" => $signed_parts[2],
3935                                         "positive" => $signed_parts[0],
3936                                         "author_signature" => $item['signature'],
3937                                         "parent_author_signature" => ""];
3938                 } else {
3939                         // Remove the comment guid
3940                         $guid = array_shift($signed_parts);
3941
3942                         // Remove the parent guid
3943                         $parent_guid = array_shift($signed_parts);
3944
3945                         // Remove the handle
3946                         $handle = array_pop($signed_parts);
3947
3948                         $message = [
3949                                 "author" => $handle,
3950                                 "guid" => $guid,
3951                                 "parent_guid" => $parent_guid,
3952                                 "text" => implode(";", $signed_parts),
3953                                 "author_signature" => $item['signature'],
3954                                 "parent_author_signature" => ""
3955                         ];
3956                 }
3957                 return $message;
3958         }
3959
3960         /**
3961          * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3962          *
3963          * @param array $item         The item that will be exported
3964          * @param array $owner        the array of the item owner
3965          * @param array $contact      Target of the communication
3966          * @param bool  $public_batch Is it a public post?
3967          *
3968          * @return int The result of the transmission
3969          * @throws \Exception
3970          */
3971         public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3972         {
3973                 if ($item["deleted"]) {
3974                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3975                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3976                         $type = "like";
3977                 } else {
3978                         $type = "comment";
3979                 }
3980
3981                 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3982
3983                 $msg = json_decode($item['signed_text'], true);
3984
3985                 $message = [];
3986                 if (is_array($msg)) {
3987                         foreach ($msg as $field => $data) {
3988                                 if (!$item["deleted"]) {
3989                                         if ($field == "diaspora_handle") {
3990                                                 $field = "author";
3991                                         }
3992                                         if ($field == "target_type") {
3993                                                 $field = "parent_type";
3994                                         }
3995                                 }
3996
3997                                 $message[$field] = $data;
3998                         }
3999                 } else {
4000                         Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
4001                 }
4002
4003                 $message["parent_author_signature"] = self::signature($owner, $message);
4004
4005                 Logger::log("Relayed data ".print_r($message, true), Logger::DEBUG);
4006
4007                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4008         }
4009
4010         /**
4011          * Sends a retraction (deletion) of a message, like or comment
4012          *
4013          * @param array $item         The item that will be exported
4014          * @param array $owner        the array of the item owner
4015          * @param array $contact      Target of the communication
4016          * @param bool  $public_batch Is it a public post?
4017          * @param bool  $relay        Is the retraction transmitted from a relay?
4018          *
4019          * @return int The result of the transmission
4020          * @throws \Exception
4021          */
4022         public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
4023         {
4024                 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4025
4026                 $msg_type = "retraction";
4027
4028                 if ($item['id'] == $item['parent']) {
4029                         $target_type = "Post";
4030                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4031                         $target_type = "Like";
4032                 } else {
4033                         $target_type = "Comment";
4034                 }
4035
4036                 $message = ["author" => $itemaddr,
4037                                 "target_guid" => $item['guid'],
4038                                 "target_type" => $target_type];
4039
4040                 Logger::log("Got message ".print_r($message, true), Logger::DEBUG);
4041
4042                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4043         }
4044
4045         /**
4046          * Sends a mail
4047          *
4048          * @param array $item    The item that will be exported
4049          * @param array $owner   The owner
4050          * @param array $contact Target of the communication
4051          *
4052          * @return int The result of the transmission
4053          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4054          * @throws \ImagickException
4055          */
4056         public static function sendMail(array $item, array $owner, array $contact)
4057         {
4058                 $myaddr = self::myHandle($owner);
4059
4060                 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
4061                 if (!DBA::isResult($cnv)) {
4062                         Logger::log("conversation not found.");
4063                         return;
4064                 }
4065
4066                 $body = BBCode::toMarkdown($item["body"]);
4067                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4068
4069                 $msg = [
4070                         "author" => $myaddr,
4071                         "guid" => $item["guid"],
4072                         "conversation_guid" => $cnv["guid"],
4073                         "text" => $body,
4074                         "created_at" => $created,
4075                 ];
4076
4077                 if ($item["reply"]) {
4078                         $message = $msg;
4079                         $type = "message";
4080                 } else {
4081                         $message = [
4082                                 "author" => $cnv["creator"],
4083                                 "guid" => $cnv["guid"],
4084                                 "subject" => $cnv["subject"],
4085                                 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4086                                 "participants" => $cnv["recips"],
4087                                 "message" => $msg
4088                         ];
4089
4090                         $type = "conversation";
4091                 }
4092
4093                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4094         }
4095
4096         /**
4097          * Split a name into first name and last name
4098          *
4099          * @param string $name The name
4100          *
4101          * @return array The array with "first" and "last"
4102          */
4103         public static function splitName($name) {
4104                 $name = trim($name);
4105
4106                 // Is the name longer than 64 characters? Then cut the rest of it.
4107                 if (strlen($name) > 64) {
4108                         if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4109                                 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4110                         } else {
4111                                 $name = substr($name, 0, 64);
4112                         }
4113                 }
4114
4115                 // Take the first word as first name
4116                 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4117                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4118                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4119                         return ['first' => $first, 'last' => $last];
4120                 }
4121
4122                 // Take the last word as last name
4123                 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4124                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4125
4126                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4127                         return ['first' => $first, 'last' => $last];
4128                 }
4129
4130                 // Take the first 32 characters if there is no space in the first 32 characters
4131                 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4132                         $first = substr($name, 0, 32);
4133                         $last = substr($name, 32);
4134                         return ['first' => $first, 'last' => $last];
4135                 }
4136
4137                 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4138                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4139
4140                 // Check if the last name is longer than 32 characters
4141                 if (strlen($last) > 32) {
4142                         if (strpos($last, ' ') <= 32) {
4143                                 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4144                         } else {
4145                                 $last = substr($last, 0, 32);
4146                         }
4147                 }
4148
4149                 return ['first' => $first, 'last' => $last];
4150         }
4151
4152         /**
4153          * Create profile data
4154          *
4155          * @param int $uid The user id
4156          *
4157          * @return array The profile data
4158          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4159          */
4160         private static function createProfileData($uid)
4161         {
4162                 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4163                 if (!DBA::isResult($profile)) {
4164                         return [];
4165                 }
4166
4167                 $handle = $profile["addr"];
4168
4169                 $split_name = self::splitName($profile['name']);
4170                 $first = $split_name['first'];
4171                 $last = $split_name['last'];
4172
4173                 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4174                 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4175                 $small = DI::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
4176                 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4177
4178                 $dob = null;
4179                 $about = null;
4180                 $location = null;
4181                 $tags = null;
4182                 if ($searchable === 'true') {
4183                         $dob = '';
4184
4185                         if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4186                                 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4187                                 if ($year < 1004) {
4188                                         $year = 1004;
4189                                 }
4190                                 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4191                         }
4192
4193                         $about = BBCode::toMarkdown($profile['about']);
4194
4195                         $location = $profile['location'];
4196                         $tags = '';
4197                         if ($profile['pub_keywords']) {
4198                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4199                                 $kw = str_replace('  ', ' ', $kw);
4200                                 $arr = explode(' ', $kw);
4201                                 if (count($arr)) {
4202                                         for ($x = 0; $x < 5; $x ++) {
4203                                                 if (!empty($arr[$x])) {
4204                                                         $tags .= '#'. trim($arr[$x]) .' ';
4205                                                 }
4206                                         }
4207                                 }
4208                         }
4209                         $tags = trim($tags);
4210                 }
4211
4212                 return ["author" => $handle,
4213                                 "first_name" => $first,
4214                                 "last_name" => $last,
4215                                 "image_url" => $large,
4216                                 "image_url_medium" => $medium,
4217                                 "image_url_small" => $small,
4218                                 "birthday" => $dob,
4219                                 "bio" => $about,
4220                                 "location" => $location,
4221                                 "searchable" => $searchable,
4222                                 "nsfw" => "false",
4223                                 "tag_string" => $tags];
4224         }
4225
4226         /**
4227          * Sends profile data
4228          *
4229          * @param int  $uid    The user id
4230          * @param bool $recips optional, default false
4231          * @return void
4232          * @throws \Exception
4233          */
4234         public static function sendProfile($uid, $recips = false)
4235         {
4236                 if (!$uid) {
4237                         return;
4238                 }
4239
4240                 $owner = User::getOwnerDataById($uid);
4241                 if (!$owner) {
4242                         return;
4243                 }
4244
4245                 if (!$recips) {
4246                         $recips = q(
4247                                 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4248                                 AND `uid` = %d AND `rel` != %d",
4249                                 DBA::escape(Protocol::DIASPORA),
4250                                 intval($uid),
4251                                 intval(Contact::SHARING)
4252                         );
4253                 }
4254
4255                 if (!$recips) {
4256                         return;
4257                 }
4258
4259                 $message = self::createProfileData($uid);
4260
4261                 // @ToDo Split this into single worker jobs
4262                 foreach ($recips as $recip) {
4263                         Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4264                         self::buildAndTransmit($owner, $recip, "profile", $message);
4265                 }
4266         }
4267
4268         /**
4269          * Creates the signature for likes that are created on our system
4270          *
4271          * @param integer $uid  The user of that comment
4272          * @param array   $item Item array
4273          *
4274          * @return array Signed content
4275          * @throws \Exception
4276          */
4277         public static function createLikeSignature($uid, array $item)
4278         {
4279                 $owner = User::getOwnerDataById($uid);
4280                 if (empty($owner)) {
4281                         Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4282                         return false;
4283                 }
4284
4285                 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4286                         return false;
4287                 }
4288
4289                 $message = self::constructLike($item, $owner);
4290                 if ($message === false) {
4291                         return false;
4292                 }
4293
4294                 $message["author_signature"] = self::signature($owner, $message);
4295
4296                 return $message;
4297         }
4298
4299         /**
4300          * Creates the signature for Comments that are created on our system
4301          *
4302          * @param integer $uid  The user of that comment
4303          * @param array   $item Item array
4304          *
4305          * @return array Signed content
4306          * @throws \Exception
4307          */
4308         public static function createCommentSignature($uid, array $item)
4309         {
4310                 $owner = User::getOwnerDataById($uid);
4311                 if (empty($owner)) {
4312                         Logger::log("No owner post, so not storing signature", Logger::DEBUG);
4313                         return false;
4314                 }
4315
4316                 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4317                 $item['thr-parent'] = $item['parent-uri'];
4318
4319                 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4320                 if (!DBA::isResult($parent)) {
4321                         return;
4322                 }
4323
4324                 $item['parent-uri'] = $parent['parent-uri'];
4325
4326                 $message = self::constructComment($item, $owner);
4327                 if ($message === false) {
4328                         return false;
4329                 }
4330
4331                 $message["author_signature"] = self::signature($owner, $message);
4332
4333                 return $message;
4334         }
4335 }