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