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