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