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