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