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