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