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