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