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