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