This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
/
XMLWriter.php
922 lines (867 loc) · 36.5 KB
/
XMLWriter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
<?php
/*
* Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <http://pyd.io/>.
*/
namespace Pydio\Core\Controller;
use Pydio\Access\Core\Model\AJXP_Node;
use Pydio\Access\Core\IAjxpWrapperProvider;
use Pydio\Access\Core\Model\Repository;
use Pydio\Core\Exception\AuthRequiredException;
use Pydio\Core\Utils\Utils;
use Pydio\Core\Exception\PydioPromptException;
use Pydio\Core\Services;
use Pydio\Core\Services\AuthService;
use Pydio\Conf\Core\AbstractAjxpUser;
use Pydio\Core\Services\ConfService;
use Pydio\Core\PluginFramework\PluginsService;
use Pydio\Core\Utils\TextEncoder;
use Pydio\Log\Core\AJXP_Logger;
defined('AJXP_EXEC') or die( 'Access not allowed');
/**
* XML output Generator
* @package Pydio
* @subpackage Core
*/
class XMLWriter
{
public static $headerSent = false;
/**
* Output Headers, XML <?xml version...?> tag and a root node
* @static
* @param string $docNode
* @param array $attributes
*/
public static function header($docNode="tree", $attributes=array())
{
if(self::$headerSent !== false && self::$headerSent == $docNode) return ;
if(!ConfService::currentContextIsCommandLine()){
header('Content-Type: text/xml; charset=UTF-8');
header('Cache-Control: no-cache');
}
print('<?xml version="1.0" encoding="UTF-8"?>');
$attString = "";
if (count($attributes)) {
foreach ($attributes as $name=>$value) {
$attString.="$name=\"$value\" ";
}
}
self::$headerSent = $docNode;
print("<$docNode $attString>");
}
/**
* Outputs a closing root not (</tree>)
* @static
* @param string $docNode
* @return void
*/
public static function close($docNode="tree")
{
print("</$docNode>");
}
public static function wrapDocument($content, $docNode = "tree", $attributes = array()){
if(self::$headerSent !== false && self::$headerSent == $docNode) {
return $content;
}
//header('Content-Type: text/xml; charset=UTF-8');
//header('Cache-Control: no-cache');
$buffer = '<?xml version="1.0" encoding="UTF-8"?>';
$attString = "";
if (count($attributes)) {
foreach ($attributes as $name=>$value) {
$attString.="$name=\"$value\" ";
}
}
self::$headerSent = $docNode;
$buffer .= "<$docNode $attString>";
$buffer .= $content;
$buffer .= "</$docNode>";
return $buffer;
}
/**
* @static
* @param string $data
* @param bool $print
* @return string
*/
public static function write($data, $print)
{
if ($print) {
print($data);
return "";
} else {
return $data;
}
}
/**
* Ouput the <pagination> tag
* @static
* @param integer $count
* @param integer $currentPage
* @param integer $totalPages
* @param integer $dirsCount
* @param null $remoteSortAttributes
*/
public static function renderPaginationData($count, $currentPage, $totalPages, $dirsCount = -1, $remoteSortAttributes = null)
{
$remoteSortString = "";
if (is_array($remoteSortAttributes)) {
foreach($remoteSortAttributes as $k => $v) $remoteSortString .= " $k='$v'";
}
$string = '<pagination count="'.$count.'" total="'.$totalPages.'" current="'.$currentPage.'" overflowMessage="'.$currentPage."/".$totalPages.'" icon="folder.png" openicon="folder_open.png" dirsCount="'.$dirsCount.'"'.$remoteSortString.'/>';
XMLWriter::write($string, true);
}
/**
* Convert an arbitrary list of data (array of associative array) as standard XML list.
* @param $data
* @param $rootPath
* @param $idKey
* @param $labelKey
*/
public static function renderSimpleListAsNodes($data, $rootPath, $idKey, $labelKey){
self::header();
foreach($data as $item){
$nodeName = rtrim($rootPath, "/")."/".$item[$idKey];
$nodeLabel = $item[$labelKey];
$isLeaf = true;
$metaData = $item;
self::renderNode($nodeName, $nodeLabel, $isLeaf, $metaData);
}
self::close();
}
/**
* Prints out the XML headers and preamble, then an open node
* @static
* @param $nodeName
* @param $nodeLabel
* @param $isLeaf
* @param array $metaData
* @return void
*/
public static function renderHeaderNode($nodeName, $nodeLabel, $isLeaf, $metaData = array())
{
if(!ConfService::currentContextIsCommandLine()) {
header('Content-Type: text/xml; charset=UTF-8');
header('Cache-Control: no-cache');
}
print('<?xml version="1.0" encoding="UTF-8"?>');
self::$headerSent = "tree";
XMLWriter::renderNode($nodeName, $nodeLabel, $isLeaf, $metaData, false);
}
/**
* @static
* @param \Pydio\Access\Core\Model\AJXP_Node $ajxpNode
* @return void
*/
public static function renderAjxpHeaderNode($ajxpNode)
{
if(!ConfService::currentContextIsCommandLine()) {
header('Content-Type: text/xml; charset=UTF-8');
header('Cache-Control: no-cache');
}
print('<?xml version="1.0" encoding="UTF-8"?>');
self::$headerSent = "tree";
self::renderAjxpNode($ajxpNode, false);
}
/**
* The basic node
* @static
* @param string $nodeName
* @param string $nodeLabel
* @param bool $isLeaf
* @param array $metaData
* @param bool $close
* @param bool $print
* @return void|string
*/
public static function renderNode($nodeName, $nodeLabel, $isLeaf, $metaData = array(), $close=true, $print = true)
{
$string = "<tree";
$metaData["filename"] = $nodeName;
if(Utils::detectXSS($nodeName)) $metaData["filename"] = "/XSS Detected - Please contact your admin";
if (!isSet($metaData["text"])) {
if(Utils::detectXSS($nodeLabel)) $nodeLabel = "XSS Detected - Please contact your admin";
$metaData["text"] = $nodeLabel;
}else{
if(Utils::detectXSS($metaData["text"])) $metaData["text"] = "XSS Detected - Please contact your admin";
}
$metaData["is_file"] = ($isLeaf?"true":"false");
$metaData["ajxp_im_time"] = time();
foreach ($metaData as $key => $value) {
if(Utils::detectXSS($value)) $value = "XSS Detected!";
$value = Utils::xmlEntities($value, true);
$string .= " $key=\"$value\"";
}
if ($close) {
$string .= "/>";
} else {
$string .= ">";
}
return XMLWriter::write($string, $print);
}
/**
* @static
* @param \Pydio\Access\Core\Model\AJXP_Node $ajxpNode
* @param bool $close
* @param bool $print
* @return void|string
*/
public static function renderAjxpNode($ajxpNode, $close = true, $print = true)
{
return XMLWriter::renderNode(
$ajxpNode->getPath(),
$ajxpNode->getLabel(),
$ajxpNode->isLeaf(),
$ajxpNode->metadata,
$close,
$print);
}
/**
* Render a node with arguments passed as array
* @static
* @param $array
* @return void
*/
public static function renderNodeArray($array)
{
self::renderNode($array[0],$array[1],$array[2],$array[3]);
}
/**
* Error Catcher for PHP errors. Depending on the SERVER_DEBUG config
* shows the file/line info or not.
* @static
* @param $code
* @param $message
* @param $fichier
* @param $ligne
* @param $context
*/
public static function catchError($code, $message, $fichier, $ligne, $context)
{
if(error_reporting() == 0) {
return ;
}
AJXP_Logger::error(basename($fichier), "error l.$ligne", array("message" => $message));
if (ConfService::getConf("SERVER_DEBUG")) {
$stack = debug_backtrace();
$stackLen = count($stack);
for ($i = 1; $i < $stackLen; $i++) {
$entry = $stack[$i];
$func = $entry['function'] . '(';
$argsLen = count($entry['args']);
for ($j = 0; $j < $argsLen; $j++) {
$s = $entry['args'][$j];
if(is_string($s)){
$func .= $s;
}else if (is_object($s)){
$func .= get_class($s);
}
if ($j < $argsLen - 1) $func .= ', ';
}
$func .= ')';
$message .= "\n". str_replace(dirname(__FILE__), '', $entry['file']) . ':' . $entry['line'] . ' - ' . $func . PHP_EOL;
}
}
if(!headers_sent()) XMLWriter::header();
if(!empty($context) && is_object($context) && $context instanceof PydioPromptException){
XMLWriter::write("<prompt type=\"".$context->getPromptType()."\"><message>".$message."</message><data><![CDATA[".json_encode($context->getPromptData())."]]></data></prompt>", true);
}else{
XMLWriter::sendMessage(null, TextEncoder::toUTF8($message), true);
}
XMLWriter::close();
}
/**
* Catch exceptions, @see catchError
* @param \Exception $exception
*/
public static function catchException($exception)
{
if($exception instanceof AuthRequiredException){
XMLWriter::header();
$message = $exception->getMessage();
if(!empty($message)){
XMLWriter::sendMessage(null, $message);
}
XMLWriter::requireAuth();
XMLWriter::close();
return;
}
try {
XMLWriter::catchError($exception->getCode(), TextEncoder::fromUTF8($exception->getMessage()), $exception->getFile(), $exception->getLine(), $exception);
} catch (\Exception $innerEx) {
error_log(get_class($innerEx)." thrown within the exception handler!");
error_log("Original exception was: ".$innerEx->getMessage()." in ".$innerEx->getFile()." on line ".$innerEx->getLine());
error_log("New exception is: ".$innerEx->getMessage()." in ".$innerEx->getFile()." on line ".$innerEx->getLine()." ".$innerEx->getTraceAsString());
print("Error");
}
}
/**
* Dynamically replace XML keywords with their live values.
* AJXP_SERVER_ACCESS, AJXP_MIMES_*,AJXP_ALL_MESSAGES, etc.
* @static
* @param string $xml
* @param bool $stripSpaces
* @return mixed
*/
public static function replaceAjxpXmlKeywords($xml, $stripSpaces = false)
{
$messages = ConfService::getMessages();
$confMessages = ConfService::getMessagesConf();
$matches = array();
if (isSet($_SESSION["AJXP_SERVER_PREFIX_URI"])) {
//$xml = str_replace("AJXP_THEME_FOLDER", $_SESSION["AJXP_SERVER_PREFIX_URI"].AJXP_THEME_FOLDER, $xml);
$xml = str_replace("AJXP_SERVER_ACCESS", $_SESSION["AJXP_SERVER_PREFIX_URI"].AJXP_SERVER_ACCESS, $xml);
} else {
//$xml = str_replace("AJXP_THEME_FOLDER", AJXP_THEME_FOLDER, $xml);
$xml = str_replace("AJXP_SERVER_ACCESS", AJXP_SERVER_ACCESS, $xml);
}
$xml = str_replace("AJXP_APPLICATION_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $xml);
$xml = str_replace("AJXP_MIMES_EDITABLE", Utils::getAjxpMimes("editable"), $xml);
$xml = str_replace("AJXP_MIMES_IMAGE", Utils::getAjxpMimes("image"), $xml);
$xml = str_replace("AJXP_MIMES_AUDIO", Utils::getAjxpMimes("audio"), $xml);
$xml = str_replace("AJXP_MIMES_ZIP", Utils::getAjxpMimes("zip"), $xml);
$authDriver = ConfService::getAuthDriverImpl();
if ($authDriver != NULL) {
$loginRedirect = $authDriver->getLoginRedirect();
$xml = str_replace("AJXP_LOGIN_REDIRECT", ($loginRedirect!==false?"'".$loginRedirect."'":"false"), $xml);
}
$xml = str_replace("AJXP_REMOTE_AUTH", "false", $xml);
$xml = str_replace("AJXP_NOT_REMOTE_AUTH", "true", $xml);
$xml = str_replace("AJXP_ALL_MESSAGES", "MessageHash=".json_encode(ConfService::getMessages()).";", $xml);
if (preg_match_all("/AJXP_MESSAGE(\[.*?\])/", $xml, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$messId = str_replace("]", "", str_replace("[", "", $match[1]));
$xml = str_replace("AJXP_MESSAGE[$messId]", $messages[$messId], $xml);
}
}
if (preg_match_all("/CONF_MESSAGE(\[.*?\])/", $xml, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$messId = str_replace(array("[", "]"), "", $match[1]);
$message = $messId;
if (array_key_exists($messId, $confMessages)) {
$message = $confMessages[$messId];
}
$xml = str_replace("CONF_MESSAGE[$messId]", Utils::xmlEntities($message), $xml);
}
}
if (preg_match_all("/MIXIN_MESSAGE(\[.*?\])/", $xml, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$messId = str_replace(array("[", "]"), "", $match[1]);
$message = $messId;
if (array_key_exists($messId, $confMessages)) {
$message = $confMessages[$messId];
}
$xml = str_replace("MIXIN_MESSAGE[$messId]", Utils::xmlEntities($message), $xml);
}
}
if ($stripSpaces) {
$xml = preg_replace("/[\n\r]?/", "", $xml);
$xml = preg_replace("/\t/", " ", $xml);
}
$xml = str_replace(array('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"','xsi:noNamespaceSchemaLocation="file:../core.ajaxplorer/ajxp_registry.xsd"'), "", $xml);
$tab = array(&$xml);
Controller::applyIncludeHook("xml.filter", $tab);
return $xml;
}
/**
* Send a <reload> XML instruction for refreshing the list
* @static
* @param string $nodePath
* @param string $pendingSelection
* @param bool $print
* @return string
*/
public static function reloadDataNode($nodePath="", $pendingSelection="", $print = true)
{
$nodePath = Utils::xmlEntities($nodePath, true);
$pendingSelection = Utils::xmlEntities($pendingSelection, true);
return XMLWriter::write("<reload_instruction object=\"data\" node=\"$nodePath\" file=\"$pendingSelection\"/>", $print);
}
/**
* Send a <reload> XML instruction for refreshing the list
* @static
* @param $diffNodes
* @param bool $print
* @return string
*/
public static function writeNodesDiff($diffNodes, $print = false)
{
/**
* @var $ajxpNode \Pydio\Access\Core\Model\AJXP_Node
*/
$mess = ConfService::getMessages();
$buffer = "<nodes_diff>";
if (isSet($diffNodes["REMOVE"]) && count($diffNodes["REMOVE"])) {
$buffer .= "<remove>";
foreach ($diffNodes["REMOVE"] as $nodePath) {
$nodePath = Utils::xmlEntities($nodePath, true);
$buffer .= "<tree filename=\"$nodePath\" ajxp_im_time=\"".time()."\"/>";
}
$buffer .= "</remove>";
}
if (isSet($diffNodes["ADD"]) && count($diffNodes["ADD"])) {
$buffer .= "<add>";
foreach ($diffNodes["ADD"] as $ajxpNode) {
$ajxpNode->loadNodeInfo(false, false, "all");
if (!empty($ajxpNode->metaData["mimestring_id"]) && array_key_exists($ajxpNode->metaData["mimestring_id"], $mess)) {
$ajxpNode->mergeMetadata(array("mimestring" => $mess[$ajxpNode->metaData["mimestring_id"]]));
}
$buffer .= self::renderAjxpNode($ajxpNode, true, false);
}
$buffer .= "</add>";
}
if (isSet($diffNodes["UPDATE"]) && count($diffNodes["UPDATE"])) {
$buffer .= "<update>";
foreach ($diffNodes["UPDATE"] as $originalPath => $ajxpNode) {
$ajxpNode->loadNodeInfo(false, false, "all");
if (!empty($ajxpNode->metaData["mimestring_id"]) && array_key_exists($ajxpNode->metaData["mimestring_id"], $mess)) {
$ajxpNode->mergeMetadata(array("mimestring" => $mess[$ajxpNode->metaData["mimestring_id"]]));
}
$ajxpNode->original_path = $originalPath;
$buffer .= self::renderAjxpNode($ajxpNode, true, false);
}
$buffer .= "</update>";
}
$buffer .= "</nodes_diff>";
return XMLWriter::write($buffer, $print);
}
/**
* Send a <reload> XML instruction for refreshing the repositories list
* @static
* @param bool $print
* @return string
*/
public static function reloadRepositoryList($print = true)
{
return XMLWriter::write("<reload_instruction object=\"repository_list\"/>", $print);
}
/**
* Outputs a <require_auth/> tag
* @static
* @param bool $print
* @return string
*/
public static function requireAuth($print = true)
{
return XMLWriter::write("<require_auth/>", $print);
}
/**
* Triggers a background action client side
* @static
* @param $actionName
* @param $parameters
* @param $messageId
* @param bool $print
* @param int $delay
* @return string
*/
public static function triggerBgAction($actionName, $parameters, $messageId, $print=true, $delay = 0)
{
$messageId = Utils::xmlEntities($messageId);
$data = XMLWriter::write("<trigger_bg_action name=\"$actionName\" messageId=\"$messageId\" delay=\"$delay\">", $print);
foreach ($parameters as $paramName=>$paramValue) {
$paramValue = Utils::xmlEntities($paramValue);
$data .= XMLWriter::write("<param name=\"$paramName\" value=\"$paramValue\"/>", $print);
}
$data .= XMLWriter::write("</trigger_bg_action>", $print);
return $data;
}
public static function triggerBgJSAction($jsCode, $messageId, $print=true, $delay = 0)
{
$data = XMLWriter::write("<trigger_bg_action name=\"javascript_instruction\" messageId=\"$messageId\" delay=\"$delay\">", $print);
$data .= XMLWriter::write("<clientCallback><![CDATA[".$jsCode."]]></clientCallback>", $print);
$data .= XMLWriter::write("</trigger_bg_action>", $print);
return $data;
}
/**
* List all bookmmarks as XML
* @static
* @param $allBookmarks
* @param bool $print
* @param string $format legacy|node_list
* @return string
*/
public static function writeBookmarks($allBookmarks, $print = true, $format = "legacy")
{
$driver = false;
if ($format == "node_list") {
$driver = ConfService::loadRepositoryDriver();
if (!($driver instanceof IAjxpWrapperProvider)) {
$driver = false;
}
}
$buffer = "";
foreach ($allBookmarks as $bookmark) {
$path = ""; $title = "";
if (is_array($bookmark)) {
$path = $bookmark["PATH"];
$title = $bookmark["TITLE"];
} else if (is_string($bookmark)) {
$path = $bookmark;
$title = basename($bookmark);
}
if ($format == "node_list") {
if ($driver) {
$node = new AJXP_Node($driver->getResourceUrl($path));
$buffer .= XMLWriter::renderAjxpNode($node, true, false);
} else {
$buffer .= XMLWriter::renderNode($path, $title, false, array('icon' => "mime_empty.png"), true, false);
}
} else {
$buffer .= "<bookmark path=\"".Utils::xmlEntities($path, true)."\" title=\"".Utils::xmlEntities($title, true)."\"/>";
}
}
if($print) {
print $buffer;
return null;
} else {
return $buffer;
}
}
/**
* Utilitary for generating a <component_config> tag for the FilesList component
* @static
* @param $config
* @return void
*/
public static function sendFilesListComponentConfig($config)
{
if (is_string($config)) {
print("<client_configs><component_config className=\"FilesList\">$config</component_config></client_configs>");
}
}
/**
* Send a success or error message to the client.
* @static
* @param $logMessage
* @param $errorMessage
* @param bool $print
* @return string
*/
public static function sendMessage($logMessage, $errorMessage, $print = true)
{
if ($errorMessage == null) {
$messageType = "SUCCESS";
$message = Utils::xmlContentEntities($logMessage);
} else {
$messageType = "ERROR";
$message = Utils::xmlContentEntities($errorMessage);
}
return XMLWriter::write("<message type=\"$messageType\">".$message."</message>", $print);
}
/**
* Extract all the user data and put it in XML
* @static
* @param AbstractAjxpUser|null $userObject
* @internal param bool $details
* @return string
*/
public static function getUserXML($userObject = null)
{
$buffer = "";
$loggedUser = AuthService::getLoggedUser();
$confDriver = ConfService::getConfStorageImpl();
if($userObject != null) $loggedUser = $userObject;
if (!Services\AuthService::usersEnabled()) {
$buffer.="<user id=\"shared\">";
$buffer.="<active_repo id=\"".ConfService::getCurrentRepositoryId()."\" write=\"1\" read=\"1\"/>";
$buffer.= XMLWriter::writeRepositoriesData(null);
$buffer.="</user>";
} else if ($loggedUser != null) {
$lock = $loggedUser->getLock();
$buffer.="<user id=\"".$loggedUser->id."\">";
$buffer.="<active_repo id=\"".ConfService::getCurrentRepositoryId()."\" write=\"".($loggedUser->canWrite(ConfService::getCurrentRepositoryId())?"1":"0")."\" read=\"".($loggedUser->canRead(ConfService::getCurrentRepositoryId())?"1":"0")."\"/>";
$buffer.= XMLWriter::writeRepositoriesData($loggedUser);
$buffer.="<preferences>";
$preferences = $confDriver->getExposedPreferences($loggedUser);
foreach ($preferences as $prefName => $prefData) {
$atts = "";
if (isSet($prefData["exposed"]) && $prefData["exposed"] == true) {
foreach ($prefData as $k => $v) {
if($k=="name") continue;
if($k == "value") $k = "default";
$atts .= "$k='$v' ";
}
}
if (isset($prefData["pluginId"])) {
$atts .= "pluginId='".$prefData["pluginId"]."' ";
}
if ($prefData["type"] == "string") {
$buffer.="<pref name=\"$prefName\" value=\"".$prefData["value"]."\" $atts/>";
} else if ($prefData["type"] == "json") {
$buffer.="<pref name=\"$prefName\" $atts><![CDATA[".$prefData["value"]."]]></pref>";
}
}
$buffer.="</preferences>";
$buffer.="<special_rights is_admin=\"".($loggedUser->isAdmin()?"1":"0")."\" ".($lock!==false?"lock=\"$lock\"":"")."/>";
/*
$bMarks = $loggedUser->getBookmarks();
if (count($bMarks)) {
$buffer.= "<bookmarks>".AJXP_XMLWriter::writeBookmarks($bMarks, false)."</bookmarks>";
}
*/
$buffer.="</user>";
}
return $buffer;
}
/**
* Write the repositories access rights in XML format
* @static
* @param AbstractAjxpUser|null $loggedUser * @internal param bool $details
* @return string
*/
public static function writeRepositoriesData($loggedUser)
{
$st = "<repositories>";
$streams = ConfService::detectRepositoryStreams(false);
$exposed = array();
$cacheHasExposed = PluginsService::getInstance()->loadFromPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']");
if ($cacheHasExposed !== null && is_array($cacheHasExposed)) {
$exposed = $cacheHasExposed;
} else {
$exposed_props = PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'repository') and @expose='true']", "node", false, false, true);
foreach($exposed_props as $exposed_prop){
$pluginId = $exposed_prop->parentNode->parentNode->getAttribute("id");
$paramName = $exposed_prop->getAttribute("name");
$paramDefault = $exposed_prop->getAttribute("default");
$exposed[] = array("PLUGIN_ID" => $pluginId, "NAME" => $paramName, "DEFAULT" => $paramDefault);
}
PluginsService::getInstance()->storeToPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']", $exposed);
}
$accessible = ConfService::getAccessibleRepositories($loggedUser, false, false);
$inboxStatus = 0;
foreach($accessible as $repoId => $repoObject){
if(!$repoObject->hasContentFilter()) {
continue;
}
$accessStatus = $repoObject->getAccessStatus();
if(empty($accessStatus) && $loggedUser != null){
$lastConnected = $loggedUser->getArrayPref("repository_last_connected", $repoId);
if(empty($lastConnected)){
$accessStatus = 1;
}
}
if(!empty($accessStatus)){
$inboxStatus ++;
}
}
foreach ($accessible as $repoId => $repoObject) {
if(!isSet($_SESSION["CURRENT_MINISITE"]) && $repoObject->hasContentFilter()){
continue;
}
$accessStatus = '';
if($repoObject->getAccessType() == "inbox"){
$accessStatus = $inboxStatus;
}
$xmlString = self::repositoryToXML($repoId, $repoObject, $exposed, $streams, $loggedUser, $accessStatus);
$st .= $xmlString;
}
$st .= "</repositories>";
return $st;
}
/**
* @param string $repoId
* @param \Pydio\Access\Core\Model\Repository $repoObject
* @param array $exposed
* @param array $streams
* @param AbstractAjxpUser $loggedUser
* @param string $accessStatus
* @return string
* @throws \Exception
*/
public static function repositoryToXML($repoId, $repoObject, $exposed, $streams, $loggedUser, $accessStatus = ""){
$statusString = " repository_type=\"".$repoObject->getRepositoryType()."\"";
if(empty($accessStatus)){
$accessStatus = $repoObject->getAccessStatus();
}
if(!empty($accessStatus)){
$statusString .= " access_status=\"$accessStatus\" ";
}else if($loggedUser != null){
$lastConnected = $loggedUser->getArrayPref("repository_last_connected", $repoId);
if(!empty($lastConnected)) $statusString .= " last_connection=\"$lastConnected\" ";
}
$streamString = "";
if (in_array($repoObject->accessType, $streams)) {
$streamString = "allowCrossRepositoryCopy=\"true\"";
}
if ($repoObject->getUniqueUser()) {
$streamString .= " user_editable_repository=\"true\" ";
}
if ($repoObject->hasContentFilter()){
$streamString .= " hasContentFilter=\"true\"";
}
$slugString = "";
$slug = $repoObject->getSlug();
if (!empty($slug)) {
$slugString = "repositorySlug=\"$slug\"";
}
$isSharedString = "";
$currentUserIsOwner = false;
$ownerLabel = null;
if ($repoObject->hasOwner()) {
$uId = $repoObject->getOwner();
if(Services\AuthService::usersEnabled() && Services\AuthService::getLoggedUser()->getId() == $uId){
$currentUserIsOwner = true;
}
$label = ConfService::getUserPersonalParameter("USER_DISPLAY_NAME", $uId, "core.conf", $uId);
$ownerLabel = $label;
$isSharedString = 'owner="'.Utils::xmlEntities($label).'"';
}
if ($repoObject->securityScope() == "USER" || $currentUserIsOwner){
$streamString .= " userScope=\"true\"";
}
$descTag = "";
$public = false;
if(!empty($_SESSION["CURRENT_MINISITE"])) $public = true;
$description = $repoObject->getDescription($public, $ownerLabel);
if (!empty($description)) {
$descTag = '<description>'.Utils::xmlEntities($description, true).'</description>';
}
$roleString="";
if($loggedUser != null){
$merged = $loggedUser->mergedRole;
$params = array();
foreach($exposed as $exposed_prop){
$metaOptions = $repoObject->getOption("META_SOURCES");
if(!isSet($metaOptions[$exposed_prop["PLUGIN_ID"]])){
continue;
}
$value = $exposed_prop["DEFAULT"];
if(isSet($metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]])){
$value = $metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]];
}
$value = $merged->filterParameterValue($exposed_prop["PLUGIN_ID"], $exposed_prop["NAME"], $repoId, $value);
if($value !== null){
if($value === true || $value === false) $value = ($value === true ?"true":"false");
$params[] = '<repository_plugin_param plugin_id="'.$exposed_prop["PLUGIN_ID"].'" name="'.$exposed_prop["NAME"].'" value="'.Utils::xmlEntities($value).'"/>';
$roleString .= str_replace(".", "_",$exposed_prop["PLUGIN_ID"])."_".$exposed_prop["NAME"].'="'.Utils::xmlEntities($value).'" ';
}
}
$roleString.='acl="'.$merged->getAcl($repoId).'"';
if($merged->hasMask($repoId)){
$roleString.= ' hasMask="true" ';
}
}
return "<repo access_type=\"".$repoObject->accessType."\" id=\"".$repoId."\"$statusString $streamString $slugString $isSharedString $roleString><label>".TextEncoder::toUTF8(Utils::xmlEntities($repoObject->getDisplay()))."</label>".$descTag.$repoObject->getClientSettings()."</repo>";
}
/**
* Writes a <logging_result> tag
* @static
* @param integer $result
* @param string $rememberLogin
* @param string $rememberPass
* @param string $secureToken
* @return void
*/
public static function loggingResult($result, $rememberLogin="", $rememberPass = "", $secureToken="")
{
$remString = "";
if ($rememberPass != "" && $rememberLogin!= "") {
$remString = " remember_login=\"$rememberLogin\" remember_pass=\"$rememberPass\"";
}
if ($secureToken != "") {
$remString .= " secure_token=\"$secureToken\"";
}
print("<logging_result value=\"$result\"$remString/>");
}
/**
* Create plain PHP associative array from XML.
*
* Example usage:
* $xmlNode = simplexml_load_file('example.xml');
* $arrayData = xmlToArray($xmlNode);
* echo json_encode($arrayData);
*
* @param \DOMNode $domXml The dom node to load
* @param array $options Associative array of options
* @return array
* @link http://outlandishideas.co.uk/blog/2012/08/xml-to-json/ More info
* @author Tamlyn Rhodes <http://tamlyn.org>
* @license http://creativecommons.org/publicdomain/mark/1.0/ Public Domain
*/
public static function xmlToArray($domXml, $options = array()) {
$xml = simplexml_import_dom($domXml);
$defaults = array(
'namespaceSeparator' => ':',//you may want this to be something other than a colon
'attributePrefix' => '@', //to distinguish between attributes and nodes with the same name
'alwaysArray' => array(), //array of xml tag names which should always become arrays
'autoArray' => true, //only create arrays for tags which appear more than once
'textContent' => '$', //key used for the text content of elements
'autoText' => true, //skip textContent key if node has no attributes or child nodes
'keySearch' => false, //optional search and replace on tag and attribute names
'keyReplace' => false //replace values for above search values (as passed to str_replace())
);
$options = array_merge($defaults, $options);
$namespaces = $xml->getDocNamespaces();
$namespaces[''] = null; //add base (empty) namespace
//get attributes from all namespaces
$attributesArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
//replace characters in attribute name
if ($options['keySearch']) $attributeName =
str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
$attributeKey = $options['attributePrefix']
. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
. $attributeName;
$attributesArray[$attributeKey] = (string)$attribute;
}
}
//get child nodes from all namespaces
$tagsArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->children($namespace) as $childXml) {
//recurse into child nodes
$childArray = self::xmlToArray($childXml, $options);
list($childTagName, $childProperties) = each($childArray);
//replace characters in tag name
if ($options['keySearch']) $childTagName =
str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
//add namespace prefix, if any
if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
if (!isset($tagsArray[$childTagName])) {
//only entry with this key
//test if tags of this type should always be arrays, no matter the element count
$tagsArray[$childTagName] =
in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
? array($childProperties) : $childProperties;
} elseif (
is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
=== range(0, count($tagsArray[$childTagName]) - 1)
) {
//key already exists and is integer indexed array
$tagsArray[$childTagName][] = $childProperties;
} else {
//key exists so convert to integer indexed array with previous value in position 0
$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
}
}
}
//get text content of node
$textContentArray = array();
$plainText = trim((string)$xml);
if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
//stick it all together
$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
//return node as array
return array(
$xml->getName() => $propertiesArray
);
}
}