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