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