/
modx.class.php
2654 lines (2530 loc) · 106 KB
/
modx.class.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
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* MODX Revolution
*
* Copyright 2006-2013 by MODX, LLC.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/**
* This is the main file to include in your scripts to use MODX.
*
* For detailed information on using this class, see {@tutorial modx/modx.pkg}.
*
* @package modx
*/
/* fix for PHP float bug: http://bugs.php.net/bug.php?id=53632 (php 4 <= 4.4.9 and php 5 <= 5.3.4) */
if (strstr(str_replace('.','',serialize(array_merge($_GET, $_POST, $_COOKIE))), '22250738585072011')) {
header('Status: 422 Unprocessable Entity');
die();
}
if (!defined('MODX_CORE_PATH')) {
define('MODX_CORE_PATH', dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR);
}
require_once (MODX_CORE_PATH . 'xpdo/xpdo.class.php');
/**
* This is the MODX gateway class.
*
* It can be used to interact with the MODX framework and serves as a front
* controller for handling requests to the virtual resources managed by the MODX
* Content Management Framework.
*
* @package modx
*/
class modX extends xPDO {
/**
* The parameter for when a session state is not able to be accessed
* @const SESSION_STATE_UNAVAILABLE
*/
const SESSION_STATE_UNAVAILABLE = -1;
/**
* The parameter for when a session has not yet been instantiated
* @const SESSION_STATE_UNINITIALIZED
*/
const SESSION_STATE_UNINITIALIZED = 0;
/**
* The parameter for when a session has been fully initialized
* @const SESSION_STATE_INITIALIZED
*/
const SESSION_STATE_INITIALIZED = 1;
/**
* The parameter marking when a session is being controlled by an external provider
* @const SESSION_STATE_EXTERNAL
*/
const SESSION_STATE_EXTERNAL = 2;
/**
* @var modContext The Context represents a unique section of the site which
* this modX instance is controlling.
*/
public $context= null;
/**
* @var array An array of secondary contexts loaded on demand.
*/
public $contexts= array();
/**
* @var modRequest Represents a web request and provides helper methods for
* dealing with request parameters and other attributes of a request.
*/
public $request= null;
/**
* @var modResponse Represents a web response, providing helper methods for
* managing response header attributes and the body containing the content of
* the response.
*/
public $response= null;
/**
* @var modParser The modParser registered for this modX instance,
* responsible for content tag parsing, and loaded only on demand.
*/
public $parser= null;
/**
* @var array An array of supplemental service classes for this modX instance.
*/
public $services= array ();
/**
* @var array A listing of site Resources and Context-specific meta data.
*/
public $resourceListing= null;
/**
* @var array A hierarchy map of Resources.
*/
public $resourceMap= null;
/**
* @var array A lookup listing of Resource alias values and associated
* Resource Ids
*/
public $aliasMap= null;
/**
* @var modSystemEvent The current event being handled by modX.
*/
public $event= null;
/**
* @var array A map of elements registered to specific events.
*/
public $eventMap= null;
/**
* @var array A map of actions registered to the manager interface.
*/
public $actionMap= null;
/**
* @var array A map of already processed Elements.
*/
public $elementCache= array ();
/**
* @var array An array of key=> value pairs that can be used by any Resource
* or Element.
*/
public $placeholders= array ();
/**
* @var modResource An instance of the current modResource controlling the
* request.
*/
public $resource= null;
/**
* @var string The preferred Culture key for the current request.
*/
public $cultureKey= '';
/**
* @var modLexicon Represents a localized dictionary of common words and phrases.
*/
public $lexicon= null;
/**
* @var modUser The current user object, if one is authenticated for the
* current request and context.
*/
public $user= null;
/**
* @var array Represents the modContentType instances that can be delivered
* by this modX deployment.
*/
public $contentTypes= null;
/**
* @var mixed The resource id or alias being requested.
*/
public $resourceIdentifier= null;
/**
* @var string The method to use to locate the Resource, 'id' or 'alias'.
*/
public $resourceMethod= null;
/**
* @var boolean Indicates if the resource was generated during this request.
*/
public $resourceGenerated= false;
/**
* @var array Version information for this MODX deployment.
*/
public $version= null;
/**
* @var boolean Indicates if modX has been successfully initialized for a
* modContext.
*/
protected $_initialized= false;
/**
* @var array An array of javascript content to be inserted into the HEAD
* of an HTML resource.
*/
public $sjscripts= array ();
/**
* @var array An array of javascript content to be inserted into the BODY
* of an HTML resource.
*/
public $jscripts= array ();
/**
* @var array An array of already loaded javascript/css code
*/
public $loadedjscripts= array ();
/**
* @var string Stores the virtual path for a request to MODX if the
* friendly_alias_paths option is enabled.
*/
public $virtualDir;
/**
* @var modErrorHandler|object An error_handler for the modX instance.
*/
public $errorHandler= null;
/**
* @var modError An error response class for the request
*/
public $error = null;
/**
* @var modManagerController A controller object that represents a page in the manager
*/
public $controller = null;
/**
* @var modRegistry $registry
*/
public $registry;
/**
* @var modMail $mail
*/
public $mail;
/**
* @var modRestClient $rest
*/
public $rest;
/**
* @var array $processors An array of loaded processors and their class name
*/
public $processors = array();
/**
* @var array An array of regex patterns regulary cleansed from content.
*/
public $sanitizePatterns = array(
'scripts' => '@<script[^>]*?>.*?</script>@si',
'entities' => '@&#(\d+);@e',
'tags1' => '@\[\[(.*?)\]\]@si',
'tags2' => '@(\[\[|\]\])@si',
);
/**
* @var integer An integer representing the session state of modX.
*/
protected $_sessionState= modX::SESSION_STATE_UNINITIALIZED;
/**
* @var array A config array that stores the bootstrap settings.
*/
protected $_config= null;
/**
* @var array A config array that stores the system-wide settings.
*/
public $_systemConfig= array();
/**
* @var array A config array that stores the user settings.
*/
public $_userConfig= array();
/**
* @var int The current log sequence
*/
protected $_logSequence= 0;
/**
* @var array An array of plugins that have been cached for execution
*/
public $pluginCache= array();
/**
* @var array The elemnt source cache used for caching and preparing Element data
*/
public $sourceCache= array(
'modChunk' => array()
,'modSnippet' => array()
,'modTemplateVar' => array()
);
/** @var modCacheManager $cacheManager */
public $cacheManager;
/**
* @deprecated
* @var modSystemEvent $Event
*/
public $Event= null;
/**
* @deprecated
* @var string $documentOutput
*/
public $documentOutput= null;
/**
* Harden the environment against common security flaws.
*
* @static
*/
public static function protect() {
if (isset ($_SERVER['QUERY_STRING']) && strpos(urldecode($_SERVER['QUERY_STRING']), chr(0)) !== false) die();
if (@ ini_get('register_globals') && isset ($_REQUEST)) {
while (list($key, $value)= each($_REQUEST)) {
$GLOBALS[$key] = null;
unset ($GLOBALS[$key]);
}
}
$targets= array ('PHP_SELF', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'QUERY_STRING');
foreach ($targets as $target) {
$_SERVER[$target] = isset ($_SERVER[$target]) ? htmlspecialchars($_SERVER[$target], ENT_QUOTES) : null;
}
}
/**
* Sanitize values of an array using regular expression patterns.
*
* @static
* @param array $target The target array to sanitize.
* @param array|string $patterns A regular expression pattern, or array of
* regular expression patterns to apply to all values of the target.
* @param integer $depth The maximum recursive depth to sanitize if the
* target contains values that are arrays.
* @param integer $nesting The maximum nesting level in which to dive
* @return array The sanitized array.
*/
public static function sanitize(array &$target, array $patterns= array(), $depth= 99, $nesting= 10) {
foreach ($target as $key => &$value) {
if (is_array($value) && $depth > 0) {
modX :: sanitize($value, $patterns, $depth-1);
} elseif (is_string($value)) {
if (!empty($patterns)) {
$iteration = 1;
$nesting = ((integer) $nesting ? (integer) $nesting : 10);
while ($iteration <= $nesting) {
$matched = false;
foreach ($patterns as $pattern) {
$patternIterator = 1;
$patternMatches = preg_match($pattern, $value);
if ($patternMatches > 0) {
$matched = true;
while ($patternMatches > 0 && $patternIterator <= $nesting) {
$value= preg_replace($pattern, '', $value);
$patternMatches = preg_match($pattern, $value);
}
}
}
if (!$matched) {
break;
}
$iteration++;
}
}
if (get_magic_quotes_gpc()) {
$target[$key]= stripslashes($value);
} else {
$target[$key]= $value;
}
}
}
return $target;
}
/**
* Sanitizes a string
*
* @param string $str The string to sanitize
* @param array $chars An array of chars to remove
* @param string $allowedTags A list of tags to allow.
* @return string The sanitized string.
*/
public function sanitizeString($str,$chars = array('/',"'",'"','(',')',';','>','<'),$allowedTags = '') {
$str = str_replace($chars,'',strip_tags($str,$allowedTags));
return preg_replace("/[^A-Za-z0-9_\-\.\/\\p{L}[\p{L} _.-]/u",'',$str);
}
/**
* Turn an associative or numeric array into a valid query string.
*
* @static
* @param array $parameters An associative or numeric-indexed array of parameters.
* @param string $numPrefix A string prefix added to the numeric-indexed array keys.
* Ignored if associative array is used.
* @param string $argSeparator The string used to separate arguments in the resulting query string.
* @return string A valid query string representing the parameters.
*/
public static function toQueryString(array $parameters = array(), $numPrefix = '', $argSeparator = '&') {
return http_build_query($parameters, $numPrefix, $argSeparator);
}
/**
* Create, retrieve, or update specific modX instances.
*
* @static
* @param string|int|null $id An optional identifier for the instance. If not set
* a uniqid will be generated and used as the key for the instance.
* @param array|null $config An optional array of config data for the instance.
* @param bool $forceNew If true a new instance will be created even if an instance
* with the provided $id already exists in modX::$instances.
* @return modX An instance of modX.
* @throws xPDOException
*/
public static function getInstance($id = null, $config = null, $forceNew = false) {
$class = __CLASS__;
if (is_null($id)) {
if (!is_null($config) || $forceNew || empty(self::$instances)) {
$id = uniqid($class);
} else {
$instances =& self::$instances;
$id = key($instances);
}
}
if ($forceNew || !array_key_exists($id, self::$instances) || !(self::$instances[$id] instanceof $class)) {
self::$instances[$id] = new $class('', $config);
} elseif (self::$instances[$id] instanceof $class && is_array($config)) {
self::$instances[$id]->config = array_merge(self::$instances[$id]->config, $config);
}
if (!(self::$instances[$id] instanceof $class)) {
throw new xPDOException("Error getting {$class} instance, id = {$id}");
}
return self::$instances[$id];
}
/**
* Construct a new modX instance.
*
* @param string $configPath An absolute filesystem path to look for the config file.
* @param array $options xPDO options that can be passed to the instance.
* @param array $driverOptions PDO driver options that can be passed to the instance.
* @return modX A new modX instance.
*/
public function __construct($configPath= '', $options = null, $driverOptions = null) {
try {
$options = $this->loadConfig($configPath, $options, $driverOptions);
parent :: __construct(
null,
null,
null,
$options,
null
);
$this->setLogLevel($this->getOption('log_level', null, xPDO::LOG_LEVEL_ERROR));
$this->setLogTarget($this->getOption('log_target', null, 'FILE'));
$debug = $this->getOption('debug');
if (!is_null($debug) && $debug !== '') {
$this->setDebug($debug);
}
$this->setPackage('modx', MODX_CORE_PATH . 'model/');
$this->loadClass('modAccess');
$this->loadClass('modAccessibleObject');
$this->loadClass('modAccessibleSimpleObject');
$this->loadClass('modResource');
$this->loadClass('modElement');
$this->loadClass('modScript');
$this->loadClass('modPrincipal');
$this->loadClass('modUser');
$this->loadClass('sources.modMediaSource');
} catch (xPDOException $xe) {
$this->sendError('unavailable', array('error_message' => $xe->getMessage()));
} catch (Exception $e) {
$this->sendError('unavailable', array('error_message' => $e->getMessage()));
}
}
/**
* Load the modX configuration when creating an instance of modX.
*
* @param string $configPath An absolute path location to search for the modX config file.
* @param array $data Data provided to initialize the instance with, overriding config file entries.
* @param null $driverOptions Driver options for the primary connection.
* @return array The merged config data ready for use by the modX::__construct() method.
*/
protected function loadConfig($configPath = '', $data = array(), $driverOptions = null) {
if (!is_array($data)) $data = array();
modX :: protect();
if (!defined('MODX_CONFIG_KEY')) {
define('MODX_CONFIG_KEY', 'config');
}
if (empty ($configPath)) {
$configPath= MODX_CORE_PATH . 'config/';
}
global $database_dsn, $database_user, $database_password, $config_options, $driver_options, $table_prefix, $site_id, $uuid;
if (file_exists($configPath . MODX_CONFIG_KEY . '.inc.php') && include ($configPath . MODX_CONFIG_KEY . '.inc.php')) {
$cachePath= MODX_CORE_PATH . 'cache/';
if (MODX_CONFIG_KEY !== 'config') $cachePath .= MODX_CONFIG_KEY . '/';
if (!is_array($config_options)) $config_options = array();
if (!is_array($driver_options)) $driver_options = array();
$data = array_merge(
array (
xPDO::OPT_CACHE_KEY => 'default',
xPDO::OPT_CACHE_HANDLER => 'xPDOFileCache',
xPDO::OPT_CACHE_PATH => $cachePath,
xPDO::OPT_TABLE_PREFIX => $table_prefix,
xPDO::OPT_HYDRATE_FIELDS => true,
xPDO::OPT_HYDRATE_RELATED_OBJECTS => true,
xPDO::OPT_HYDRATE_ADHOC_FIELDS => true,
xPDO::OPT_VALIDATOR_CLASS => 'validation.modValidator',
xPDO::OPT_VALIDATE_ON_SAVE => true,
'cache_system_settings' => true,
'cache_system_settings_key' => 'system_settings'
),
$config_options,
$data
);
$primaryConnection = array(
'dsn' => $database_dsn,
'username' => $database_user,
'password' => $database_password,
'options' => array(
xPDO::OPT_CONN_MUTABLE => isset($data[xPDO::OPT_CONN_MUTABLE]) ? (boolean) $data[xPDO::OPT_CONN_MUTABLE] : true,
),
'driverOptions' => $driver_options
);
if (!array_key_exists(xPDO::OPT_CONNECTIONS, $data) || !is_array($data[xPDO::OPT_CONNECTIONS])) {
$data[xPDO::OPT_CONNECTIONS] = array();
}
array_unshift($data[xPDO::OPT_CONNECTIONS], $primaryConnection);
if (!empty($site_id)) $this->site_id = $site_id;
if (!empty($uuid)) $this->uuid = $uuid;
} else {
throw new xPDOException("Could not load MODX config file.");
}
return $data;
}
/**
* Initializes the modX engine.
*
* This includes preparing the session, pre-loading some common
* classes and objects, the current site and context settings, extension
* packages used to override session handling, error handling, or other
* initialization classes
*
* @param string $contextKey Indicates the context to initialize.
* @param array|null $options An array of options for the initialization.
* @return bool True if initialized successfully, or already initialized.
*/
public function initialize($contextKey= 'web', $options = null) {
if (!$this->_initialized) {
if (!$this->startTime) {
$this->startTime= $this->getMicroTime();
}
$this->getCacheManager();
$this->getConfig();
$this->_initContext($contextKey, false, $options);
$this->_loadExtensionPackages($options);
$this->_initSession($options);
$this->_initErrorHandler($options);
$this->_initCulture($options);
$this->getService('registry', 'registry.modRegistry');
$this->invokeEvent(
'OnMODXInit',
array(
'contextKey' => $contextKey,
'options' => $options
)
);
if (is_array ($this->config)) {
$this->setPlaceholders($this->config, '+');
}
$this->_initialized= true;
}
return $this->_initialized;
}
/**
* Loads any extension packages.
*
* @param array|null An optional array of options that can contain additional
* extension packages which will be merged with those specified via config.
*/
protected function _loadExtensionPackages($options = null) {
$cache = $this->call('modExtensionPackage','loadCache',array(&$this));
if (!empty($cache)) {
foreach ($cache as $package) {
$package['tablePrefix'] = !empty($package['tablePrefix']) ? $package['tablePrefix'] : null;
$this->addPackage($package['namespace'],$package['path'],$package['tablePrefix']);
if (!empty($package['serviceName']) && !empty($package['serviceClass'])) {
$this->getService($package['serviceName'],$package['serviceClass'],$package['path']);
}
}
}
$this->_loadExtensionPackagesDeprecated($options);
}
/**
* Load system-setting based extension packages. This is not recommended; use modExtensionPackage from 2.3 onward.
* The System Setting will be automatically removed in 2.4/3.0 and no longer functional.
*
* @deprecated To be removed in 2.4/3.0
* @param null $options
*/
protected function _loadExtensionPackagesDeprecated($options = null) {
$extPackages = $this->getOption('extension_packages');
$extPackages = $this->fromJSON($extPackages);
if (!is_array($extPackages)) $extPackages = array();
if (is_array($options) && array_key_exists('extension_packages', $options)) {
$optPackages = $this->fromJSON($options['extension_packages']);
if (is_array($optPackages)) {
$extPackages = array_merge($extPackages, $optPackages);
}
}
if (!empty($extPackages)) {
foreach ($extPackages as $extPackage) {
if (!is_array($extPackage)) continue;
foreach ($extPackage as $packageName => $package) {
if (!empty($package) && !empty($package['path'])) {
$package['tablePrefix'] = !empty($package['tablePrefix']) ? $package['tablePrefix'] : null;
$package['path'] = str_replace(array(
'[[++core_path]]',
'[[++base_path]]',
'[[++assets_path]]',
'[[++manager_path]]',
),array(
$this->config['core_path'],
$this->config['base_path'],
$this->config['assets_path'],
$this->config['manager_path'],
),$package['path']);
$this->addPackage($packageName,$package['path'],$package['tablePrefix']);
if (!empty($package['serviceName']) && !empty($package['serviceClass'])) {
$packagePath = str_replace('//','/',$package['path'].$packageName.'/');
$this->getService($package['serviceName'],$package['serviceClass'],$packagePath);
}
}
}
}
}
}
/**
* Sets the debugging features of the modX instance.
*
* @param boolean|int $debug Boolean or bitwise integer describing the
* debug state and/or PHP error reporting level.
* @param boolean $stopOnNotice Indicates if processing should stop when
* encountering PHP errors of type E_NOTICE.
* @return boolean|int The previous value.
*/
public function setDebug($debug= true) {
$oldValue= $this->getDebug();
if ($debug === true) {
error_reporting(-1);
parent :: setDebug(true);
} elseif ($debug === false) {
error_reporting(0);
parent :: setDebug(false);
} else {
error_reporting(intval($debug));
parent :: setDebug(intval($debug));
}
return $oldValue;
}
/**
* Get an extended xPDOCacheManager instance responsible for MODX caching.
*
* @param string $class The class name of the cache manager to load
* @param array $options An array of options to send to the cache manager instance
* @return modCacheManager A modCacheManager instance registered for this modX instance.
*/
public function getCacheManager($class= 'cache.xPDOCacheManager', $options = array('path' => XPDO_CORE_PATH, 'ignorePkg' => true)) {
if ($this->cacheManager === null) {
if ($this->loadClass($class, $options['path'], $options['ignorePkg'], true)) {
$cacheManagerClass= $this->getOption('modCacheManager.class', null, 'modCacheManager');
if ($className= $this->loadClass($cacheManagerClass, '', false, true)) {
if ($this->cacheManager= new $className ($this)) {
$this->_cacheEnabled= true;
}
}
}
}
return $this->cacheManager;
}
/**
* Gets the MODX parser.
*
* Returns an instance of modParser responsible for parsing tags in element
* content, performing actions, returning content and/or sending other responses
* in the process.
*
* @return modParser The modParser for this modX instance.
*/
public function getParser() {
return $this->getService('parser', $this->getOption('parser_class', null, 'modParser'), $this->getOption('parser_class_path', null, ''));
}
/**
* Gets all of the parent resource ids for a given resource.
*
* @param integer $id The resource id for the starting node.
* @param integer $height How many levels max to search for parents (default 10).
* @param array $options An array of filtering options, such as 'context' to specify the context to grab from
* @return array An array of all the parent resource ids for the specified resource.
*/
public function getParentIds($id= null, $height= 10,array $options = array()) {
$parentId= 0;
$parents= array ();
if ($id && $height > 0) {
$context = '';
if (!empty($options['context'])) {
$this->getContext($options['context']);
$context = $options['context'];
}
$resourceMap = !empty($context) && !empty($this->contexts[$context]->resourceMap) ? $this->contexts[$context]->resourceMap : $this->resourceMap;
foreach ($resourceMap as $parentId => $mapNode) {
if (array_search($id, $mapNode) !== false) {
$parents[]= $parentId;
break;
}
}
if ($parentId && !empty($parents)) {
$height--;
$parents= array_merge($parents, $this->getParentIds($parentId,$height,$options));
}
}
return $parents;
}
/**
* Gets all of the child resource ids for a given resource.
*
* @see getTree for hierarchical node results
* @param integer $id The resource id for the starting node.
* @param integer $depth How many levels max to search for children (default 10).
* @param array $options An array of filtering options, such as 'context' to specify the context to grab from
* @return array An array of all the child resource ids for the specified resource.
*/
public function getChildIds($id= null, $depth= 10,array $options = array()) {
$children= array ();
if ($id !== null && intval($depth) >= 1) {
$id= is_int($id) ? $id : intval($id);
$context = '';
if (!empty($options['context'])) {
$this->getContext($options['context']);
$context = $options['context'];
}
$resourceMap = !empty($context) && !empty($this->contexts[$context]->resourceMap) ? $this->contexts[$context]->resourceMap : $this->resourceMap;
if (isset ($resourceMap["{$id}"])) {
if ($children= $resourceMap["{$id}"]) {
foreach ($children as $child) {
$processDepth = $depth - 1;
if ($c= $this->getChildIds($child,$processDepth,$options)) {
$children= array_merge($children, $c);
}
}
}
}
}
return $children;
}
/**
* Get a site tree from a single or multiple modResource instances.
*
* @see getChildIds for linear results
* @param int|array $id A single or multiple modResource ids to build the
* tree from.
* @param int $depth The maximum depth to build the tree (default 10).
* @param array $options An array of filtering options, such as 'context' to specify the context to grab from
* @return array An array containing the tree structure.
*/
public function getTree($id= null, $depth= 10, array $options = array()) {
$tree= array ();
$context = '';
if (!empty($options['context'])) {
$this->getContext($options['context']);
$context = $options['context'];
}
if ($id !== null) {
if (is_array ($id)) {
foreach ($id as $k => $v) {
$tree[$v]= $this->getTree($v, $depth, $options);
}
}
elseif ($branch= $this->getChildIds($id, 1, $options)) {
foreach ($branch as $key => $child) {
if ($depth > 0 && $leaf= $this->getTree($child, $depth--, $options)) {
$tree[$child]= $leaf;
} else {
$tree[$child]= $child;
}
}
}
}
return $tree;
}
/**
* Sets a placeholder value.
*
* @param string $key The unique string key which identifies the
* placeholder.
* @param mixed $value The value to set the placeholder to.
*/
public function setPlaceholder($key, $value) {
if (is_string($key)) {
$this->placeholders["{$key}"]= $value;
}
}
/**
* Sets a collection of placeholders stored in an array or as object vars.
*
* An optional namespace parameter can be prepended to each placeholder key in the collection,
* to isolate the collection of placeholders.
*
* Note that unlike toPlaceholders(), this function does not add separators between the
* namespace and the placeholder key. Use toPlaceholders() when working with multi-dimensional
* arrays or objects with variables other than scalars so each level gets delimited by a
* separator.
*
* @param array|object $placeholders An array of values or object to set as placeholders.
* @param string $namespace A namespace prefix to prepend to each placeholder key.
*/
public function setPlaceholders($placeholders, $namespace= '') {
$this->toPlaceholders($placeholders, $namespace, '');
}
/**
* Sets placeholders from values stored in arrays and objects.
*
* Each recursive level adds to the prefix, building an access path using an optional separator.
*
* @param array|object $subject An array or object to process.
* @param string $prefix An optional prefix to be prepended to the placeholder keys. Recursive
* calls prepend the parent keys.
* @param string $separator A separator to place in between the prefixes and keys. Default is a
* dot or period: '.'.
* @param boolean $restore Set to true if you want overwritten placeholder values returned.
* @return array A multi-dimensional array containing up to two elements: 'keys' which always
* contains an array of placeholder keys that were set, and optionally, if the restore parameter
* is true, 'restore' containing an array of placeholder values that were overwritten by the method.
*/
public function toPlaceholders($subject, $prefix= '', $separator= '.', $restore= false) {
$keys = array();
$restored = array();
if (is_object($subject)) {
if ($subject instanceof xPDOObject) {
$subject= $subject->toArray();
} else {
$subject= get_object_vars($subject);
}
}
if (is_array($subject)) {
foreach ($subject as $key => $value) {
$rv = $this->toPlaceholder($key, $value, $prefix, $separator, $restore);
if (isset($rv['keys'])) {
foreach ($rv['keys'] as $rvKey) $keys[] = $rvKey;
}
if ($restore === true && isset($rv['restore'])) {
$restored = array_merge($restored, $rv['restore']);
}
}
}
$return = array('keys' => $keys);
if ($restore === true) $return['restore'] = $restored;
return $return;
}
/**
* Recursively validates and sets placeholders appropriate to the value type passed.
*
* @param string $key The key identifying the value.
* @param mixed $value The value to set.
* @param string $prefix A string prefix to prepend to the key. Recursive calls prepend the
* parent keys as well.
* @param string $separator A separator placed in between the prefix and the key. Default is a
* dot or period: '.'.
* @param boolean $restore Set to true if you want overwritten placeholder values returned.
* @return array A multi-dimensional array containing up to two elements: 'keys' which always
* contains an array of placeholder keys that were set, and optionally, if the restore parameter
* is true, 'restore' containing an array of placeholder values that were overwritten by the method.
*/
public function toPlaceholder($key, $value, $prefix= '', $separator= '.', $restore= false) {
$return = array('keys' => array());
if ($restore === true) $return['restore'] = array();
if (!empty($prefix) && !empty($separator)) {
$prefix .= $separator;
}
if (is_array($value) || is_object($value)) {
$return = $this->toPlaceholders($value, "{$prefix}{$key}", $separator, $restore);
} elseif (is_scalar($value)) {
$return['keys'][] = "{$prefix}{$key}";
if ($restore === true && array_key_exists("{$prefix}{$key}", $this->placeholders)) {
$return['restore']["{$prefix}{$key}"] = $this->getPlaceholder("{$prefix}{$key}");
}
$this->setPlaceholder("{$prefix}{$key}", $value);
}
return $return;
}
/**
* Get a placeholder value by key.
*
* @param string $key The key of the placeholder to a return a value from.
* @return mixed The value of the requested placeholder, or an empty string if not located.
*/
public function getPlaceholder($key) {
$placeholder= null;
if (is_string($key) && array_key_exists($key, $this->placeholders)) {
$placeholder= & $this->placeholders["{$key}"];
}
return $placeholder;
}
/**
* Unset a placeholder value by key.
*
* @param string $key The key of the placeholder to unset.
*/
public function unsetPlaceholder($key) {
if (is_string($key) && array_key_exists($key, $this->placeholders)) {
unset($this->placeholders[$key]);
}
}
/**
* Unset multiple placeholders, either by prefix or an array of keys.
*
* @param string|array $keys A string prefix or an array of keys indicating
* the placeholders to unset.
*/
public function unsetPlaceholders($keys) {
if (is_array($keys)) {
foreach ($keys as $key) {
if (is_string($key)) $this->unsetPlaceholder($key);
if (is_array($key)) $this->unsetPlaceholders($key);
}
} elseif (is_string($keys)) {
$placeholderKeys = array_keys($this->placeholders);
foreach ($placeholderKeys as $key) {
if (strpos($key, $keys) === 0) $this->unsetPlaceholder($key);
}
}
}
/**
* Generates a URL representing a specified resource.
*
* @param integer $id The id of a resource.
* @param string $context Specifies a context to limit URL generation to.
* @param string $args A query string to append to the generated URL.
* @param mixed $scheme The scheme indicates in what format the URL is generated.<br>
* <pre>
* -1 : (default value) URL is relative to site_url
* 0 : see http
* 1 : see https
* full : URL is absolute, prepended with site_url from config
* abs : URL is absolute, prepended with base_url from config
* http : URL is absolute, forced to http scheme
* https : URL is absolute, forced to https scheme
* </pre>
* @param array $options An array of options for generating the Resource URL.
* @return string The URL for the resource.
*/
public function makeUrl($id, $context= '', $args= '', $scheme= -1, array $options= array()) {
$url= '';
if ($validid = intval($id)) {
$id = $validid;
if ($context == '' || $this->context->get('key') == $context) {
$url= $this->context->makeUrl($id, $args, $scheme, $options);
}
if (empty($url) && ($context !== $this->context->get('key'))) {
$ctx= null;
if ($context == '') {
/** @var PDOStatement $stmt */
if ($stmt = $this->prepare("SELECT context_key FROM " . $this->getTableName('modResource') . " WHERE id = :id")) {
$stmt->bindValue(':id', $id);
if ($contextKey = $this->getValue($stmt)) {
$ctx = $this->getContext($contextKey);
}
}
} else {
$ctx = $this->getContext($context);
}
if ($ctx) {
$url= $ctx->makeUrl($id, $args, 'full', $options);
}
}
if (!empty($url) && $this->getOption('xhtml_urls', $options, false)) {
$url= preg_replace("/&(?!amp;)/","&", $url);
}
} else {
$this->log(modX::LOG_LEVEL_ERROR, '`' . $id . '` is not a valid integer and may not be passed to makeUrl()');
}
return $url;
}
/**
* Filter a string for use as a URL path segment.
*
* @param string $string The string to filter into a valid path segment.
* @param array $options Optional filter setting overrides.
*
* @return string|null A valid path segment string or null if an error occurs.
*/
public function filterPathSegment($string, array $options = array()) {
return $this->call('modResource', 'filterPathSegment', array(&$this, $string, $options));
}