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