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