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