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