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