/
pdotools.class.php
1359 lines (1212 loc) · 47.2 KB
/
pdotools.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
class pdoTools
{
/** @var modX $modx */
public $modx;
/** @var array $timings Array with query log */
public $timings = array();
/** @var array $config Array with class config */
public $config = array();
/** @var array $store Array for cache elements and user data */
public $store = array(
'chunk' => array(),
'snippet' => array(),
'tv' => array(),
'data' => array(),
'resource' => array(),
);
/** @var integer $idx Index of iterator of rows processing */
public $idx = 1;
/** @var integer $time Time of script start */
protected $time;
/** @var integer $count Total number of results for chunks processing */
protected $count = 0;
/** @var boolean $preparing Specifies that now is the preparation */
protected $preparing = false;
protected $start = 0;
/** @var pdoParser $parser */
public $parser;
/** @var Fenom $fenom */
public $fenom;
/**
* @param modX $modx
* @param array $config
*/
public function __construct(modX & $modx, $config = array())
{
$this->modx = $modx;
$this->time = $this->start = microtime(true);
$this->setConfig($config);
}
/**
* Set config from default values and given array.
*
* @param array $config
* @param bool $clean_timings Clean timings array
*/
public function setConfig(array $config = array(), $clean_timings = true)
{
$this->config = array_merge(array(
'fastMode' => false,
'nestedChunkPrefix' => 'pdotools_',
'offset' => 0,
'checkPermissions' => '',
'loadModels' => '',
'prepareSnippet' => '',
'prepareTVs' => '',
'processTVs' => '',
'outputSeparator' => "\n",
'decodeJSON' => true,
'scheme' => '',
'fenomModifiers' => $this->modx->getOption('pdotools_fenom_modifiers'),
), $config);
if ($clean_timings) {
$this->timings = array();
}
if (empty($this->config['scheme'])) {
$this->config['scheme'] = $this->modx->getOption('link_tag_scheme');
}
if (is_numeric($this->config['scheme'])) {
$this->config['scheme'] = (int)$this->config['scheme'];
}
$this->config['useFenom'] = $this->modx->getOption('pdotools_fenom_default', null, true);
$this->config['useFenomParser'] = $this->modx->getOption('pdotools_fenom_parser', null, false);
$this->config['useFenomCache'] = $this->modx->getOption('pdotools_fenom_cache', null, false);
$this->config['useFenomMODX'] = $this->modx->getOption('pdotools_fenom_modx', null, false);
}
/**
* Loads pdoTools parser
*
* @return pdoParser
*/
protected function getParser()
{
$this->parser = $this->modx->getParser();
if (!($this->parser instanceof pdoParser)) {
if (!class_exists('pdoParser')) {
require_once dirname(__FILE__) . '/pdoparser.class.php';
}
$this->parser = new pdoParser($this->modx);
}
return $this->parser;
}
/**
* Loads template engine
*
* @return bool|Fenom
*/
public function getFenom()
{
if (!$this->fenom) {
try {
if (!class_exists('Fenom')) {
require dirname(dirname(__FILE__)) . '/fenom/Fenom.php';
require dirname(dirname(__FILE__)) . '/fenom/Fenom/ProviderInterface.php';
require dirname(dirname(__FILE__)) . '/fenom/Providers/ModChunk.php';
require dirname(dirname(__FILE__)) . '/fenom/Providers/ModTemplate.php';
Fenom::registerAutoload();
}
$cache = MODX_CORE_PATH . 'cache/';
if (!file_exists($cache)) {
mkdir($cache);
}
$this->fenom = Fenom::factory(new modChunkProvider($this), $cache);
$this->fenom->addProvider('template', new modTemplateProvider($this));
$default_options = array(
'force_compile' => true,
'disable_cache' => true,
'force_include' => true,
);
if (!$this->modx->getOption('pdotools_fenom_php', null, false)) {
$this->fenom->removeAccessor('php');
$default_options['disable_native_funcs'] = true;
}
if ($options = $this->modx->fromJSON($this->modx->getOption('pdotools_fenom_options'))) {
$options = array_merge($options, $default_options);
} else {
$options = $default_options;
}
$this->fenom->setOptions($options);
$this->_addModifiers();
} catch (Exception $e) {
$this->modx->log(xPDO::LOG_LEVEL_ERROR, $e->getMessage());
return false;
}
}
return $this->fenom;
}
/**
* Add new record to timings log
*
* @var string $message
* @var integer $delta
*
* @param $message
*/
public function addTime($message, $delta = null)
{
$time = microtime(true);
if (!$delta) {
$delta = $time - $this->time;
}
$this->timings[] = array(
'time' => number_format(round(($delta), 7), 7),
'message' => $message,
);
$this->time = $time;
}
/**
* Return timings log
*
* @param bool $string Return array or formatted string
*
* @return array|string
*/
public function getTime($string = true)
{
$this->timings[] = array(
'time' => number_format(round(microtime(true) - $this->start, 7), 7),
'message' => '<b>Total time</b>',
);
$this->timings[] = array(
'time' => number_format(round((memory_get_usage(true)), 2), 0, ',', ' '),
'message' => '<b>Memory usage</b>',
);
if (!$string) {
return $this->timings;
} else {
$res = '';
foreach ($this->timings as $v) {
$res .= $v['time'] . ': ' . $v['message'] . "\n";
}
return $res;
}
}
/**
* Set data to cache
*
* @param $name
* @param $object
* @param string $type
*/
public function setStore($name, $object, $type = 'data')
{
$this->store[$type][$name] = $object;
}
/**
* Get data from cache
*
* @param $name
* @param string $type
*
* @return mixed|null
*/
public function getStore($name, $type = 'data')
{
return isset($this->store[$type][$name])
? $this->store[$type][$name]
: null;
}
/**
* Loads specified list of packages models
*/
public function loadModels()
{
if (empty($this->config['loadModels'])) {
return;
}
$time = microtime(true);
$models = array();
if (strpos(ltrim($this->config['loadModels']), '{') === 0) {
$tmp = $this->modx->fromJSON($this->config['loadModels']);
foreach ($tmp as $k => $v) {
$v = trim(strtolower($v));
$models[$k] = (strpos($v, MODX_CORE_PATH) === false)
? MODX_CORE_PATH . ltrim($v, '/')
: $v;
}
} else {
$tmp = array_map('trim', explode(',', $this->config['loadModels']));
foreach ($tmp as $v) {
$models[$v] = MODX_CORE_PATH . 'components/' . strtolower($v) . '/model/';
}
}
if (!empty($models)) {
foreach ($models as $k => $v) {
$t = '/' . str_replace(MODX_BASE_PATH, '', $v);
if ($this->modx->addPackage(strtolower($k), $v)) {
$this->addTime('Loaded model "' . $k . '" from "' . $t . '"', microtime(true) - $time);
} else {
$this->addTime('Could not load model "' . $k . '" from "' . $t . '"', microtime(true) - $time);
}
$time = microtime(true);
}
}
$this->config['loadModels'] = '';
}
/**
* Transform array to placeholders
*
* @param array $array
* @param string $plPrefix
* @param string $prefix
* @param string $suffix
* @param bool $uncacheable
*
* @return array
*/
public function makePlaceholders(
array $array = array(),
$plPrefix = '',
$prefix = '[[+',
$suffix = ']]',
$uncacheable = true
) {
$result = array('pl' => array(), 'vl' => array());
$uncached_prefix = str_replace('[[', '[[!', $prefix);
foreach ($array as $k => $v) {
if (is_array($v)) {
$result = array_merge_recursive($result,
$this->makePlaceholders($v, $plPrefix . $k . '.', $prefix, $suffix, $uncacheable));
} else {
$pl = $plPrefix . $k;
$result['pl'][$pl] = $prefix . $pl . $suffix;
$result['vl'][$pl] = $v;
if ($uncacheable) {
$result['pl']['!' . $pl] = $uncached_prefix . $pl . $suffix;
$result['vl']['!' . $pl] = $v;
}
}
}
return $result;
}
/**
* Process and return the output from a Chunk by name.
*
* @param string $name The name of the chunk.
* @param array $properties An associative array of properties to process the Chunk with, treated as placeholders within the scope of the Element.
* @param boolean $fastMode If false, all MODX tags in chunk will be processed.
*
* @return mixed The processed output of the Chunk.
*/
public function getChunk($name = '', array $properties = array(), $fastMode = false)
{
$properties = $this->prepareRow($properties);
$name = trim($name);
/** @var array $chunk */
if (!empty($name)) {
$chunk = $this->_loadChunk($name, $properties);
}
if (empty($name) || empty($chunk) || !($chunk['object'] instanceof modChunk)) {
return !empty($properties)
? str_replace(array('[', ']', '`'), array('[', ']', '`'),
htmlentities(print_r($properties, true), ENT_QUOTES, 'UTF-8'))
: '';
}
$properties = array_merge($chunk['properties'], $properties);
$content = $this->config['useFenom']
? $this->fenom($chunk, $properties)
: $chunk['content'];
if (strpos($content, '[[') !== false) {
// Processing quick placeholders
if (!empty($chunk['placeholders'])) {
$properties = $this->flattenArray($properties);
$pl = $chunk['placeholders'];
foreach ($pl as $k => $v) {
if ($k[0] == '!') {
if (empty($properties[substr($k, 1)])) {
$pl[substr($k, 1)] = $v;
}
unset($pl[$k]);
} elseif (empty($properties[$k])) {
$pl[$k] = '';
}
}
if (!empty($pl)) {
$pl = $this->makePlaceholders($pl);
$content = str_replace($pl['pl'], $pl['vl'], $content);
}
}
// Processing given placeholders
if (!empty($properties)) {
$pl = $this->makePlaceholders($properties);
$content = str_replace($pl['pl'], $pl['vl'], $content);
}
}
// Processing other placeholders
if (strpos($content, '[[') !== false) {
if ($fastMode) {
$content = $this->fastProcess($content, true);
} else {
$chunk['object']->_cacheable = false;
$chunk['object']->_processed = false;
$chunk['object']->_content = '';
/** @var $chunk modChunk[] */
$content = $chunk['object']->process($properties, $content);
}
}
return $content;
}
/**
* Parse a chunk using an associative array of replacement variables.
*
* @param string $name The name of the chunk.
* @param array $properties An array of properties to replace in the chunk.
* @param string $prefix The placeholder prefix, defaults to [[+.
* @param string $suffix The placeholder suffix, defaults to ]].
*
* @return string The processed chunk with the placeholders replaced.
*/
public function parseChunk($name = '', array $properties = array(), $prefix = '[[+', $suffix = ']]')
{
$properties = $this->prepareRow($properties);
$name = trim($name);
/** @var array $chunk */
if (!empty($name)) {
$chunk = $this->_loadChunk($name, $properties);
}
if (empty($name) || empty($chunk['content'])) {
return !empty($properties)
? str_replace(array('[', ']', '`'), array('[', ']', '`'),
htmlentities(print_r($properties, true), ENT_QUOTES, 'UTF-8'))
: '';
}
$properties = array_merge($chunk['properties'], $properties);
$content = $this->config['useFenom']
? $this->fenom($chunk, $properties)
: $chunk['content'];
if (strpos($content, '[[') !== false) {
$pl = $this->makePlaceholders($properties, '', $prefix, $suffix);
$content = str_replace($pl['pl'], $pl['vl'], $content);
}
return $content;
}
/**
* @param string|array $chunk
* @param array $properties
*
* @return mixed|string
*/
public function fenom($chunk, array $properties = array())
{
$content = is_array($chunk)
? trim($chunk['content'])
: trim($chunk);
if (empty($this->config['useFenom']) || !preg_match('#\{(\$|\/|\w+\s|[\'|"|\(])#', $content)) {
return $content;
}
if ($fenom = $this->getFenom()) {
$name = '';
if (is_array($chunk)) {
if (!empty($chunk['binding'])) {
$name = $chunk['binding'] . '/';
}
if (!empty($chunk['id'])) {
$name .= $chunk['id'];
} elseif (!empty($chunk['name'])) {
$name .= $chunk['name'];
} else {
$name .= md5($content);
}
} else {
$name = md5($content);
}
/** @var Fenom\Template $tpl */
if (!$tpl = $this->getStore($name, 'fenom')) {
if (!empty($this->config['useFenomCache'])) {
$cache_options = array(
'cache_key' => 'fenom/' . $name,
);
if (!$cache = $this->getCache($cache_options)) {
if ($tpl = $this->_compileChunk($content, $name)) {
$this->setCache($tpl->getTemplateCode(), $cache_options);
}
} else {
$cache = preg_replace('#^<\?php#', '', $cache);
$tpl = eval($cache);
}
} else {
$tpl = $this->_compileChunk($content, $name);
}
if ($tpl) {
$this->setStore($name, $tpl, 'fenom');
}
}
if ($tpl instanceof Fenom\Render) {
// Add system variables
if (!$microMODX = $this->getStore('microMODX')) {
if (!class_exists('microMODX')) {
require '_micromodx.php';
}
$microMODX = new microMODX($this);
$this->setStore('microMODX', $microMODX);
}
$properties['_modx'] = $microMODX;
$properties['_pls'] = $properties;
// Add system objects
if (!empty($this->config['useFenomMODX'])) {
$properties['modx'] = $this->modx;
$properties['pdoTools'] = $this;
}
try {
$content = $tpl->fetch($properties);
} catch (Exception $e) {
$this->modx->log(modX::LOG_LEVEL_ERROR, $e->getMessage());
$this->modx->log(modX::LOG_LEVEL_INFO, $tpl->getTemplateCode());
}
}
}
return $content;
}
/**
* Fast processing of MODX tags.
*
* @param string $content
* @param bool $processUncacheable
*
* @return mixed
*/
public function fastProcess($content, $processUncacheable = true)
{
$matches = array();
$this->getParser()->collectElementTags($content, $matches);
$unprocessed = $pl = $vl = array();
foreach ($matches as $tag) {
$tmp = $this->parser->processTag($tag, $processUncacheable);
if ($tmp === $tag[0]) {
$unprocessed[] = $tmp;
} else {
$pl[] = $tag[0];
$vl[] = $tmp;
}
}
$content = str_replace($pl, $vl, $content);
$content = str_replace($unprocessed, '', $content);
return $content;
}
/**
* Method for define name of a chunk serving as resource template
* This algorithm taken from snippet getResources by opengeek
*
* @param array $properties Resource fields
*
* @return mixed
*/
public function defineChunk($properties = array())
{
$idx = isset($properties['idx']) ? (integer)$properties['idx'] : $this->idx++;
$idx -= $this->config['offset'];
$first = empty($this->config['first']) ? ($this->config['offset'] + 1) : (integer)$this->config['first'];
$last = empty($this->config['last']) ? ($this->count + $this->config['offset']) : (integer)$this->config['last'];
$odd = !($idx & 1);
$resourceTpl = '';
if ($idx == $first && !empty($this->config['tplFirst'])) {
$resourceTpl = $this->config['tplFirst'];
} else {
if ($idx == $last && !empty($this->config['tplLast'])) {
$resourceTpl = $this->config['tplLast'];
} else {
if (!empty($this->config['tpl_' . $idx])) {
$resourceTpl = $this->config['tpl_' . $idx];
} else {
if ($idx > 1) {
$divisors = array();
for ($i = $idx; $i > 1; $i--) {
if (($idx % $i) === 0) {
$divisors[] = $i;
}
}
if (!empty($divisors)) {
foreach ($divisors as $divisor) {
if (!empty($this->config['tpl_n' . $divisor])) {
$resourceTpl = $this->config['tpl_n' . $divisor];
break;
}
}
}
}
}
}
}
if (empty($resourceTpl) && $odd && !empty($this->config['tplOdd'])) {
$resourceTpl = $this->config['tplOdd'];
} else {
if (empty($resourceTpl) && !empty($this->config['tplCondition']) && !empty($this->config['conditionalTpls'])) {
$conTpls = $this->modx->fromJSON($this->config['conditionalTpls']);
if (isset($properties[$this->config['tplCondition']])) {
$subject = $properties[$this->config['tplCondition']];
$tplOperator = !empty($this->config['tplOperator']) ? strtolower($this->config['tplOperator']) : '=';
$tplCon = '';
foreach ($conTpls as $operand => $conditionalTpl) {
switch ($tplOperator) {
case '!=':
case 'neq':
case 'not':
case 'isnot':
case 'isnt':
case 'unequal':
case 'notequal':
$tplCon = (($subject != $operand) ? $conditionalTpl : $tplCon);
break;
case '<':
case 'lt':
case 'less':
case 'lessthan':
$tplCon = (($subject < $operand) ? $conditionalTpl : $tplCon);
break;
case '>':
case 'gt':
case 'greater':
case 'greaterthan':
$tplCon = (($subject > $operand) ? $conditionalTpl : $tplCon);
break;
case '<=':
case 'lte':
case 'lessthanequals':
case 'lessthanorequalto':
$tplCon = (($subject <= $operand) ? $conditionalTpl : $tplCon);
break;
case '>=':
case 'gte':
case 'greaterthanequals':
case 'greaterthanequalto':
$tplCon = (($subject >= $operand) ? $conditionalTpl : $tplCon);
break;
case 'isempty':
case 'empty':
$tplCon = empty($subject) ? $conditionalTpl : $tplCon;
break;
case '!empty':
case 'notempty':
case 'isnotempty':
$tplCon = !empty($subject) && $subject != '' ? $conditionalTpl : $tplCon;
break;
case 'isnull':
case 'null':
$tplCon = $subject == null || strtolower($subject) == 'null' ? $conditionalTpl : $tplCon;
break;
case 'inarray':
case 'in_array':
case 'ia':
$operand = explode(',', $operand);
$tplCon = in_array($subject, $operand) ? $conditionalTpl : $tplCon;
break;
case 'between':
case 'range':
case '>=<':
case '><':
$operand = explode(',', $operand);
$tplCon = ($subject >= min($operand) && $subject <= max($operand)) ? $conditionalTpl : $tplCon;
break;
case 'contains':
$tplCon = (is_string($subject) && (strpos($subject,
$operand) !== false) ? $conditionalTpl : $tplCon);
break;
case '==':
case '=':
case 'eq':
case 'is':
case 'equal':
case 'equals':
case 'equalto':
default:
$tplCon = (($subject == $operand) ? $conditionalTpl : $tplCon);
break;
}
}
}
if (!empty($tplCon)) {
$resourceTpl = $tplCon;
}
}
}
if (empty($resourceTpl) && !empty($this->config['tpl'])) {
$resourceTpl = $this->config['tpl'];
}
return $resourceTpl;
}
/**
* Loads and returns chunk by various methods.
*
* @param string $name Name or binding
* @param array $row Current row with results being processed
*
* @return array
*/
protected function _loadChunk($name, $row = array())
{
$binding = $content = $propertySet = '';
$name = trim($name);
if (preg_match('/^@([A-Z]+)/', $name, $matches)) {
$binding = $matches[1];
$content = substr($name, strlen($binding) + 1);
$content = ltrim($content, ' :');
}
// Get property set
if (!$binding && $pos = strpos($name, '@')) {
$propertySet = substr($name, $pos + 1);
$name = substr($name, 0, $pos);
} elseif (in_array($binding, array('CHUNK', 'TEMPLATE')) && $pos = strpos($content, '@')) {
$propertySet = substr($content, $pos + 1);
$content = substr($content, 0, $pos);
}
// Replace inline tags
$content = str_replace(array('{{', '}}'), array('[[', ']]'), $content);
// Change name for empty TEMPLATE binding so will be used template of given row
if ($binding == 'TEMPLATE' && empty($content) && isset($row['template'])) {
$name = '@TEMPLATE ' . $row['template'];
$content = $row['template'];
}
// Load from cache
$cache_name = !empty($binding) && $binding != 'CHUNK' ? md5($name) : $name;
if ($chunk = $this->getStore($cache_name, 'chunk')) {
return $chunk;
}
$id = 0;
$properties = array();
/** @var modChunk $element */
switch ($binding) {
case 'CODE':
case 'INLINE':
$element = $this->modx->newObject('modChunk', array('name' => $cache_name));
$element->setContent($content);
$this->addTime('Created inline chunk with name "' . $cache_name . '"');
break;
case 'FILE':
$path = isset($this->config['tplPath'])
? $this->config['tplPath'] . '/'
: MODX_ASSETS_PATH . 'elements/chunks/';
if (strpos($path, MODX_BASE_PATH) === false) {
$path = MODX_BASE_PATH . $path;
}
$path = preg_replace('#/+#', '/', $path . $content);
if (!preg_match('/(.html|.tpl)$/i', $path)) {
$this->addTime('Allowed extensions for @FILE chunks is "html" and "tpl"');
} elseif (!file_exists($path)) {
$this->addTime('Could not find tpl file at "' . str_replace(MODX_BASE_PATH, '', $path) . '".');
return false;
} elseif ($content = file_get_contents($path)) {
$element = $this->modx->newObject('modChunk', array('name' => $cache_name));
$element->setContent($content);
$this->addTime('Loaded chunk from "' . str_replace(MODX_BASE_PATH, '', $path) . '"');
}
break;
case 'TEMPLATE':
/** @var modTemplate $template */
if ($template = $this->modx->getObject('modTemplate',
array('id' => $content, 'OR:templatename:=' => $content))
) {
$content = $template->getContent();
if (!empty($propertySet)) {
if ($tmp = $template->getPropertySet($propertySet)) {
$properties = $tmp;
}
} else {
$properties = $template->getProperties();
}
$element = $this->modx->newObject('modChunk', array('name' => $cache_name));
$element->setContent($content);
$this->addTime('Created chunk from template "' . $template->templatename . '"');
$id = $template->get('id');
}
break;
case 'CHUNK':
$cache_name = $content;
if ($element = $this->modx->getObject('modChunk', array('name' => $cache_name))) {
$content = $element->getContent();
if (!empty($propertySet)) {
if ($tmp = $element->getPropertySet($propertySet)) {
$properties = $tmp;
}
} else {
$properties = $element->getProperties();
}
$this->addTime('Loaded chunk "' . $cache_name . '"');
$id = $element->get('id');
}
break;
default:
if ($element = $this->modx->getObject('modChunk', array('name' => $cache_name))) {
$content = $element->getContent();
if (!empty($propertySet)) {
if ($tmp = $element->getPropertySet($propertySet)) {
$properties = $tmp;
}
} else {
$properties = $element->getProperties();
}
$this->addTime('Loaded chunk "' . $cache_name . '"');
$binding = 'CHUNK';
$id = $element->get('id');
}
}
if (!$element) {
$this->addTime('Could not load or create chunk "' . $name . '".');
return false;
}
// Preparing special tags
if (strpos($content, '<!--' . $this->config['nestedChunkPrefix']) !== false) {
preg_match_all('/\<!--' . $this->config['nestedChunkPrefix'] . '(.*?)[\s|\n|\r\n](.*?)-->/s', $content,
$matches);
$src = $dst = $placeholders = array();
foreach ($matches[1] as $k => $v) {
$src[] = $matches[0][$k];
$dst[] = '';
$placeholders[$v] = $matches[2][$k];
}
if (!empty($src) && !empty($dst)) {
$content = str_replace($src, $dst, $content);
}
} else {
$placeholders = array();
}
$chunk = array(
'object' => $element,
'content' => $content,
'placeholders' => $placeholders,
'properties' => $properties,
'name' => $cache_name,
'id' => $id,
'binding' => strtolower($binding),
);
$this->setStore($cache_name, $chunk, 'chunk');
return $chunk;
}
/**
* Compiles Fenom chunk
*
* @param $content
* @param string $name
*
* @return bool|\Fenom\Template
*/
protected function _compileChunk($content, $name = '')
{
$tpl = false;
if ($fenom = $this->getFenom()) {
if (empty($name)) {
$name = md5($content);
}
try {
$tpl = $fenom->getRawTemplate()->source($name, $content, true);
} catch (Exception $e) {
$this->modx->log(modX::LOG_LEVEL_ERROR, $e->getMessage());
$this->modx->log(modX::LOG_LEVEL_INFO, $content);
}
}
$this->addTime('Compiled Fenom chunk with name "' . $name . '"');
return $tpl;
}
/**
* Add modifiers to Fenom
*/
protected function _addModifiers()
{
$modx = $this->modx;
$pdo = $this;
// Default modifiers
$this->fenom->addModifier('url', function ($id, $options = array(), $args = array()) use ($pdo) {
return $pdo->makeUrl($id, $options, $args);
});
$this->fenom->addModifier('lexicon', function ($key, $params = array(), $language = '') use ($modx) {
return $modx->lexicon($key, $params, $language);
});
// User modifiers
if (!empty($this->config['fenomModifiers'])) {
$modifiers = is_string($this->config['fenomModifiers'])
? explode(',', $this->config['fenomModifiers'])
: $this->config['fenomModifiers'];
foreach ($modifiers as $name) {
$name = trim(strtolower($name));
if (!empty($name)) {
$this->fenom->addModifier($name, function ($input, $options = null) use ($name, $modx, $pdo) {
/** @var modSnippet $snippet */
if (!$snippet = $pdo->getStore($name, 'snippet')) {
if ($snippet = $modx->getObject('modSnippet', array('name' => $name))) {
$pdo->setStore($name, $snippet, 'snippet');
} else {
return $input;
}
}
$snippet->_cacheable = false;
$snippet->_processed = false;
$snippet->_content = '';
$result = $snippet->process(array(
'input' => $input,
'options' => $options,
'pdoTools' => $pdo,
));
return !empty($result)
? $result
: $input;
});
}
}
}
}
/**
* Builds a hierarchical tree from given array
*
* @param array $tmp Array with rows
* @param string $id Name of primary key
* @param string $parent Name of parent key
*
* @return array
*/
public function buildTree($tmp = array(), $id = 'id', $parent = 'parent')
{
$time = microtime(true);
if (empty($id)) {
$id = 'id';
}
if (empty($parent)) {
$parent = 'parent';
}
if (count($tmp) == 1) {
$row = current($tmp);
$tree = array(
$row[$parent] => array(
'children' => array(
$row[$id] => $row,
),
),
);
} else {
$rows = $tree = array();
foreach ($tmp as $v) {
$rows[$v[$id]] = $v;
}
foreach ($rows as $id => &$row) {
if (empty($row[$parent])) {
$tree[$id] = &$row;
} else {
$rows[$row[$parent]]['children'][$id] = &$row;
}
}
}
$this->addTime('Tree was built', microtime(true) - $time);
return $tree;
}
/**
* Prepares fetched rows and process template variables
*
* @param array $rows
*
* @return array
*/
public function prepareRows(array $rows = array())
{
$time = microtime(true);
$prepare = $process = $prepareTypes = array();
if (!empty($this->config['includeTVs']) && (!empty($this->config['prepareTVs']) || !empty($this->config['processTVs']))) {