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