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