]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
added hints how to specify a port for the database connection
[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                 // We don't seem to like that person
936                 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
937                         return false;
938                 // We are following this person? Then it is okay
939                 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
940                         return true;
941                 // Is it a post to a community? That's good
942                 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
943                         return true;
944                 }
945                 // Messages for the global users and comments are always accepted
946                 if (($importer["uid"] == 0) || $is_comment) {
947                         return true;
948                 }
949
950                 return false;
951         }
952
953         /**
954          * @brief Fetches the contact id for a handle and checks if posting is allowed
955          *
956          * @param array $importer Array of the importer user
957          * @param string $handle The checked handle in the format user@domain.tld
958          * @param bool $is_comment Is the check for a comment?
959          *
960          * @return array The contact data
961          */
962         private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
963                 $contact = self::contact_by_handle($importer["uid"], $handle);
964                 if (!$contact) {
965                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
966                         // If a contact isn't found, we accept it anyway if it is a comment
967                         if ($is_comment) {
968                                 return $importer;
969                         } else {
970                                 return false;
971                         }
972                 }
973
974                 if (!self::post_allow($importer, $contact, $is_comment)) {
975                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
976                         return false;
977                 }
978                 return $contact;
979         }
980
981         /**
982          * @brief Does the message already exists on the system?
983          *
984          * @param int $uid The user id
985          * @param string $guid The guid of the message
986          *
987          * @return int|bool message id if the message already was stored into the system - or false.
988          */
989         private static function message_exists($uid, $guid) {
990                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
991                         intval($uid),
992                         dbesc($guid)
993                 );
994
995                 if (dbm::is_result($r)) {
996                         logger("message ".$guid." already exists for user ".$uid);
997                         return $r[0]["id"];
998                 }
999
1000                 return false;
1001         }
1002
1003         /**
1004          * @brief Checks for links to posts in a message
1005          *
1006          * @param array $item The item array
1007          */
1008         private static function fetch_guid($item) {
1009                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1010                         function ($match) use ($item){
1011                                 return(self::fetch_guid_sub($match, $item));
1012                         },$item["body"]);
1013         }
1014
1015         /**
1016          * @brief Checks for relative /people/* links in an item body to match local
1017          * contacts or prepends the remote host taken from the author link.
1018          *
1019          * @param string $body The item body to replace links from
1020          * @param string $author_link The author link for missing local contact fallback
1021          *
1022          * @return the replaced string
1023          */
1024         public function replace_people_guid($body, $author_link) {
1025                 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1026                         function ($match) use ($author_link) {
1027                                 // $match
1028                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1029                                 // 1 => '0123456789abcdef'
1030                                 // 2 => 'Foo Bar'
1031                                 $handle = self::url_from_contact_guid($match[1]);
1032
1033                                 if ($handle) {
1034                                         $return = '@[url='.$handle.']'.$match[2].'[/url]';
1035                                 } else {
1036                                         // No local match, restoring absolute remote URL from author scheme and host
1037                                         $author_url = parse_url($author_link);
1038                                         $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1039                                 }
1040
1041                                 return $return;
1042                         }, $body);
1043
1044                 return $return;
1045         }
1046
1047         /**
1048          * @brief sub function of "fetch_guid" which checks for links in messages
1049          *
1050          * @param array $match array containing a link that has to be checked for a message link
1051          * @param array $item The item array
1052          */
1053         private static function fetch_guid_sub($match, $item) {
1054                 if (!self::store_by_guid($match[1], $item["author-link"]))
1055                         self::store_by_guid($match[1], $item["owner-link"]);
1056         }
1057
1058         /**
1059          * @brief Fetches an item with a given guid from a given server
1060          *
1061          * @param string $guid the message guid
1062          * @param string $server The server address
1063          * @param int $uid The user id of the user
1064          *
1065          * @return int the message id of the stored message or false
1066          */
1067         private static function store_by_guid($guid, $server, $uid = 0) {
1068                 $serverparts = parse_url($server);
1069                 $server = $serverparts["scheme"]."://".$serverparts["host"];
1070
1071                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1072
1073                 $msg = self::message($guid, $server);
1074
1075                 if (!$msg)
1076                         return false;
1077
1078                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1079
1080                 // Now call the dispatcher
1081                 return self::dispatch_public($msg);
1082         }
1083
1084         /**
1085          * @brief Fetches a message from a server
1086          *
1087          * @param string $guid message guid
1088          * @param string $server The url of the server
1089          * @param int $level Endless loop prevention
1090          *
1091          * @return array
1092          *      'message' => The message XML
1093          *      'author' => The author handle
1094          *      'key' => The public key of the author
1095          */
1096         private static function message($guid, $server, $level = 0) {
1097
1098                 if ($level > 5)
1099                         return false;
1100
1101                 // This will work for new Diaspora servers and Friendica servers from 3.5
1102                 $source_url = $server."/fetch/post/".$guid;
1103                 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1104
1105                 $envelope = fetch_url($source_url);
1106                 if ($envelope) {
1107                         logger("Envelope was fetched.", LOGGER_DEBUG);
1108                         $x = self::verify_magic_envelope($envelope);
1109                         if (!$x)
1110                                 logger("Envelope could not be verified.", LOGGER_DEBUG);
1111                         else
1112                                 logger("Envelope was verified.", LOGGER_DEBUG);
1113                 } else
1114                         $x = false;
1115
1116                 // This will work for older Diaspora and Friendica servers
1117                 if (!$x) {
1118                         $source_url = $server."/p/".$guid.".xml";
1119                         logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1120
1121                         $x = fetch_url($source_url);
1122                         if (!$x)
1123                                 return false;
1124                 }
1125
1126                 $source_xml = parse_xml_string($x, false);
1127
1128                 if (!is_object($source_xml))
1129                         return false;
1130
1131                 if ($source_xml->post->reshare) {
1132                         // Reshare of a reshare - old Diaspora version
1133                         logger("Message is a reshare", LOGGER_DEBUG);
1134                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1135                 } elseif ($source_xml->getName() == "reshare") {
1136                         // Reshare of a reshare - new Diaspora version
1137                         logger("Message is a new reshare", LOGGER_DEBUG);
1138                         return self::message($source_xml->root_guid, $server, ++$level);
1139                 }
1140
1141                 $author = "";
1142
1143                 // Fetch the author - for the old and the new Diaspora version
1144                 if ($source_xml->post->status_message->diaspora_handle)
1145                         $author = (string)$source_xml->post->status_message->diaspora_handle;
1146                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1147                         $author = (string)$source_xml->author;
1148
1149                 // If this isn't a "status_message" then quit
1150                 if (!$author) {
1151                         logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1152                         return false;
1153                 }
1154
1155                 $msg = array("message" => $x, "author" => $author);
1156
1157                 $msg["key"] = self::key($msg["author"]);
1158
1159                 return $msg;
1160         }
1161
1162         /**
1163          * @brief Fetches the item record of a given guid
1164          *
1165          * @param int $uid The user id
1166          * @param string $guid message guid
1167          * @param string $author The handle of the item
1168          * @param array $contact The contact of the item owner
1169          *
1170          * @return array the item record
1171          */
1172         private static function parent_item($uid, $guid, $author, $contact) {
1173                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1174                                 `author-name`, `author-link`, `author-avatar`,
1175                                 `owner-name`, `owner-link`, `owner-avatar`
1176                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1177                         intval($uid), dbesc($guid));
1178
1179                 if (!$r) {
1180                         $result = self::store_by_guid($guid, $contact["url"], $uid);
1181
1182                         if (!$result) {
1183                                 $person = self::person_by_handle($author);
1184                                 $result = self::store_by_guid($guid, $person["url"], $uid);
1185                         }
1186
1187                         if ($result) {
1188                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1189
1190                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1191                                                 `author-name`, `author-link`, `author-avatar`,
1192                                                 `owner-name`, `owner-link`, `owner-avatar`
1193                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1194                                         intval($uid), dbesc($guid));
1195                         }
1196                 }
1197
1198                 if (!$r) {
1199                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
1200                         return false;
1201                 } else {
1202                         logger("parent item found: parent: ".$guid." - user: ".$uid);
1203                         return $r[0];
1204                 }
1205         }
1206
1207         /**
1208          * @brief returns contact details
1209          *
1210          * @param array $contact The default contact if the person isn't found
1211          * @param array $person The record of the person
1212          * @param int $uid The user id
1213          *
1214          * @return array
1215          *      'cid' => contact id
1216          *      'network' => network type
1217          */
1218         private static function author_contact_by_url($contact, $person, $uid) {
1219
1220                 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1221                         dbesc(normalise_link($person["url"])), intval($uid));
1222                 if ($r) {
1223                         $cid = $r[0]["id"];
1224                         $network = $r[0]["network"];
1225
1226                         // We are receiving content from a user that possibly is about to be terminated
1227                         // This means the user is vital, so we remove a possible termination date.
1228                         unmark_for_death($r[0]);
1229                 } else {
1230                         $cid = $contact["id"];
1231                         $network = NETWORK_DIASPORA;
1232                 }
1233
1234                 return array("cid" => $cid, "network" => $network);
1235         }
1236
1237         /**
1238          * @brief Is the profile a hubzilla profile?
1239          *
1240          * @param string $url The profile link
1241          *
1242          * @return bool is it a hubzilla server?
1243          */
1244         public static function is_redmatrix($url) {
1245                 return(strstr($url, "/channel/"));
1246         }
1247
1248         /**
1249          * @brief Generate a post link with a given handle and message guid
1250          *
1251          * @param string $addr The user handle
1252          * @param string $guid message guid
1253          *
1254          * @return string the post link
1255          */
1256         private static function plink($addr, $guid) {
1257                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1258
1259                 // Fallback
1260                 if (!$r)
1261                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1262
1263                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1264                 // So we try another way as well.
1265                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1266                 if ($s)
1267                         $r[0]["network"] = $s[0]["network"];
1268
1269                 if ($r[0]["network"] == NETWORK_DFRN)
1270                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1271
1272                 if (self::is_redmatrix($r[0]["url"]))
1273                         return $r[0]["url"]."/?f=&mid=".$guid;
1274
1275                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1276         }
1277
1278         /**
1279          * @brief Processes an account deletion
1280          *
1281          * @param array $importer Array of the importer user
1282          * @param object $data The message object
1283          *
1284          * @return bool Success
1285          */
1286         private static function receive_account_deletion($importer, $data) {
1287
1288                 /// @todo Account deletion should remove the contact from the global contacts as well
1289
1290                 $author = notags(unxmlify($data->author));
1291
1292                 $contact = self::contact_by_handle($importer["uid"], $author);
1293                 if (!$contact) {
1294                         logger("cannot find contact for author: ".$author);
1295                         return false;
1296                 }
1297
1298                 // We now remove the contact
1299                 contact_remove($contact["id"]);
1300                 return true;
1301         }
1302
1303         /**
1304          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1305          *
1306          * @param string $author Author handle
1307          * @param string $guid Message guid
1308          * @param boolean $onlyfound Only return uri when found in the database
1309          *
1310          * @return string The constructed uri or the one from our database
1311          */
1312         private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1313
1314                 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1315                 if (dbm::is_result($r)) {
1316                         return $r[0]["uri"];
1317                 } elseif (!$onlyfound) {
1318                         return $author.":".$guid;
1319                 }
1320
1321                 return "";
1322         }
1323
1324         /**
1325          * @brief Fetch the guid from our database with a given uri
1326          *
1327          * @param string $author Author handle
1328          * @param string $uri Message uri
1329          *
1330          * @return string The post guid
1331          */
1332         private static function get_guid_from_uri($uri, $uid) {
1333
1334                 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1335                 if (dbm::is_result($r)) {
1336                         return $r[0]["guid"];
1337                 } else {
1338                         return false;
1339                 }
1340         }
1341
1342         /**
1343          * @brief Find the best importer for a comment, like, ...
1344          *
1345          * @param string $guid The guid of the item
1346          *
1347          * @return array|boolean the origin owner of that post - or false
1348          */
1349         private static function importer_for_guid($guid) {
1350                 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1351
1352                 if (dbm::is_result($item)) {
1353                         logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1354                         $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1355                         if (dbm::is_result($contact)) {
1356                                 return $contact;
1357                         }
1358                 }
1359                 return false;
1360         }
1361
1362         /**
1363          * @brief Processes an incoming comment
1364          *
1365          * @param array $importer Array of the importer user
1366          * @param string $sender The sender of the message
1367          * @param object $data The message object
1368          * @param string $xml The original XML of the message
1369          *
1370          * @return int The message id of the generated comment or "false" if there was an error
1371          */
1372         private static function receive_comment($importer, $sender, $data, $xml) {
1373                 $author = notags(unxmlify($data->author));
1374                 $guid = notags(unxmlify($data->guid));
1375                 $parent_guid = notags(unxmlify($data->parent_guid));
1376                 $text = unxmlify($data->text);
1377
1378                 if (isset($data->created_at)) {
1379                         $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1380                 } else {
1381                         $created_at = datetime_convert();
1382                 }
1383
1384                 if (isset($data->thread_parent_guid)) {
1385                         $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1386                         $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1387                 } else {
1388                         $thr_uri = "";
1389                 }
1390
1391                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1392                 if (!$contact) {
1393                         return false;
1394                 }
1395
1396                 $message_id = self::message_exists($importer["uid"], $guid);
1397                 if ($message_id) {
1398                         return true;
1399                 }
1400
1401                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1402                 if (!$parent_item) {
1403                         return false;
1404                 }
1405
1406                 $person = self::person_by_handle($author);
1407                 if (!is_array($person)) {
1408                         logger("unable to find author details");
1409                         return false;
1410                 }
1411
1412                 // Fetch the contact id - if we know this contact
1413                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1414
1415                 $datarray = array();
1416
1417                 $datarray["uid"] = $importer["uid"];
1418                 $datarray["contact-id"] = $author_contact["cid"];
1419                 $datarray["network"]  = $author_contact["network"];
1420
1421                 $datarray["author-name"] = $person["name"];
1422                 $datarray["author-link"] = $person["url"];
1423                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1424
1425                 $datarray["owner-name"] = $contact["name"];
1426                 $datarray["owner-link"] = $contact["url"];
1427                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1428
1429                 $datarray["guid"] = $guid;
1430                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1431
1432                 $datarray["type"] = "remote-comment";
1433                 $datarray["verb"] = ACTIVITY_POST;
1434                 $datarray["gravity"] = GRAVITY_COMMENT;
1435
1436                 if ($thr_uri != "") {
1437                         $datarray["parent-uri"] = $thr_uri;
1438                 } else {
1439                         $datarray["parent-uri"] = $parent_item["uri"];
1440                 }
1441
1442                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1443
1444                 $datarray["protocol"] = PROTOCOL_DIASPORA;
1445                 $datarray["source"] = $xml;
1446
1447                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1448
1449                 $body = diaspora2bb($text);
1450
1451                 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1452
1453                 self::fetch_guid($datarray);
1454
1455                 $message_id = item_store($datarray);
1456
1457                 if ($message_id <= 0) {
1458                         return false;
1459                 }
1460
1461                 if ($message_id) {
1462                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1463                 }
1464
1465                 // If we are the origin of the parent we store the original data and notify our followers
1466                 if ($message_id AND $parent_item["origin"]) {
1467
1468                         // Formerly we stored the signed text, the signature and the author in different fields.
1469                         // We now store the raw data so that we are more flexible.
1470                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1471                                 intval($message_id),
1472                                 dbesc(json_encode($data))
1473                         );
1474
1475                         // notify others
1476                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1477                 }
1478
1479                 return true;
1480         }
1481
1482         /**
1483          * @brief processes and stores private messages
1484          *
1485          * @param array $importer Array of the importer user
1486          * @param array $contact The contact of the message
1487          * @param object $data The message object
1488          * @param array $msg Array of the processed message, author handle and key
1489          * @param object $mesg The private message
1490          * @param array $conversation The conversation record to which this message belongs
1491          *
1492          * @return bool "true" if it was successful
1493          */
1494         private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1495                 $author = notags(unxmlify($data->author));
1496                 $guid = notags(unxmlify($data->guid));
1497                 $subject = notags(unxmlify($data->subject));
1498
1499                 // "diaspora_handle" is the element name from the old version
1500                 // "author" is the element name from the new version
1501                 if ($mesg->author) {
1502                         $msg_author = notags(unxmlify($mesg->author));
1503                 } elseif ($mesg->diaspora_handle) {
1504                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1505                 } else {
1506                         return false;
1507                 }
1508
1509                 $msg_guid = notags(unxmlify($mesg->guid));
1510                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1511                 $msg_text = unxmlify($mesg->text);
1512                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1513
1514                 if ($msg_conversation_guid != $guid) {
1515                         logger("message conversation guid does not belong to the current conversation.");
1516                         return false;
1517                 }
1518
1519                 $body = diaspora2bb($msg_text);
1520                 $message_uri = $msg_author.":".$msg_guid;
1521
1522                 $person = self::person_by_handle($msg_author);
1523
1524                 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1525                         dbesc($msg_guid),
1526                         intval($importer["uid"])
1527                 );
1528                 if (dbm::is_result($r)) {
1529                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1530                         return false;
1531                 }
1532
1533                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1534                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1535                         intval($importer["uid"]),
1536                         dbesc($msg_guid),
1537                         intval($conversation["id"]),
1538                         dbesc($person["name"]),
1539                         dbesc($person["photo"]),
1540                         dbesc($person["url"]),
1541                         intval($contact["id"]),
1542                         dbesc($subject),
1543                         dbesc($body),
1544                         0,
1545                         0,
1546                         dbesc($message_uri),
1547                         dbesc($author.":".$guid),
1548                         dbesc($msg_created_at)
1549                 );
1550
1551                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1552                         dbesc(datetime_convert()),
1553                         intval($conversation["id"])
1554                 );
1555
1556                 notification(array(
1557                         "type" => NOTIFY_MAIL,
1558                         "notify_flags" => $importer["notify-flags"],
1559                         "language" => $importer["language"],
1560                         "to_name" => $importer["username"],
1561                         "to_email" => $importer["email"],
1562                         "uid" =>$importer["uid"],
1563                         "item" => array("subject" => $subject, "body" => $body),
1564                         "source_name" => $person["name"],
1565                         "source_link" => $person["url"],
1566                         "source_photo" => $person["thumb"],
1567                         "verb" => ACTIVITY_POST,
1568                         "otype" => "mail"
1569                 ));
1570                 return true;
1571         }
1572
1573         /**
1574          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1575          *
1576          * @param array $importer Array of the importer user
1577          * @param array $msg Array of the processed message, author handle and key
1578          * @param object $data The message object
1579          *
1580          * @return bool Success
1581          */
1582         private static function receive_conversation($importer, $msg, $data) {
1583                 $author = notags(unxmlify($data->author));
1584                 $guid = notags(unxmlify($data->guid));
1585                 $subject = notags(unxmlify($data->subject));
1586                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1587                 $participants = notags(unxmlify($data->participants));
1588
1589                 $messages = $data->message;
1590
1591                 if (!count($messages)) {
1592                         logger("empty conversation");
1593                         return false;
1594                 }
1595
1596                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1597                 if (!$contact)
1598                         return false;
1599
1600                 $conversation = null;
1601
1602                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1603                         intval($importer["uid"]),
1604                         dbesc($guid)
1605                 );
1606                 if ($c)
1607                         $conversation = $c[0];
1608                 else {
1609                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1610                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1611                                 intval($importer["uid"]),
1612                                 dbesc($guid),
1613                                 dbesc($author),
1614                                 dbesc($created_at),
1615                                 dbesc(datetime_convert()),
1616                                 dbesc($subject),
1617                                 dbesc($participants)
1618                         );
1619                         if ($r)
1620                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1621                                         intval($importer["uid"]),
1622                                         dbesc($guid)
1623                                 );
1624
1625                         if ($c)
1626                                 $conversation = $c[0];
1627                 }
1628                 if (!$conversation) {
1629                         logger("unable to create conversation.");
1630                         return false;
1631                 }
1632
1633                 foreach ($messages as $mesg)
1634                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1635
1636                 return true;
1637         }
1638
1639         /**
1640          * @brief Creates the body for a "like" message
1641          *
1642          * @param array $contact The contact that send us the "like"
1643          * @param array $parent_item The item array of the parent item
1644          * @param string $guid message guid
1645          *
1646          * @return string the body
1647          */
1648         private static function construct_like_body($contact, $parent_item, $guid) {
1649                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1650
1651                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1652                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1653                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1654
1655                 return sprintf($bodyverb, $ulink, $alink, $plink);
1656         }
1657
1658         /**
1659          * @brief Creates a XML object for a "like"
1660          *
1661          * @param array $importer Array of the importer user
1662          * @param array $parent_item The item array of the parent item
1663          *
1664          * @return string The XML
1665          */
1666         private static function construct_like_object($importer, $parent_item) {
1667                 $objtype = ACTIVITY_OBJ_NOTE;
1668                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1669                 $parent_body = $parent_item["body"];
1670
1671                 $xmldata = array("object" => array("type" => $objtype,
1672                                                 "local" => "1",
1673                                                 "id" => $parent_item["uri"],
1674                                                 "link" => $link,
1675                                                 "title" => "",
1676                                                 "content" => $parent_body));
1677
1678                 return xml::from_array($xmldata, $xml, true);
1679         }
1680
1681         /**
1682          * @brief Processes "like" messages
1683          *
1684          * @param array $importer Array of the importer user
1685          * @param string $sender The sender of the message
1686          * @param object $data The message object
1687          *
1688          * @return int The message id of the generated like or "false" if there was an error
1689          */
1690         private static function receive_like($importer, $sender, $data) {
1691                 $author = notags(unxmlify($data->author));
1692                 $guid = notags(unxmlify($data->guid));
1693                 $parent_guid = notags(unxmlify($data->parent_guid));
1694                 $parent_type = notags(unxmlify($data->parent_type));
1695                 $positive = notags(unxmlify($data->positive));
1696
1697                 // likes on comments aren't supported by Diaspora - only on posts
1698                 // But maybe this will be supported in the future, so we will accept it.
1699                 if (!in_array($parent_type, array("Post", "Comment")))
1700                         return false;
1701
1702                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1703                 if (!$contact)
1704                         return false;
1705
1706                 $message_id = self::message_exists($importer["uid"], $guid);
1707                 if ($message_id)
1708                         return true;
1709
1710                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1711                 if (!$parent_item)
1712                         return false;
1713
1714                 $person = self::person_by_handle($author);
1715                 if (!is_array($person)) {
1716                         logger("unable to find author details");
1717                         return false;
1718                 }
1719
1720                 // Fetch the contact id - if we know this contact
1721                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1722
1723                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1724                 // We would accept this anyhow.
1725                 if ($positive == "true")
1726                         $verb = ACTIVITY_LIKE;
1727                 else
1728                         $verb = ACTIVITY_DISLIKE;
1729
1730                 $datarray = array();
1731
1732                 $datarray["protocol"] = PROTOCOL_DIASPORA;
1733
1734                 $datarray["uid"] = $importer["uid"];
1735                 $datarray["contact-id"] = $author_contact["cid"];
1736                 $datarray["network"]  = $author_contact["network"];
1737
1738                 $datarray["author-name"] = $person["name"];
1739                 $datarray["author-link"] = $person["url"];
1740                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1741
1742                 $datarray["owner-name"] = $contact["name"];
1743                 $datarray["owner-link"] = $contact["url"];
1744                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1745
1746                 $datarray["guid"] = $guid;
1747                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1748
1749                 $datarray["type"] = "activity";
1750                 $datarray["verb"] = $verb;
1751                 $datarray["gravity"] = GRAVITY_LIKE;
1752                 $datarray["parent-uri"] = $parent_item["uri"];
1753
1754                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1755                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1756
1757                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1758
1759                 $message_id = item_store($datarray);
1760
1761                 if ($message_id <= 0) {
1762                         return false;
1763                 }
1764
1765                 if ($message_id) {
1766                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1767                 }
1768
1769                 // If we are the origin of the parent we store the original data and notify our followers
1770                 if ($message_id AND $parent_item["origin"]) {
1771
1772                         // Formerly we stored the signed text, the signature and the author in different fields.
1773                         // We now store the raw data so that we are more flexible.
1774                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1775                                 intval($message_id),
1776                                 dbesc(json_encode($data))
1777                         );
1778
1779                         // notify others
1780                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1781                 }
1782
1783                 return true;
1784         }
1785
1786         /**
1787          * @brief Processes private messages
1788          *
1789          * @param array $importer Array of the importer user
1790          * @param object $data The message object
1791          *
1792          * @return bool Success?
1793          */
1794         private static function receive_message($importer, $data) {
1795                 $author = notags(unxmlify($data->author));
1796                 $guid = notags(unxmlify($data->guid));
1797                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1798                 $text = unxmlify($data->text);
1799                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1800
1801                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1802                 if (!$contact) {
1803                         return false;
1804                 }
1805
1806                 $conversation = null;
1807
1808                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1809                         intval($importer["uid"]),
1810                         dbesc($conversation_guid)
1811                 );
1812                 if ($c) {
1813                         $conversation = $c[0];
1814                 } else {
1815                         logger("conversation not available.");
1816                         return false;
1817                 }
1818
1819                 $message_uri = $author.":".$guid;
1820
1821                 $person = self::person_by_handle($author);
1822                 if (!$person) {
1823                         logger("unable to find author details");
1824                         return false;
1825                 }
1826
1827                 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1828                         dbesc($guid),
1829                         intval($importer["uid"])
1830                 );
1831                 if (dbm::is_result($r)) {
1832                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1833                         return false;
1834                 }
1835
1836                 $body = diaspora2bb($text);
1837
1838                 $body = self::replace_people_guid($body, $person["url"]);
1839
1840                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1841                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1842                         intval($importer["uid"]),
1843                         dbesc($guid),
1844                         intval($conversation["id"]),
1845                         dbesc($person["name"]),
1846                         dbesc($person["photo"]),
1847                         dbesc($person["url"]),
1848                         intval($contact["id"]),
1849                         dbesc($conversation["subject"]),
1850                         dbesc($body),
1851                         0,
1852                         1,
1853                         dbesc($message_uri),
1854                         dbesc($author.":".$conversation["guid"]),
1855                         dbesc($created_at)
1856                 );
1857
1858                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1859                         dbesc(datetime_convert()),
1860                         intval($conversation["id"])
1861                 );
1862
1863                 return true;
1864         }
1865
1866         /**
1867          * @brief Processes participations - unsupported by now
1868          *
1869          * @param array $importer Array of the importer user
1870          * @param object $data The message object
1871          *
1872          * @return bool always true
1873          */
1874         private static function receive_participation($importer, $data) {
1875                 // I'm not sure if we can fully support this message type
1876                 return true;
1877         }
1878
1879         /**
1880          * @brief Processes photos - unneeded
1881          *
1882          * @param array $importer Array of the importer user
1883          * @param object $data The message object
1884          *
1885          * @return bool always true
1886          */
1887         private static function receive_photo($importer, $data) {
1888                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1889                 return true;
1890         }
1891
1892         /**
1893          * @brief Processes poll participations - unssupported
1894          *
1895          * @param array $importer Array of the importer user
1896          * @param object $data The message object
1897          *
1898          * @return bool always true
1899          */
1900         private static function receive_poll_participation($importer, $data) {
1901                 // We don't support polls by now
1902                 return true;
1903         }
1904
1905         /**
1906          * @brief Processes incoming profile updates
1907          *
1908          * @param array $importer Array of the importer user
1909          * @param object $data The message object
1910          *
1911          * @return bool Success
1912          */
1913         private static function receive_profile($importer, $data) {
1914                 $author = strtolower(notags(unxmlify($data->author)));
1915
1916                 $contact = self::contact_by_handle($importer["uid"], $author);
1917                 if (!$contact)
1918                         return false;
1919
1920                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1921                 $image_url = unxmlify($data->image_url);
1922                 $birthday = unxmlify($data->birthday);
1923                 $gender = unxmlify($data->gender);
1924                 $about = diaspora2bb(unxmlify($data->bio));
1925                 $location = diaspora2bb(unxmlify($data->location));
1926                 $searchable = (unxmlify($data->searchable) == "true");
1927                 $nsfw = (unxmlify($data->nsfw) == "true");
1928                 $tags = unxmlify($data->tag_string);
1929
1930                 $tags = explode("#", $tags);
1931
1932                 $keywords = array();
1933                 foreach ($tags as $tag) {
1934                         $tag = trim(strtolower($tag));
1935                         if ($tag != "")
1936                                 $keywords[] = $tag;
1937                 }
1938
1939                 $keywords = implode(", ", $keywords);
1940
1941                 $handle_parts = explode("@", $author);
1942                 $nick = $handle_parts[0];
1943
1944                 if ($name === "")
1945                         $name = $handle_parts[0];
1946
1947                 if ( preg_match("|^https?://|", $image_url) === 0)
1948                         $image_url = "http://".$handle_parts[1].$image_url;
1949
1950                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1951
1952                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1953
1954                 $birthday = str_replace("1000", "1901", $birthday);
1955
1956                 if ($birthday != "")
1957                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1958
1959                 // this is to prevent multiple birthday notifications in a single year
1960                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1961
1962                 if (substr($birthday,5) === substr($contact["bd"],5))
1963                         $birthday = $contact["bd"];
1964
1965                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1966                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1967                         dbesc($name),
1968                         dbesc($nick),
1969                         dbesc($author),
1970                         dbesc(datetime_convert()),
1971                         dbesc($birthday),
1972                         dbesc($location),
1973                         dbesc($about),
1974                         dbesc($keywords),
1975                         dbesc($gender),
1976                         intval($contact["id"]),
1977                         intval($importer["uid"])
1978                 );
1979
1980                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1981                                         "photo" => $image_url, "name" => $name, "location" => $location,
1982                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1983                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1984                                         "hide" => !$searchable, "nsfw" => $nsfw);
1985
1986                 $gcid = update_gcontact($gcontact);
1987
1988                 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1989
1990                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1991
1992                 return true;
1993         }
1994
1995         /**
1996          * @brief Processes incoming friend requests
1997          *
1998          * @param array $importer Array of the importer user
1999          * @param array $contact The contact that send the request
2000          */
2001         private static function receive_request_make_friend($importer, $contact) {
2002
2003                 $a = get_app();
2004
2005                 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
2006                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
2007                                 intval(CONTACT_IS_FRIEND),
2008                                 intval($contact["id"]),
2009                                 intval($importer["uid"])
2010                         );
2011                 }
2012                 // send notification
2013
2014                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2015                         intval($importer["uid"])
2016                 );
2017
2018                 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
2019
2020                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2021                                 intval($importer["uid"])
2022                         );
2023
2024                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2025
2026                         if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2027
2028                                 $arr = array();
2029                                 $arr["protocol"] = PROTOCOL_DIASPORA;
2030                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2031                                 $arr["uid"] = $importer["uid"];
2032                                 $arr["contact-id"] = $self[0]["id"];
2033                                 $arr["wall"] = 1;
2034                                 $arr["type"] = 'wall';
2035                                 $arr["gravity"] = 0;
2036                                 $arr["origin"] = 1;
2037                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2038                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2039                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2040                                 $arr["verb"] = ACTIVITY_FRIEND;
2041                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2042
2043                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2044                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2045                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2046                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2047
2048                                 $arr["object"] = self::construct_new_friend_object($contact);
2049
2050                                 $arr["last-child"] = 1;
2051
2052                                 $arr["allow_cid"] = $user[0]["allow_cid"];
2053                                 $arr["allow_gid"] = $user[0]["allow_gid"];
2054                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
2055                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
2056
2057                                 $i = item_store($arr);
2058                                 if ($i)
2059                                         proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2060                         }
2061                 }
2062         }
2063
2064         /**
2065          * @brief Creates a XML object for a "new friend" message
2066          *
2067          * @param array $contact Array of the contact
2068          *
2069          * @return string The XML
2070          */
2071         private static function construct_new_friend_object($contact) {
2072                 $objtype = ACTIVITY_OBJ_PERSON;
2073                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2074                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2075
2076                 $xmldata = array("object" => array("type" => $objtype,
2077                                                 "title" => $contact["name"],
2078                                                 "id" => $contact["url"]."/".$contact["name"],
2079                                                 "link" => $link));
2080
2081                 return xml::from_array($xmldata, $xml, true);
2082         }
2083
2084         /**
2085          * @brief Processes incoming sharing notification
2086          *
2087          * @param array $importer Array of the importer user
2088          * @param object $data The message object
2089          *
2090          * @return bool Success
2091          */
2092         private static function receive_contact_request($importer, $data) {
2093                 $author = unxmlify($data->author);
2094                 $recipient = unxmlify($data->recipient);
2095
2096                 if (!$author || !$recipient) {
2097                         return false;
2098                 }
2099
2100                 // the current protocol version doesn't know these fields
2101                 // That means that we will assume their existance
2102                 if (isset($data->following)) {
2103                         $following = (unxmlify($data->following) == "true");
2104                 } else {
2105                         $following = true;
2106                 }
2107
2108                 if (isset($data->sharing)) {
2109                         $sharing = (unxmlify($data->sharing) == "true");
2110                 } else {
2111                         $sharing = true;
2112                 }
2113
2114                 $contact = self::contact_by_handle($importer["uid"],$author);
2115
2116                 // perhaps we were already sharing with this person. Now they're sharing with us.
2117                 // That makes us friends.
2118                 if ($contact) {
2119                         if ($following AND $sharing) {
2120                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2121                                 self::receive_request_make_friend($importer, $contact);
2122
2123                                 // refetch the contact array
2124                                 $contact = self::contact_by_handle($importer["uid"],$author);
2125
2126                                 // If we are now friends, we are sending a share message.
2127                                 // Normally we needn't to do so, but the first message could have been vanished.
2128                                 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2129                                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2130                                         if ($u) {
2131                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2132                                                 $ret = self::send_share($u[0], $contact);
2133                                         }
2134                                 }
2135                                 return true;
2136                         } else { /// @todo Handle all possible variations of adding and retracting of permissions
2137                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2138                                 return false;
2139                         }
2140                 }
2141
2142                 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2143                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2144                         return false;
2145                 } elseif (!$following AND !$sharing) {
2146                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2147                         return false;
2148                 } elseif (!$following AND $sharing) {
2149                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2150                 } elseif ($following AND $sharing) {
2151                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2152                 } elseif ($following AND !$sharing) {
2153                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2154                 }
2155
2156                 $ret = self::person_by_handle($author);
2157
2158                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2159                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2160                         return false;
2161                 }
2162
2163                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2164
2165                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2166                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2167                         intval($importer["uid"]),
2168                         dbesc($ret["network"]),
2169                         dbesc($ret["addr"]),
2170                         datetime_convert(),
2171                         dbesc($ret["url"]),
2172                         dbesc(normalise_link($ret["url"])),
2173                         dbesc($batch),
2174                         dbesc($ret["name"]),
2175                         dbesc($ret["nick"]),
2176                         dbesc($ret["photo"]),
2177                         dbesc($ret["pubkey"]),
2178                         dbesc($ret["notify"]),
2179                         dbesc($ret["poll"]),
2180                         1,
2181                         2
2182                 );
2183
2184                 // find the contact record we just created
2185
2186                 $contact_record = self::contact_by_handle($importer["uid"],$author);
2187
2188                 if (!$contact_record) {
2189                         logger("unable to locate newly created contact record.");
2190                         return;
2191                 }
2192
2193                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2194
2195                 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2196
2197                 if (intval($def_gid))
2198                         group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2199
2200                 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2201
2202                 if ($importer["page-flags"] == PAGE_NORMAL) {
2203
2204                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2205
2206                         $hash = random_string().(string)time();   // Generate a confirm_key
2207
2208                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2209                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2210                                 intval($importer["uid"]),
2211                                 intval($contact_record["id"]),
2212                                 0,
2213                                 0,
2214                                 dbesc(t("Sharing notification from Diaspora network")),
2215                                 dbesc($hash),
2216                                 dbesc(datetime_convert())
2217                         );
2218                 } else {
2219
2220                         // automatic friend approval
2221
2222                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2223
2224                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2225
2226                         // technically they are sharing with us (CONTACT_IS_SHARING),
2227                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2228                         // we are going to change the relationship and make them a follower.
2229
2230                         if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2231                                 $new_relation = CONTACT_IS_FRIEND;
2232                         elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2233                                 $new_relation = CONTACT_IS_SHARING;
2234                         else
2235                                 $new_relation = CONTACT_IS_FOLLOWER;
2236
2237                         $r = q("UPDATE `contact` SET `rel` = %d,
2238                                 `name-date` = '%s',
2239                                 `uri-date` = '%s',
2240                                 `blocked` = 0,
2241                                 `pending` = 0,
2242                                 `writable` = 1
2243                                 WHERE `id` = %d
2244                                 ",
2245                                 intval($new_relation),
2246                                 dbesc(datetime_convert()),
2247                                 dbesc(datetime_convert()),
2248                                 intval($contact_record["id"])
2249                         );
2250
2251                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2252                         if ($u) {
2253                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2254                                 $ret = self::send_share($u[0], $contact_record);
2255
2256                                 // Send the profile data, maybe it weren't transmitted before
2257                                 self::send_profile($importer["uid"], array($contact_record));
2258                         }
2259                 }
2260
2261                 return true;
2262         }
2263
2264         /**
2265          * @brief Fetches a message with a given guid
2266          *
2267          * @param string $guid message guid
2268          * @param string $orig_author handle of the original post
2269          * @param string $author handle of the sharer
2270          *
2271          * @return array The fetched item
2272          */
2273         private static function original_item($guid, $orig_author, $author) {
2274
2275                 // Do we already have this item?
2276                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2277                                 `author-name`, `author-link`, `author-avatar`
2278                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2279                         dbesc($guid));
2280
2281                 if (dbm::is_result($r)) {
2282                         logger("reshared message ".$guid." already exists on system.");
2283
2284                         // Maybe it is already a reshared item?
2285                         // Then refetch the content, if it is a reshare from a reshare.
2286                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2287                         if (self::is_reshare($r[0]["body"], true)) {
2288                                 $r = array();
2289                         } elseif (self::is_reshare($r[0]["body"], false)) {
2290                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2291
2292                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2293
2294                                 // Add OEmbed and other information to the body
2295                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2296
2297                                 return $r[0];
2298                         } else {
2299                                 return $r[0];
2300                         }
2301                 }
2302
2303                 if (!dbm::is_result($r)) {
2304                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2305                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2306                         $item_id = self::store_by_guid($guid, $server);
2307
2308                         if (!$item_id) {
2309                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2310                                 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2311                                 $item_id = self::store_by_guid($guid, $server);
2312                         }
2313
2314                         if ($item_id) {
2315                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2316                                                 `author-name`, `author-link`, `author-avatar`
2317                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2318                                         intval($item_id));
2319
2320                                 if (dbm::is_result($r)) {
2321                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2322                                         if (self::is_reshare($r[0]["body"], false)) {
2323                                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2324                                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2325                                         }
2326
2327                                         return $r[0];
2328                                 }
2329
2330                         }
2331                 }
2332                 return false;
2333         }
2334
2335         /**
2336          * @brief Processes a reshare message
2337          *
2338          * @param array $importer Array of the importer user
2339          * @param object $data The message object
2340          * @param string $xml The original XML of the message
2341          *
2342          * @return int the message id
2343          */
2344         private static function receive_reshare($importer, $data, $xml) {
2345                 $author = notags(unxmlify($data->author));
2346                 $guid = notags(unxmlify($data->guid));
2347                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2348                 $root_author = notags(unxmlify($data->root_author));
2349                 $root_guid = notags(unxmlify($data->root_guid));
2350                 /// @todo handle unprocessed property "provider_display_name"
2351                 $public = notags(unxmlify($data->public));
2352
2353                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2354                 if (!$contact) {
2355                         return false;
2356                 }
2357
2358                 $message_id = self::message_exists($importer["uid"], $guid);
2359                 if ($message_id) {
2360                         return true;
2361                 }
2362
2363                 $original_item = self::original_item($root_guid, $root_author, $author);
2364                 if (!$original_item) {
2365                         return false;
2366                 }
2367
2368                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2369
2370                 $datarray = array();
2371
2372                 $datarray["uid"] = $importer["uid"];
2373                 $datarray["contact-id"] = $contact["id"];
2374                 $datarray["network"]  = NETWORK_DIASPORA;
2375
2376                 $datarray["author-name"] = $contact["name"];
2377                 $datarray["author-link"] = $contact["url"];
2378                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2379
2380                 $datarray["owner-name"] = $datarray["author-name"];
2381                 $datarray["owner-link"] = $datarray["author-link"];
2382                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2383
2384                 $datarray["guid"] = $guid;
2385                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2386
2387                 $datarray["verb"] = ACTIVITY_POST;
2388                 $datarray["gravity"] = GRAVITY_PARENT;
2389
2390                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2391                 $datarray["source"] = $xml;
2392
2393                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2394                                         $original_item["guid"], $original_item["created"], $orig_url);
2395                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2396
2397                 $datarray["tag"] = $original_item["tag"];
2398                 $datarray["app"]  = $original_item["app"];
2399
2400                 $datarray["plink"] = self::plink($author, $guid);
2401                 $datarray["private"] = (($public == "false") ? 1 : 0);
2402                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2403
2404                 $datarray["object-type"] = $original_item["object-type"];
2405
2406                 self::fetch_guid($datarray);
2407                 $message_id = item_store($datarray);
2408
2409                 if ($message_id) {
2410                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2411                         return true;
2412                 } else {
2413                         return false;
2414                 }
2415         }
2416
2417         /**
2418          * @brief Processes retractions
2419          *
2420          * @param array $importer Array of the importer user
2421          * @param array $contact The contact of the item owner
2422          * @param object $data The message object
2423          *
2424          * @return bool success
2425          */
2426         private static function item_retraction($importer, $contact, $data) {
2427                 $author = notags(unxmlify($data->author));
2428                 $target_guid = notags(unxmlify($data->target_guid));
2429                 $target_type = notags(unxmlify($data->target_type));
2430
2431                 $person = self::person_by_handle($author);
2432                 if (!is_array($person)) {
2433                         logger("unable to find author detail for ".$author);
2434                         return false;
2435                 }
2436
2437                 if (!isset($contact["url"])) {
2438                         $contact["url"] = $person["url"];
2439                 }
2440
2441                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2442                         dbesc($target_guid),
2443                         intval($importer["uid"])
2444                 );
2445                 if (!$r) {
2446                         logger("Target guid ".$target_guid." was not found for user ".$importer["uid"]);
2447                         return false;
2448                 }
2449
2450                 // Check if the sender is the thread owner
2451                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2452                         intval($r[0]["parent"]));
2453
2454                 // Only delete it if the parent author really fits
2455                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2456                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2457                         return false;
2458                 }
2459
2460                 // 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
2461                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2462                         dbesc(datetime_convert()),
2463                         dbesc(datetime_convert()),
2464                         intval($r[0]["id"])
2465                 );
2466                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2467
2468                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2469
2470                 // Now check if the retraction needs to be relayed by us
2471                 if ($p[0]["origin"]) {
2472                         // notify others
2473                         proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2474                 }
2475
2476                 return true;
2477         }
2478
2479         /**
2480          * @brief Receives retraction messages
2481          *
2482          * @param array $importer Array of the importer user
2483          * @param string $sender The sender of the message
2484          * @param object $data The message object
2485          *
2486          * @return bool Success
2487          */
2488         private static function receive_retraction($importer, $sender, $data) {
2489                 $target_type = notags(unxmlify($data->target_type));
2490
2491                 $contact = self::contact_by_handle($importer["uid"], $sender);
2492                 if (!$contact AND (in_array($target_type, array("Contact", "Person")))) {
2493                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2494                         return false;
2495                 }
2496
2497                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2498
2499                 switch ($target_type) {
2500                         case "Comment":
2501                         case "Like":
2502                         case "Post": // "Post" will be supported in a future version
2503                         case "Reshare":
2504                         case "StatusMessage":
2505                                 return self::item_retraction($importer, $contact, $data);
2506
2507                         case "Contact":
2508                         case "Person":
2509                                 /// @todo What should we do with an "unshare"?
2510                                 // Removing the contact isn't correct since we still can read the public items
2511                                 contact_remove($contact["id"]);
2512                                 return true;
2513
2514                         default:
2515                                 logger("Unknown target type ".$target_type);
2516                                 return false;
2517                 }
2518                 return true;
2519         }
2520
2521         /**
2522          * @brief Receives status messages
2523          *
2524          * @param array $importer Array of the importer user
2525          * @param object $data The message object
2526          * @param string $xml The original XML of the message
2527          *
2528          * @return int The message id of the newly created item
2529          */
2530         private static function receive_status_message($importer, $data, $xml) {
2531                 $author = notags(unxmlify($data->author));
2532                 $guid = notags(unxmlify($data->guid));
2533                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2534                 $public = notags(unxmlify($data->public));
2535                 $text = unxmlify($data->text);
2536                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2537
2538                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2539                 if (!$contact) {
2540                         return false;
2541                 }
2542
2543                 $message_id = self::message_exists($importer["uid"], $guid);
2544                 if ($message_id) {
2545                         return true;
2546                 }
2547
2548                 $address = array();
2549                 if ($data->location) {
2550                         foreach ($data->location->children() AS $fieldname => $data) {
2551                                 $address[$fieldname] = notags(unxmlify($data));
2552                         }
2553                 }
2554
2555                 $body = diaspora2bb($text);
2556
2557                 $datarray = array();
2558
2559                 // Attach embedded pictures to the body
2560                 if ($data->photo) {
2561                         foreach ($data->photo AS $photo) {
2562                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2563                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2564                         }
2565
2566                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2567                 } else {
2568                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2569
2570                         // Add OEmbed and other information to the body
2571                         if (!self::is_redmatrix($contact["url"])) {
2572                                 $body = add_page_info_to_body($body, false, true);
2573                         }
2574                 }
2575
2576                 /// @todo enable support for polls
2577                 //if ($data->poll) {
2578                 //      foreach ($data->poll AS $poll)
2579                 //              print_r($poll);
2580                 //      die("poll!\n");
2581                 //}
2582
2583                 /// @todo enable support for events
2584
2585                 $datarray["uid"] = $importer["uid"];
2586                 $datarray["contact-id"] = $contact["id"];
2587                 $datarray["network"] = NETWORK_DIASPORA;
2588
2589                 $datarray["author-name"] = $contact["name"];
2590                 $datarray["author-link"] = $contact["url"];
2591                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2592
2593                 $datarray["owner-name"] = $datarray["author-name"];
2594                 $datarray["owner-link"] = $datarray["author-link"];
2595                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2596
2597                 $datarray["guid"] = $guid;
2598                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2599
2600                 $datarray["verb"] = ACTIVITY_POST;
2601                 $datarray["gravity"] = GRAVITY_PARENT;
2602
2603                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2604                 $datarray["source"] = $xml;
2605
2606                 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2607
2608                 if ($provider_display_name != "") {
2609                         $datarray["app"] = $provider_display_name;
2610                 }
2611
2612                 $datarray["plink"] = self::plink($author, $guid);
2613                 $datarray["private"] = (($public == "false") ? 1 : 0);
2614                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2615
2616                 if (isset($address["address"])) {
2617                         $datarray["location"] = $address["address"];
2618                 }
2619
2620                 if (isset($address["lat"]) AND isset($address["lng"])) {
2621                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2622                 }
2623
2624                 self::fetch_guid($datarray);
2625                 $message_id = item_store($datarray);
2626
2627                 if ($message_id) {
2628                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2629                         return true;
2630                 } else {
2631                         return false;
2632                 }
2633         }
2634
2635         /* ************************************************************************************** *
2636          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2637          * ************************************************************************************** */
2638
2639         /**
2640          * @brief returnes the handle of a contact
2641          *
2642          * @param array $me contact array
2643          *
2644          * @return string the handle in the format user@domain.tld
2645          */
2646         private static function my_handle($contact) {
2647                 if ($contact["addr"] != "") {
2648                         return $contact["addr"];
2649                 }
2650
2651                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2652                 // So - just in case - we build the the address here.
2653                 if ($contact["nickname"] != "") {
2654                         $nick = $contact["nickname"];
2655                 } else {
2656                         $nick = $contact["nick"];
2657                 }
2658
2659                 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2660         }
2661
2662         /**
2663          * @brief Creates the envelope for the "fetch" endpoint
2664          *
2665          * @param string $msg The message that is to be transmitted
2666          * @param array $user The record of the sender
2667          *
2668          * @return string The envelope
2669          */
2670
2671         public static function build_magic_envelope($msg, $user) {
2672
2673                 $b64url_data = base64url_encode($msg);
2674                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2675
2676                 $key_id = base64url_encode(self::my_handle($user));
2677                 $type = "application/xml";
2678                 $encoding = "base64url";
2679                 $alg = "RSA-SHA256";
2680                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2681                 $signature = rsa_sign($signable_data, $user["prvkey"]);
2682                 $sig = base64url_encode($signature);
2683
2684                 $xmldata = array("me:env" => array("me:data" => $data,
2685                                                         "@attributes" => array("type" => $type),
2686                                                         "me:encoding" => $encoding,
2687                                                         "me:alg" => $alg,
2688                                                         "me:sig" => $sig,
2689                                                         "@attributes2" => array("key_id" => $key_id)));
2690
2691                 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2692
2693                 return xml::from_array($xmldata, $xml, false, $namespaces);
2694         }
2695
2696         /**
2697          * @brief Creates the envelope for a public message
2698          *
2699          * @param string $msg The message that is to be transmitted
2700          * @param array $user The record of the sender
2701          * @param array $contact Target of the communication
2702          * @param string $prvkey The private key of the sender
2703          * @param string $pubkey The public key of the receiver
2704          *
2705          * @return string The envelope
2706          */
2707         private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2708
2709                 logger("Message: ".$msg, LOGGER_DATA);
2710
2711                 $handle = self::my_handle($user);
2712
2713                 $b64url_data = base64url_encode($msg);
2714
2715                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2716
2717                 $type = "application/xml";
2718                 $encoding = "base64url";
2719                 $alg = "RSA-SHA256";
2720
2721                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2722
2723                 $signature = rsa_sign($signable_data,$prvkey);
2724                 $sig = base64url_encode($signature);
2725
2726                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2727                                                         "me:env" => array("me:encoding" => $encoding,
2728                                                         "me:alg" => $alg,
2729                                                         "me:data" => $data,
2730                                                         "@attributes" => array("type" => $type),
2731                                                         "me:sig" => $sig)));
2732
2733                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2734                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2735
2736                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2737
2738                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2739                 return $magic_env;
2740         }
2741
2742         /**
2743          * @brief Creates the envelope for a private message
2744          *
2745          * @param string $msg The message that is to be transmitted
2746          * @param array $user The record of the sender
2747          * @param array $contact Target of the communication
2748          * @param string $prvkey The private key of the sender
2749          * @param string $pubkey The public key of the receiver
2750          *
2751          * @return string The envelope
2752          */
2753         private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2754
2755                 logger("Message: ".$msg, LOGGER_DATA);
2756
2757                 // without a public key nothing will work
2758
2759                 if (!$pubkey) {
2760                         logger("pubkey missing: contact id: ".$contact["id"]);
2761                         return false;
2762                 }
2763
2764                 $inner_aes_key = openssl_random_pseudo_bytes(32);
2765                 $b_inner_aes_key = base64_encode($inner_aes_key);
2766                 $inner_iv = openssl_random_pseudo_bytes(16);
2767                 $b_inner_iv = base64_encode($inner_iv);
2768
2769                 $outer_aes_key = openssl_random_pseudo_bytes(32);
2770                 $b_outer_aes_key = base64_encode($outer_aes_key);
2771                 $outer_iv = openssl_random_pseudo_bytes(16);
2772                 $b_outer_iv = base64_encode($outer_iv);
2773
2774                 $handle = self::my_handle($user);
2775
2776                 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2777
2778                 $b64_data = base64_encode($inner_encrypted);
2779
2780
2781                 $b64url_data = base64url_encode($b64_data);
2782                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2783
2784                 $type = "application/xml";
2785                 $encoding = "base64url";
2786                 $alg = "RSA-SHA256";
2787
2788                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2789
2790                 $signature = rsa_sign($signable_data,$prvkey);
2791                 $sig = base64url_encode($signature);
2792
2793                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2794                                                         "aes_key" => $b_inner_aes_key,
2795                                                         "author_id" => $handle));
2796
2797                 $decrypted_header = xml::from_array($xmldata, $xml, true);
2798
2799                 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2800
2801                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2802
2803                 $encrypted_outer_key_bundle = "";
2804                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2805
2806                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2807
2808                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2809
2810                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2811                                                                 "ciphertext" => base64_encode($ciphertext)));
2812                 $cipher_json = base64_encode($encrypted_header_json_object);
2813
2814                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2815                                                 "me:env" => array("me:encoding" => $encoding,
2816                                                                 "me:alg" => $alg,
2817                                                                 "me:data" => $data,
2818                                                                 "@attributes" => array("type" => $type),
2819                                                                 "me:sig" => $sig)));
2820
2821                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2822                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2823
2824                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2825
2826                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2827                 return $magic_env;
2828         }
2829
2830         /**
2831          * @brief Create the envelope for a message
2832          *
2833          * @param string $msg The message that is to be transmitted
2834          * @param array $user The record of the sender
2835          * @param array $contact Target of the communication
2836          * @param string $prvkey The private key of the sender
2837          * @param string $pubkey The public key of the receiver
2838          * @param bool $public Is the message public?
2839          *
2840          * @return string The message that will be transmitted to other servers
2841          */
2842         private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2843
2844                 if ($public)
2845                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2846                 else
2847                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2848
2849                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2850                 $slap = "xml=".urlencode(urlencode($magic_env));
2851                 return $slap;
2852         }
2853
2854         /**
2855          * @brief Creates a signature for a message
2856          *
2857          * @param array $owner the array of the owner of the message
2858          * @param array $message The message that is to be signed
2859          *
2860          * @return string The signature
2861          */
2862         private static function signature($owner, $message) {
2863                 $sigmsg = $message;
2864                 unset($sigmsg["author_signature"]);
2865                 unset($sigmsg["parent_author_signature"]);
2866
2867                 $signed_text = implode(";", $sigmsg);
2868
2869                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2870         }
2871
2872         /**
2873          * @brief Transmit a message to a target server
2874          *
2875          * @param array $owner the array of the item owner
2876          * @param array $contact Target of the communication
2877          * @param string $slap The message that is to be transmitted
2878          * @param bool $public_batch Is it a public post?
2879          * @param bool $queue_run Is the transmission called from the queue?
2880          * @param string $guid message guid
2881          *
2882          * @return int Result of the transmission
2883          */
2884         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2885
2886                 $a = get_app();
2887
2888                 $enabled = intval(get_config("system", "diaspora_enabled"));
2889                 if (!$enabled)
2890                         return 200;
2891
2892                 $logid = random_string(4);
2893                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2894                 if (!$dest_url) {
2895                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2896                         return 0;
2897                 }
2898
2899                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2900
2901                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2902                         $return_code = 0;
2903                 } else {
2904                         if (!intval(get_config("system", "diaspora_test"))) {
2905                                 post_url($dest_url."/", $slap);
2906                                 $return_code = $a->get_curl_code();
2907                         } else {
2908                                 logger("test_mode");
2909                                 return 200;
2910                         }
2911                 }
2912
2913                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2914
2915                 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2916                         logger("queue message");
2917
2918                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2919                                 intval($contact["id"]),
2920                                 dbesc(NETWORK_DIASPORA),
2921                                 dbesc($slap),
2922                                 intval($public_batch)
2923                         );
2924                         if ($r) {
2925                                 logger("add_to_queue ignored - identical item already in queue");
2926                         } else {
2927                                 // queue message for redelivery
2928                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2929
2930                                 // The message could not be delivered. We mark the contact as "dead"
2931                                 mark_for_death($contact);
2932                         }
2933                 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2934                         // We successfully delivered a message, the contact is alive
2935                         unmark_for_death($contact);
2936                 }
2937
2938                 return(($return_code) ? $return_code : (-1));
2939         }
2940
2941
2942         /**
2943          * @brief Build the post xml
2944          *
2945          * @param string $type The message type
2946          * @param array $message The message data
2947          *
2948          * @return string The post XML
2949          */
2950         public static function build_post_xml($type, $message) {
2951
2952                 $data = array("XML" => array("post" => array($type => $message)));
2953                 return xml::from_array($data, $xml);
2954         }
2955
2956         /**
2957          * @brief Builds and transmit messages
2958          *
2959          * @param array $owner the array of the item owner
2960          * @param array $contact Target of the communication
2961          * @param string $type The message type
2962          * @param array $message The message data
2963          * @param bool $public_batch Is it a public post?
2964          * @param string $guid message guid
2965          * @param bool $spool Should the transmission be spooled or transmitted?
2966          *
2967          * @return int Result of the transmission
2968          */
2969         private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2970
2971                 $msg = self::build_post_xml($type, $message);
2972
2973                 logger('message: '.$msg, LOGGER_DATA);
2974                 logger('send guid '.$guid, LOGGER_DEBUG);
2975
2976                 // Fallback if the private key wasn't transmitted in the expected field
2977                 if ($owner['uprvkey'] == "")
2978                         $owner['uprvkey'] = $owner['prvkey'];
2979
2980                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2981
2982                 if ($spool) {
2983                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2984                         return true;
2985                 } else
2986                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2987
2988                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2989
2990                 return $return_code;
2991         }
2992
2993         /**
2994          * @brief Sends a "share" message
2995          *
2996          * @param array $owner the array of the item owner
2997          * @param array $contact Target of the communication
2998          *
2999          * @return int The result of the transmission
3000          */
3001         public static function send_share($owner,$contact) {
3002
3003                 $message = array("sender_handle" => self::my_handle($owner),
3004                                 "recipient_handle" => $contact["addr"]);
3005
3006                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3007
3008                 return self::build_and_transmit($owner, $contact, "request", $message);
3009         }
3010
3011         /**
3012          * @brief sends an "unshare"
3013          *
3014          * @param array $owner the array of the item owner
3015          * @param array $contact Target of the communication
3016          *
3017          * @return int The result of the transmission
3018          */
3019         public static function send_unshare($owner,$contact) {
3020
3021                 $message = array("post_guid" => $owner["guid"],
3022                                 "diaspora_handle" => self::my_handle($owner),
3023                                 "type" => "Person");
3024
3025                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3026
3027                 return self::build_and_transmit($owner, $contact, "retraction", $message);
3028         }
3029
3030         /**
3031          * @brief Checks a message body if it is a reshare
3032          *
3033          * @param string $body The message body that is to be check
3034          * @param bool $complete Should it be a complete check or a simple check?
3035          *
3036          * @return array|bool Reshare details or "false" if no reshare
3037          */
3038         public static function is_reshare($body, $complete = true) {
3039                 $body = trim($body);
3040
3041                 // Skip if it isn't a pure repeated messages
3042                 // Does it start with a share?
3043                 if ((strpos($body, "[share") > 0) AND $complete)
3044                         return(false);
3045
3046                 // Does it end with a share?
3047                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3048                         return(false);
3049
3050                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3051                 // Skip if there is no shared message in there
3052                 if ($body == $attributes)
3053                         return(false);
3054
3055                 // If we don't do the complete check we quit here
3056                 if (!$complete)
3057                         return true;
3058
3059                 $guid = "";
3060                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3061                 if ($matches[1] != "")
3062                         $guid = $matches[1];
3063
3064                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3065                 if ($matches[1] != "")
3066                         $guid = $matches[1];
3067
3068                 if ($guid != "") {
3069                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3070                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3071                         if ($r) {
3072                                 $ret= array();
3073                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3074                                 $ret["root_guid"] = $guid;
3075                                 return($ret);
3076                         }
3077                 }
3078
3079                 $profile = "";
3080                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3081                 if ($matches[1] != "")
3082                         $profile = $matches[1];
3083
3084                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3085                 if ($matches[1] != "")
3086                         $profile = $matches[1];
3087
3088                 $ret= array();
3089
3090                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3091                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
3092                         return(false);
3093
3094                 $link = "";
3095                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3096                 if ($matches[1] != "")
3097                         $link = $matches[1];
3098
3099                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3100                 if ($matches[1] != "")
3101                         $link = $matches[1];
3102
3103                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3104                 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
3105                         return(false);
3106
3107                 return($ret);
3108         }
3109
3110         /**
3111          * @brief Create an event array
3112          *
3113          * @param integer $event_id The id of the event
3114          *
3115          * @return array with event data
3116          */
3117         private static function build_event($event_id) {
3118
3119                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3120                 if (!dbm::is_result($r)) {
3121                         return array();
3122                 }
3123
3124                 $event = $r[0];
3125
3126                 $eventdata = array();
3127
3128                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3129                 if (!dbm::is_result($r)) {
3130                         return array();
3131                 }
3132
3133                 $user = $r[0];
3134
3135                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3136                 if (!dbm::is_result($r)) {
3137                         return array();
3138                 }
3139
3140                 $owner = $r[0];
3141
3142                 $eventdata['author'] = self::my_handle($owner);
3143
3144                 if ($event['guid']) {
3145                         $eventdata['guid'] = $event['guid'];
3146                 }
3147
3148                 $mask = 'Y-m-d\TH:i:s\Z';
3149
3150                 /// @todo - establish "all day" events in Friendica
3151                 $eventdata["all_day"] = "false";
3152
3153                 if (!$event['adjust']) {
3154                         $eventdata['timezone'] = $user['timezone'];
3155
3156                         if ($eventdata['timezone'] == "") {
3157                                 $eventdata['timezone'] = 'UTC';
3158                         }
3159                 }
3160
3161                 if ($event['start']) {
3162                         $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3163                 }
3164                 if ($event['finish'] AND !$event['nofinish']) {
3165                         $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3166                 }
3167                 if ($event['summary']) {
3168                         $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3169                 }
3170                 if ($event['desc']) {
3171                         $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3172                 }
3173                 if ($event['location']) {
3174                         $location = array();
3175                         $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3176                         $location["lat"] = 0;
3177                         $location["lng"] = 0;
3178                         $eventdata['location'] = $location;
3179                 }
3180
3181                 return $eventdata;
3182         }
3183
3184         /**
3185          * @brief Create a post (status message or reshare)
3186          *
3187          * @param array $item The item that will be exported
3188          * @param array $owner the array of the item owner
3189          *
3190          * @return array
3191          * 'type' -> Message type ("status_message" or "reshare")
3192          * 'message' -> Array of XML elements of the status
3193          */
3194         public static function build_status($item, $owner) {
3195
3196                 $cachekey = "diaspora:build_status:".$item['guid'];
3197
3198                 $result = Cache::get($cachekey);
3199                 if (!is_null($result)) {
3200                         return $result;
3201                 }
3202
3203                 $myaddr = self::my_handle($owner);
3204
3205                 $public = (($item["private"]) ? "false" : "true");
3206
3207                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3208
3209                 // Detect a share element and do a reshare
3210                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3211                         $message = array("root_diaspora_id" => $ret["root_handle"],
3212                                         "root_guid" => $ret["root_guid"],
3213                                         "guid" => $item["guid"],
3214                                         "diaspora_handle" => $myaddr,
3215                                         "public" => $public,
3216                                         "created_at" => $created,
3217                                         "provider_display_name" => $item["app"]);
3218
3219                         $type = "reshare";
3220                 } else {
3221                         $title = $item["title"];
3222                         $body = $item["body"];
3223
3224                         // convert to markdown
3225                         $body = html_entity_decode(bb2diaspora($body));
3226
3227                         // Adding the title
3228                         if (strlen($title))
3229                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3230
3231                         if ($item["attach"]) {
3232                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3233                                 if (cnt) {
3234                                         $body .= "\n".t("Attachments:")."\n";
3235                                         foreach ($matches as $mtch)
3236                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3237                                 }
3238                         }
3239
3240                         $location = array();
3241
3242                         if ($item["location"] != "")
3243                                 $location["address"] = $item["location"];
3244
3245                         if ($item["coord"] != "") {
3246                                 $coord = explode(" ", $item["coord"]);
3247                                 $location["lat"] = $coord[0];
3248                                 $location["lng"] = $coord[1];
3249                         }
3250
3251                         $message = array("raw_message" => $body,
3252                                         "location" => $location,
3253                                         "guid" => $item["guid"],
3254                                         "diaspora_handle" => $myaddr,
3255                                         "public" => $public,
3256                                         "created_at" => $created,
3257                                         "provider_display_name" => $item["app"]);
3258
3259                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3260                         if (!isset($location["lat"]) OR !isset($location["lng"])) {
3261                                 unset($message["location"]);
3262                         }
3263
3264                         if ($item['event-id'] > 0) {
3265                                 $event = self::build_event($item['event-id']);
3266                                 if (count($event)) {
3267                                         $message['event'] = $event;
3268
3269                                         /// @todo Once Diaspora supports it, we will remove the body
3270                                         // $message['raw_message'] = '';
3271                                 }
3272                         }
3273
3274                         $type = "status_message";
3275                 }
3276
3277                 $msg = array("type" => $type, "message" => $message);
3278
3279                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3280
3281                 return $msg;
3282         }
3283
3284         /**
3285          * @brief Sends a post
3286          *
3287          * @param array $item The item that will be exported
3288          * @param array $owner the array of the item owner
3289          * @param array $contact Target of the communication
3290          * @param bool $public_batch Is it a public post?
3291          *
3292          * @return int The result of the transmission
3293          */
3294         public static function send_status($item, $owner, $contact, $public_batch = false) {
3295
3296                 $status = self::build_status($item, $owner);
3297
3298                 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3299         }
3300
3301         /**
3302          * @brief Creates a "like" object
3303          *
3304          * @param array $item The item that will be exported
3305          * @param array $owner the array of the item owner
3306          *
3307          * @return array The data for a "like"
3308          */
3309         private static function construct_like($item, $owner) {
3310
3311                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3312                         dbesc($item["thr-parent"]));
3313                 if (!dbm::is_result($p))
3314                         return false;
3315
3316                 $parent = $p[0];
3317
3318                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3319                 if ($item['verb'] === ACTIVITY_LIKE) {
3320                         $positive = "true";
3321                 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3322                         $positive = "false";
3323                 }
3324
3325                 return(array("positive" => $positive,
3326                                 "guid" => $item["guid"],
3327                                 "target_type" => $target_type,
3328                                 "parent_guid" => $parent["guid"],
3329                                 "author_signature" => "",
3330                                 "diaspora_handle" => self::my_handle($owner)));
3331         }
3332
3333         /**
3334          * @brief Creates an "EventParticipation" object
3335          *
3336          * @param array $item The item that will be exported
3337          * @param array $owner the array of the item owner
3338          *
3339          * @return array The data for an "EventParticipation"
3340          */
3341         private static function construct_attend($item, $owner) {
3342
3343                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3344                         dbesc($item["thr-parent"]));
3345                 if (!dbm::is_result($p))
3346                         return false;
3347
3348                 $parent = $p[0];
3349
3350                 switch ($item['verb']) {
3351                         case ACTIVITY_ATTEND:
3352                                 $attend_answer = 'accepted';
3353                                 break;
3354                         case ACTIVITY_ATTENDNO:
3355                                 $attend_answer = 'declined';
3356                                 break;
3357                         case ACTIVITY_ATTENDMAYBE:
3358                                 $attend_answer = 'tentative';
3359                                 break;
3360                         default:
3361                                 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3362                                 return false;
3363                 }
3364
3365                 return(array("author" => self::my_handle($owner),
3366                                 "guid" => $item["guid"],
3367                                 "parent_guid" => $parent["guid"],
3368                                 "status" => $attend_answer,
3369                                 "author_signature" => ""));
3370         }
3371
3372         /**
3373          * @brief Creates the object for a comment
3374          *
3375          * @param array $item The item that will be exported
3376          * @param array $owner the array of the item owner
3377          *
3378          * @return array The data for a comment
3379          */
3380         private static function construct_comment($item, $owner) {
3381
3382                 $cachekey = "diaspora:construct_comment:".$item['guid'];
3383
3384                 $result = Cache::get($cachekey);
3385                 if (!is_null($result)) {
3386                         return $result;
3387                 }
3388
3389                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3390                         intval($item["parent"]),
3391                         intval($item["parent"])
3392                 );
3393
3394                 if (!dbm::is_result($p))
3395                         return false;
3396
3397                 $parent = $p[0];
3398
3399                 $text = html_entity_decode(bb2diaspora($item["body"]));
3400                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3401
3402                 $comment = array("guid" => $item["guid"],
3403                                 "parent_guid" => $parent["guid"],
3404                                 "author_signature" => "",
3405                                 "text" => $text,
3406                                 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3407                                 "diaspora_handle" => self::my_handle($owner));
3408
3409                 // Send the thread parent guid only if it is a threaded comment
3410                 if ($item['thr-parent'] != $item['parent-uri']) {
3411                         $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3412                 }
3413
3414                 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3415
3416                 return($comment);
3417         }
3418
3419         /**
3420          * @brief Send a like or a comment
3421          *
3422          * @param array $item The item that will be exported
3423          * @param array $owner the array of the item owner
3424          * @param array $contact Target of the communication
3425          * @param bool $public_batch Is it a public post?
3426          *
3427          * @return int The result of the transmission
3428          */
3429         public static function send_followup($item,$owner,$contact,$public_batch = false) {
3430
3431                 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3432                         $message = self::construct_attend($item, $owner);
3433                         $type = "event_participation";
3434                 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3435                         $message = self::construct_like($item, $owner);
3436                         $type = "like";
3437                 } else {
3438                         $message = self::construct_comment($item, $owner);
3439                         $type = "comment";
3440                 }
3441
3442                 if (!$message)
3443                         return false;
3444
3445                 $message["author_signature"] = self::signature($owner, $message);
3446
3447                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3448         }
3449
3450         /**
3451          * @brief Creates a message from a signature record entry
3452          *
3453          * @param array $item The item that will be exported
3454          * @param array $signature The entry of the "sign" record
3455          *
3456          * @return string The message
3457          */
3458         private static function message_from_signature($item, $signature) {
3459
3460                 // Split the signed text
3461                 $signed_parts = explode(";", $signature['signed_text']);
3462
3463                 if ($item["deleted"])
3464                         $message = array("parent_author_signature" => "",
3465                                         "target_guid" => $signed_parts[0],
3466                                         "target_type" => $signed_parts[1],
3467                                         "sender_handle" => $signature['signer'],
3468                                         "target_author_signature" => $signature['signature']);
3469                 elseif ($item['verb'] === ACTIVITY_LIKE)
3470                         $message = array("positive" => $signed_parts[0],
3471                                         "guid" => $signed_parts[1],
3472                                         "target_type" => $signed_parts[2],
3473                                         "parent_guid" => $signed_parts[3],
3474                                         "parent_author_signature" => "",
3475                                         "author_signature" => $signature['signature'],
3476                                         "diaspora_handle" => $signed_parts[4]);
3477                 else {
3478                         // Remove the comment guid
3479                         $guid = array_shift($signed_parts);
3480
3481                         // Remove the parent guid
3482                         $parent_guid = array_shift($signed_parts);
3483
3484                         // Remove the handle
3485                         $handle = array_pop($signed_parts);
3486
3487                         // Glue the parts together
3488                         $text = implode(";", $signed_parts);
3489
3490                         $message = array("guid" => $guid,
3491                                         "parent_guid" => $parent_guid,
3492                                         "parent_author_signature" => "",
3493                                         "author_signature" => $signature['signature'],
3494                                         "text" => implode(";", $signed_parts),
3495                                         "diaspora_handle" => $handle);
3496                 }
3497                 return $message;
3498         }
3499
3500         /**
3501          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3502          *
3503          * @param array $item The item that will be exported
3504          * @param array $owner the array of the item owner
3505          * @param array $contact Target of the communication
3506          * @param bool $public_batch Is it a public post?
3507          *
3508          * @return int The result of the transmission
3509          */
3510         public static function send_relay($item, $owner, $contact, $public_batch = false) {
3511
3512                 if ($item["deleted"])
3513                         return self::send_retraction($item, $owner, $contact, $public_batch, true);
3514                 elseif ($item['verb'] === ACTIVITY_LIKE)
3515                         $type = "like";
3516                 else
3517                         $type = "comment";
3518
3519                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3520
3521                 // fetch the original signature
3522
3523                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3524                         intval($item["id"]));
3525
3526                 if (!$r) {
3527                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3528                         return false;
3529                 }
3530
3531                 $signature = $r[0];
3532
3533                 // Old way - is used by the internal Friendica functions
3534                 /// @todo Change all signatur storing functions to the new format
3535                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3536                         $message = self::message_from_signature($item, $signature);
3537                 else {// New way
3538                         $msg = json_decode($signature['signed_text'], true);
3539
3540                         $message = array();
3541                         if (is_array($msg)) {
3542                                 foreach ($msg AS $field => $data) {
3543                                         if (!$item["deleted"]) {
3544                                                 if ($field == "author")
3545                                                         $field = "diaspora_handle";
3546                                                 if ($field == "parent_type")
3547                                                         $field = "target_type";
3548                                         }
3549
3550                                         $message[$field] = $data;
3551                                 }
3552                         } else
3553                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3554                 }
3555
3556                 $message["parent_author_signature"] = self::signature($owner, $message);
3557
3558                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3559
3560                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3561         }
3562
3563         /**
3564          * @brief Sends a retraction (deletion) of a message, like or comment
3565          *
3566          * @param array $item The item that will be exported
3567          * @param array $owner the array of the item owner
3568          * @param array $contact Target of the communication
3569          * @param bool $public_batch Is it a public post?
3570          * @param bool $relay Is the retraction transmitted from a relay?
3571          *
3572          * @return int The result of the transmission
3573          */
3574         public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3575
3576                 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3577
3578                 // Check whether the retraction is for a top-level post or whether it's a relayable
3579                 if ($item["uri"] !== $item["parent-uri"]) {
3580                         $msg_type = "relayable_retraction";
3581                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3582                 } else {
3583                         $msg_type = "signed_retraction";
3584                         $target_type = "StatusMessage";
3585                 }
3586
3587                 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3588                         $signature = "parent_author_signature";
3589                 else
3590                         $signature = "target_author_signature";
3591
3592                 $signed_text = $item["guid"].";".$target_type;
3593
3594                 $message = array("target_guid" => $item['guid'],
3595                                 "target_type" => $target_type,
3596                                 "sender_handle" => $itemaddr,
3597                                 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3598
3599                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3600
3601                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3602         }
3603
3604         /**
3605          * @brief Sends a mail
3606          *
3607          * @param array $item The item that will be exported
3608          * @param array $owner The owner
3609          * @param array $contact Target of the communication
3610          *
3611          * @return int The result of the transmission
3612          */
3613         public static function send_mail($item, $owner, $contact) {
3614
3615                 $myaddr = self::my_handle($owner);
3616
3617                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3618                         intval($item["convid"]),
3619                         intval($item["uid"])
3620                 );
3621
3622                 if (!dbm::is_result($r)) {
3623                         logger("conversation not found.");
3624                         return;
3625                 }
3626                 $cnv = $r[0];
3627
3628                 $conv = array(
3629                         "guid" => $cnv["guid"],
3630                         "subject" => $cnv["subject"],
3631                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3632                         "diaspora_handle" => $cnv["creator"],
3633                         "participant_handles" => $cnv["recips"]
3634                 );
3635
3636                 $body = bb2diaspora($item["body"]);
3637                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3638
3639                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3640                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3641
3642                 $msg = array(
3643                         "guid" => $item["guid"],
3644                         "parent_guid" => $cnv["guid"],
3645                         "parent_author_signature" => $sig,
3646                         "author_signature" => $sig,
3647                         "text" => $body,
3648                         "created_at" => $created,
3649                         "diaspora_handle" => $myaddr,
3650                         "conversation_guid" => $cnv["guid"]
3651                 );
3652
3653                 if ($item["reply"]) {
3654                         $message = $msg;
3655                         $type = "message";
3656                 } else {
3657                         $message = array("guid" => $cnv["guid"],
3658                                         "subject" => $cnv["subject"],
3659                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3660                                         "message" => $msg,
3661                                         "diaspora_handle" => $cnv["creator"],
3662                                         "participant_handles" => $cnv["recips"]);
3663
3664                         $type = "conversation";
3665                 }
3666
3667                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3668         }
3669
3670         /**
3671          * @brief Sends profile data
3672          *
3673          * @param int $uid The user id
3674          */
3675         public static function send_profile($uid, $recips = false) {
3676
3677                 if (!$uid)
3678                         return;
3679
3680                 if (!$recips)
3681                         $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3682                                 AND `uid` = %d AND `rel` != %d",
3683                                 dbesc(NETWORK_DIASPORA),
3684                                 intval($uid),
3685                                 intval(CONTACT_IS_SHARING)
3686                         );
3687                 if (!$recips)
3688                         return;
3689
3690                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3691                         FROM `profile`
3692                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3693                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3694                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3695                         intval($uid)
3696                 );
3697
3698                 if (!$r)
3699                         return;
3700
3701                 $profile = $r[0];
3702
3703                 $handle = $profile["addr"];
3704                 $first = ((strpos($profile['name'],' ')
3705                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3706                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3707                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3708                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3709                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
3710                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3711
3712                 if ($searchable === 'true') {
3713                         $dob = '1000-00-00';
3714
3715                         if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3716                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3717
3718                         $about = $profile['about'];
3719                         $about = strip_tags(bbcode($about));
3720
3721                         $location = formatted_location($profile);
3722                         $tags = '';
3723                         if ($profile['pub_keywords']) {
3724                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
3725                                 $kw = str_replace('  ',' ',$kw);
3726                                 $arr = explode(' ',$profile['pub_keywords']);
3727                                 if (count($arr)) {
3728                                         for ($x = 0; $x < 5; $x ++) {
3729                                                 if (trim($arr[$x]))
3730                                                         $tags .= '#'. trim($arr[$x]) .' ';
3731                                         }
3732                                 }
3733                         }
3734                         $tags = trim($tags);
3735                 }
3736
3737                 $message = array("diaspora_handle" => $handle,
3738                                 "first_name" => $first,
3739                                 "last_name" => $last,
3740                                 "image_url" => $large,
3741                                 "image_url_medium" => $medium,
3742                                 "image_url_small" => $small,
3743                                 "birthday" => $dob,
3744                                 "gender" => $profile['gender'],
3745                                 "bio" => $about,
3746                                 "location" => $location,
3747                                 "searchable" => $searchable,
3748                                 "tag_string" => $tags);
3749
3750                 foreach ($recips as $recip) {
3751                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3752                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3753                 }
3754         }
3755
3756         /**
3757          * @brief Stores the signature for likes that are created on our system
3758          *
3759          * @param array $contact The contact array of the "like"
3760          * @param int $post_id The post id of the "like"
3761          *
3762          * @return bool Success
3763          */
3764         public static function store_like_signature($contact, $post_id) {
3765
3766                 // Is the contact the owner? Then fetch the private key
3767                 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3768                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
3769                         return false;
3770                 }
3771
3772                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3773                 if (!dbm::is_result($r)) {
3774                         return false;
3775                 }
3776
3777                 $contact["uprvkey"] = $r[0]['prvkey'];
3778
3779                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3780                 if (!dbm::is_result($r)) {
3781                         return false;
3782                 }
3783
3784                 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3785                         return false;
3786                 }
3787
3788                 $message = self::construct_like($r[0], $contact);
3789                 $message["author_signature"] = self::signature($contact, $message);
3790
3791                 /*
3792                  * Now store the signature more flexible to dynamically support new fields.
3793                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3794                  */
3795                 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3796                         intval($message_id),
3797                         dbesc(json_encode($message))
3798                 );
3799
3800                 logger('Stored diaspora like signature');
3801                 return true;
3802         }
3803
3804         /**
3805          * @brief Stores the signature for comments that are created on our system
3806          *
3807          * @param array $item The item array of the comment
3808          * @param array $contact The contact array of the item owner
3809          * @param string $uprvkey The private key of the sender
3810          * @param int $message_id The message id of the comment
3811          *
3812          * @return bool Success
3813          */
3814         public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3815
3816                 if ($uprvkey == "") {
3817                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3818                         return false;
3819                 }
3820
3821                 $contact["uprvkey"] = $uprvkey;
3822
3823                 $message = self::construct_comment($item, $contact);
3824                 $message["author_signature"] = self::signature($contact, $message);
3825
3826                 /*
3827                  * Now store the signature more flexible to dynamically support new fields.
3828                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3829                  */
3830                 q("INSERT INTO `sign` (`iid`, `signed_text`) VALUES (%d, '%s')",
3831                         intval($message_id),
3832                         dbesc(json_encode($message))
3833                 );
3834
3835                 logger('Stored diaspora comment signature');
3836                 return true;
3837         }
3838 }