]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
Renamed function
[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                 $datarray["guid"] = $guid;
1739                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1740                 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
1741
1742                 $datarray["verb"] = Activity::POST;
1743                 $datarray["gravity"] = GRAVITY_COMMENT;
1744
1745                 if ($thr_uri != "") {
1746                         $datarray["parent-uri"] = $thr_uri;
1747                 } else {
1748                         $datarray["parent-uri"] = $parent_item["uri"];
1749                 }
1750
1751                 $datarray["object-type"] = Activity\ObjectType::COMMENT;
1752
1753                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1754                 $datarray["source"] = $xml;
1755
1756                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1757
1758                 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1759                 $body = Markdown::toBBCode($text);
1760
1761                 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1762
1763                 self::storeMentions($datarray['uri-id'], $text);
1764                 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
1765
1766                 self::fetchGuid($datarray);
1767
1768                 // If we are the origin of the parent we store the original data.
1769                 // We notify our followers during the item storage.
1770                 if ($parent_item["origin"]) {
1771                         $datarray['diaspora_signed_text'] = json_encode($data);
1772                 }
1773
1774                 $message_id = Item::insert($datarray);
1775
1776                 if ($message_id <= 0) {
1777                         return false;
1778                 }
1779
1780                 if ($message_id) {
1781                         Logger::log("Stored comment ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
1782                         if ($datarray['uid'] == 0) {
1783                                 Item::distribute($message_id, json_encode($data));
1784                         }
1785                 }
1786
1787                 return true;
1788         }
1789
1790         /**
1791          * processes and stores private messages
1792          *
1793          * @param array  $importer     Array of the importer user
1794          * @param array  $contact      The contact of the message
1795          * @param object $data         The message object
1796          * @param array  $msg          Array of the processed message, author handle and key
1797          * @param object $mesg         The private message
1798          * @param array  $conversation The conversation record to which this message belongs
1799          *
1800          * @return bool "true" if it was successful
1801          * @throws \Exception
1802          */
1803         private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1804         {
1805                 $author = Strings::escapeTags(XML::unescape($data->author));
1806                 $guid = Strings::escapeTags(XML::unescape($data->guid));
1807                 $subject = Strings::escapeTags(XML::unescape($data->subject));
1808
1809                 // "diaspora_handle" is the element name from the old version
1810                 // "author" is the element name from the new version
1811                 if ($mesg->author) {
1812                         $msg_author = Strings::escapeTags(XML::unescape($mesg->author));
1813                 } elseif ($mesg->diaspora_handle) {
1814                         $msg_author = Strings::escapeTags(XML::unescape($mesg->diaspora_handle));
1815                 } else {
1816                         return false;
1817                 }
1818
1819                 $msg_guid = Strings::escapeTags(XML::unescape($mesg->guid));
1820                 $msg_conversation_guid = Strings::escapeTags(XML::unescape($mesg->conversation_guid));
1821                 $msg_text = XML::unescape($mesg->text);
1822                 $msg_created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($mesg->created_at)));
1823
1824                 if ($msg_conversation_guid != $guid) {
1825                         Logger::log("message conversation guid does not belong to the current conversation.");
1826                         return false;
1827                 }
1828
1829                 $body = Markdown::toBBCode($msg_text);
1830                 $message_uri = $msg_author.":".$msg_guid;
1831
1832                 $person = FContact::getByURL($msg_author);
1833
1834                 return Mail::insert([
1835                         'uid'        => $importer['uid'],
1836                         'guid'       => $msg_guid,
1837                         'convid'     => $conversation['id'],
1838                         'from-name'  => $person['name'],
1839                         'from-photo' => $person['photo'],
1840                         'from-url'   => $person['url'],
1841                         'contact-id' => $contact['id'],
1842                         'title'      => $subject,
1843                         'body'       => $body,
1844                         'uri'        => $message_uri,
1845                         'parent-uri' => $author . ':' . $guid,
1846                         'created'    => $msg_created_at
1847                 ]);
1848         }
1849
1850         /**
1851          * Processes new private messages (answers to private messages are processed elsewhere)
1852          *
1853          * @param array  $importer Array of the importer user
1854          * @param array  $msg      Array of the processed message, author handle and key
1855          * @param object $data     The message object
1856          *
1857          * @return bool Success
1858          * @throws \Exception
1859          */
1860         private static function receiveConversation(array $importer, $msg, $data)
1861         {
1862                 $author = Strings::escapeTags(XML::unescape($data->author));
1863                 $guid = Strings::escapeTags(XML::unescape($data->guid));
1864                 $subject = Strings::escapeTags(XML::unescape($data->subject));
1865                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
1866                 $participants = Strings::escapeTags(XML::unescape($data->participants));
1867
1868                 $messages = $data->message;
1869
1870                 if (!count($messages)) {
1871                         Logger::log("empty conversation");
1872                         return false;
1873                 }
1874
1875                 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1876                 if (!$contact) {
1877                         return false;
1878                 }
1879
1880                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1881                 if (!DBA::isResult($conversation)) {
1882                         $r = q(
1883                                 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1884                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1885                                 intval($importer["uid"]),
1886                                 DBA::escape($guid),
1887                                 DBA::escape($author),
1888                                 DBA::escape($created_at),
1889                                 DBA::escape(DateTimeFormat::utcNow()),
1890                                 DBA::escape($subject),
1891                                 DBA::escape($participants)
1892                         );
1893                         if ($r) {
1894                                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1895                         }
1896                 }
1897                 if (!$conversation) {
1898                         Logger::log("unable to create conversation.");
1899                         return false;
1900                 }
1901
1902                 foreach ($messages as $mesg) {
1903                         self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1904                 }
1905
1906                 return true;
1907         }
1908
1909         /**
1910          * Processes "like" messages
1911          *
1912          * @param array  $importer Array of the importer user
1913          * @param string $sender   The sender of the message
1914          * @param object $data     The message object
1915          *
1916          * @return int The message id of the generated like or "false" if there was an error
1917          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918          * @throws \ImagickException
1919          */
1920         private static function receiveLike(array $importer, $sender, $data)
1921         {
1922                 $author = Strings::escapeTags(XML::unescape($data->author));
1923                 $guid = Strings::escapeTags(XML::unescape($data->guid));
1924                 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
1925                 $parent_type = Strings::escapeTags(XML::unescape($data->parent_type));
1926                 $positive = Strings::escapeTags(XML::unescape($data->positive));
1927
1928                 // likes on comments aren't supported by Diaspora - only on posts
1929                 // But maybe this will be supported in the future, so we will accept it.
1930                 if (!in_array($parent_type, ["Post", "Comment"])) {
1931                         return false;
1932                 }
1933
1934                 $contact = self::allowedContactByHandle($importer, $sender, true);
1935                 if (!$contact) {
1936                         return false;
1937                 }
1938
1939                 $message_id = self::messageExists($importer["uid"], $guid);
1940                 if ($message_id) {
1941                         return true;
1942                 }
1943
1944                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1945                 if (!$parent_item) {
1946                         return false;
1947                 }
1948
1949                 $person = FContact::getByURL($author);
1950                 if (!is_array($person)) {
1951                         Logger::log("unable to find author details");
1952                         return false;
1953                 }
1954
1955                 // Fetch the contact id - if we know this contact
1956                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1957
1958                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1959                 // We would accept this anyhow.
1960                 if ($positive == "true") {
1961                         $verb = Activity::LIKE;
1962                 } else {
1963                         $verb = Activity::DISLIKE;
1964                 }
1965
1966                 $datarray = [];
1967
1968                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1969
1970                 $datarray["uid"] = $importer["uid"];
1971                 $datarray["contact-id"] = $author_contact["cid"];
1972                 $datarray["network"]  = $author_contact["network"];
1973
1974                 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
1975                 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1976
1977                 $datarray["guid"] = $guid;
1978                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1979
1980                 $datarray["verb"] = $verb;
1981                 $datarray["gravity"] = GRAVITY_ACTIVITY;
1982                 $datarray["parent-uri"] = $parent_item["uri"];
1983
1984                 $datarray["object-type"] = Activity\ObjectType::NOTE;
1985
1986                 $datarray["body"] = $verb;
1987
1988                 // Diaspora doesn't provide a date for likes
1989                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1990
1991                 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1992                 if ($parent_item['gravity'] != GRAVITY_PARENT) {
1993                         $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item['parent']]);
1994                         $origin = $toplevel["origin"];
1995                 } else {
1996                         $origin = $parent_item["origin"];
1997                 }
1998
1999                 // If we are the origin of the parent we store the original data.
2000                 // We notify our followers during the item storage.
2001                 if ($origin) {
2002                         $datarray['diaspora_signed_text'] = json_encode($data);
2003                 }
2004
2005                 $message_id = Item::insert($datarray);
2006
2007                 if ($message_id <= 0) {
2008                         return false;
2009                 }
2010
2011                 if ($message_id) {
2012                         Logger::log("Stored like ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2013                         if ($datarray['uid'] == 0) {
2014                                 Item::distribute($message_id, json_encode($data));
2015                         }
2016                 }
2017
2018                 return true;
2019         }
2020
2021         /**
2022          * Processes private messages
2023          *
2024          * @param array  $importer Array of the importer user
2025          * @param object $data     The message object
2026          *
2027          * @return bool Success?
2028          * @throws \Exception
2029          */
2030         private static function receiveMessage(array $importer, $data)
2031         {
2032                 $author = Strings::escapeTags(XML::unescape($data->author));
2033                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2034                 $conversation_guid = Strings::escapeTags(XML::unescape($data->conversation_guid));
2035                 $text = XML::unescape($data->text);
2036                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2037
2038                 $contact = self::allowedContactByHandle($importer, $author, true);
2039                 if (!$contact) {
2040                         return false;
2041                 }
2042
2043                 $conversation = null;
2044
2045                 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2046                 $conversation = DBA::selectFirst('conv', [], $condition);
2047
2048                 if (!DBA::isResult($conversation)) {
2049                         Logger::log("conversation not available.");
2050                         return false;
2051                 }
2052
2053                 $message_uri = $author.":".$guid;
2054
2055                 $person = FContact::getByURL($author);
2056                 if (!$person) {
2057                         Logger::log("unable to find author details");
2058                         return false;
2059                 }
2060
2061                 $body = Markdown::toBBCode($text);
2062
2063                 $body = self::replacePeopleGuid($body, $person["url"]);
2064
2065                 return Mail::insert([
2066                         'uid'        => $importer['uid'],
2067                         'guid'       => $guid,
2068                         'convid'     => $conversation['id'],
2069                         'from-name'  => $person['name'],
2070                         'from-photo' => $person['photo'],
2071                         'from-url'   => $person['url'],
2072                         'contact-id' => $contact['id'],
2073                         'title'      => $conversation['subject'],
2074                         'body'       => $body,
2075                         'reply'      => 1,
2076                         'uri'        => $message_uri,
2077                         'parent-uri' => $author.":".$conversation['guid'],
2078                         'created'    => $created_at
2079                 ]);
2080         }
2081
2082         /**
2083          * Processes participations - unsupported by now
2084          *
2085          * @param array  $importer Array of the importer user
2086          * @param object $data     The message object
2087          *
2088          * @return bool success
2089          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2090          * @throws \ImagickException
2091          */
2092         private static function receiveParticipation(array $importer, $data)
2093         {
2094                 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2095                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2096                 $parent_guid = Strings::escapeTags(XML::unescape($data->parent_guid));
2097
2098                 $contact = self::allowedContactByHandle($importer, $author, true);
2099                 if (!$contact) {
2100                         return false;
2101                 }
2102
2103                 if (self::messageExists($importer["uid"], $guid)) {
2104                         return true;
2105                 }
2106
2107                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2108                 if (!$parent_item) {
2109                         return false;
2110                 }
2111
2112                 if (!$parent_item['origin']) {
2113                         Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2114                 }
2115
2116                 if (!in_array($parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) {
2117                         Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]);
2118                         return false;
2119                 }
2120
2121                 $person = FContact::getByURL($author);
2122                 if (!is_array($person)) {
2123                         Logger::log("Person not found: ".$author);
2124                         return false;
2125                 }
2126
2127                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2128
2129                 // Store participation
2130                 $datarray = [];
2131
2132                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2133
2134                 $datarray["uid"] = $importer["uid"];
2135                 $datarray["contact-id"] = $author_contact["cid"];
2136                 $datarray["network"]  = $author_contact["network"];
2137
2138                 $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
2139                 $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
2140
2141                 $datarray["guid"] = $guid;
2142                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2143
2144                 $datarray["verb"] = Activity::FOLLOW;
2145                 $datarray["gravity"] = GRAVITY_ACTIVITY;
2146                 $datarray["parent-uri"] = $parent_item["uri"];
2147
2148                 $datarray["object-type"] = Activity\ObjectType::NOTE;
2149
2150                 $datarray["body"] = Activity::FOLLOW;
2151
2152                 // Diaspora doesn't provide a date for a participation
2153                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
2154
2155                 $message_id = Item::insert($datarray);
2156
2157                 Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]);
2158
2159                 // Send all existing comments and likes to the requesting server
2160                 $comments = Item::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb'],
2161                         ['parent' => $parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
2162                 while ($comment = Item::fetch($comments)) {
2163                         if (in_array($comment['verb'], [Activity::FOLLOW, Activity::TAG])) {
2164                                 Logger::info('participation messages are not relayed', ['item' => $comment['id']]);
2165                                 continue;
2166                         }
2167
2168                         if ($comment['author-network'] == Protocol::ACTIVITYPUB) {
2169                                 Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2170                                 continue;
2171                         }
2172
2173                         if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) {
2174                                 Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]);
2175                                 continue;
2176                         }
2177
2178                         Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]);
2179                         if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) {
2180                                 Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
2181                         }
2182                 }
2183                 DBA::close($comments);
2184
2185                 return true;
2186         }
2187
2188         /**
2189          * Processes photos - unneeded
2190          *
2191          * @param array  $importer Array of the importer user
2192          * @param object $data     The message object
2193          *
2194          * @return bool always true
2195          */
2196         private static function receivePhoto(array $importer, $data)
2197         {
2198                 // There doesn't seem to be a reason for this function,
2199                 // since the photo data is transmitted in the status message as well
2200                 return true;
2201         }
2202
2203         /**
2204          * Processes poll participations - unssupported
2205          *
2206          * @param array  $importer Array of the importer user
2207          * @param object $data     The message object
2208          *
2209          * @return bool always true
2210          */
2211         private static function receivePollParticipation(array $importer, $data)
2212         {
2213                 // We don't support polls by now
2214                 return true;
2215         }
2216
2217         /**
2218          * Processes incoming profile updates
2219          *
2220          * @param array  $importer Array of the importer user
2221          * @param object $data     The message object
2222          *
2223          * @return bool Success
2224          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2225          * @throws \ImagickException
2226          */
2227         private static function receiveProfile(array $importer, $data)
2228         {
2229                 $author = strtolower(Strings::escapeTags(XML::unescape($data->author)));
2230
2231                 $contact = self::contactByHandle($importer["uid"], $author);
2232                 if (!$contact) {
2233                         return false;
2234                 }
2235
2236                 $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : "");
2237                 $image_url = XML::unescape($data->image_url);
2238                 $birthday = XML::unescape($data->birthday);
2239                 $about = Markdown::toBBCode(XML::unescape($data->bio));
2240                 $location = Markdown::toBBCode(XML::unescape($data->location));
2241                 $searchable = (XML::unescape($data->searchable) == "true");
2242                 $nsfw = (XML::unescape($data->nsfw) == "true");
2243                 $tags = XML::unescape($data->tag_string);
2244
2245                 $tags = explode("#", $tags);
2246
2247                 $keywords = [];
2248                 foreach ($tags as $tag) {
2249                         $tag = trim(strtolower($tag));
2250                         if ($tag != "") {
2251                                 $keywords[] = $tag;
2252                         }
2253                 }
2254
2255                 $keywords = implode(", ", $keywords);
2256
2257                 $handle_parts = explode("@", $author);
2258                 $nick = $handle_parts[0];
2259
2260                 if ($name === "") {
2261                         $name = $handle_parts[0];
2262                 }
2263
2264                 if (preg_match("|^https?://|", $image_url) === 0) {
2265                         $image_url = "http://".$handle_parts[1].$image_url;
2266                 }
2267
2268                 Contact::updateAvatar($contact["id"], $image_url);
2269
2270                 // Generic birthday. We don't know the timezone. The year is irrelevant.
2271
2272                 $birthday = str_replace("1000", "1901", $birthday);
2273
2274                 if ($birthday != "") {
2275                         $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2276                 }
2277
2278                 // this is to prevent multiple birthday notifications in a single year
2279                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2280
2281                 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2282                         $birthday = $contact["bd"];
2283                 }
2284
2285                 $fields = ['name' => $name, 'location' => $location,
2286                         'name-date' => DateTimeFormat::utcNow(), 'about' => $about,
2287                         'addr' => $author, 'nick' => $nick, 'keywords' => $keywords,
2288                         'unsearchable' => !$searchable, 'sensitive' => $nsfw];
2289
2290                 if (!empty($birthday)) {
2291                         $fields['bd'] = $birthday;
2292                 }
2293
2294                 DBA::update('contact', $fields, ['id' => $contact['id']]);
2295
2296                 Logger::log("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], Logger::DEBUG);
2297
2298                 return true;
2299         }
2300
2301         /**
2302          * Processes incoming friend requests
2303          *
2304          * @param array $importer Array of the importer user
2305          * @param array $contact  The contact that send the request
2306          * @return void
2307          * @throws \Exception
2308          */
2309         private static function receiveRequestMakeFriend(array $importer, array $contact)
2310         {
2311                 if ($contact["rel"] == Contact::SHARING) {
2312                         DBA::update(
2313                                 'contact',
2314                                 ['rel' => Contact::FRIEND, 'writable' => true],
2315                                 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2316                         );
2317                 }
2318         }
2319
2320         /**
2321          * Processes incoming sharing notification
2322          *
2323          * @param array  $importer Array of the importer user
2324          * @param object $data     The message object
2325          *
2326          * @return bool Success
2327          * @throws \Exception
2328          */
2329         private static function receiveContactRequest(array $importer, $data)
2330         {
2331                 $author = XML::unescape($data->author);
2332                 $recipient = XML::unescape($data->recipient);
2333
2334                 if (!$author || !$recipient) {
2335                         return false;
2336                 }
2337
2338                 // the current protocol version doesn't know these fields
2339                 // That means that we will assume their existance
2340                 if (isset($data->following)) {
2341                         $following = (XML::unescape($data->following) == "true");
2342                 } else {
2343                         $following = true;
2344                 }
2345
2346                 if (isset($data->sharing)) {
2347                         $sharing = (XML::unescape($data->sharing) == "true");
2348                 } else {
2349                         $sharing = true;
2350                 }
2351
2352                 $contact = self::contactByHandle($importer["uid"], $author);
2353
2354                 // perhaps we were already sharing with this person. Now they're sharing with us.
2355                 // That makes us friends.
2356                 if ($contact) {
2357                         if ($following) {
2358                                 Logger::log("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", Logger::DEBUG);
2359                                 self::receiveRequestMakeFriend($importer, $contact);
2360
2361                                 // refetch the contact array
2362                                 $contact = self::contactByHandle($importer["uid"], $author);
2363
2364                                 // If we are now friends, we are sending a share message.
2365                                 // Normally we needn't to do so, but the first message could have been vanished.
2366                                 if (in_array($contact["rel"], [Contact::FRIEND])) {
2367                                         $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2368                                         if (DBA::isResult($user)) {
2369                                                 Logger::log("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], Logger::DEBUG);
2370                                                 self::sendShare($user, $contact);
2371                                         }
2372                                 }
2373                                 return true;
2374                         } else {
2375                                 Logger::log("Author ".$author." doesn't want to follow us anymore.", Logger::DEBUG);
2376                                 Contact::removeFollower($importer, $contact);
2377                                 return true;
2378                         }
2379                 }
2380
2381                 if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
2382                         Logger::log("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", Logger::DEBUG);
2383                         return false;
2384                 } elseif (!$following && !$sharing) {
2385                         Logger::log("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", Logger::DEBUG);
2386                         return false;
2387                 } elseif (!$following && $sharing) {
2388                         Logger::log("Author ".$author." wants to share with us.", Logger::DEBUG);
2389                 } elseif ($following && $sharing) {
2390                         Logger::log("Author ".$author." wants to have a bidirectional conection.", Logger::DEBUG);
2391                 } elseif ($following && !$sharing) {
2392                         Logger::log("Author ".$author." wants to listen to us.", Logger::DEBUG);
2393                 }
2394
2395                 $ret = FContact::getByURL($author);
2396
2397                 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2398                         Logger::log("Cannot resolve diaspora handle ".$author." for ".$recipient);
2399                         return false;
2400                 }
2401
2402                 $cid = Contact::getIdForURL($ret['url'], $importer['uid']);
2403                 if (!empty($cid)) {
2404                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
2405                 } else {
2406                         $contact = [];
2407                 }
2408
2409                 $item = ['author-id' => Contact::getIdForURL($ret['url']),
2410                         'author-link' => $ret['url']];
2411
2412                 $result = Contact::addRelationship($importer, $contact, $item, false);
2413                 if ($result === true) {
2414                         $contact_record = self::contactByHandle($importer['uid'], $author);
2415                         if (!$contact_record) {
2416                                 Logger::info('unable to locate newly created contact record.');
2417                                 return;
2418                         }
2419
2420                         $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
2421                         if (DBA::isResult($user)) {
2422                                 self::sendShare($user, $contact_record);
2423
2424                                 // Send the profile data, maybe it weren't transmitted before
2425                                 self::sendProfile($importer['uid'], [$contact_record]);
2426                         }
2427                 }
2428
2429                 return true;
2430         }
2431
2432         /**
2433          * Fetches a message with a given guid
2434          *
2435          * @param string $guid        message guid
2436          * @param string $orig_author handle of the original post
2437          * @return array The fetched item
2438          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2439          * @throws \ImagickException
2440          */
2441         public static function originalItem($guid, $orig_author)
2442         {
2443                 if (empty($guid)) {
2444                         Logger::log('Empty guid. Quitting.');
2445                         return false;
2446                 }
2447
2448                 // Do we already have this item?
2449                 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2450                         'author-name', 'author-link', 'author-avatar', 'plink'];
2451                 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2452                 $item = Item::selectFirst($fields, $condition);
2453
2454                 if (DBA::isResult($item)) {
2455                         Logger::log("reshared message ".$guid." already exists on system.");
2456
2457                         // Maybe it is already a reshared item?
2458                         // Then refetch the content, if it is a reshare from a reshare.
2459                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2460                         if (self::isReshare($item["body"], true)) {
2461                                 $item = [];
2462                         } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2463                                 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2464
2465                                 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2466
2467                                 // Add OEmbed and other information to the body
2468                                 $item["body"] = PageInfo::searchAndAppendToBody($item["body"], false, true);
2469
2470                                 return $item;
2471                         } else {
2472                                 return $item;
2473                         }
2474                 }
2475
2476                 if (!DBA::isResult($item)) {
2477                         if (empty($orig_author)) {
2478                                 Logger::log('Empty author for guid ' . $guid . '. Quitting.');
2479                                 return false;
2480                         }
2481
2482                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2483                         Logger::log("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2484                         $stored = self::storeByGuid($guid, $server);
2485
2486                         if (!$stored) {
2487                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2488                                 Logger::log("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2489                                 $stored = self::storeByGuid($guid, $server);
2490                         }
2491
2492                         if ($stored) {
2493                                 $fields = ['body', 'title', 'attach', 'app', 'created', 'object-type', 'uri', 'guid',
2494                                         'author-name', 'author-link', 'author-avatar', 'plink'];
2495                                 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]];
2496                                 $item = Item::selectFirst($fields, $condition);
2497
2498                                 if (DBA::isResult($item)) {
2499                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2500                                         if (self::isReshare($item["body"], false)) {
2501                                                 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2502                                                 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2503                                         }
2504
2505                                         return $item;
2506                                 }
2507                         }
2508                 }
2509                 return false;
2510         }
2511
2512         /**
2513          * Stores a reshare activity
2514          *
2515          * @param array   $item              Array of reshare post
2516          * @param integer $parent_message_id Id of the parent post
2517          * @param string  $guid              GUID string of reshare action
2518          * @param string  $author            Author handle
2519          */
2520         private static function addReshareActivity($item, $parent_message_id, $guid, $author)
2521         {
2522                 $parent = Item::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
2523
2524                 $datarray = [];
2525
2526                 $datarray['uid'] = $item['uid'];
2527                 $datarray['contact-id'] = $item['contact-id'];
2528                 $datarray['network'] = $item['network'];
2529
2530                 $datarray['author-link'] = $item['author-link'];
2531                 $datarray['author-id'] = $item['author-id'];
2532
2533                 $datarray['owner-link'] = $datarray['author-link'];
2534                 $datarray['owner-id'] = $datarray['author-id'];
2535
2536                 $datarray['guid'] = $parent['guid'] . '-' . $guid;
2537                 $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']);
2538                 $datarray['parent-uri'] = $parent['uri'];
2539
2540                 $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
2541                 $datarray['gravity'] = GRAVITY_ACTIVITY;
2542                 $datarray['object-type'] = Activity\ObjectType::NOTE;
2543
2544                 $datarray['protocol'] = $item['protocol'];
2545
2546                 $datarray['plink'] = self::plink($author, $datarray['guid']);
2547                 $datarray['private'] = $item['private'];
2548                 $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $item['created'];
2549
2550                 $message_id = Item::insert($datarray);
2551
2552                 if ($message_id) {
2553                         Logger::info('Stored reshare activity.', ['guid' => $guid, 'id' => $message_id]);
2554                         if ($datarray['uid'] == 0) {
2555                                 Item::distribute($message_id);
2556                         }
2557                 }
2558         }
2559
2560         /**
2561          * Processes a reshare message
2562          *
2563          * @param array  $importer Array of the importer user
2564          * @param object $data     The message object
2565          * @param string $xml      The original XML of the message
2566          *
2567          * @return int the message id
2568          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2569          * @throws \ImagickException
2570          */
2571         private static function receiveReshare(array $importer, $data, $xml)
2572         {
2573                 $author = Strings::escapeTags(XML::unescape($data->author));
2574                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2575                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2576                 $root_author = Strings::escapeTags(XML::unescape($data->root_author));
2577                 $root_guid = Strings::escapeTags(XML::unescape($data->root_guid));
2578                 /// @todo handle unprocessed property "provider_display_name"
2579                 $public = Strings::escapeTags(XML::unescape($data->public));
2580
2581                 $contact = self::allowedContactByHandle($importer, $author, false);
2582                 if (!$contact) {
2583                         return false;
2584                 }
2585
2586                 $message_id = self::messageExists($importer["uid"], $guid);
2587                 if ($message_id) {
2588                         return true;
2589                 }
2590
2591                 $original_item = self::originalItem($root_guid, $root_author);
2592                 if (!$original_item) {
2593                         return false;
2594                 }
2595
2596                 $datarray = [];
2597
2598                 $datarray["uid"] = $importer["uid"];
2599                 $datarray["contact-id"] = $contact["id"];
2600                 $datarray["network"]  = Protocol::DIASPORA;
2601
2602                 $datarray["author-link"] = $contact["url"];
2603                 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2604
2605                 $datarray["owner-link"] = $datarray["author-link"];
2606                 $datarray["owner-id"] = $datarray["author-id"];
2607
2608                 $datarray["guid"] = $guid;
2609                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2610                 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2611
2612                 $datarray["verb"] = Activity::POST;
2613                 $datarray["gravity"] = GRAVITY_PARENT;
2614
2615                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2616                 $datarray["source"] = $xml;
2617
2618                 /// @todo Copy tag data from original post
2619
2620                 $prefix = BBCode::getShareOpeningTag(
2621                         $original_item["author-name"],
2622                         $original_item["author-link"],
2623                         $original_item["author-avatar"],
2624                         $original_item["plink"],
2625                         $original_item["created"],
2626                         $original_item["guid"]
2627                 );
2628
2629                 if (!empty($original_item['title'])) {
2630                         $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
2631                 }
2632
2633                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2634
2635                 Tag::storeFromBody($datarray['uri-id'], $datarray["body"]);
2636
2637                 $datarray["attach"] = $original_item["attach"];
2638                 $datarray["app"]  = $original_item["app"];
2639
2640                 $datarray["plink"] = self::plink($author, $guid);
2641                 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2642                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2643
2644                 $datarray["object-type"] = $original_item["object-type"];
2645
2646                 self::fetchGuid($datarray);
2647                 $message_id = Item::insert($datarray);
2648
2649                 self::sendParticipation($contact, $datarray);
2650
2651                 $root_message_id = self::messageExists($importer["uid"], $root_guid);
2652                 if ($root_message_id) {
2653                         self::addReshareActivity($datarray, $root_message_id, $guid, $author);
2654                 }
2655
2656                 if ($message_id) {
2657                         Logger::log("Stored reshare ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2658                         if ($datarray['uid'] == 0) {
2659                                 Item::distribute($message_id);
2660                         }
2661                         return true;
2662                 } else {
2663                         return false;
2664                 }
2665         }
2666
2667         /**
2668          * Processes retractions
2669          *
2670          * @param array  $importer Array of the importer user
2671          * @param array  $contact  The contact of the item owner
2672          * @param object $data     The message object
2673          *
2674          * @return bool success
2675          * @throws \Exception
2676          */
2677         private static function itemRetraction(array $importer, array $contact, $data)
2678         {
2679                 $author = Strings::escapeTags(XML::unescape($data->author));
2680                 $target_guid = Strings::escapeTags(XML::unescape($data->target_guid));
2681                 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2682
2683                 $person = FContact::getByURL($author);
2684                 if (!is_array($person)) {
2685                         Logger::log("unable to find author detail for ".$author);
2686                         return false;
2687                 }
2688
2689                 if (empty($contact["url"])) {
2690                         $contact["url"] = $person["url"];
2691                 }
2692
2693                 // Fetch items that are about to be deleted
2694                 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2695
2696                 // When we receive a public retraction, we delete every item that we find.
2697                 if ($importer['uid'] == 0) {
2698                         $condition = ['guid' => $target_guid, 'deleted' => false];
2699                 } else {
2700                         $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2701                 }
2702
2703                 $r = Item::select($fields, $condition);
2704                 if (!DBA::isResult($r)) {
2705                         Logger::log("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2706                         return false;
2707                 }
2708
2709                 while ($item = Item::fetch($r)) {
2710                         if (strstr($item['file'], '[')) {
2711                                 Logger::log("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", Logger::DEBUG);
2712                                 continue;
2713                         }
2714
2715                         // Fetch the parent item
2716                         $parent = Item::selectFirst(['author-link'], ['id' => $item['parent']]);
2717
2718                         // Only delete it if the parent author really fits
2719                         if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) {
2720                                 Logger::log("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], Logger::DEBUG);
2721                                 continue;
2722                         }
2723
2724                         Item::markForDeletion(['id' => $item['id']]);
2725
2726                         Logger::log("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent'], Logger::DEBUG);
2727                 }
2728
2729                 return true;
2730         }
2731
2732         /**
2733          * Receives retraction messages
2734          *
2735          * @param array  $importer Array of the importer user
2736          * @param string $sender   The sender of the message
2737          * @param object $data     The message object
2738          *
2739          * @return bool Success
2740          * @throws \Exception
2741          */
2742         private static function receiveRetraction(array $importer, $sender, $data)
2743         {
2744                 $target_type = Strings::escapeTags(XML::unescape($data->target_type));
2745
2746                 $contact = self::contactByHandle($importer["uid"], $sender);
2747                 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2748                         Logger::log("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2749                         return false;
2750                 }
2751
2752                 if (!$contact) {
2753                         $contact = [];
2754                 }
2755
2756                 Logger::log("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], Logger::DEBUG);
2757
2758                 switch ($target_type) {
2759                         case "Comment":
2760                         case "Like":
2761                         case "Post":
2762                         case "Reshare":
2763                         case "StatusMessage":
2764                                 return self::itemRetraction($importer, $contact, $data);
2765
2766                         case "PollParticipation":
2767                         case "Photo":
2768                                 // Currently unsupported
2769                                 break;
2770
2771                         default:
2772                                 Logger::log("Unknown target type ".$target_type);
2773                                 return false;
2774                 }
2775                 return true;
2776         }
2777
2778         /**
2779          * Receives status messages
2780          *
2781          * @param array            $importer Array of the importer user
2782          * @param SimpleXMLElement $data     The message object
2783          * @param string           $xml      The original XML of the message
2784          *
2785          * @return int The message id of the newly created item
2786          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2787          * @throws \ImagickException
2788          */
2789         private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2790         {
2791                 $author = Strings::escapeTags(XML::unescape($data->author));
2792                 $guid = Strings::escapeTags(XML::unescape($data->guid));
2793                 $created_at = DateTimeFormat::utc(Strings::escapeTags(XML::unescape($data->created_at)));
2794                 $public = Strings::escapeTags(XML::unescape($data->public));
2795                 $text = XML::unescape($data->text);
2796                 $provider_display_name = Strings::escapeTags(XML::unescape($data->provider_display_name));
2797
2798                 $contact = self::allowedContactByHandle($importer, $author, false);
2799                 if (!$contact) {
2800                         return false;
2801                 }
2802
2803                 $message_id = self::messageExists($importer["uid"], $guid);
2804                 if ($message_id) {
2805                         return true;
2806                 }
2807
2808                 $address = [];
2809                 if ($data->location) {
2810                         foreach ($data->location->children() as $fieldname => $data) {
2811                                 $address[$fieldname] = Strings::escapeTags(XML::unescape($data));
2812                         }
2813                 }
2814
2815                 $body = Markdown::toBBCode($text);
2816
2817                 $datarray = [];
2818
2819                 // Attach embedded pictures to the body
2820                 if ($data->photo) {
2821                         foreach ($data->photo as $photo) {
2822                                 $body = "[img]".XML::unescape($photo->remote_photo_path).
2823                                         XML::unescape($photo->remote_photo_name)."[/img]\n".$body;
2824                         }
2825
2826                         $datarray["object-type"] = Activity\ObjectType::IMAGE;
2827                 } else {
2828                         $datarray["object-type"] = Activity\ObjectType::NOTE;
2829
2830                         // Add OEmbed and other information to the body
2831                         if (!self::isHubzilla($contact["url"])) {
2832                                 $body = PageInfo::searchAndAppendToBody($body, false, true);
2833                         }
2834                 }
2835
2836                 /// @todo enable support for polls
2837                 //if ($data->poll) {
2838                 //      foreach ($data->poll AS $poll)
2839                 //              print_r($poll);
2840                 //      die("poll!\n");
2841                 //}
2842
2843                 /// @todo enable support for events
2844
2845                 $datarray["uid"] = $importer["uid"];
2846                 $datarray["contact-id"] = $contact["id"];
2847                 $datarray["network"] = Protocol::DIASPORA;
2848
2849                 $datarray["author-link"] = $contact["url"];
2850                 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2851
2852                 $datarray["owner-link"] = $datarray["author-link"];
2853                 $datarray["owner-id"] = $datarray["author-id"];
2854
2855                 $datarray["guid"] = $guid;
2856                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2857                 $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
2858
2859                 $datarray["verb"] = Activity::POST;
2860                 $datarray["gravity"] = GRAVITY_PARENT;
2861
2862                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2863                 $datarray["source"] = $xml;
2864
2865                 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2866
2867                 self::storeMentions($datarray['uri-id'], $text);
2868                 Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]);
2869
2870                 if ($provider_display_name != "") {
2871                         $datarray["app"] = $provider_display_name;
2872                 }
2873
2874                 $datarray["plink"] = self::plink($author, $guid);
2875                 $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC);
2876                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2877
2878                 if (isset($address["address"])) {
2879                         $datarray["location"] = $address["address"];
2880                 }
2881
2882                 if (isset($address["lat"]) && isset($address["lng"])) {
2883                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2884                 }
2885
2886                 self::fetchGuid($datarray);
2887                 $message_id = Item::insert($datarray);
2888
2889                 self::sendParticipation($contact, $datarray);
2890
2891                 if ($message_id) {
2892                         Logger::log("Stored item ".$datarray["guid"]." with message id ".$message_id, Logger::DEBUG);
2893                         if ($datarray['uid'] == 0) {
2894                                 Item::distribute($message_id);
2895                         }
2896                         return true;
2897                 } else {
2898                         return false;
2899                 }
2900         }
2901
2902         /* ************************************************************************************** *
2903          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2904          * ************************************************************************************** */
2905
2906         /**
2907          * returnes the handle of a contact
2908          *
2909          * @param array $contact contact array
2910          *
2911          * @return string the handle in the format user@domain.tld
2912          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2913          */
2914         private static function myHandle(array $contact)
2915         {
2916                 if (!empty($contact["addr"])) {
2917                         return $contact["addr"];
2918                 }
2919
2920                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2921                 // So - just in case - we build the the address here.
2922                 if ($contact["nickname"] != "") {
2923                         $nick = $contact["nickname"];
2924                 } else {
2925                         $nick = $contact["nick"];
2926                 }
2927
2928                 return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3);
2929         }
2930
2931
2932         /**
2933          * Creates the data for a private message in the new format
2934          *
2935          * @param string $msg     The message that is to be transmitted
2936          * @param array  $user    The record of the sender
2937          * @param array  $contact Target of the communication
2938          * @param string $prvkey  The private key of the sender
2939          * @param string $pubkey  The public key of the receiver
2940          *
2941          * @return string The encrypted data
2942          * @throws \Exception
2943          */
2944         public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2945         {
2946                 Logger::log("Message: ".$msg, Logger::DATA);
2947
2948                 // without a public key nothing will work
2949                 if (!$pubkey) {
2950                         Logger::log("pubkey missing: contact id: ".$contact["id"]);
2951                         return false;
2952                 }
2953
2954                 $aes_key = openssl_random_pseudo_bytes(32);
2955                 $b_aes_key = base64_encode($aes_key);
2956                 $iv = openssl_random_pseudo_bytes(16);
2957                 $b_iv = base64_encode($iv);
2958
2959                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2960
2961                 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2962
2963                 $encrypted_key_bundle = "";
2964                 if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
2965                         return false;
2966                 }
2967
2968                 $json_object = json_encode(
2969                         ["aes_key" => base64_encode($encrypted_key_bundle),
2970                                         "encrypted_magic_envelope" => base64_encode($ciphertext)]
2971                 );
2972
2973                 return $json_object;
2974         }
2975
2976         /**
2977          * Creates the envelope for the "fetch" endpoint and for the new format
2978          *
2979          * @param string $msg  The message that is to be transmitted
2980          * @param array  $user The record of the sender
2981          *
2982          * @return string The envelope
2983          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2984          */
2985         public static function buildMagicEnvelope($msg, array $user)
2986         {
2987                 $b64url_data = Strings::base64UrlEncode($msg);
2988                 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2989
2990                 $key_id = Strings::base64UrlEncode(self::myHandle($user));
2991                 $type = "application/xml";
2992                 $encoding = "base64url";
2993                 $alg = "RSA-SHA256";
2994                 $signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg);
2995
2996                 // Fallback if the private key wasn't transmitted in the expected field
2997                 if ($user['uprvkey'] == "") {
2998                         $user['uprvkey'] = $user['prvkey'];
2999                 }
3000
3001                 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3002                 $sig = Strings::base64UrlEncode($signature);
3003
3004                 $xmldata = ["me:env" => ["me:data" => $data,
3005                                                         "@attributes" => ["type" => $type],
3006                                                         "me:encoding" => $encoding,
3007                                                         "me:alg" => $alg,
3008                                                         "me:sig" => $sig,
3009                                                         "@attributes2" => ["key_id" => $key_id]]];
3010
3011                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3012
3013                 return XML::fromArray($xmldata, $xml, false, $namespaces);
3014         }
3015
3016         /**
3017          * Create the envelope for a message
3018          *
3019          * @param string $msg     The message that is to be transmitted
3020          * @param array  $user    The record of the sender
3021          * @param array  $contact Target of the communication
3022          * @param string $prvkey  The private key of the sender
3023          * @param string $pubkey  The public key of the receiver
3024          * @param bool   $public  Is the message public?
3025          *
3026          * @return string The message that will be transmitted to other servers
3027          * @throws \Exception
3028          */
3029         public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3030         {
3031                 // The message is put into an envelope with the sender's signature
3032                 $envelope = self::buildMagicEnvelope($msg, $user);
3033
3034                 // Private messages are put into a second envelope, encrypted with the receivers public key
3035                 if (!$public) {
3036                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3037                 }
3038
3039                 return $envelope;
3040         }
3041
3042         /**
3043          * Creates a signature for a message
3044          *
3045          * @param array $owner   the array of the owner of the message
3046          * @param array $message The message that is to be signed
3047          *
3048          * @return string The signature
3049          */
3050         private static function signature($owner, $message)
3051         {
3052                 $sigmsg = $message;
3053                 unset($sigmsg["author_signature"]);
3054                 unset($sigmsg["parent_author_signature"]);
3055
3056                 $signed_text = implode(";", $sigmsg);
3057
3058                 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3059         }
3060
3061         /**
3062          * Transmit a message to a target server
3063          *
3064          * @param array  $owner        the array of the item owner
3065          * @param array  $contact      Target of the communication
3066          * @param string $envelope     The message that is to be transmitted
3067          * @param bool   $public_batch Is it a public post?
3068          * @param string $guid         message guid
3069          *
3070          * @return int Result of the transmission
3071          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3072          * @throws \ImagickException
3073          */
3074         private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "")
3075         {
3076                 $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
3077                 if (!$enabled) {
3078                         return 200;
3079                 }
3080
3081                 $logid = Strings::getRandomHex(4);
3082
3083                 // We always try to use the data from the fcontact table.
3084                 // This is important for transmitting data to Friendica servers.
3085                 if (!empty($contact['addr'])) {
3086                         $fcontact = FContact::getByURL($contact['addr']);
3087                         if (!empty($fcontact)) {
3088                                 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3089                         }
3090                 }
3091
3092                 if (empty($dest_url)) {
3093                         $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3094                 }
3095
3096                 if (!$dest_url) {
3097                         Logger::log("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3098                         return 0;
3099                 }
3100
3101                 Logger::log("transmit: ".$logid."-".$guid." ".$dest_url);
3102
3103                 if (!intval(DI::config()->get("system", "diaspora_test"))) {
3104                         $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3105
3106                         $postResult = DI::httpRequest()->post($dest_url . "/", $envelope, ["Content-Type: " . $content_type]);
3107                         $return_code = $postResult->getReturnCode();
3108                 } else {
3109                         Logger::log("test_mode");
3110                         return 200;
3111                 }
3112
3113                 Logger::log("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3114
3115                 return $return_code ? $return_code : -1;
3116         }
3117
3118
3119         /**
3120          * Build the post xml
3121          *
3122          * @param string $type    The message type
3123          * @param array  $message The message data
3124          *
3125          * @return string The post XML
3126          */
3127         public static function buildPostXml($type, $message)
3128         {
3129                 $data = [$type => $message];
3130
3131                 return XML::fromArray($data, $xml);
3132         }
3133
3134         /**
3135          * Builds and transmit messages
3136          *
3137          * @param array  $owner        the array of the item owner
3138          * @param array  $contact      Target of the communication
3139          * @param string $type         The message type
3140          * @param array  $message      The message data
3141          * @param bool   $public_batch Is it a public post?
3142          * @param string $guid         message guid
3143          *
3144          * @return int Result of the transmission
3145          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3146          * @throws \ImagickException
3147          */
3148         private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "")
3149         {
3150                 $msg = self::buildPostXml($type, $message);
3151
3152                 Logger::log('message: '.$msg, Logger::DATA);
3153                 Logger::log('send guid '.$guid, Logger::DEBUG);
3154
3155                 // Fallback if the private key wasn't transmitted in the expected field
3156                 if (empty($owner['uprvkey'])) {
3157                         $owner['uprvkey'] = $owner['prvkey'];
3158                 }
3159
3160                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3161
3162                 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, $guid);
3163
3164                 Logger::log("guid: ".$guid." result ".$return_code, Logger::DEBUG);
3165
3166                 return $return_code;
3167         }
3168
3169         /**
3170          * sends a participation (Used to get all further updates)
3171          *
3172          * @param array $contact Target of the communication
3173          * @param array $item    Item array
3174          *
3175          * @return int The result of the transmission
3176          * @throws \Exception
3177          */
3178         private static function sendParticipation(array $contact, array $item)
3179         {
3180                 // Don't send notifications for private postings
3181                 if ($item['private'] == Item::PRIVATE) {
3182                         return;
3183                 }
3184
3185                 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3186
3187                 $result = DI::cache()->get($cachekey);
3188                 if (!is_null($result)) {
3189                         return;
3190                 }
3191
3192                 // Fetch some user id to have a valid handle to transmit the participation.
3193                 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3194                 // If the item belongs to a user, we take this user id.
3195                 if ($item['uid'] == 0) {
3196                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3197                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
3198                         $owner = User::getOwnerDataById($first_user['uid']);
3199                 } else {
3200                         $owner = User::getOwnerDataById($item['uid']);
3201                 }
3202
3203                 $author = self::myHandle($owner);
3204
3205                 $message = ["author" => $author,
3206                                 "guid" => System::createUUID(),
3207                                 "parent_type" => "Post",
3208                                 "parent_guid" => $item["guid"]];
3209
3210                 Logger::log("Send participation for ".$item["guid"]." by ".$author, Logger::DEBUG);
3211
3212                 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3213                 DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR);
3214
3215                 return self::buildAndTransmit($owner, $contact, "participation", $message);
3216         }
3217
3218         /**
3219          * sends an account migration
3220          *
3221          * @param array $owner   the array of the item owner
3222          * @param array $contact Target of the communication
3223          * @param int   $uid     User ID
3224          *
3225          * @return int The result of the transmission
3226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3227          * @throws \ImagickException
3228          */
3229         public static function sendAccountMigration(array $owner, array $contact, $uid)
3230         {
3231                 $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
3232                 $profile = self::createProfileData($uid);
3233
3234                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3235                 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3236
3237                 $message = ["author" => $old_handle,
3238                                 "profile" => $profile,
3239                                 "signature" => $signature];
3240
3241                 Logger::info('Send account migration', ['msg' => $message]);
3242
3243                 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3244         }
3245
3246         /**
3247          * Sends a "share" message
3248          *
3249          * @param array $owner   the array of the item owner
3250          * @param array $contact Target of the communication
3251          *
3252          * @return int The result of the transmission
3253          * @throws \Exception
3254          */
3255         public static function sendShare(array $owner, array $contact)
3256         {
3257                 /**
3258                  * @todo support the different possible combinations of "following" and "sharing"
3259                  * Currently, Diaspora only interprets the "sharing" field
3260                  *
3261                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3262                  */
3263
3264                 /*
3265                 switch ($contact["rel"]) {
3266                         case Contact::FRIEND:
3267                                 $following = true;
3268                                 $sharing = true;
3269
3270                         case Contact::SHARING:
3271                                 $following = false;
3272                                 $sharing = true;
3273
3274                         case Contact::FOLLOWER:
3275                                 $following = true;
3276                                 $sharing = false;
3277                 }
3278                 */
3279
3280                 $message = ["author" => self::myHandle($owner),
3281                                 "recipient" => $contact["addr"],
3282                                 "following" => "true",
3283                                 "sharing" => "true"];
3284
3285                 Logger::info('Send share', ['msg' => $message]);
3286
3287                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3288         }
3289
3290         /**
3291          * sends an "unshare"
3292          *
3293          * @param array $owner   the array of the item owner
3294          * @param array $contact Target of the communication
3295          *
3296          * @return int The result of the transmission
3297          * @throws \Exception
3298          */
3299         public static function sendUnshare(array $owner, array $contact)
3300         {
3301                 $message = ["author" => self::myHandle($owner),
3302                                 "recipient" => $contact["addr"],
3303                                 "following" => "false",
3304                                 "sharing" => "false"];
3305
3306                 Logger::info('Send unshare', ['msg' => $message]);
3307
3308                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3309         }
3310
3311         /**
3312          * Checks a message body if it is a reshare
3313          *
3314          * @param string $body     The message body that is to be check
3315          * @param bool   $complete Should it be a complete check or a simple check?
3316          *
3317          * @return array|bool Reshare details or "false" if no reshare
3318          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3319          * @throws \ImagickException
3320          */
3321         public static function isReshare($body, $complete = true)
3322         {
3323                 $body = trim($body);
3324
3325                 $reshared = Item::getShareArray(['body' => $body]);
3326                 if (empty($reshared)) {
3327                         return false;
3328                 }
3329
3330                 // Skip if it isn't a pure repeated messages
3331                 // Does it start with a share?
3332                 if (!empty($reshared['comment']) && $complete) {
3333                         return false;
3334                 }
3335
3336                 if (!empty($reshared['guid']) && $complete) {
3337                         $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3338                         $item = Item::selectFirst(['contact-id'], $condition);
3339                         if (DBA::isResult($item)) {
3340                                 $ret = [];
3341                                 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3342                                 $ret["root_guid"] = $reshared['guid'];
3343                                 return $ret;
3344                         } elseif ($complete) {
3345                                 // We are resharing something that isn't a DFRN or Diaspora post.
3346                                 // So we have to return "false" on "$complete" to not trigger a reshare.
3347                                 return false;
3348                         }
3349                 } elseif (empty($reshared['guid']) && $complete) {
3350                         return false;
3351                 }
3352
3353                 $ret = [];
3354
3355                 if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
3356                         $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
3357                         if (!empty($contact['addr'])) {
3358                                 $ret['root_handle'] = $contact['addr'];
3359                         }
3360                 }
3361
3362                 if (empty($ret) && !$complete) {
3363                         return true;
3364                 }
3365
3366                 return $ret;
3367         }
3368
3369         /**
3370          * Create an event array
3371          *
3372          * @param integer $event_id The id of the event
3373          *
3374          * @return array with event data
3375          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3376          */
3377         private static function buildEvent($event_id)
3378         {
3379                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3380                 if (!DBA::isResult($r)) {
3381                         return [];
3382                 }
3383
3384                 $event = $r[0];
3385
3386                 $eventdata = [];
3387
3388                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3389                 if (!DBA::isResult($r)) {
3390                         return [];
3391                 }
3392
3393                 $user = $r[0];
3394
3395                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3396                 if (!DBA::isResult($r)) {
3397                         return [];
3398                 }
3399
3400                 $owner = $r[0];
3401
3402                 $eventdata['author'] = self::myHandle($owner);
3403
3404                 if ($event['guid']) {
3405                         $eventdata['guid'] = $event['guid'];
3406                 }
3407
3408                 $mask = DateTimeFormat::ATOM;
3409
3410                 /// @todo - establish "all day" events in Friendica
3411                 $eventdata["all_day"] = "false";
3412
3413                 $eventdata['timezone'] = 'UTC';
3414                 if (!$event['adjust'] && $user['timezone']) {
3415                         $eventdata['timezone'] = $user['timezone'];
3416                 }
3417
3418                 if ($event['start']) {
3419                         $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3420                 }
3421                 if ($event['finish'] && !$event['nofinish']) {
3422                         $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3423                 }
3424                 if ($event['summary']) {
3425                         $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3426                 }
3427                 if ($event['desc']) {
3428                         $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3429                 }
3430                 if ($event['location']) {
3431                         $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3432                         $coord = Map::getCoordinates($event['location']);
3433
3434                         $location = [];
3435                         $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3436                         if (!empty($coord['lat']) && !empty($coord['lon'])) {
3437                                 $location["lat"] = $coord['lat'];
3438                                 $location["lng"] = $coord['lon'];
3439                         } else {
3440                                 $location["lat"] = 0;
3441                                 $location["lng"] = 0;
3442                         }
3443                         $eventdata['location'] = $location;
3444                 }
3445
3446                 return $eventdata;
3447         }
3448
3449         /**
3450          * Create a post (status message or reshare)
3451          *
3452          * @param array $item  The item that will be exported
3453          * @param array $owner the array of the item owner
3454          *
3455          * @return array
3456          * 'type' -> Message type ("status_message" or "reshare")
3457          * 'message' -> Array of XML elements of the status
3458          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3459          * @throws \ImagickException
3460          */
3461         public static function buildStatus(array $item, array $owner)
3462         {
3463                 $cachekey = "diaspora:buildStatus:".$item['guid'];
3464
3465                 $result = DI::cache()->get($cachekey);
3466                 if (!is_null($result)) {
3467                         return $result;
3468                 }
3469
3470                 $myaddr = self::myHandle($owner);
3471
3472                 $public = ($item["private"] == Item::PRIVATE ? "false" : "true");
3473                 $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
3474                 $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM);
3475
3476                 // Detect a share element and do a reshare
3477                 if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) {
3478                         $message = ["author" => $myaddr,
3479                                         "guid" => $item["guid"],
3480                                         "created_at" => $created,
3481                                         "root_author" => $ret["root_handle"],
3482                                         "root_guid" => $ret["root_guid"],
3483                                         "provider_display_name" => $item["app"],
3484                                         "public" => $public];
3485
3486                         $type = "reshare";
3487                 } else {
3488                         $title = $item["title"];
3489                         $body = $item["body"];
3490
3491                         // Fetch the title from an attached link - if there is one
3492                         if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
3493                                 $page_data = BBCode::getAttachmentData($item['body']);
3494                                 if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
3495                                         $title = $page_data['title'];
3496                                 }
3497                         }
3498
3499                         if ($item['author-link'] != $item['owner-link']) {
3500                                 require_once 'mod/share.php';
3501                                 $body = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
3502                                         $item['plink'], $item['created']) . $body . '[/share]';
3503                         }
3504
3505                         // convert to markdown
3506                         $body = html_entity_decode(BBCode::toMarkdown($body));
3507
3508                         // Adding the title
3509                         if (strlen($title)) {
3510                                 $body = "### ".html_entity_decode($title)."\n\n".$body;
3511                         }
3512
3513                         if ($item["attach"]) {
3514                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3515                                 if ($cnt) {
3516                                         $body .= "\n".DI::l10n()->t("Attachments:")."\n";
3517                                         foreach ($matches as $mtch) {
3518                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3519                                         }
3520                                 }
3521                         }
3522
3523                         $location = [];
3524
3525                         if ($item["location"] != "")
3526                                 $location["address"] = $item["location"];
3527
3528                         if ($item["coord"] != "") {
3529                                 $coord = explode(" ", $item["coord"]);
3530                                 $location["lat"] = $coord[0];
3531                                 $location["lng"] = $coord[1];
3532                         }
3533
3534                         $message = ["author" => $myaddr,
3535                                         "guid" => $item["guid"],
3536                                         "created_at" => $created,
3537                                         "edited_at" => $edited,
3538                                         "public" => $public,
3539                                         "text" => $body,
3540                                         "provider_display_name" => $item["app"],
3541                                         "location" => $location];
3542
3543                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3544                         if (!isset($location["lat"]) || !isset($location["lng"])) {
3545                                 unset($message["location"]);
3546                         }
3547
3548                         if ($item['event-id'] > 0) {
3549                                 $event = self::buildEvent($item['event-id']);
3550                                 if (count($event)) {
3551                                         $message['event'] = $event;
3552
3553                                         if (!empty($event['location']['address']) &&
3554                                                 !empty($event['location']['lat']) &&
3555                                                 !empty($event['location']['lng'])) {
3556                                                 $message['location'] = $event['location'];
3557                                         }
3558
3559                                         /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3560                                         // $message['text'] = '';
3561                                 }
3562                         }
3563
3564                         $type = "status_message";
3565                 }
3566
3567                 $msg = ["type" => $type, "message" => $message];
3568
3569                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
3570
3571                 return $msg;
3572         }
3573
3574         private static function prependParentAuthorMention($body, $profile_url)
3575         {
3576                 $profile = Contact::getByURL($profile_url, false, ['addr', 'name', 'contact-type']);
3577                 if (!empty($profile['addr'])
3578                         && $profile['contact-type'] != Contact::TYPE_COMMUNITY
3579                         && !strstr($body, $profile['addr'])
3580                         && !strstr($body, $profile_url)
3581                 ) {
3582                         $body = '@[url=' . $profile_url . ']' . $profile['name'] . '[/url] ' . $body;
3583                 }
3584
3585                 return $body;
3586         }
3587
3588         /**
3589          * Sends a post
3590          *
3591          * @param array $item         The item that will be exported
3592          * @param array $owner        the array of the item owner
3593          * @param array $contact      Target of the communication
3594          * @param bool  $public_batch Is it a public post?
3595          *
3596          * @return int The result of the transmission
3597          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3598          * @throws \ImagickException
3599          */
3600         public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3601         {
3602                 $status = self::buildStatus($item, $owner);
3603
3604                 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3605         }
3606
3607         /**
3608          * Creates a "like" object
3609          *
3610          * @param array $item  The item that will be exported
3611          * @param array $owner the array of the item owner
3612          *
3613          * @return array The data for a "like"
3614          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3615          */
3616         private static function constructLike(array $item, array $owner)
3617         {
3618                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3619                 if (!DBA::isResult($parent)) {
3620                         return false;
3621                 }
3622
3623                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3624                 $positive = null;
3625                 if ($item['verb'] === Activity::LIKE) {
3626                         $positive = "true";
3627                 } elseif ($item['verb'] === Activity::DISLIKE) {
3628                         $positive = "false";
3629                 }
3630
3631                 return(["author" => self::myHandle($owner),
3632                                 "guid" => $item["guid"],
3633                                 "parent_guid" => $parent["guid"],
3634                                 "parent_type" => $target_type,
3635                                 "positive" => $positive,
3636                                 "author_signature" => ""]);
3637         }
3638
3639         /**
3640          * Creates an "EventParticipation" object
3641          *
3642          * @param array $item  The item that will be exported
3643          * @param array $owner the array of the item owner
3644          *
3645          * @return array The data for an "EventParticipation"
3646          * @throws \Exception
3647          */
3648         private static function constructAttend(array $item, array $owner)
3649         {
3650                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3651                 if (!DBA::isResult($parent)) {
3652                         return false;
3653                 }
3654
3655                 switch ($item['verb']) {
3656                         case Activity::ATTEND:
3657                                 $attend_answer = 'accepted';
3658                                 break;
3659                         case Activity::ATTENDNO:
3660                                 $attend_answer = 'declined';
3661                                 break;
3662                         case Activity::ATTENDMAYBE:
3663                                 $attend_answer = 'tentative';
3664                                 break;
3665                         default:
3666                                 Logger::log('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3667                                 return false;
3668                 }
3669
3670                 return(["author" => self::myHandle($owner),
3671                                 "guid" => $item["guid"],
3672                                 "parent_guid" => $parent["guid"],
3673                                 "status" => $attend_answer,
3674                                 "author_signature" => ""]);
3675         }
3676
3677         /**
3678          * Creates the object for a comment
3679          *
3680          * @param array $item  The item that will be exported
3681          * @param array $owner the array of the item owner
3682          *
3683          * @return array|false The data for a comment
3684          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3685          */
3686         private static function constructComment(array $item, array $owner)
3687         {
3688                 $cachekey = "diaspora:constructComment:".$item['guid'];
3689
3690                 $result = DI::cache()->get($cachekey);
3691                 if (!is_null($result)) {
3692                         return $result;
3693                 }
3694
3695                 $toplevel_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['id' => $item['parent'], 'parent' => $item['parent']]);
3696                 if (!DBA::isResult($toplevel_item)) {
3697                         Logger::error('Missing parent conversation item', ['parent' => $item['parent']]);
3698                         return false;
3699                 }
3700
3701                 $thread_parent_item = $toplevel_item;
3702                 if ($item['thr-parent'] != $item['parent-uri']) {
3703                         $thread_parent_item = Item::selectFirst(['guid', 'author-id', 'author-link'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
3704                 }
3705
3706                 $body = $item["body"];
3707
3708                 // The replied to autor mention is prepended for clarity if:
3709                 // - Item replied isn't yours
3710                 // - Item is public or explicit mentions are disabled
3711                 // - Implicit mentions are enabled
3712                 if (
3713                         $item['author-id'] != $thread_parent_item['author-id']
3714                         && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
3715                         && !DI::config()->get('system', 'disable_implicit_mentions')
3716                 ) {
3717                         $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']);
3718                 }
3719
3720                 $text = html_entity_decode(BBCode::toMarkdown($body));
3721                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3722                 $edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM);
3723
3724                 $comment = [
3725                         "author"      => self::myHandle($owner),
3726                         "guid"        => $item["guid"],
3727                         "created_at"  => $created,
3728                         "edited_at"   => $edited,
3729                         "parent_guid" => $toplevel_item["guid"],
3730                         "text"        => $text,
3731                         "author_signature" => ""
3732                 ];
3733
3734                 // Send the thread parent guid only if it is a threaded comment
3735                 if ($item['thr-parent'] != $item['parent-uri']) {
3736                         $comment['thread_parent_guid'] = $thread_parent_item['guid'];
3737                 }
3738
3739                 DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
3740
3741                 return($comment);
3742         }
3743
3744         /**
3745          * Send a like or a comment
3746          *
3747          * @param array $item         The item that will be exported
3748          * @param array $owner        the array of the item owner
3749          * @param array $contact      Target of the communication
3750          * @param bool  $public_batch Is it a public post?
3751          *
3752          * @return int The result of the transmission
3753          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3754          * @throws \ImagickException
3755          */
3756         public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3757         {
3758                 if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
3759                         $message = self::constructAttend($item, $owner);
3760                         $type = "event_participation";
3761                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3762                         $message = self::constructLike($item, $owner);
3763                         $type = "like";
3764                 } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) {
3765                         $message = self::constructComment($item, $owner);
3766                         $type = "comment";
3767                 }
3768
3769                 if (empty($message)) {
3770                         return false;
3771                 }
3772
3773                 $message["author_signature"] = self::signature($owner, $message);
3774
3775                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3776         }
3777
3778         /**
3779          * Creates a message from a signature record entry
3780          *
3781          * @param array $item The item that will be exported
3782          * @return array The message
3783          */
3784         private static function messageFromSignature(array $item)
3785         {
3786                 // Split the signed text
3787                 $signed_parts = explode(";", $item['signed_text']);
3788
3789                 if ($item["deleted"]) {
3790                         $message = ["author" => $item['signer'],
3791                                         "target_guid" => $signed_parts[0],
3792                                         "target_type" => $signed_parts[1]];
3793                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3794                         $message = ["author" => $signed_parts[4],
3795                                         "guid" => $signed_parts[1],
3796                                         "parent_guid" => $signed_parts[3],
3797                                         "parent_type" => $signed_parts[2],
3798                                         "positive" => $signed_parts[0],
3799                                         "author_signature" => $item['signature'],
3800                                         "parent_author_signature" => ""];
3801                 } else {
3802                         // Remove the comment guid
3803                         $guid = array_shift($signed_parts);
3804
3805                         // Remove the parent guid
3806                         $parent_guid = array_shift($signed_parts);
3807
3808                         // Remove the handle
3809                         $handle = array_pop($signed_parts);
3810
3811                         $message = [
3812                                 "author" => $handle,
3813                                 "guid" => $guid,
3814                                 "parent_guid" => $parent_guid,
3815                                 "text" => implode(";", $signed_parts),
3816                                 "author_signature" => $item['signature'],
3817                                 "parent_author_signature" => ""
3818                         ];
3819                 }
3820                 return $message;
3821         }
3822
3823         /**
3824          * Relays messages (like, comment, retraction) to other servers if we are the thread owner
3825          *
3826          * @param array $item         The item that will be exported
3827          * @param array $owner        the array of the item owner
3828          * @param array $contact      Target of the communication
3829          * @param bool  $public_batch Is it a public post?
3830          *
3831          * @return int The result of the transmission
3832          * @throws \Exception
3833          */
3834         public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3835         {
3836                 if ($item["deleted"]) {
3837                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3838                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3839                         $type = "like";
3840                 } else {
3841                         $type = "comment";
3842                 }
3843
3844                 Logger::log("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", Logger::DEBUG);
3845
3846                 $msg = json_decode($item['signed_text'], true);
3847
3848                 $message = [];
3849                 if (is_array($msg)) {
3850                         foreach ($msg as $field => $data) {
3851                                 if (!$item["deleted"]) {
3852                                         if ($field == "diaspora_handle") {
3853                                                 $field = "author";
3854                                         }
3855                                         if ($field == "target_type") {
3856                                                 $field = "parent_type";
3857                                         }
3858                                 }
3859
3860                                 $message[$field] = $data;
3861                         }
3862                 } else {
3863                         Logger::log("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text'], Logger::DEBUG);
3864                 }
3865
3866                 $message["parent_author_signature"] = self::signature($owner, $message);
3867
3868                 Logger::info('Relayed data', ['msg' => $message]);
3869
3870                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3871         }
3872
3873         /**
3874          * Sends a retraction (deletion) of a message, like or comment
3875          *
3876          * @param array $item         The item that will be exported
3877          * @param array $owner        the array of the item owner
3878          * @param array $contact      Target of the communication
3879          * @param bool  $public_batch Is it a public post?
3880          * @param bool  $relay        Is the retraction transmitted from a relay?
3881          *
3882          * @return int The result of the transmission
3883          * @throws \Exception
3884          */
3885         public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3886         {
3887                 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3888
3889                 $msg_type = "retraction";
3890
3891                 if ($item['gravity'] == GRAVITY_PARENT) {
3892                         $target_type = "Post";
3893                 } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
3894                         $target_type = "Like";
3895                 } else {
3896                         $target_type = "Comment";
3897                 }
3898
3899                 $message = ["author" => $itemaddr,
3900                                 "target_guid" => $item['guid'],
3901                                 "target_type" => $target_type];
3902
3903                 Logger::info('Got message', ['msg' => $message]);
3904
3905                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3906         }
3907
3908         /**
3909          * Sends a mail
3910          *
3911          * @param array $item    The item that will be exported
3912          * @param array $owner   The owner
3913          * @param array $contact Target of the communication
3914          *
3915          * @return int The result of the transmission
3916          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3917          * @throws \ImagickException
3918          */
3919         public static function sendMail(array $item, array $owner, array $contact)
3920         {
3921                 $myaddr = self::myHandle($owner);
3922
3923                 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3924                 if (!DBA::isResult($cnv)) {
3925                         Logger::log("conversation not found.");
3926                         return;
3927                 }
3928
3929                 $body = BBCode::toMarkdown($item["body"]);
3930                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3931
3932                 $msg = [
3933                         "author" => $myaddr,
3934                         "guid" => $item["guid"],
3935                         "conversation_guid" => $cnv["guid"],
3936                         "text" => $body,
3937                         "created_at" => $created,
3938                 ];
3939
3940                 if ($item["reply"]) {
3941                         $message = $msg;
3942                         $type = "message";
3943                 } else {
3944                         $message = [
3945                                 "author" => $cnv["creator"],
3946                                 "guid" => $cnv["guid"],
3947                                 "subject" => $cnv["subject"],
3948                                 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3949                                 "participants" => $cnv["recips"],
3950                                 "message" => $msg
3951                         ];
3952
3953                         $type = "conversation";
3954                 }
3955
3956                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3957         }
3958
3959         /**
3960          * Split a name into first name and last name
3961          *
3962          * @param string $name The name
3963          *
3964          * @return array The array with "first" and "last"
3965          */
3966         public static function splitName($name) {
3967                 $name = trim($name);
3968
3969                 // Is the name longer than 64 characters? Then cut the rest of it.
3970                 if (strlen($name) > 64) {
3971                         if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3972                                 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3973                         } else {
3974                                 $name = substr($name, 0, 64);
3975                         }
3976                 }
3977
3978                 // Take the first word as first name
3979                 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3980                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3981                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3982                         return ['first' => $first, 'last' => $last];
3983                 }
3984
3985                 // Take the last word as last name
3986                 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3987                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3988
3989                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3990                         return ['first' => $first, 'last' => $last];
3991                 }
3992
3993                 // Take the first 32 characters if there is no space in the first 32 characters
3994                 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3995                         $first = substr($name, 0, 32);
3996                         $last = substr($name, 32);
3997                         return ['first' => $first, 'last' => $last];
3998                 }
3999
4000                 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4001                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4002
4003                 // Check if the last name is longer than 32 characters
4004                 if (strlen($last) > 32) {
4005                         if (strpos($last, ' ') <= 32) {
4006                                 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4007                         } else {
4008                                 $last = substr($last, 0, 32);
4009                         }
4010                 }
4011
4012                 return ['first' => $first, 'last' => $last];
4013         }
4014
4015         /**
4016          * Create profile data
4017          *
4018          * @param int $uid The user id
4019          *
4020          * @return array The profile data
4021          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
4022          */
4023         private static function createProfileData($uid)
4024         {
4025                 $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
4026                 if (!DBA::isResult($profile)) {
4027                         return [];
4028                 }
4029
4030                 $handle = $profile["addr"];
4031
4032                 $split_name = self::splitName($profile['name']);
4033                 $first = $split_name['first'];
4034                 $last = $split_name['last'];
4035
4036                 $large = DI::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4037                 $medium = DI::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4038                 $small = DI::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
4039                 $searchable = ($profile['net-publish'] ? 'true' : 'false');
4040
4041                 $dob = null;
4042                 $about = null;
4043                 $location = null;
4044                 $tags = null;
4045                 if ($searchable === 'true') {
4046                         $dob = '';
4047
4048                         if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4049                                 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4050                                 if ($year < 1004) {
4051                                         $year = 1004;
4052                                 }
4053                                 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4054                         }
4055
4056                         $about = BBCode::toMarkdown($profile['about']);
4057
4058                         $location = $profile['location'];
4059                         $tags = '';
4060                         if ($profile['pub_keywords']) {
4061                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4062                                 $kw = str_replace('  ', ' ', $kw);
4063                                 $arr = explode(' ', $kw);
4064                                 if (count($arr)) {
4065                                         for ($x = 0; $x < 5; $x ++) {
4066                                                 if (!empty($arr[$x])) {
4067                                                         $tags .= '#'. trim($arr[$x]) .' ';
4068                                                 }
4069                                         }
4070                                 }
4071                         }
4072                         $tags = trim($tags);
4073                 }
4074
4075                 return ["author" => $handle,
4076                                 "first_name" => $first,
4077                                 "last_name" => $last,
4078                                 "image_url" => $large,
4079                                 "image_url_medium" => $medium,
4080                                 "image_url_small" => $small,
4081                                 "birthday" => $dob,
4082                                 "bio" => $about,
4083                                 "location" => $location,
4084                                 "searchable" => $searchable,
4085                                 "nsfw" => "false",
4086                                 "tag_string" => $tags];
4087         }
4088
4089         /**
4090          * Sends profile data
4091          *
4092          * @param int  $uid    The user id
4093          * @param bool $recips optional, default false
4094          * @return void
4095          * @throws \Exception
4096          */
4097         public static function sendProfile($uid, $recips = false)
4098         {
4099                 if (!$uid) {
4100                         return;
4101                 }
4102
4103                 $owner = User::getOwnerDataById($uid);
4104                 if (!$owner) {
4105                         return;
4106                 }
4107
4108                 if (!$recips) {
4109                         $recips = q(
4110                                 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4111                                 AND `uid` = %d AND `rel` != %d",
4112                                 DBA::escape(Protocol::DIASPORA),
4113                                 intval($uid),
4114                                 intval(Contact::SHARING)
4115                         );
4116                 }
4117
4118                 if (!$recips) {
4119                         return;
4120                 }
4121
4122                 $message = self::createProfileData($uid);
4123
4124                 // @ToDo Split this into single worker jobs
4125                 foreach ($recips as $recip) {
4126                         Logger::log("Send updated profile data for user ".$uid." to contact ".$recip["id"], Logger::DEBUG);
4127                         self::buildAndTransmit($owner, $recip, "profile", $message);
4128                 }
4129         }
4130
4131         /**
4132          * Creates the signature for likes that are created on our system
4133          *
4134          * @param integer $uid  The user of that comment
4135          * @param array   $item Item array
4136          *
4137          * @return array Signed content
4138          * @throws \Exception
4139          */
4140         public static function createLikeSignature($uid, array $item)
4141         {
4142                 $owner = User::getOwnerDataById($uid);
4143                 if (empty($owner)) {
4144                         Logger::info('No owner post, so not storing signature');
4145                         return false;
4146                 }
4147
4148                 if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) {
4149                         return false;
4150                 }
4151
4152                 $message = self::constructLike($item, $owner);
4153                 if ($message === false) {
4154                         return false;
4155                 }
4156
4157                 $message["author_signature"] = self::signature($owner, $message);
4158
4159                 return $message;
4160         }
4161
4162         /**
4163          * Creates the signature for Comments that are created on our system
4164          *
4165          * @param integer $uid  The user of that comment
4166          * @param array   $item Item array
4167          *
4168          * @return array Signed content
4169          * @throws \Exception
4170          */
4171         public static function createCommentSignature($uid, array $item)
4172         {
4173                 $owner = User::getOwnerDataById($uid);
4174                 if (empty($owner)) {
4175                         Logger::info('No owner post, so not storing signature');
4176                         return false;
4177                 }
4178
4179                 // This is a workaround for the behaviour of the "insert" function, see mod/item.php
4180                 $item['thr-parent'] = $item['parent-uri'];
4181
4182                 $parent = Item::selectFirst(['parent-uri'], ['uri' => $item['parent-uri']]);
4183                 if (!DBA::isResult($parent)) {
4184                         return;
4185                 }
4186
4187                 $item['parent-uri'] = $parent['parent-uri'];
4188
4189                 $message = self::constructComment($item, $owner);
4190                 if ($message === false) {
4191                         return false;
4192                 }
4193
4194                 $message["author_signature"] = self::signature($owner, $message);
4195
4196                 return $message;
4197         }
4198 }