]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
847809a36b716d96a17314f67a45f5bc3e03eef3
[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                                 }
953                         }
954                 }
955
956                 return $person;
957         }
958
959         /**
960          * @brief Updates the fcontact table
961          *
962          * @param array $arr The fcontact data
963          */
964         private static function updateFContact($arr)
965         {
966                 $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
967                         'request' => $arr["request"], 'nick' => $arr["nick"],
968                         'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
969                         'batch' => $arr["batch"], 'notify' => $arr["notify"],
970                         'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
971                         'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
972                         'updated' => DateTimeFormat::utcNow()];
973
974                 $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
975
976                 DBA::update('fcontact', $fields, $condition, true);
977         }
978
979         /**
980          * @brief get a handle (user@domain.tld) from a given contact id
981          *
982          * @param int $contact_id  The id in the contact table
983          * @param int $pcontact_id The id in the contact table (Used for the public contact)
984          *
985          * @return string the handle
986          */
987         private static function handleFromContact($contact_id, $pcontact_id = 0)
988         {
989                 $handle = false;
990
991                 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
992
993                 if ($pcontact_id != 0) {
994                         $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
995
996                         if (DBA::isResult($contact) && !empty($contact["addr"])) {
997                                 return strtolower($contact["addr"]);
998                         }
999                 }
1000
1001                 $r = q(
1002                         "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
1003                         intval($contact_id)
1004                 );
1005
1006                 if (DBA::isResult($r)) {
1007                         $contact = $r[0];
1008
1009                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
1010
1011                         if ($contact['addr'] != "") {
1012                                 $handle = $contact['addr'];
1013                         } else {
1014                                 $baseurl_start = strpos($contact['url'], '://') + 3;
1015                                 // allows installations in a subdirectory--not sure how Diaspora will handle
1016                                 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
1017                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
1018                                 $handle = $contact['nick'].'@'.$baseurl;
1019                         }
1020                 }
1021
1022                 return strtolower($handle);
1023         }
1024
1025         /**
1026          * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
1027          * fcontact guid
1028          *
1029          * @param mixed $fcontact_guid Hexadecimal string guid
1030          *
1031          * @return string the contact url or null
1032          */
1033         public static function urlFromContactGuid($fcontact_guid)
1034         {
1035                 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
1036
1037                 $r = q(
1038                         "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
1039                         DBA::escape(Protocol::DIASPORA),
1040                         DBA::escape($fcontact_guid)
1041                 );
1042
1043                 if (DBA::isResult($r)) {
1044                         return $r[0]['url'];
1045                 }
1046
1047                 return null;
1048         }
1049
1050         /**
1051          * @brief Get a contact id for a given handle
1052          *
1053          * @todo Move to Friendica\Model\Contact
1054          *
1055          * @param int    $uid    The user id
1056          * @param string $handle The handle in the format user@domain.tld
1057          *
1058          * @return int Contact id
1059          */
1060         private static function contactByHandle($uid, $handle)
1061         {
1062                 $cid = Contact::getIdForURL($handle, $uid);
1063                 if (!$cid) {
1064                         $handle_parts = explode("@", $handle);
1065                         $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
1066                         $cid = Contact::getIdForURL($nurl_sql, $uid);
1067                 }
1068
1069                 if (!$cid) {
1070                         logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
1071                         return false;
1072                 }
1073
1074                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1075                 if (!DBA::isResult($contact)) {
1076                         // This here shouldn't happen at all
1077                         logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
1078                         return false;
1079                 }
1080
1081                 return $contact;
1082         }
1083
1084         /**
1085          * @brief Check if posting is allowed for this contact
1086          *
1087          * @param array $importer   Array of the importer user
1088          * @param array $contact    The contact that is checked
1089          * @param bool  $is_comment Is the check for a comment?
1090          *
1091          * @return bool is the contact allowed to post?
1092          */
1093         private static function postAllow(array $importer, array $contact, $is_comment = false)
1094         {
1095                 /*
1096                  * Perhaps we were already sharing with this person. Now they're sharing with us.
1097                  * That makes us friends.
1098                  * Normally this should have handled by getting a request - but this could get lost
1099                  */
1100                 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1101                 // It is not removed by now. Possibly the code is needed?
1102                 //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(Contact::PAGE_FREELOVE))) {
1103                 //      DBA::update(
1104                 //              'contact',
1105                 //              array('rel' => Contact::FRIEND, 'writable' => true),
1106                 //              array('id' => $contact["id"], 'uid' => $contact["uid"])
1107                 //      );
1108                 //
1109                 //      $contact["rel"] = Contact::FRIEND;
1110                 //      logger("defining user ".$contact["nick"]." as friend");
1111                 //}
1112
1113                 // We don't seem to like that person
1114                 if ($contact["blocked"]) {
1115                         // Maybe blocked, don't accept.
1116                         return false;
1117                         // We are following this person?
1118                 } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
1119                         // Yes, then it is fine.
1120                         return true;
1121                         // Is it a post to a community?
1122                 } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
1123                         // That's good
1124                         return true;
1125                         // Is the message a global user or a comment?
1126                 } elseif (($importer["uid"] == 0) || $is_comment) {
1127                         // Messages for the global users and comments are always accepted
1128                         return true;
1129                 }
1130
1131                 return false;
1132         }
1133
1134         /**
1135          * @brief Fetches the contact id for a handle and checks if posting is allowed
1136          *
1137          * @param array  $importer   Array of the importer user
1138          * @param string $handle     The checked handle in the format user@domain.tld
1139          * @param bool   $is_comment Is the check for a comment?
1140          *
1141          * @return array The contact data
1142          */
1143         private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
1144         {
1145                 $contact = self::contactByHandle($importer["uid"], $handle);
1146                 if (!$contact) {
1147                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1148                         // If a contact isn't found, we accept it anyway if it is a comment
1149                         if ($is_comment && ($importer["uid"] != 0)) {
1150                                 return self::contactByHandle(0, $handle);
1151                         } elseif ($is_comment) {
1152                                 return $importer;
1153                         } else {
1154                                 return false;
1155                         }
1156                 }
1157
1158                 if (!self::postAllow($importer, $contact, $is_comment)) {
1159                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1160                         return false;
1161                 }
1162                 return $contact;
1163         }
1164
1165         /**
1166          * @brief Does the message already exists on the system?
1167          *
1168          * @param int    $uid  The user id
1169          * @param string $guid The guid of the message
1170          *
1171          * @return int|bool message id if the message already was stored into the system - or false.
1172          */
1173         private static function messageExists($uid, $guid)
1174         {
1175                 $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
1176                 if (DBA::isResult($item)) {
1177                         logger("message ".$guid." already exists for user ".$uid);
1178                         return $item["id"];
1179                 }
1180
1181                 return false;
1182         }
1183
1184         /**
1185          * @brief Checks for links to posts in a message
1186          *
1187          * @param array $item The item array
1188          * @return void
1189          */
1190         private static function fetchGuid(array $item)
1191         {
1192                 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1193                 preg_replace_callback(
1194                         $expression,
1195                         function ($match) use ($item) {
1196                                 self::fetchGuidSub($match, $item);
1197                         },
1198                         $item["body"]
1199                 );
1200
1201                 preg_replace_callback(
1202                         "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1203                         function ($match) use ($item) {
1204                                 self::fetchGuidSub($match, $item);
1205                         },
1206                         $item["body"]
1207                 );
1208         }
1209
1210         /**
1211          * @brief Checks for relative /people/* links in an item body to match local
1212          * contacts or prepends the remote host taken from the author link.
1213          *
1214          * @param string $body        The item body to replace links from
1215          * @param string $author_link The author link for missing local contact fallback
1216          *
1217          * @return string the replaced string
1218          */
1219         public static function replacePeopleGuid($body, $author_link)
1220         {
1221                 $return = preg_replace_callback(
1222                         "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1223                         function ($match) use ($author_link) {
1224                                 // $match
1225                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1226                                 // 1 => '0123456789abcdef'
1227                                 // 2 => 'Foo Bar'
1228                                 $handle = self::urlFromContactGuid($match[1]);
1229
1230                                 if ($handle) {
1231                                         $return = '@[url='.$handle.']'.$match[2].'[/url]';
1232                                 } else {
1233                                         // No local match, restoring absolute remote URL from author scheme and host
1234                                         $author_url = parse_url($author_link);
1235                                         $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1236                                 }
1237
1238                                 return $return;
1239                         },
1240                         $body
1241                 );
1242
1243                 return $return;
1244         }
1245
1246         /**
1247          * @brief sub function of "fetchGuid" which checks for links in messages
1248          *
1249          * @param array $match array containing a link that has to be checked for a message link
1250          * @param array $item  The item array
1251          * @return void
1252          */
1253         private static function fetchGuidSub($match, $item)
1254         {
1255                 if (!self::storeByGuid($match[1], $item["author-link"])) {
1256                         self::storeByGuid($match[1], $item["owner-link"]);
1257                 }
1258         }
1259
1260         /**
1261          * @brief Fetches an item with a given guid from a given server
1262          *
1263          * @param string $guid   the message guid
1264          * @param string $server The server address
1265          * @param int    $uid    The user id of the user
1266          *
1267          * @return int the message id of the stored message or false
1268          */
1269         private static function storeByGuid($guid, $server, $uid = 0)
1270         {
1271                 $serverparts = parse_url($server);
1272
1273                 if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
1274                         return false;
1275                 }
1276
1277                 $server = $serverparts["scheme"]."://".$serverparts["host"];
1278
1279                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1280
1281                 $msg = self::message($guid, $server);
1282
1283                 if (!$msg) {
1284                         return false;
1285                 }
1286
1287                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1288
1289                 // Now call the dispatcher
1290                 return self::dispatchPublic($msg);
1291         }
1292
1293         /**
1294          * @brief Fetches a message from a server
1295          *
1296          * @param string $guid   message guid
1297          * @param string $server The url of the server
1298          * @param int    $level  Endless loop prevention
1299          *
1300          * @return array
1301          *      'message' => The message XML
1302          *      'author' => The author handle
1303          *      'key' => The public key of the author
1304          */
1305         private static function message($guid, $server, $level = 0)
1306         {
1307                 if ($level > 5) {
1308                         return false;
1309                 }
1310
1311                 // This will work for new Diaspora servers and Friendica servers from 3.5
1312                 $source_url = $server."/fetch/post/".urlencode($guid);
1313
1314                 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1315
1316                 $envelope = Network::fetchUrl($source_url);
1317                 if ($envelope) {
1318                         logger("Envelope was fetched.", LOGGER_DEBUG);
1319                         $x = self::verifyMagicEnvelope($envelope);
1320                         if (!$x) {
1321                                 logger("Envelope could not be verified.", LOGGER_DEBUG);
1322                         } else {
1323                                 logger("Envelope was verified.", LOGGER_DEBUG);
1324                         }
1325                 } else {
1326                         $x = false;
1327                 }
1328
1329                 // This will work for older Diaspora and Friendica servers
1330                 if (!$x) {
1331                         $source_url = $server."/p/".urlencode($guid).".xml";
1332                         logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1333
1334                         $x = Network::fetchUrl($source_url);
1335                         if (!$x) {
1336                                 return false;
1337                         }
1338                 }
1339
1340                 $source_xml = XML::parseString($x);
1341
1342                 if (!is_object($source_xml)) {
1343                         return false;
1344                 }
1345
1346                 if ($source_xml->post->reshare) {
1347                         // Reshare of a reshare - old Diaspora version
1348                         logger("Message is a reshare", LOGGER_DEBUG);
1349                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1350                 } elseif ($source_xml->getName() == "reshare") {
1351                         // Reshare of a reshare - new Diaspora version
1352                         logger("Message is a new reshare", LOGGER_DEBUG);
1353                         return self::message($source_xml->root_guid, $server, ++$level);
1354                 }
1355
1356                 $author = "";
1357
1358                 // Fetch the author - for the old and the new Diaspora version
1359                 if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
1360                         $author = (string)$source_xml->post->status_message->diaspora_handle;
1361                 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1362                         $author = (string)$source_xml->author;
1363                 }
1364
1365                 // If this isn't a "status_message" then quit
1366                 if (!$author) {
1367                         logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1368                         return false;
1369                 }
1370
1371                 $msg = ["message" => $x, "author" => $author];
1372
1373                 $msg["key"] = self::key($msg["author"]);
1374
1375                 return $msg;
1376         }
1377
1378         /**
1379          * @brief Fetches the item record of a given guid
1380          *
1381          * @param int    $uid     The user id
1382          * @param string $guid    message guid
1383          * @param string $author  The handle of the item
1384          * @param array  $contact The contact of the item owner
1385          *
1386          * @return array the item record
1387          */
1388         private static function parentItem($uid, $guid, $author, array $contact)
1389         {
1390                 $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
1391                         'author-name', 'author-link', 'author-avatar',
1392                         'owner-name', 'owner-link', 'owner-avatar'];
1393                 $condition = ['uid' => $uid, 'guid' => $guid];
1394                 $item = Item::selectFirst($fields, $condition);
1395
1396                 if (!DBA::isResult($item)) {
1397                         $person = self::personByHandle($author);
1398                         $result = self::storeByGuid($guid, $person["url"], $uid);
1399
1400                         // We don't have an url for items that arrived at the public dispatcher
1401                         if (!$result && !empty($contact["url"])) {
1402                                 $result = self::storeByGuid($guid, $contact["url"], $uid);
1403                         }
1404
1405                         if ($result) {
1406                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1407
1408                                 $item = Item::selectFirst($fields, $condition);
1409                         }
1410                 }
1411
1412                 if (!DBA::isResult($item)) {
1413                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
1414                         return false;
1415                 } else {
1416                         logger("parent item found: parent: ".$guid." - user: ".$uid);
1417                         return $item;
1418                 }
1419         }
1420
1421         /**
1422          * @brief returns contact details
1423          *
1424          * @param array $def_contact The default contact if the person isn't found
1425          * @param array $person      The record of the person
1426          * @param int   $uid         The user id
1427          *
1428          * @return array
1429          *      'cid' => contact id
1430          *      'network' => network type
1431          */
1432         private static function authorContactByUrl($def_contact, $person, $uid)
1433         {
1434                 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1435                 $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
1436                 if (DBA::isResult($contact)) {
1437                         $cid = $contact["id"];
1438                         $network = $contact["network"];
1439                 } else {
1440                         $cid = $def_contact["id"];
1441                         $network = Protocol::DIASPORA;
1442                 }
1443
1444                 return ["cid" => $cid, "network" => $network];
1445         }
1446
1447         /**
1448          * @brief Is the profile a hubzilla profile?
1449          *
1450          * @param string $url The profile link
1451          *
1452          * @return bool is it a hubzilla server?
1453          */
1454         public static function isRedmatrix($url)
1455         {
1456                 return(strstr($url, "/channel/"));
1457         }
1458
1459         /**
1460          * @brief Generate a post link with a given handle and message guid
1461          *
1462          * @param string $addr        The user handle
1463          * @param string $guid        message guid
1464          * @param string $parent_guid optional parent guid
1465          *
1466          * @return string the post link
1467          */
1468         private static function plink($addr, $guid, $parent_guid = '')
1469         {
1470                 $contact = Contact::getDetailsByAddr($addr);
1471
1472                 // Fallback
1473                 if (!$contact) {
1474                         if ($parent_guid != '') {
1475                                 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1476                         } else {
1477                                 return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1478                         }
1479                 }
1480
1481                 if ($contact["network"] == Protocol::DFRN) {
1482                         return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
1483                 }
1484
1485                 if (self::isRedmatrix($contact["url"])) {
1486                         return $contact["url"] . "/?f=&mid=" . $guid;
1487                 }
1488
1489                 if ($parent_guid != '') {
1490                         return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1491                 } else {
1492                         return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1493                 }
1494         }
1495
1496         /**
1497          * @brief Receives account migration
1498          *
1499          * @param array  $importer Array of the importer user
1500          * @param object $data     The message object
1501          *
1502          * @return bool Success
1503          */
1504         private static function receiveAccountMigration(array $importer, $data)
1505         {
1506                 $old_handle = notags(unxmlify($data->author));
1507                 $new_handle = notags(unxmlify($data->profile->author));
1508                 $signature = notags(unxmlify($data->signature));
1509
1510                 $contact = self::contactByHandle($importer["uid"], $old_handle);
1511                 if (!$contact) {
1512                         logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1513                         return false;
1514                 }
1515
1516                 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1517
1518                 // Check signature
1519                 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1520                 $key = self::key($old_handle);
1521                 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1522                         logger('No valid signature for migration.');
1523                         return false;
1524                 }
1525
1526                 // Update the profile
1527                 self::receiveProfile($importer, $data->profile);
1528
1529                 // change the technical stuff in contact and gcontact
1530                 $data = Probe::uri($new_handle);
1531                 if ($data['network'] == Protocol::PHANTOM) {
1532                         logger('Account for '.$new_handle." couldn't be probed.");
1533                         return false;
1534                 }
1535
1536                 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1537                                 'name' => $data['name'], 'nick' => $data['nick'],
1538                                 'addr' => $data['addr'], 'batch' => $data['batch'],
1539                                 'notify' => $data['notify'], 'poll' => $data['poll'],
1540                                 'network' => $data['network']];
1541
1542                 DBA::update('contact', $fields, ['addr' => $old_handle]);
1543
1544                 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1545                                 'name' => $data['name'], 'nick' => $data['nick'],
1546                                 'addr' => $data['addr'], 'connect' => $data['addr'],
1547                                 'notify' => $data['notify'], 'photo' => $data['photo'],
1548                                 'server_url' => $data['baseurl'], 'network' => $data['network']];
1549
1550                 DBA::update('gcontact', $fields, ['addr' => $old_handle]);
1551
1552                 logger('Contacts are updated.');
1553
1554                 return true;
1555         }
1556
1557         /**
1558          * @brief Processes an account deletion
1559          *
1560          * @param object $data     The message object
1561          *
1562          * @return bool Success
1563          */
1564         private static function receiveAccountDeletion($data)
1565         {
1566                 $author = notags(unxmlify($data->author));
1567
1568                 $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
1569                 while ($contact = DBA::fetch($contacts)) {
1570                         Contact::remove($contact["id"]);
1571                 }
1572
1573                 DBA::delete('gcontact', ['addr' => $author]);
1574
1575                 logger('Removed contacts for ' . $author);
1576
1577                 return true;
1578         }
1579
1580         /**
1581          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1582          *
1583          * @param string  $author    Author handle
1584          * @param string  $guid      Message guid
1585          * @param boolean $onlyfound Only return uri when found in the database
1586          *
1587          * @return string The constructed uri or the one from our database
1588          */
1589         private static function getUriFromGuid($author, $guid, $onlyfound = false)
1590         {
1591                 $item = Item::selectFirst(['uri'], ['guid' => $guid]);
1592                 if (DBA::isResult($item)) {
1593                         return $item["uri"];
1594                 } elseif (!$onlyfound) {
1595                         $person = self::personByHandle($author);
1596
1597                         $parts = parse_url($person['url']);
1598                         unset($parts['path']);
1599                         $host_url = Network::unparseURL($parts);
1600
1601                         return $host_url . '/object/' . $guid;
1602                 }
1603
1604                 return "";
1605         }
1606
1607         /**
1608          * @brief Fetch the guid from our database with a given uri
1609          *
1610          * @param string $uri Message uri
1611          * @param string $uid Author handle
1612          *
1613          * @return string The post guid
1614          */
1615         private static function getGuidFromUri($uri, $uid)
1616         {
1617                 $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
1618                 if (DBA::isResult($item)) {
1619                         return $item["guid"];
1620                 } else {
1621                         return false;
1622                 }
1623         }
1624
1625         /**
1626          * @brief Find the best importer for a comment, like, ...
1627          *
1628          * @param string $guid The guid of the item
1629          *
1630          * @return array|boolean the origin owner of that post - or false
1631          */
1632         private static function importerForGuid($guid)
1633         {
1634                 $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
1635                 if (DBA::isResult($item)) {
1636                         logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1637                         $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
1638                         if (DBA::isResult($contact)) {
1639                                 return $contact;
1640                         }
1641                 }
1642                 return false;
1643         }
1644
1645         /**
1646          * @brief Processes an incoming comment
1647          *
1648          * @param array  $importer Array of the importer user
1649          * @param string $sender   The sender of the message
1650          * @param object $data     The message object
1651          * @param string $xml      The original XML of the message
1652          *
1653          * @return int The message id of the generated comment or "false" if there was an error
1654          */
1655         private static function receiveComment(array $importer, $sender, $data, $xml)
1656         {
1657                 $author = notags(unxmlify($data->author));
1658                 $guid = notags(unxmlify($data->guid));
1659                 $parent_guid = notags(unxmlify($data->parent_guid));
1660                 $text = unxmlify($data->text);
1661
1662                 if (isset($data->created_at)) {
1663                         $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1664                 } else {
1665                         $created_at = DateTimeFormat::utcNow();
1666                 }
1667
1668                 if (isset($data->thread_parent_guid)) {
1669                         $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1670                         $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1671                 } else {
1672                         $thr_uri = "";
1673                 }
1674
1675                 $contact = self::allowedContactByHandle($importer, $sender, true);
1676                 if (!$contact) {
1677                         return false;
1678                 }
1679
1680                 $message_id = self::messageExists($importer["uid"], $guid);
1681                 if ($message_id) {
1682                         return true;
1683                 }
1684
1685                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1686                 if (!$parent_item) {
1687                         return false;
1688                 }
1689
1690                 $person = self::personByHandle($author);
1691                 if (!is_array($person)) {
1692                         logger("unable to find author details");
1693                         return false;
1694                 }
1695
1696                 // Fetch the contact id - if we know this contact
1697                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1698
1699                 $datarray = [];
1700
1701                 $datarray["uid"] = $importer["uid"];
1702                 $datarray["contact-id"] = $author_contact["cid"];
1703                 $datarray["network"]  = $author_contact["network"];
1704
1705                 $datarray["author-link"] = $person["url"];
1706                 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1707
1708                 $datarray["owner-link"] = $contact["url"];
1709                 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1710
1711                 $datarray["guid"] = $guid;
1712                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1713
1714                 $datarray["verb"] = ACTIVITY_POST;
1715                 $datarray["gravity"] = GRAVITY_COMMENT;
1716
1717                 if ($thr_uri != "") {
1718                         $datarray["parent-uri"] = $thr_uri;
1719                 } else {
1720                         $datarray["parent-uri"] = $parent_item["uri"];
1721                 }
1722
1723                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1724
1725                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1726                 $datarray["source"] = $xml;
1727
1728                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1729
1730                 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1731
1732                 $body = Markdown::toBBCode($text);
1733
1734                 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1735
1736                 self::fetchGuid($datarray);
1737
1738                 // If we are the origin of the parent we store the original data.
1739                 // We notify our followers during the item storage.
1740                 if ($parent_item["origin"]) {
1741                         $datarray['diaspora_signed_text'] = json_encode($data);
1742                 }
1743
1744                 $message_id = Item::insert($datarray);
1745
1746                 if ($message_id <= 0) {
1747                         return false;
1748                 }
1749
1750                 if ($message_id) {
1751                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1752                         if ($datarray['uid'] == 0) {
1753                                 Item::distribute($message_id, json_encode($data));
1754                         }
1755                 }
1756
1757                 return true;
1758         }
1759
1760         /**
1761          * @brief processes and stores private messages
1762          *
1763          * @param array  $importer     Array of the importer user
1764          * @param array  $contact      The contact of the message
1765          * @param object $data         The message object
1766          * @param array  $msg          Array of the processed message, author handle and key
1767          * @param object $mesg         The private message
1768          * @param array  $conversation The conversation record to which this message belongs
1769          *
1770          * @return bool "true" if it was successful
1771          */
1772         private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
1773         {
1774                 $author = notags(unxmlify($data->author));
1775                 $guid = notags(unxmlify($data->guid));
1776                 $subject = notags(unxmlify($data->subject));
1777
1778                 // "diaspora_handle" is the element name from the old version
1779                 // "author" is the element name from the new version
1780                 if ($mesg->author) {
1781                         $msg_author = notags(unxmlify($mesg->author));
1782                 } elseif ($mesg->diaspora_handle) {
1783                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1784                 } else {
1785                         return false;
1786                 }
1787
1788                 $msg_guid = notags(unxmlify($mesg->guid));
1789                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1790                 $msg_text = unxmlify($mesg->text);
1791                 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1792
1793                 if ($msg_conversation_guid != $guid) {
1794                         logger("message conversation guid does not belong to the current conversation.");
1795                         return false;
1796                 }
1797
1798                 $body = Markdown::toBBCode($msg_text);
1799                 $message_uri = $msg_author.":".$msg_guid;
1800
1801                 $person = self::personByHandle($msg_author);
1802
1803                 DBA::lock('mail');
1804
1805                 if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
1806                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1807                         return false;
1808                 }
1809
1810                 q(
1811                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1812                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1813                         intval($importer["uid"]),
1814                         DBA::escape($msg_guid),
1815                         intval($conversation["id"]),
1816                         DBA::escape($person["name"]),
1817                         DBA::escape($person["photo"]),
1818                         DBA::escape($person["url"]),
1819                         intval($contact["id"]),
1820                         DBA::escape($subject),
1821                         DBA::escape($body),
1822                         0,
1823                         0,
1824                         DBA::escape($message_uri),
1825                         DBA::escape($author.":".$guid),
1826                         DBA::escape($msg_created_at)
1827                 );
1828
1829                 DBA::unlock();
1830
1831                 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1832
1833                 notification(
1834                         [
1835                         "type" => NOTIFY_MAIL,
1836                         "notify_flags" => $importer["notify-flags"],
1837                         "language" => $importer["language"],
1838                         "to_name" => $importer["username"],
1839                         "to_email" => $importer["email"],
1840                         "uid" =>$importer["uid"],
1841                         "item" => ["id" => $conversation["id"], "title" => $subject, "subject" => $subject, "body" => $body],
1842                         "source_name" => $person["name"],
1843                         "source_link" => $person["url"],
1844                         "source_photo" => $person["photo"],
1845                         "verb" => ACTIVITY_POST,
1846                         "otype" => "mail"]
1847                 );
1848                 return true;
1849         }
1850
1851         /**
1852          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1853          *
1854          * @param array  $importer Array of the importer user
1855          * @param array  $msg      Array of the processed message, author handle and key
1856          * @param object $data     The message object
1857          *
1858          * @return bool Success
1859          */
1860         private static function receiveConversation(array $importer, $msg, $data)
1861         {
1862                 $author = notags(unxmlify($data->author));
1863                 $guid = notags(unxmlify($data->guid));
1864                 $subject = notags(unxmlify($data->subject));
1865                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1866                 $participants = notags(unxmlify($data->participants));
1867
1868                 $messages = $data->message;
1869
1870                 if (!count($messages)) {
1871                         logger("empty conversation");
1872                         return false;
1873                 }
1874
1875                 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1876                 if (!$contact) {
1877                         return false;
1878                 }
1879
1880                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1881                 if (!DBA::isResult($conversation)) {
1882                         $r = q(
1883                                 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1884                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1885                                 intval($importer["uid"]),
1886                                 DBA::escape($guid),
1887                                 DBA::escape($author),
1888                                 DBA::escape($created_at),
1889                                 DBA::escape(DateTimeFormat::utcNow()),
1890                                 DBA::escape($subject),
1891                                 DBA::escape($participants)
1892                         );
1893                         if ($r) {
1894                                 $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
1895                         }
1896                 }
1897                 if (!$conversation) {
1898                         logger("unable to create conversation.");
1899                         return false;
1900                 }
1901
1902                 foreach ($messages as $mesg) {
1903                         self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1904                 }
1905
1906                 return true;
1907         }
1908
1909         /**
1910          * @brief Processes "like" messages
1911          *
1912          * @param array  $importer Array of the importer user
1913          * @param string $sender   The sender of the message
1914          * @param object $data     The message object
1915          *
1916          * @return int The message id of the generated like or "false" if there was an error
1917          */
1918         private static function receiveLike(array $importer, $sender, $data)
1919         {
1920                 $author = notags(unxmlify($data->author));
1921                 $guid = notags(unxmlify($data->guid));
1922                 $parent_guid = notags(unxmlify($data->parent_guid));
1923                 $parent_type = notags(unxmlify($data->parent_type));
1924                 $positive = notags(unxmlify($data->positive));
1925
1926                 // likes on comments aren't supported by Diaspora - only on posts
1927                 // But maybe this will be supported in the future, so we will accept it.
1928                 if (!in_array($parent_type, ["Post", "Comment"])) {
1929                         return false;
1930                 }
1931
1932                 $contact = self::allowedContactByHandle($importer, $sender, true);
1933                 if (!$contact) {
1934                         return false;
1935                 }
1936
1937                 $message_id = self::messageExists($importer["uid"], $guid);
1938                 if ($message_id) {
1939                         return true;
1940                 }
1941
1942                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1943                 if (!$parent_item) {
1944                         return false;
1945                 }
1946
1947                 $person = self::personByHandle($author);
1948                 if (!is_array($person)) {
1949                         logger("unable to find author details");
1950                         return false;
1951                 }
1952
1953                 // Fetch the contact id - if we know this contact
1954                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1955
1956                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1957                 // We would accept this anyhow.
1958                 if ($positive == "true") {
1959                         $verb = ACTIVITY_LIKE;
1960                 } else {
1961                         $verb = ACTIVITY_DISLIKE;
1962                 }
1963
1964                 $datarray = [];
1965
1966                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
1967
1968                 $datarray["uid"] = $importer["uid"];
1969                 $datarray["contact-id"] = $author_contact["cid"];
1970                 $datarray["network"]  = $author_contact["network"];
1971
1972                 $datarray["author-link"] = $person["url"];
1973                 $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
1974
1975                 $datarray["owner-link"] = $contact["url"];
1976                 $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
1977
1978                 $datarray["guid"] = $guid;
1979                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1980
1981                 $datarray["verb"] = $verb;
1982                 $datarray["gravity"] = GRAVITY_ACTIVITY;
1983                 $datarray["parent-uri"] = $parent_item["uri"];
1984
1985                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1986
1987                 $datarray["body"] = $verb;
1988
1989                 // Diaspora doesn't provide a date for likes
1990                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
1991
1992                 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1993                 if ($parent_item["id"] != $parent_item["parent"]) {
1994                         $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
1995                         $origin = $toplevel["origin"];
1996                 } else {
1997                         $origin = $parent_item["origin"];
1998                 }
1999
2000                 // If we are the origin of the parent we store the original data.
2001                 // We notify our followers during the item storage.
2002                 if ($origin) {
2003                         $datarray['diaspora_signed_text'] = json_encode($data);
2004                 }
2005
2006                 $message_id = Item::insert($datarray);
2007
2008                 if ($message_id <= 0) {
2009                         return false;
2010                 }
2011
2012                 if ($message_id) {
2013                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2014                         if ($datarray['uid'] == 0) {
2015                                 Item::distribute($message_id, json_encode($data));
2016                         }
2017                 }
2018
2019                 return true;
2020         }
2021
2022         /**
2023          * @brief Processes private messages
2024          *
2025          * @param array  $importer Array of the importer user
2026          * @param object $data     The message object
2027          *
2028          * @return bool Success?
2029          */
2030         private static function receiveMessage(array $importer, $data)
2031         {
2032                 $author = notags(unxmlify($data->author));
2033                 $guid = notags(unxmlify($data->guid));
2034                 $conversation_guid = notags(unxmlify($data->conversation_guid));
2035                 $text = unxmlify($data->text);
2036                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2037
2038                 $contact = self::allowedContactByHandle($importer, $author, true);
2039                 if (!$contact) {
2040                         return false;
2041                 }
2042
2043                 $conversation = null;
2044
2045                 $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
2046                 $conversation = DBA::selectFirst('conv', [], $condition);
2047
2048                 if (!DBA::isResult($conversation)) {
2049                         logger("conversation not available.");
2050                         return false;
2051                 }
2052
2053                 $message_uri = $author.":".$guid;
2054
2055                 $person = self::personByHandle($author);
2056                 if (!$person) {
2057                         logger("unable to find author details");
2058                         return false;
2059                 }
2060
2061                 $body = Markdown::toBBCode($text);
2062
2063                 $body = self::replacePeopleGuid($body, $person["url"]);
2064
2065                 DBA::lock('mail');
2066
2067                 if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
2068                         logger("duplicate message already delivered.", LOGGER_DEBUG);
2069                         return false;
2070                 }
2071
2072                 q(
2073                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2074                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2075                         intval($importer["uid"]),
2076                         DBA::escape($guid),
2077                         intval($conversation["id"]),
2078                         DBA::escape($person["name"]),
2079                         DBA::escape($person["photo"]),
2080                         DBA::escape($person["url"]),
2081                         intval($contact["id"]),
2082                         DBA::escape($conversation["subject"]),
2083                         DBA::escape($body),
2084                         0,
2085                         1,
2086                         DBA::escape($message_uri),
2087                         DBA::escape($author.":".$conversation["guid"]),
2088                         DBA::escape($created_at)
2089                 );
2090
2091                 DBA::unlock();
2092
2093                 DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2094                 return true;
2095         }
2096
2097         /**
2098          * @brief Processes participations - unsupported by now
2099          *
2100          * @param array  $importer Array of the importer user
2101          * @param object $data     The message object
2102          *
2103          * @return bool always true
2104          */
2105         private static function receiveParticipation(array $importer, $data)
2106         {
2107                 $author = strtolower(notags(unxmlify($data->author)));
2108                 $parent_guid = notags(unxmlify($data->parent_guid));
2109
2110                 $contact_id = Contact::getIdForURL($author);
2111                 if (!$contact_id) {
2112                         logger('Contact not found: '.$author);
2113                         return false;
2114                 }
2115
2116                 $person = self::personByHandle($author);
2117                 if (!is_array($person)) {
2118                         logger("Person not found: ".$author);
2119                         return false;
2120                 }
2121
2122                 $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2123                 if (!DBA::isResult($item)) {
2124                         logger('Item not found, no origin or private: '.$parent_guid);
2125                         return false;
2126                 }
2127
2128                 $author_parts = explode('@', $author);
2129                 if (isset($author_parts[1])) {
2130                         $server = $author_parts[1];
2131                 } else {
2132                         // Should never happen
2133                         $server = $author;
2134                 }
2135
2136                 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2137
2138                 if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
2139                         DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2140                 }
2141
2142                 // Send all existing comments and likes to the requesting server
2143                 $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
2144                 while ($comment = Item::fetch($comments)) {
2145                         if ($comment['id'] == $comment['parent']) {
2146                                 continue;
2147                         }
2148                         if ($comment['verb'] == ACTIVITY_POST) {
2149                                 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2150                         } else {
2151                                 $cmd = $comment['self'] ? 'like' : 'comment-import';
2152                         }
2153                         logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2154                         Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2155                 }
2156                 DBA::close($comments);
2157
2158                 return true;
2159         }
2160
2161         /**
2162          * @brief Processes photos - unneeded
2163          *
2164          * @param array  $importer Array of the importer user
2165          * @param object $data     The message object
2166          *
2167          * @return bool always true
2168          */
2169         private static function receivePhoto(array $importer, $data)
2170         {
2171                 // There doesn't seem to be a reason for this function,
2172                 // since the photo data is transmitted in the status message as well
2173                 return true;
2174         }
2175
2176         /**
2177          * @brief Processes poll participations - unssupported
2178          *
2179          * @param array  $importer Array of the importer user
2180          * @param object $data     The message object
2181          *
2182          * @return bool always true
2183          */
2184         private static function receivePollParticipation(array $importer, $data)
2185         {
2186                 // We don't support polls by now
2187                 return true;
2188         }
2189
2190         /**
2191          * @brief Processes incoming profile updates
2192          *
2193          * @param array  $importer Array of the importer user
2194          * @param object $data     The message object
2195          *
2196          * @return bool Success
2197          */
2198         private static function receiveProfile(array $importer, $data)
2199         {
2200                 $author = strtolower(notags(unxmlify($data->author)));
2201
2202                 $contact = self::contactByHandle($importer["uid"], $author);
2203                 if (!$contact) {
2204                         return false;
2205                 }
2206
2207                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2208                 $image_url = unxmlify($data->image_url);
2209                 $birthday = unxmlify($data->birthday);
2210                 $gender = unxmlify($data->gender);
2211                 $about = Markdown::toBBCode(unxmlify($data->bio));
2212                 $location = Markdown::toBBCode(unxmlify($data->location));
2213                 $searchable = (unxmlify($data->searchable) == "true");
2214                 $nsfw = (unxmlify($data->nsfw) == "true");
2215                 $tags = unxmlify($data->tag_string);
2216
2217                 $tags = explode("#", $tags);
2218
2219                 $keywords = [];
2220                 foreach ($tags as $tag) {
2221                         $tag = trim(strtolower($tag));
2222                         if ($tag != "") {
2223                                 $keywords[] = $tag;
2224                         }
2225                 }
2226
2227                 $keywords = implode(", ", $keywords);
2228
2229                 $handle_parts = explode("@", $author);
2230                 $nick = $handle_parts[0];
2231
2232                 if ($name === "") {
2233                         $name = $handle_parts[0];
2234                 }
2235
2236                 if (preg_match("|^https?://|", $image_url) === 0) {
2237                         $image_url = "http://".$handle_parts[1].$image_url;
2238                 }
2239
2240                 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2241
2242                 // Generic birthday. We don't know the timezone. The year is irrelevant.
2243
2244                 $birthday = str_replace("1000", "1901", $birthday);
2245
2246                 if ($birthday != "") {
2247                         $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2248                 }
2249
2250                 // this is to prevent multiple birthday notifications in a single year
2251                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2252
2253                 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2254                         $birthday = $contact["bd"];
2255                 }
2256
2257                 $fields = ['name' => $name, 'location' => $location,
2258                         'name-date' => DateTimeFormat::utcNow(),
2259                         'about' => $about, 'gender' => $gender,
2260                         'addr' => $author, 'nick' => $nick,
2261                         'keywords' => $keywords];
2262
2263                 if (!empty($birthday)) {
2264                         $fields['bd'] = $birthday;
2265                 }
2266
2267                 DBA::update('contact', $fields, ['id' => $contact['id']]);
2268
2269                 $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
2270                                         "photo" => $image_url, "name" => $name, "location" => $location,
2271                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
2272                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2273                                         "hide" => !$searchable, "nsfw" => $nsfw];
2274
2275                 $gcid = GContact::update($gcontact);
2276
2277                 GContact::link($gcid, $importer["uid"], $contact["id"]);
2278
2279                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2280
2281                 return true;
2282         }
2283
2284         /**
2285          * @brief Processes incoming friend requests
2286          *
2287          * @param array $importer Array of the importer user
2288          * @param array $contact  The contact that send the request
2289          * @return void
2290          */
2291         private static function receiveRequestMakeFriend(array $importer, array $contact)
2292         {
2293                 $a = get_app();
2294
2295                 if ($contact["rel"] == Contact::SHARING) {
2296                         DBA::update(
2297                                 'contact',
2298                                 ['rel' => Contact::FRIEND, 'writable' => true],
2299                                 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2300                         );
2301                 }
2302         }
2303
2304         /**
2305          * @brief Processes incoming sharing notification
2306          *
2307          * @param array  $importer Array of the importer user
2308          * @param object $data     The message object
2309          *
2310          * @return bool Success
2311          */
2312         private static function receiveContactRequest(array $importer, $data)
2313         {
2314                 $author = unxmlify($data->author);
2315                 $recipient = unxmlify($data->recipient);
2316
2317                 if (!$author || !$recipient) {
2318                         return false;
2319                 }
2320
2321                 // the current protocol version doesn't know these fields
2322                 // That means that we will assume their existance
2323                 if (isset($data->following)) {
2324                         $following = (unxmlify($data->following) == "true");
2325                 } else {
2326                         $following = true;
2327                 }
2328
2329                 if (isset($data->sharing)) {
2330                         $sharing = (unxmlify($data->sharing) == "true");
2331                 } else {
2332                         $sharing = true;
2333                 }
2334
2335                 $contact = self::contactByHandle($importer["uid"], $author);
2336
2337                 // perhaps we were already sharing with this person. Now they're sharing with us.
2338                 // That makes us friends.
2339                 if ($contact) {
2340                         if ($following) {
2341                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2342                                 self::receiveRequestMakeFriend($importer, $contact);
2343
2344                                 // refetch the contact array
2345                                 $contact = self::contactByHandle($importer["uid"], $author);
2346
2347                                 // If we are now friends, we are sending a share message.
2348                                 // Normally we needn't to do so, but the first message could have been vanished.
2349                                 if (in_array($contact["rel"], [Contact::FRIEND])) {
2350                                         $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2351                                         if (DBA::isResult($user)) {
2352                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2353                                                 $ret = self::sendShare($user, $contact);
2354                                         }
2355                                 }
2356                                 return true;
2357                         } else {
2358                                 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2359                                 Contact::removeFollower($importer, $contact);
2360                                 return true;
2361                         }
2362                 }
2363
2364                 if (!$following && $sharing && in_array($importer["page-flags"], [Contact::PAGE_SOAPBOX, Contact::PAGE_NORMAL])) {
2365                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2366                         return false;
2367                 } elseif (!$following && !$sharing) {
2368                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2369                         return false;
2370                 } elseif (!$following && $sharing) {
2371                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2372                 } elseif ($following && $sharing) {
2373                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2374                 } elseif ($following && !$sharing) {
2375                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2376                 }
2377
2378                 $ret = self::personByHandle($author);
2379
2380                 if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
2381                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2382                         return false;
2383                 }
2384
2385                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2386
2387                 $r = q(
2388                         "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2389                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2390                         intval($importer["uid"]),
2391                         DBA::escape($ret["network"]),
2392                         DBA::escape($ret["addr"]),
2393                         DateTimeFormat::utcNow(),
2394                         DBA::escape($ret["url"]),
2395                         DBA::escape(normalise_link($ret["url"])),
2396                         DBA::escape($batch),
2397                         DBA::escape($ret["name"]),
2398                         DBA::escape($ret["nick"]),
2399                         DBA::escape($ret["photo"]),
2400                         DBA::escape($ret["pubkey"]),
2401                         DBA::escape($ret["notify"]),
2402                         DBA::escape($ret["poll"]),
2403                         1,
2404                         2
2405                 );
2406
2407                 // find the contact record we just created
2408
2409                 $contact_record = self::contactByHandle($importer["uid"], $author);
2410
2411                 if (!$contact_record) {
2412                         logger("unable to locate newly created contact record.");
2413                         return;
2414                 }
2415
2416                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2417
2418                 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2419
2420                 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2421
2422                 if (in_array($importer["page-flags"], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP])) {
2423                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2424
2425                         $hash = random_string().(string)time();   // Generate a confirm_key
2426
2427                         $ret = q(
2428                                 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2429                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2430                                 intval($importer["uid"]),
2431                                 intval($contact_record["id"]),
2432                                 0,
2433                                 0,
2434                                 DBA::escape(L10n::t("Sharing notification from Diaspora network")),
2435                                 DBA::escape($hash),
2436                                 DBA::escape(DateTimeFormat::utcNow())
2437                         );
2438                 } else {
2439                         // automatic friend approval
2440
2441                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2442
2443                         Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2444
2445                         /*
2446                          * technically they are sharing with us (Contact::SHARING),
2447                          * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
2448                          * we are going to change the relationship and make them a follower.
2449                          */
2450                         if (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing && $following) {
2451                                 $new_relation = Contact::FRIEND;
2452                         } elseif (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing) {
2453                                 $new_relation = Contact::SHARING;
2454                         } else {
2455                                 $new_relation = Contact::FOLLOWER;
2456                         }
2457
2458                         $r = q(
2459                                 "UPDATE `contact` SET `rel` = %d,
2460                                 `name-date` = '%s',
2461                                 `uri-date` = '%s',
2462                                 `blocked` = 0,
2463                                 `pending` = 0,
2464                                 `writable` = 1
2465                                 WHERE `id` = %d
2466                                 ",
2467                                 intval($new_relation),
2468                                 DBA::escape(DateTimeFormat::utcNow()),
2469                                 DBA::escape(DateTimeFormat::utcNow()),
2470                                 intval($contact_record["id"])
2471                         );
2472
2473                         $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
2474                         if (DBA::isResult($user)) {
2475                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2476                                 $ret = self::sendShare($user, $contact_record);
2477
2478                                 // Send the profile data, maybe it weren't transmitted before
2479                                 self::sendProfile($importer["uid"], [$contact_record]);
2480                         }
2481                 }
2482
2483                 return true;
2484         }
2485
2486         /**
2487          * @brief Fetches a message with a given guid
2488          *
2489          * @param string $guid        message guid
2490          * @param string $orig_author handle of the original post
2491          * @param string $author      handle of the sharer
2492          *
2493          * @return array The fetched item
2494          */
2495         public static function originalItem($guid, $orig_author)
2496         {
2497                 if (empty($guid)) {
2498                         logger('Empty guid. Quitting.');
2499                         return false;
2500                 }
2501
2502                 // Do we already have this item?
2503                 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2504                         'author-name', 'author-link', 'author-avatar'];
2505                 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2506                 $item = Item::selectFirst($fields, $condition);
2507
2508                 if (DBA::isResult($item)) {
2509                         logger("reshared message ".$guid." already exists on system.");
2510
2511                         // Maybe it is already a reshared item?
2512                         // Then refetch the content, if it is a reshare from a reshare.
2513                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2514                         if (self::isReshare($item["body"], true)) {
2515                                 $item = [];
2516                         } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
2517                                 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2518
2519                                 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2520
2521                                 // Add OEmbed and other information to the body
2522                                 $item["body"] = add_page_info_to_body($item["body"], false, true);
2523
2524                                 return $item;
2525                         } else {
2526                                 return $item;
2527                         }
2528                 }
2529
2530                 if (!DBA::isResult($item)) {
2531                         if (empty($orig_author)) {
2532                                 logger('Empty author for guid ' . $guid . '. Quitting.');
2533                                 return false;
2534                         }
2535
2536                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2537                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2538                         $stored = self::storeByGuid($guid, $server);
2539
2540                         if (!$stored) {
2541                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2542                                 logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
2543                                 $stored = self::storeByGuid($guid, $server);
2544                         }
2545
2546                         if ($stored) {
2547                                 $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
2548                                         'author-name', 'author-link', 'author-avatar'];
2549                                 $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
2550                                 $item = Item::selectFirst($fields, $condition);
2551
2552                                 if (DBA::isResult($item)) {
2553                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2554                                         if (self::isReshare($item["body"], false)) {
2555                                                 $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
2556                                                 $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
2557                                         }
2558
2559                                         return $item;
2560                                 }
2561                         }
2562                 }
2563                 return false;
2564         }
2565
2566         /**
2567          * @brief Processes a reshare message
2568          *
2569          * @param array  $importer Array of the importer user
2570          * @param object $data     The message object
2571          * @param string $xml      The original XML of the message
2572          *
2573          * @return int the message id
2574          */
2575         private static function receiveReshare(array $importer, $data, $xml)
2576         {
2577                 $author = notags(unxmlify($data->author));
2578                 $guid = notags(unxmlify($data->guid));
2579                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2580                 $root_author = notags(unxmlify($data->root_author));
2581                 $root_guid = notags(unxmlify($data->root_guid));
2582                 /// @todo handle unprocessed property "provider_display_name"
2583                 $public = notags(unxmlify($data->public));
2584
2585                 $contact = self::allowedContactByHandle($importer, $author, false);
2586                 if (!$contact) {
2587                         return false;
2588                 }
2589
2590                 $message_id = self::messageExists($importer["uid"], $guid);
2591                 if ($message_id) {
2592                         return true;
2593                 }
2594
2595                 $original_item = self::originalItem($root_guid, $root_author);
2596                 if (!$original_item) {
2597                         return false;
2598                 }
2599
2600                 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2601
2602                 $datarray = [];
2603
2604                 $datarray["uid"] = $importer["uid"];
2605                 $datarray["contact-id"] = $contact["id"];
2606                 $datarray["network"]  = Protocol::DIASPORA;
2607
2608                 $datarray["author-link"] = $contact["url"];
2609                 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2610
2611                 $datarray["owner-link"] = $datarray["author-link"];
2612                 $datarray["owner-id"] = $datarray["author-id"];
2613
2614                 $datarray["guid"] = $guid;
2615                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2616
2617                 $datarray["verb"] = ACTIVITY_POST;
2618                 $datarray["gravity"] = GRAVITY_PARENT;
2619
2620                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2621                 $datarray["source"] = $xml;
2622
2623                 $prefix = share_header(
2624                         $original_item["author-name"],
2625                         $original_item["author-link"],
2626                         $original_item["author-avatar"],
2627                         $original_item["guid"],
2628                         $original_item["created"],
2629                         $orig_url
2630                 );
2631                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2632
2633                 $datarray["tag"] = $original_item["tag"];
2634                 $datarray["app"]  = $original_item["app"];
2635
2636                 $datarray["plink"] = self::plink($author, $guid);
2637                 $datarray["private"] = (($public == "false") ? 1 : 0);
2638                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2639
2640                 $datarray["object-type"] = $original_item["object-type"];
2641
2642                 self::fetchGuid($datarray);
2643                 $message_id = Item::insert($datarray);
2644
2645                 self::sendParticipation($contact, $datarray);
2646
2647                 if ($message_id) {
2648                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2649                         if ($datarray['uid'] == 0) {
2650                                 Item::distribute($message_id);
2651                         }
2652                         return true;
2653                 } else {
2654                         return false;
2655                 }
2656         }
2657
2658         /**
2659          * @brief Processes retractions
2660          *
2661          * @param array  $importer Array of the importer user
2662          * @param array  $contact  The contact of the item owner
2663          * @param object $data     The message object
2664          *
2665          * @return bool success
2666          */
2667         private static function itemRetraction(array $importer, array $contact, $data)
2668         {
2669                 $author = notags(unxmlify($data->author));
2670                 $target_guid = notags(unxmlify($data->target_guid));
2671                 $target_type = notags(unxmlify($data->target_type));
2672
2673                 $person = self::personByHandle($author);
2674                 if (!is_array($person)) {
2675                         logger("unable to find author detail for ".$author);
2676                         return false;
2677                 }
2678
2679                 if (empty($contact["url"])) {
2680                         $contact["url"] = $person["url"];
2681                 }
2682
2683                 // Fetch items that are about to be deleted
2684                 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
2685
2686                 // When we receive a public retraction, we delete every item that we find.
2687                 if ($importer['uid'] == 0) {
2688                         $condition = ['guid' => $target_guid, 'deleted' => false];
2689                 } else {
2690                         $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
2691                 }
2692
2693                 $r = Item::select($fields, $condition);
2694                 if (!DBA::isResult($r)) {
2695                         logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2696                         return false;
2697                 }
2698
2699                 while ($item = Item::fetch($r)) {
2700                         if (strstr($item['file'], '[')) {
2701                                 logger("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2702                                 continue;
2703                         }
2704
2705                         // Fetch the parent item
2706                         $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
2707
2708                         // Only delete it if the parent author really fits
2709                         if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2710                                 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2711                                 continue;
2712                         }
2713
2714                         Item::delete(['id' => $item['id']]);
2715
2716                         logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2717                 }
2718
2719                 return true;
2720         }
2721
2722         /**
2723          * @brief Receives retraction messages
2724          *
2725          * @param array  $importer Array of the importer user
2726          * @param string $sender   The sender of the message
2727          * @param object $data     The message object
2728          *
2729          * @return bool Success
2730          */
2731         private static function receiveRetraction(array $importer, $sender, $data)
2732         {
2733                 $target_type = notags(unxmlify($data->target_type));
2734
2735                 $contact = self::contactByHandle($importer["uid"], $sender);
2736                 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2737                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2738                         return false;
2739                 }
2740
2741                 if (!$contact) {
2742                         $contact = [];
2743                 }
2744
2745                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2746
2747                 switch ($target_type) {
2748                         case "Comment":
2749                         case "Like":
2750                         case "Post":
2751                         case "Reshare":
2752                         case "StatusMessage":
2753                                 return self::itemRetraction($importer, $contact, $data);
2754
2755                         case "PollParticipation":
2756                         case "Photo":
2757                                 // Currently unsupported
2758                                 break;
2759
2760                         default:
2761                                 logger("Unknown target type ".$target_type);
2762                                 return false;
2763                 }
2764                 return true;
2765         }
2766
2767         /**
2768          * @brief Receives status messages
2769          *
2770          * @param array  $importer Array of the importer user
2771          * @param object $data     The message object
2772          * @param string $xml      The original XML of the message
2773          *
2774          * @return int The message id of the newly created item
2775          */
2776         private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
2777         {
2778                 $author = notags(unxmlify($data->author));
2779                 $guid = notags(unxmlify($data->guid));
2780                 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2781                 $public = notags(unxmlify($data->public));
2782                 $text = unxmlify($data->text);
2783                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2784
2785                 $contact = self::allowedContactByHandle($importer, $author, false);
2786                 if (!$contact) {
2787                         return false;
2788                 }
2789
2790                 $message_id = self::messageExists($importer["uid"], $guid);
2791                 if ($message_id) {
2792                         return true;
2793                 }
2794
2795                 $address = [];
2796                 if ($data->location) {
2797                         foreach ($data->location->children() as $fieldname => $data) {
2798                                 $address[$fieldname] = notags(unxmlify($data));
2799                         }
2800                 }
2801
2802                 $body = Markdown::toBBCode($text);
2803
2804                 $datarray = [];
2805
2806                 // Attach embedded pictures to the body
2807                 if ($data->photo) {
2808                         foreach ($data->photo as $photo) {
2809                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2810                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2811                         }
2812
2813                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2814                 } else {
2815                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2816
2817                         // Add OEmbed and other information to the body
2818                         if (!self::isRedmatrix($contact["url"])) {
2819                                 $body = add_page_info_to_body($body, false, true);
2820                         }
2821                 }
2822
2823                 /// @todo enable support for polls
2824                 //if ($data->poll) {
2825                 //      foreach ($data->poll AS $poll)
2826                 //              print_r($poll);
2827                 //      die("poll!\n");
2828                 //}
2829
2830                 /// @todo enable support for events
2831
2832                 $datarray["uid"] = $importer["uid"];
2833                 $datarray["contact-id"] = $contact["id"];
2834                 $datarray["network"] = Protocol::DIASPORA;
2835
2836                 $datarray["author-link"] = $contact["url"];
2837                 $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
2838
2839                 $datarray["owner-link"] = $datarray["author-link"];
2840                 $datarray["owner-id"] = $datarray["author-id"];
2841
2842                 $datarray["guid"] = $guid;
2843                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2844
2845                 $datarray["verb"] = ACTIVITY_POST;
2846                 $datarray["gravity"] = GRAVITY_PARENT;
2847
2848                 $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
2849                 $datarray["source"] = $xml;
2850
2851                 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2852
2853                 if ($provider_display_name != "") {
2854                         $datarray["app"] = $provider_display_name;
2855                 }
2856
2857                 $datarray["plink"] = self::plink($author, $guid);
2858                 $datarray["private"] = (($public == "false") ? 1 : 0);
2859                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2860
2861                 if (isset($address["address"])) {
2862                         $datarray["location"] = $address["address"];
2863                 }
2864
2865                 if (isset($address["lat"]) && isset($address["lng"])) {
2866                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2867                 }
2868
2869                 self::fetchGuid($datarray);
2870                 $message_id = Item::insert($datarray);
2871
2872                 self::sendParticipation($contact, $datarray);
2873
2874                 if ($message_id) {
2875                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2876                         if ($datarray['uid'] == 0) {
2877                                 Item::distribute($message_id);
2878                         }
2879                         return true;
2880                 } else {
2881                         return false;
2882                 }
2883         }
2884
2885         /* ************************************************************************************** *
2886          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2887          * ************************************************************************************** */
2888
2889         /**
2890          * @brief returnes the handle of a contact
2891          *
2892          * @param array $contact contact array
2893          *
2894          * @return string the handle in the format user@domain.tld
2895          */
2896         private static function myHandle(array $contact)
2897         {
2898                 if (!empty($contact["addr"])) {
2899                         return $contact["addr"];
2900                 }
2901
2902                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2903                 // So - just in case - we build the the address here.
2904                 if ($contact["nickname"] != "") {
2905                         $nick = $contact["nickname"];
2906                 } else {
2907                         $nick = $contact["nick"];
2908                 }
2909
2910                 return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2911         }
2912
2913
2914         /**
2915          * @brief Creates the data for a private message in the new format
2916          *
2917          * @param string $msg     The message that is to be transmitted
2918          * @param array  $user    The record of the sender
2919          * @param array  $contact Target of the communication
2920          * @param string $prvkey  The private key of the sender
2921          * @param string $pubkey  The public key of the receiver
2922          *
2923          * @return string The encrypted data
2924          */
2925         public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
2926         {
2927                 logger("Message: ".$msg, LOGGER_DATA);
2928
2929                 // without a public key nothing will work
2930                 if (!$pubkey) {
2931                         logger("pubkey missing: contact id: ".$contact["id"]);
2932                         return false;
2933                 }
2934
2935                 $aes_key = openssl_random_pseudo_bytes(32);
2936                 $b_aes_key = base64_encode($aes_key);
2937                 $iv = openssl_random_pseudo_bytes(16);
2938                 $b_iv = base64_encode($iv);
2939
2940                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2941
2942                 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
2943
2944                 $encrypted_key_bundle = "";
2945                 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2946
2947                 $json_object = json_encode(
2948                         ["aes_key" => base64_encode($encrypted_key_bundle),
2949                                         "encrypted_magic_envelope" => base64_encode($ciphertext)]
2950                 );
2951
2952                 return $json_object;
2953         }
2954
2955         /**
2956          * @brief Creates the envelope for the "fetch" endpoint and for the new format
2957          *
2958          * @param string $msg  The message that is to be transmitted
2959          * @param array  $user The record of the sender
2960          *
2961          * @return string The envelope
2962          */
2963         public static function buildMagicEnvelope($msg, array $user)
2964         {
2965                 $b64url_data = base64url_encode($msg);
2966                 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
2967
2968                 $key_id = base64url_encode(self::myHandle($user));
2969                 $type = "application/xml";
2970                 $encoding = "base64url";
2971                 $alg = "RSA-SHA256";
2972                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2973
2974                 // Fallback if the private key wasn't transmitted in the expected field
2975                 if ($user['uprvkey'] == "") {
2976                         $user['uprvkey'] = $user['prvkey'];
2977                 }
2978
2979                 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
2980                 $sig = base64url_encode($signature);
2981
2982                 $xmldata = ["me:env" => ["me:data" => $data,
2983                                                         "@attributes" => ["type" => $type],
2984                                                         "me:encoding" => $encoding,
2985                                                         "me:alg" => $alg,
2986                                                         "me:sig" => $sig,
2987                                                         "@attributes2" => ["key_id" => $key_id]]];
2988
2989                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
2990
2991                 return XML::fromArray($xmldata, $xml, false, $namespaces);
2992         }
2993
2994         /**
2995          * @brief Create the envelope for a message
2996          *
2997          * @param string $msg     The message that is to be transmitted
2998          * @param array  $user    The record of the sender
2999          * @param array  $contact Target of the communication
3000          * @param string $prvkey  The private key of the sender
3001          * @param string $pubkey  The public key of the receiver
3002          * @param bool   $public  Is the message public?
3003          *
3004          * @return string The message that will be transmitted to other servers
3005          */
3006         public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
3007         {
3008                 // The message is put into an envelope with the sender's signature
3009                 $envelope = self::buildMagicEnvelope($msg, $user);
3010
3011                 // Private messages are put into a second envelope, encrypted with the receivers public key
3012                 if (!$public) {
3013                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3014                 }
3015
3016                 return $envelope;
3017         }
3018
3019         /**
3020          * @brief Creates a signature for a message
3021          *
3022          * @param array $owner   the array of the owner of the message
3023          * @param array $message The message that is to be signed
3024          *
3025          * @return string The signature
3026          */
3027         private static function signature($owner, $message)
3028         {
3029                 $sigmsg = $message;
3030                 unset($sigmsg["author_signature"]);
3031                 unset($sigmsg["parent_author_signature"]);
3032
3033                 $signed_text = implode(";", $sigmsg);
3034
3035                 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3036         }
3037
3038         /**
3039          * @brief Transmit a message to a target server
3040          *
3041          * @param array  $owner        the array of the item owner
3042          * @param array  $contact      Target of the communication
3043          * @param string $envelope     The message that is to be transmitted
3044          * @param bool   $public_batch Is it a public post?
3045          * @param bool   $queue_run    Is the transmission called from the queue?
3046          * @param string $guid         message guid
3047          *
3048          * @return int Result of the transmission
3049          */
3050         public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3051         {
3052                 $a = get_app();
3053
3054                 $enabled = intval(Config::get("system", "diaspora_enabled"));
3055                 if (!$enabled) {
3056                         return 200;
3057                 }
3058
3059                 $logid = random_string(4);
3060
3061                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3062
3063                 // We always try to use the data from the fcontact table.
3064                 // This is important for transmitting data to Friendica servers.
3065                 if (!empty($contact['addr'])) {
3066                         $fcontact = self::personByHandle($contact['addr']);
3067                         if (!empty($fcontact)) {
3068                                 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3069                         }
3070                 }
3071
3072                 if (!$dest_url) {
3073                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3074                         return 0;
3075                 }
3076
3077                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3078
3079                 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3080                         $return_code = 0;
3081                 } else {
3082                         if (!intval(Config::get("system", "diaspora_test"))) {
3083                                 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3084
3085                                 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3086                                 $return_code = $a->get_curl_code();
3087                         } else {
3088                                 logger("test_mode");
3089                                 return 200;
3090                         }
3091                 }
3092
3093                 logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
3094
3095                 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3096                         if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::ACCOUNT_TYPE_RELAY)) {
3097                                 logger("queue message");
3098                                 // queue message for redelivery
3099                                 Queue::add($contact["id"], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3100                         }
3101
3102                         // The message could not be delivered. We mark the contact as "dead"
3103                         Contact::markForArchival($contact);
3104                 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3105                         // We successfully delivered a message, the contact is alive
3106                         Contact::unmarkForArchival($contact);
3107                 }
3108
3109                 return $return_code ? $return_code : -1;
3110         }
3111
3112
3113         /**
3114          * @brief Build the post xml
3115          *
3116          * @param string $type    The message type
3117          * @param array  $message The message data
3118          *
3119          * @return string The post XML
3120          */
3121         public static function buildPostXml($type, $message)
3122         {
3123                 $data = [$type => $message];
3124
3125                 return XML::fromArray($data, $xml);
3126         }
3127
3128         /**
3129          * @brief Builds and transmit messages
3130          *
3131          * @param array  $owner        the array of the item owner
3132          * @param array  $contact      Target of the communication
3133          * @param string $type         The message type
3134          * @param array  $message      The message data
3135          * @param bool   $public_batch Is it a public post?
3136          * @param string $guid         message guid
3137          * @param bool   $spool        Should the transmission be spooled or transmitted?
3138          *
3139          * @return int Result of the transmission
3140          */
3141         private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3142         {
3143                 $msg = self::buildPostXml($type, $message);
3144
3145                 logger('message: '.$msg, LOGGER_DATA);
3146                 logger('send guid '.$guid, LOGGER_DEBUG);
3147
3148                 // Fallback if the private key wasn't transmitted in the expected field
3149                 if (empty($owner['uprvkey'])) {
3150                         $owner['uprvkey'] = $owner['prvkey'];
3151                 }
3152
3153                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3154
3155                 if ($spool) {
3156                         Queue::add($contact['id'], Protocol::DIASPORA, $envelope, $public_batch, $guid);
3157                         return true;
3158                 } else {
3159                         $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3160                 }
3161
3162                 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3163
3164                 return $return_code;
3165         }
3166
3167         /**
3168          * @brief sends a participation (Used to get all further updates)
3169          *
3170          * @param array $contact Target of the communication
3171          * @param array $item    Item array
3172          *
3173          * @return int The result of the transmission
3174          */
3175         private static function sendParticipation(array $contact, array $item)
3176         {
3177                 // Don't send notifications for private postings
3178                 if ($item['private']) {
3179                         return;
3180                 }
3181
3182                 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3183
3184                 $result = Cache::get($cachekey);
3185                 if (!is_null($result)) {
3186                         return;
3187                 }
3188
3189                 // Fetch some user id to have a valid handle to transmit the participation.
3190                 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3191                 // If the item belongs to a user, we take this user id.
3192                 if ($item['uid'] == 0) {
3193                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3194                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
3195                         $owner = User::getOwnerDataById($first_user['uid']);
3196                 } else {
3197                         $owner = User::getOwnerDataById($item['uid']);
3198                 }
3199
3200                 $author = self::myHandle($owner);
3201
3202                 $message = ["author" => $author,
3203                                 "guid" => System::createUUID(),
3204                                 "parent_type" => "Post",
3205                                 "parent_guid" => $item["guid"]];
3206
3207                 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3208
3209                 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3210                 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3211
3212                 return self::buildAndTransmit($owner, $contact, "participation", $message);
3213         }
3214
3215         /**
3216          * @brief sends an account migration
3217          *
3218          * @param array $owner   the array of the item owner
3219          * @param array $contact Target of the communication
3220          * @param int   $uid     User ID
3221          *
3222          * @return int The result of the transmission
3223          */
3224         public static function sendAccountMigration(array $owner, array $contact, $uid)
3225         {
3226                 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3227                 $profile = self::createProfileData($uid);
3228
3229                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3230                 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3231
3232                 $message = ["author" => $old_handle,
3233                                 "profile" => $profile,
3234                                 "signature" => $signature];
3235
3236                 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3237
3238                 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3239         }
3240
3241         /**
3242          * @brief Sends a "share" message
3243          *
3244          * @param array $owner   the array of the item owner
3245          * @param array $contact Target of the communication
3246          *
3247          * @return int The result of the transmission
3248          */
3249         public static function sendShare(array $owner, array $contact)
3250         {
3251                 /**
3252                  * @todo support the different possible combinations of "following" and "sharing"
3253                  * Currently, Diaspora only interprets the "sharing" field
3254                  *
3255                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3256                  */
3257
3258                 /*
3259                 switch ($contact["rel"]) {
3260                         case Contact::FRIEND:
3261                                 $following = true;
3262                                 $sharing = true;
3263
3264                         case Contact::SHARING:
3265                                 $following = false;
3266                                 $sharing = true;
3267
3268                         case Contact::FOLLOWER:
3269                                 $following = true;
3270                                 $sharing = false;
3271                 }
3272                 */
3273
3274                 $message = ["author" => self::myHandle($owner),
3275                                 "recipient" => $contact["addr"],
3276                                 "following" => "true",
3277                                 "sharing" => "true"];
3278
3279                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3280
3281                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3282         }
3283
3284         /**
3285          * @brief sends an "unshare"
3286          *
3287          * @param array $owner   the array of the item owner
3288          * @param array $contact Target of the communication
3289          *
3290          * @return int The result of the transmission
3291          */
3292         public static function sendUnshare(array $owner, array $contact)
3293         {
3294                 $message = ["author" => self::myHandle($owner),
3295                                 "recipient" => $contact["addr"],
3296                                 "following" => "false",
3297                                 "sharing" => "false"];
3298
3299                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3300
3301                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3302         }
3303
3304         /**
3305          * @brief Checks a message body if it is a reshare
3306          *
3307          * @param string $body     The message body that is to be check
3308          * @param bool   $complete Should it be a complete check or a simple check?
3309          *
3310          * @return array|bool Reshare details or "false" if no reshare
3311          */
3312         public static function isReshare($body, $complete = true)
3313         {
3314                 $body = trim($body);
3315
3316                 // Skip if it isn't a pure repeated messages
3317                 // Does it start with a share?
3318                 if ((strpos($body, "[share") > 0) && $complete) {
3319                         return false;
3320                 }
3321
3322                 // Does it end with a share?
3323                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3324                         return false;
3325                 }
3326
3327                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3328                 // Skip if there is no shared message in there
3329                 if ($body == $attributes) {
3330                         return false;
3331                 }
3332
3333                 // If we don't do the complete check we quit here
3334
3335                 $guid = "";
3336                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3337                 if (!empty($matches[1])) {
3338                         $guid = $matches[1];
3339                 }
3340
3341                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3342                 if (!empty($matches[1])) {
3343                         $guid = $matches[1];
3344                 }
3345
3346                 if (($guid != "") && $complete) {
3347                         $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
3348                         $item = Item::selectFirst(['contact-id'], $condition);
3349                         if (DBA::isResult($item)) {
3350                                 $ret= [];
3351                                 $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
3352                                 $ret["root_guid"] = $guid;
3353                                 return $ret;
3354                         } elseif ($complete) {
3355                                 // We are resharing something that isn't a DFRN or Diaspora post.
3356                                 // So we have to return "false" on "$complete" to not trigger a reshare.
3357                                 return false;
3358                         }
3359                 } elseif (($guid == "") && $complete) {
3360                         return false;
3361                 }
3362
3363                 $ret["root_guid"] = $guid;
3364
3365                 $profile = "";
3366                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3367                 if (!empty($matches[1])) {
3368                         $profile = $matches[1];
3369                 }
3370
3371                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3372                 if (!empty($matches[1])) {
3373                         $profile = $matches[1];
3374                 }
3375
3376                 $ret= [];
3377
3378                 if ($profile != "") {
3379                         if (Contact::getIdForURL($profile)) {
3380                                 $author = Contact::getDetailsByURL($profile);
3381                                 $ret["root_handle"] = $author['addr'];
3382                         }
3383                 }
3384
3385                 if (empty($ret) && !$complete) {
3386                         return true;
3387                 }
3388
3389                 return $ret;
3390         }
3391
3392         /**
3393          * @brief Create an event array
3394          *
3395          * @param integer $event_id The id of the event
3396          *
3397          * @return array with event data
3398          */
3399         private static function buildEvent($event_id)
3400         {
3401                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3402                 if (!DBA::isResult($r)) {
3403                         return [];
3404                 }
3405
3406                 $event = $r[0];
3407
3408                 $eventdata = [];
3409
3410                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3411                 if (!DBA::isResult($r)) {
3412                         return [];
3413                 }
3414
3415                 $user = $r[0];
3416
3417                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3418                 if (!DBA::isResult($r)) {
3419                         return [];
3420                 }
3421
3422                 $owner = $r[0];
3423
3424                 $eventdata['author'] = self::myHandle($owner);
3425
3426                 if ($event['guid']) {
3427                         $eventdata['guid'] = $event['guid'];
3428                 }
3429
3430                 $mask = DateTimeFormat::ATOM;
3431
3432                 /// @todo - establish "all day" events in Friendica
3433                 $eventdata["all_day"] = "false";
3434
3435                 if (!$event['adjust']) {
3436                         $eventdata['timezone'] = $user['timezone'];
3437
3438                         if ($eventdata['timezone'] == "") {
3439                                 $eventdata['timezone'] = 'UTC';
3440                         }
3441                 }
3442
3443                 if ($event['start']) {
3444                         $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3445                 }
3446                 if ($event['finish'] && !$event['nofinish']) {
3447                         $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3448                 }
3449                 if ($event['summary']) {
3450                         $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3451                 }
3452                 if ($event['desc']) {
3453                         $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3454                 }
3455                 if ($event['location']) {
3456                         $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
3457                         $coord = Map::getCoordinates($event['location']);
3458
3459                         $location = [];
3460                         $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3461                         if (!empty($coord['lat']) && !empty($coord['lon'])) {
3462                                 $location["lat"] = $coord['lat'];
3463                                 $location["lng"] = $coord['lon'];
3464                         } else {
3465                                 $location["lat"] = 0;
3466                                 $location["lng"] = 0;
3467                         }
3468                         $eventdata['location'] = $location;
3469                 }
3470
3471                 return $eventdata;
3472         }
3473
3474         /**
3475          * @brief Create a post (status message or reshare)
3476          *
3477          * @param array $item  The item that will be exported
3478          * @param array $owner the array of the item owner
3479          *
3480          * @return array
3481          * 'type' -> Message type ("status_message" or "reshare")
3482          * 'message' -> Array of XML elements of the status
3483          */
3484         public static function buildStatus(array $item, array $owner)
3485         {
3486                 $cachekey = "diaspora:buildStatus:".$item['guid'];
3487
3488                 $result = Cache::get($cachekey);
3489                 if (!is_null($result)) {
3490                         return $result;
3491                 }
3492
3493                 $myaddr = self::myHandle($owner);
3494
3495                 $public = ($item["private"] ? "false" : "true");
3496
3497                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3498
3499                 // Detect a share element and do a reshare
3500                 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3501                         $message = ["author" => $myaddr,
3502                                         "guid" => $item["guid"],
3503                                         "created_at" => $created,
3504                                         "root_author" => $ret["root_handle"],
3505                                         "root_guid" => $ret["root_guid"],
3506                                         "provider_display_name" => $item["app"],
3507                                         "public" => $public];
3508
3509                         $type = "reshare";
3510                 } else {
3511                         $title = $item["title"];
3512                         $body = $item["body"];
3513
3514                         if ($item['author-link'] != $item['owner-link']) {
3515                                 require_once 'mod/share.php';
3516                                 $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
3517                                         "", $item['created'], $item['plink']) . $body . '[/share]';
3518                         }
3519
3520                         // convert to markdown
3521                         $body = html_entity_decode(BBCode::toMarkdown($body));
3522
3523                         // Adding the title
3524                         if (strlen($title)) {
3525                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3526                         }
3527
3528                         if ($item["attach"]) {
3529                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3530                                 if ($cnt) {
3531                                         $body .= "\n".L10n::t("Attachments:")."\n";
3532                                         foreach ($matches as $mtch) {
3533                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3534                                         }
3535                                 }
3536                         }
3537
3538                         $location = [];
3539
3540                         if ($item["location"] != "")
3541                                 $location["address"] = $item["location"];
3542
3543                         if ($item["coord"] != "") {
3544                                 $coord = explode(" ", $item["coord"]);
3545                                 $location["lat"] = $coord[0];
3546                                 $location["lng"] = $coord[1];
3547                         }
3548
3549                         $message = ["author" => $myaddr,
3550                                         "guid" => $item["guid"],
3551                                         "created_at" => $created,
3552                                         "public" => $public,
3553                                         "text" => $body,
3554                                         "provider_display_name" => $item["app"],
3555                                         "location" => $location];
3556
3557                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3558                         if (!isset($location["lat"]) || !isset($location["lng"])) {
3559                                 unset($message["location"]);
3560                         }
3561
3562                         if ($item['event-id'] > 0) {
3563                                 $event = self::buildEvent($item['event-id']);
3564                                 if (count($event)) {
3565                                         $message['event'] = $event;
3566
3567                                         if (!empty($event['location']['address']) &&
3568                                                 !empty($event['location']['lat']) &&
3569                                                 !empty($event['location']['lng'])) {
3570                                                 $message['location'] = $event['location'];
3571                                         }
3572
3573                                         /// @todo Once Diaspora supports it, we will remove the body and the location hack above
3574                                         // $message['text'] = '';
3575                                 }
3576                         }
3577
3578                         $type = "status_message";
3579                 }
3580
3581                 $msg = ["type" => $type, "message" => $message];
3582
3583                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3584
3585                 return $msg;
3586         }
3587
3588         /**
3589          * @brief Sends a post
3590          *
3591          * @param array $item         The item that will be exported
3592          * @param array $owner        the array of the item owner
3593          * @param array $contact      Target of the communication
3594          * @param bool  $public_batch Is it a public post?
3595          *
3596          * @return int The result of the transmission
3597          */
3598         public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
3599         {
3600                 $status = self::buildStatus($item, $owner);
3601
3602                 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3603         }
3604
3605         /**
3606          * @brief Creates a "like" object
3607          *
3608          * @param array $item  The item that will be exported
3609          * @param array $owner the array of the item owner
3610          *
3611          * @return array The data for a "like"
3612          */
3613         private static function constructLike(array $item, array $owner)
3614         {
3615                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3616                 if (!DBA::isResult($parent)) {
3617                         return false;
3618                 }
3619
3620                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3621                 $positive = null;
3622                 if ($item['verb'] === ACTIVITY_LIKE) {
3623                         $positive = "true";
3624                 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3625                         $positive = "false";
3626                 }
3627
3628                 return(["author" => self::myHandle($owner),
3629                                 "guid" => $item["guid"],
3630                                 "parent_guid" => $parent["guid"],
3631                                 "parent_type" => $target_type,
3632                                 "positive" => $positive,
3633                                 "author_signature" => ""]);
3634         }
3635
3636         /**
3637          * @brief Creates an "EventParticipation" object
3638          *
3639          * @param array $item  The item that will be exported
3640          * @param array $owner the array of the item owner
3641          *
3642          * @return array The data for an "EventParticipation"
3643          */
3644         private static function constructAttend(array $item, array $owner)
3645         {
3646                 $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
3647                 if (!DBA::isResult($parent)) {
3648                         return false;
3649                 }
3650
3651                 switch ($item['verb']) {
3652                         case ACTIVITY_ATTEND:
3653                                 $attend_answer = 'accepted';
3654                                 break;
3655                         case ACTIVITY_ATTENDNO:
3656                                 $attend_answer = 'declined';
3657                                 break;
3658                         case ACTIVITY_ATTENDMAYBE:
3659                                 $attend_answer = 'tentative';
3660                                 break;
3661                         default:
3662                                 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3663                                 return false;
3664                 }
3665
3666                 return(["author" => self::myHandle($owner),
3667                                 "guid" => $item["guid"],
3668                                 "parent_guid" => $parent["guid"],
3669                                 "status" => $attend_answer,
3670                                 "author_signature" => ""]);
3671         }
3672
3673         /**
3674          * @brief Creates the object for a comment
3675          *
3676          * @param array $item  The item that will be exported
3677          * @param array $owner the array of the item owner
3678          *
3679          * @return array The data for a comment
3680          */
3681         private static function constructComment(array $item, array $owner)
3682         {
3683                 $cachekey = "diaspora:constructComment:".$item['guid'];
3684
3685                 $result = Cache::get($cachekey);
3686                 if (!is_null($result)) {
3687                         return $result;
3688                 }
3689
3690                 $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
3691                 if (!DBA::isResult($parent)) {
3692                         return false;
3693                 }
3694
3695                 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3696                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3697
3698                 $comment = ["author" => self::myHandle($owner),
3699                                 "guid" => $item["guid"],
3700                                 "created_at" => $created,
3701                                 "parent_guid" => $parent["guid"],
3702                                 "text" => $text,
3703                                 "author_signature" => ""];
3704
3705                 // Send the thread parent guid only if it is a threaded comment
3706                 if ($item['thr-parent'] != $item['parent-uri']) {
3707                         $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3708                 }
3709
3710                 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3711
3712                 return($comment);
3713         }
3714
3715         /**
3716          * @brief Send a like or a comment
3717          *
3718          * @param array $item         The item that will be exported
3719          * @param array $owner        the array of the item owner
3720          * @param array $contact      Target of the communication
3721          * @param bool  $public_batch Is it a public post?
3722          *
3723          * @return int The result of the transmission
3724          */
3725         public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
3726         {
3727                 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3728                         $message = self::constructAttend($item, $owner);
3729                         $type = "event_participation";
3730                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3731                         $message = self::constructLike($item, $owner);
3732                         $type = "like";
3733                 } else {
3734                         $message = self::constructComment($item, $owner);
3735                         $type = "comment";
3736                 }
3737
3738                 if (!$message) {
3739                         return false;
3740                 }
3741
3742                 $message["author_signature"] = self::signature($owner, $message);
3743
3744                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3745         }
3746
3747         /**
3748          * @brief Creates a message from a signature record entry
3749          *
3750          * @param array $item      The item that will be exported
3751          * @param array $signature The entry of the "sign" record
3752          *
3753          * @return string The message
3754          */
3755         private static function messageFromSignature(array $item, array $signature)
3756         {
3757                 // Split the signed text
3758                 $signed_parts = explode(";", $signature['signed_text']);
3759
3760                 if ($item["deleted"]) {
3761                         $message = ["author" => $signature['signer'],
3762                                         "target_guid" => $signed_parts[0],
3763                                         "target_type" => $signed_parts[1]];
3764                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3765                         $message = ["author" => $signed_parts[4],
3766                                         "guid" => $signed_parts[1],
3767                                         "parent_guid" => $signed_parts[3],
3768                                         "parent_type" => $signed_parts[2],
3769                                         "positive" => $signed_parts[0],
3770                                         "author_signature" => $signature['signature'],
3771                                         "parent_author_signature" => ""];
3772                 } else {
3773                         // Remove the comment guid
3774                         $guid = array_shift($signed_parts);
3775
3776                         // Remove the parent guid
3777                         $parent_guid = array_shift($signed_parts);
3778
3779                         // Remove the handle
3780                         $handle = array_pop($signed_parts);
3781
3782                         // Glue the parts together
3783                         $text = implode(";", $signed_parts);
3784
3785                         $message = ["author" => $handle,
3786                                         "guid" => $guid,
3787                                         "parent_guid" => $parent_guid,
3788                                         "text" => implode(";", $signed_parts),
3789                                         "author_signature" => $signature['signature'],
3790                                         "parent_author_signature" => ""];
3791                 }
3792                 return $message;
3793         }
3794
3795         /**
3796          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3797          *
3798          * @param array $item         The item that will be exported
3799          * @param array $owner        the array of the item owner
3800          * @param array $contact      Target of the communication
3801          * @param bool  $public_batch Is it a public post?
3802          *
3803          * @return int The result of the transmission
3804          */
3805         public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
3806         {
3807                 if ($item["deleted"]) {
3808                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3809                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3810                         $type = "like";
3811                 } else {
3812                         $type = "comment";
3813                 }
3814
3815                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3816
3817                 // fetch the original signature
3818                 $fields = ['signed_text', 'signature', 'signer'];
3819                 $signature = DBA::selectFirst('sign', $fields, ['iid' => $item["id"]]);
3820                 if (!DBA::isResult($signature)) {
3821                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3822                         return false;
3823                 }
3824
3825                 // Old way - is used by the internal Friendica functions
3826                 /// @todo Change all signatur storing functions to the new format
3827                 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3828                         $message = self::messageFromSignature($item, $signature);
3829                 } else {// New way
3830                         $msg = json_decode($signature['signed_text'], true);
3831
3832                         $message = [];
3833                         if (is_array($msg)) {
3834                                 foreach ($msg as $field => $data) {
3835                                         if (!$item["deleted"]) {
3836                                                 if ($field == "diaspora_handle") {
3837                                                         $field = "author";
3838                                                 }
3839                                                 if ($field == "target_type") {
3840                                                         $field = "parent_type";
3841                                                 }
3842                                         }
3843
3844                                         $message[$field] = $data;
3845                                 }
3846                         } else {
3847                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3848                         }
3849                 }
3850
3851                 $message["parent_author_signature"] = self::signature($owner, $message);
3852
3853                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3854
3855                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3856         }
3857
3858         /**
3859          * @brief Sends a retraction (deletion) of a message, like or comment
3860          *
3861          * @param array $item         The item that will be exported
3862          * @param array $owner        the array of the item owner
3863          * @param array $contact      Target of the communication
3864          * @param bool  $public_batch Is it a public post?
3865          * @param bool  $relay        Is the retraction transmitted from a relay?
3866          *
3867          * @return int The result of the transmission
3868          */
3869         public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
3870         {
3871                 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
3872
3873                 $msg_type = "retraction";
3874
3875                 if ($item['id'] == $item['parent']) {
3876                         $target_type = "Post";
3877                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3878                         $target_type = "Like";
3879                 } else {
3880                         $target_type = "Comment";
3881                 }
3882
3883                 $message = ["author" => $itemaddr,
3884                                 "target_guid" => $item['guid'],
3885                                 "target_type" => $target_type];
3886
3887                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3888
3889                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3890         }
3891
3892         /**
3893          * @brief Sends a mail
3894          *
3895          * @param array $item    The item that will be exported
3896          * @param array $owner   The owner
3897          * @param array $contact Target of the communication
3898          *
3899          * @return int The result of the transmission
3900          */
3901         public static function sendMail(array $item, array $owner, array $contact)
3902         {
3903                 $myaddr = self::myHandle($owner);
3904
3905                 $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
3906                 if (!DBA::isResult($cnv)) {
3907                         logger("conversation not found.");
3908                         return;
3909                 }
3910
3911                 $conv = [
3912                         "author" => $cnv["creator"],
3913                         "guid" => $cnv["guid"],
3914                         "subject" => $cnv["subject"],
3915                         "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3916                         "participants" => $cnv["recips"]
3917                 ];
3918
3919                 $body = BBCode::toMarkdown($item["body"]);
3920                 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3921
3922                 $msg = [
3923                         "author" => $myaddr,
3924                         "guid" => $item["guid"],
3925                         "conversation_guid" => $cnv["guid"],
3926                         "text" => $body,
3927                         "created_at" => $created,
3928                 ];
3929
3930                 if ($item["reply"]) {
3931                         $message = $msg;
3932                         $type = "message";
3933                 } else {
3934                         $message = [
3935                                         "author" => $cnv["creator"],
3936                                         "guid" => $cnv["guid"],
3937                                         "subject" => $cnv["subject"],
3938                                         "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
3939                                         "participants" => $cnv["recips"],
3940                                         "message" => $msg];
3941
3942                         $type = "conversation";
3943                 }
3944
3945                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3946         }
3947
3948         /**
3949          * @brief Split a name into first name and last name
3950          *
3951          * @param string $name The name
3952          *
3953          * @return array The array with "first" and "last"
3954          */
3955         public static function splitName($name) {
3956                 $name = trim($name);
3957
3958                 // Is the name longer than 64 characters? Then cut the rest of it.
3959                 if (strlen($name) > 64) {
3960                         if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
3961                                 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
3962                         } else {
3963                                 $name = substr($name, 0, 64);
3964                         }
3965                 }
3966
3967                 // Take the first word as first name
3968                 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
3969                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3970                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3971                         return ['first' => $first, 'last' => $last];
3972                 }
3973
3974                 // Take the last word as last name
3975                 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
3976                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3977
3978                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
3979                         return ['first' => $first, 'last' => $last];
3980                 }
3981
3982                 // Take the first 32 characters if there is no space in the first 32 characters
3983                 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
3984                         $first = substr($name, 0, 32);
3985                         $last = substr($name, 32);
3986                         return ['first' => $first, 'last' => $last];
3987                 }
3988
3989                 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
3990                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
3991
3992                 // Check if the last name is longer than 32 characters
3993                 if (strlen($last) > 32) {
3994                         if (strpos($last, ' ') <= 32) {
3995                                 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
3996                         } else {
3997                                 $last = substr($last, 0, 32);
3998                         }
3999                 }
4000
4001                 return ['first' => $first, 'last' => $last];
4002         }
4003
4004         /**
4005          * @brief Create profile data
4006          *
4007          * @param int $uid The user id
4008          *
4009          * @return array The profile data
4010          */
4011         private static function createProfileData($uid)
4012         {
4013                 $r = q(
4014                         "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4015                         FROM `profile`
4016                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4017                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4018                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4019                         intval($uid)
4020                 );
4021
4022                 if (!$r) {
4023                         return [];
4024                 }
4025
4026                 $profile = $r[0];
4027                 $handle = $profile["addr"];
4028
4029                 $split_name = self::splitName($profile['name']);
4030                 $first = $split_name['first'];
4031                 $last = $split_name['last'];
4032
4033                 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4034                 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4035                 $small = System::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
4036                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4037
4038                 $dob = null;
4039                 $about = null;
4040                 $location = null;
4041                 $tags = null;
4042                 if ($searchable === 'true') {
4043                         $dob = '';
4044
4045                         if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4046                                 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4047                                 if ($year < 1004) {
4048                                         $year = 1004;
4049                                 }
4050                                 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4051                         }
4052
4053                         $about = $profile['about'];
4054                         $about = strip_tags(BBCode::convert($about));
4055
4056                         $location = Profile::formatLocation($profile);
4057                         $tags = '';
4058                         if ($profile['pub_keywords']) {
4059                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4060                                 $kw = str_replace('  ', ' ', $kw);
4061                                 $arr = explode(' ', $profile['pub_keywords']);
4062                                 if (count($arr)) {
4063                                         for ($x = 0; $x < 5; $x ++) {
4064                                                 if (!empty($arr[$x])) {
4065                                                         $tags .= '#'. trim($arr[$x]) .' ';
4066                                                 }
4067                                         }
4068                                 }
4069                         }
4070                         $tags = trim($tags);
4071                 }
4072
4073                 return ["author" => $handle,
4074                                 "first_name" => $first,
4075                                 "last_name" => $last,
4076                                 "image_url" => $large,
4077                                 "image_url_medium" => $medium,
4078                                 "image_url_small" => $small,
4079                                 "birthday" => $dob,
4080                                 "gender" => $profile['gender'],
4081                                 "bio" => $about,
4082                                 "location" => $location,
4083                                 "searchable" => $searchable,
4084                                 "nsfw" => "false",
4085                                 "tag_string" => $tags];
4086         }
4087
4088         /**
4089          * @brief Sends profile data
4090          *
4091          * @param int  $uid    The user id
4092          * @param bool $recips optional, default false
4093          * @return void
4094          */
4095         public static function sendProfile($uid, $recips = false)
4096         {
4097                 if (!$uid) {
4098                         return;
4099                 }
4100
4101                 $owner = User::getOwnerDataById($uid);
4102                 if (!$owner) {
4103                         return;
4104                 }
4105
4106                 if (!$recips) {
4107                         $recips = q(
4108                                 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4109                                 AND `uid` = %d AND `rel` != %d",
4110                                 DBA::escape(Protocol::DIASPORA),
4111                                 intval($uid),
4112                                 intval(Contact::SHARING)
4113                         );
4114                 }
4115
4116                 if (!$recips) {
4117                         return;
4118                 }
4119
4120                 $message = self::createProfileData($uid);
4121
4122                 foreach ($recips as $recip) {
4123                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4124                         self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4125                 }
4126         }
4127
4128         /**
4129          * @brief Stores the signature for likes that are created on our system
4130          *
4131          * @param array $contact The contact array of the "like"
4132          * @param int   $post_id The post id of the "like"
4133          *
4134          * @return bool Success
4135          */
4136         public static function storeLikeSignature(array $contact, $post_id)
4137         {
4138                 // Is the contact the owner? Then fetch the private key
4139                 if (!$contact['self'] || ($contact['uid'] == 0)) {
4140                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
4141                         return false;
4142                 }
4143
4144                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $contact["uid"]]);
4145                 if (!DBA::isResult($user)) {
4146                         return false;
4147                 }
4148
4149                 $contact["uprvkey"] = $user['prvkey'];
4150
4151                 $item = Item::selectFirst([], ['id' => $post_id]);
4152                 if (!DBA::isResult($item)) {
4153                         return false;
4154                 }
4155
4156                 if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4157                         return false;
4158                 }
4159
4160                 $message = self::constructLike($item, $contact);
4161                 if ($message === false) {
4162                         return false;
4163                 }
4164
4165                 $message["author_signature"] = self::signature($contact, $message);
4166
4167                 /*
4168                  * Now store the signature more flexible to dynamically support new fields.
4169                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4170                  */
4171                 DBA::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4172
4173                 logger('Stored diaspora like signature');
4174                 return true;
4175         }
4176
4177         /**
4178          * @brief Stores the signature for comments that are created on our system
4179          *
4180          * @param array  $item       The item array of the comment
4181          * @param array  $contact    The contact array of the item owner
4182          * @param string $uprvkey    The private key of the sender
4183          * @param int    $message_id The message id of the comment
4184          *
4185          * @return bool Success
4186          */
4187         public static function storeCommentSignature(array $item, array $contact, $uprvkey, $message_id)
4188         {
4189                 if ($uprvkey == "") {
4190                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4191                         return false;
4192                 }
4193
4194                 $contact["uprvkey"] = $uprvkey;
4195
4196                 $message = self::constructComment($item, $contact);
4197                 if ($message === false) {
4198                         return false;
4199                 }
4200
4201                 $message["author_signature"] = self::signature($contact, $message);
4202
4203                 /*
4204                  * Now store the signature more flexible to dynamically support new fields.
4205                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4206                  */
4207                 DBA::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4208
4209                 logger('Stored diaspora comment signature');
4210                 return true;
4211         }
4212 }