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