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