-
Notifications
You must be signed in to change notification settings - Fork 2
/
your.class.php
537 lines (497 loc) · 19.5 KB
/
your.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
<?php
/**
* @license public domain
* @package class helper methods
*/
class ClassName {
const VERSION = '1.0.0';
const RELEASE = 'pl';
/**
* modX object
* @var object
*/
public $modx;
/**
* $scriptProperties
* @var array
*/
public $config;
/**
* To hold error message
* @var array
*/
private $_error = array();
/**
* To hold output message
* @var array
*/
private $_output = array();
/**
* To hold placeholder array, flatten array with prefixable
* @var array
*/
private $_placeholders = array();
/**
* store the chunk's HTML to property to save memory of loop rendering
* @var array
*/
private $_chunks = array();
/**
* constructor
* @param modX $modx
* @param array $config parameters
*/
public function __construct(modX $modx, $config = array()) {
$this->modx = & $modx;
$config = is_array($config) ? $config : array();
$basePath = $this->modx->getOption('mypackage.core_path', $config, $this->modx->getOption('core_path') . 'components/mypackage/');
$assetsUrl = $this->modx->getOption('mypackage.assets_url', $config, $this->modx->getOption('assets_url') . 'components/mypackage/');
$this->config = array_merge(array(
'version' => self::VERSION . '-' . self::RELEASE,
'basePath' => $basePath,
'corePath' => $basePath,
'modelPath' => $basePath . 'model/',
'processorsPath' => $basePath . 'processors/',
'chunksPath' => $basePath . 'elements/chunks/',
'templatesPath' => $basePath . 'templates/',
'jsUrl' => $assetsUrl . 'js/',
'cssUrl' => $assetsUrl . 'css/',
'assetsUrl' => $assetsUrl,
'connectorUrl' => $assetsUrl . 'connector.php',
'phsPrefix' => '',
), $config);
$this->modx->lexicon->load('mypackage:default');
$tablePrefix = $this->modx->getOption('mypackage.table_prefix', null, $this->modx->config[modX::OPT_TABLE_PREFIX] . 'mypackage_');
$this->modx->addPackage('mypackage', $this->config['modelPath'], $tablePrefix);
}
/**
* Set class configuration exclusively for multiple snippet calls
* @param array $config snippet's parameters
*/
public function setConfigs(array $config = array()) {
$this->config = array_merge($this->config, $config);
}
/**
* Define individual config for the class
* @param string $key array's key
* @param string $val array's value
*/
public function setConfig($key, $val) {
$this->config[$key] = $val;
}
/**
* Set string error for boolean returned methods
* @return void
*/
public function setError($msg) {
$this->_error[] = $msg;
}
/**
*
* Get string error for boolean returned methods
* @param string $delimiter delimiter of the imploded output (default: "\n")
* @return string output
*/
public function getError($delimiter = "\n") {
if ($delimiter === '\n') {
$delimiter = "\n";
}
return @implode($delimiter, $this->_error);
}
/**
* Set string output for boolean returned methods
* @return void
*/
public function setOutput($msg) {
$this->_output[] = $msg;
}
/**
* Get string output for boolean returned methods
* @param string $delimiter delimiter of the imploded output (default: "\n")
* @return string output
*/
public function getOutput($delimiter = "\n") {
if ($delimiter === '\n') {
$delimiter = "\n";
}
return @implode($delimiter, $this->_output);
}
/**
* Set internal placeholder
* @param string $key key
* @param string $value value
* @param string $prefix add prefix if it's required
*/
public function setPlaceholder($key, $value, $prefix = '') {
$prefix = !empty($prefix) ? $prefix : (isset($this->config['phsPrefix']) ? $this->config['phsPrefix'] : '');
$this->_placeholders[$prefix . $key] = $this->trimString($value);
}
/**
* Get an internal placeholder
* @param string $key key
* @return string value
*/
public function getPlaceholder($key) {
return $this->_placeholders[$key];
}
/**
* Set internal placeholders
* @param array $placeholders placeholders in an associative array
* @param string $prefix add prefix if it's required
* @param boolean $merge define whether the output will be merge to global properties or not
* @param string $delimiter define placeholder's delimiter
* @return mixed boolean|array of placeholders
*/
public function setPlaceholders($placeholders, $prefix = '', $merge = true, $delimiter = '.') {
if (empty($placeholders)) {
return FALSE;
}
$prefix = !empty($prefix) ? $prefix : (isset($this->config['phsPrefix']) ? $this->config['phsPrefix'] : '');
$placeholders = $this->trimArray($placeholders);
$placeholders = $this->implodePhs($placeholders, rtrim($prefix, $delimiter));
// enclosed private scope
if ($merge) {
$this->_placeholders = array_merge($this->_placeholders, $placeholders);
}
// return only for this scope
return $placeholders;
}
/**
* Get internal placeholders in an associative array
* @return array
*/
public function getPlaceholders() {
return $this->_placeholders;
}
/**
* Merge multi dimensional associative arrays with separator
* @param array $array raw associative array
* @param string $keyName parent key of this array
* @param string $separator separator between the merged keys
* @param array $holder to hold temporary array results
* @return array one level array
*/
public function implodePhs(array $array, $keyName = null, $separator = '.', array $holder = array()) {
$phs = !empty($holder) ? $holder : array();
foreach ($array as $k => $v) {
$key = !empty($keyName) ? $keyName . $separator . $k : $k;
if (is_array($v)) {
$phs = $this->implodePhs($v, $key, $separator, $phs);
} else {
$phs[$key] = $v;
}
}
return $phs;
}
/**
* Trim string value
* @param string $string source text
* @param string $charlist defined characters to be trimmed
* @link http://php.net/manual/en/function.trim.php
* @return string trimmed text
*/
public function trimString($string, $charlist = null) {
if (empty($string) && !is_numeric($string)) {
return '';
}
$string = htmlentities($string);
// blame TinyMCE!
$string = preg_replace('/(Â| )+/i', '', $string);
$string = trim($string, $charlist);
$string = trim(preg_replace('/\s+^(\r|\n|\r\n)/', ' ', $string));
$charSet = $this->modx->getOption('modx_charset', null, 'UTF-8');
$string = html_entity_decode($string, ENT_COMPAT | ENT_HTML5, $charSet);
return $string;
}
/**
* Trim array values
* @param array $array array contents
* @param string $charlist [default: null] defined characters to be trimmed
* @link http://php.net/manual/en/function.trim.php
* @return array trimmed array
*/
public function trimArray($input, $charlist = null) {
if (is_array($input)) {
$output = array_map(array($this, 'trimArray'), $input);
} else {
$output = $this->trimString($input, $charlist);
}
return $output;
}
/**
* Parsing template
* @param string $tpl @BINDINGs options
* @param array $phs placeholders
* @return string parsed output
* @link http://forums.modx.com/thread/74071/help-with-getchunk-and-modx-speed-please?page=2#dis-post-413789
*/
public function parseTpl($tpl, array $phs = array()) {
$output = '';
if (isset($this->_chunks[$tpl]) && !empty($this->_chunks[$tpl])) {
return $this->parseTplCode($this->_chunks[$tpl], $phs);
}
if (preg_match('/^(@CODE|@INLINE)/i', $tpl)) {
$tplString = preg_replace('/^(@CODE|@INLINE)/i', '', $tpl);
// tricks @CODE: / @INLINE:
$tplString = ltrim($tplString, ':');
$tplString = trim($tplString);
$this->_chunks[$tpl] = $tplString;
$output = $this->parseTplCode($tplString, $phs);
} elseif (preg_match('/^@FILE/i', $tpl)) {
$tplFile = preg_replace('/^@FILE/i', '', $tpl);
// tricks @FILE:
$tplFile = ltrim($tplFile, ':');
$tplFile = trim($tplFile);
$tplFile = $this->replacePropPhs($tplFile);
try {
$output = $this->parseTplFile($tplFile, $phs);
} catch (Exception $e) {
$err = $e->getMessage();
$this->setError($err);
$this->modx->log(modX::LOG_LEVEL_ERROR, $err);
return false;
}
}
// ignore @CHUNK / @CHUNK: / empty @BINDING
else {
$tplChunk = preg_replace('/^@CHUNK/i', '', $tpl);
// tricks @CHUNK:
$tplChunk = ltrim($tpl, ':');
$tplChunk = trim($tpl);
$chunk = $this->modx->getObject('modChunk', array('name' => $tplChunk), true);
if (empty($chunk)) {
// try to use @splittingred's fallback
$f = $this->config['chunksPath'] . strtolower($tplChunk) . '.chunk.tpl';
try {
$output = $this->parseTplFile($f, $phs);
} catch (Exception $e) {
$err = 'Chunk: ' . $tplChunk . ' is not found, neither the file ' . $e->getMessage();
$this->setError($err);
$this->modx->log(modX::LOG_LEVEL_ERROR, $err);
return false;
}
} else {
// $output = $this->modx->getChunk($tplChunk, $phs);
/**
* @link http://forums.modx.com/thread/74071/help-with-getchunk-and-modx-speed-please?page=4#dis-post-464137
*/
$chunk = $this->modx->getParser()->getElement('modChunk', $tplChunk);
$this->_chunks[$tpl] = $chunk->get('content');
$chunk->setCacheable(false);
$chunk->_processed = false;
$output = $chunk->process($phs);
}
}
return $output;
}
/**
* Parsing inline template code
* @param string $code HTML with tags
* @param array $phs placeholders
* @return string parsed output
*/
public function parseTplCode($code, array $phs = array()) {
$chunk = $this->modx->newObject('modChunk');
$chunk->setContent($code);
$chunk->setCacheable(false);
$phs = $this->replacePropPhs($phs);
$chunk->_processed = false;
return $chunk->process($phs);
}
/**
* Parsing file based template
* @param string $file file path
* @param array $phs placeholders
* @return string parsed output
* @throws Exception if file is not found
*/
public function parseTplFile($file, array $phs = array()) {
if (!file_exists($file)) {
throw new Exception('File: ' . $file . ' is not found.');
}
if (empty($this->_chunks[$file])) {
$o = file_get_contents($file);
$this->_chunks[$file] = $o;
}
$chunk = $this->modx->newObject('modChunk');
// just to create a name for the modChunk object.
$name = strtolower(basename($file));
$name = rtrim($name, '.tpl');
$name = rtrim($name, '.chunk');
$chunk->set('name', $name);
$chunk->setCacheable(false);
$chunk->setContent($this->_chunks[$file]);
$chunk->_processed = false;
$output = $chunk->process($phs);
return $output;
}
/**
* Parse template recursively for nesting items
* @param string $tplItem name of item template
* @param string $tplWrapper name of wrapper template
* @param array $phs placeholders
* @param int $docId if required to make a link, add the document ID here
* @param string $childKey if required, define the keyname of the child's placeholder here
* @return string final output
*/
public function parseRecursiveTpl($tplItem, $tplWrapper, $phs = array(), $docId = null, $childKey = 'children') {
if (empty($phs)) {
return;
}
$childrenOutput = array();
foreach ($phs as $k => $v) {
if (is_array($v) && !empty($v)) {
$children = array();
foreach ($v as $i => $j) {
if (is_array($j) && !empty($j)) {
if (!empty($docId)) {
array_walk($j, create_function('&$value,$key', '$value[\'docId\'] = ' . $docId . ';'));
}
$children[] = $this->parseRecursiveTpl($tplItem, $tplWrapper, $j, $docId);
}
}
$v[$childKey] = @implode('', $children);
} else {
$v[$childKey] = '';
}
/**
* Start the parsing from here
*/
if (!empty($docId)) {
$v['docId'] = $docId;
}
$v = $this->setPlaceholders($v, $this->config['phsPrefix']);
$output = $this->parseTpl($tplItem, $v);
$childrenOutput[] = $this->processElementTags($output);
}
$childrenWrapper = array(
$childKey . '.rows' => @implode('', $childrenOutput),
$childKey . '.count' => count($childrenOutput)
);
$childrenWrapper = $this->setPlaceholders($childrenWrapper, $this->config['phsPrefix']);
$wrapperOutput = $this->parseTpl($tplWrapper, $childrenWrapper);
return $wrapperOutput;
}
/**
* If the chunk is called by AJAX processor, it needs to be parsed for the
* other elements to work, like snippet and output filters.
*
* Example:
* <pre><code>
* <?php
* $content = $myObject->parseTpl('tplName', $placeholders);
* $content = $myObject->processElementTags($content);
* </code></pre>
*
* @param string $content the chunk output
* @param array $options option for iteration
* @return string parsed content
*/
public function processElementTags($content, array $options = array()) {
$maxIterations = intval($this->modx->getOption('parser_max_iterations', $options, 10));
if (!$this->modx->parser) {
$this->modx->getParser();
}
$this->modx->parser->processElementTags('', $content, true, false, '[[', ']]', array(), $maxIterations);
$this->modx->parser->processElementTags('', $content, true, true, '[[', ']]', array(), $maxIterations);
return $content;
}
/**
* Replace the property's placeholders
* @param string|array $subject Property
* @return array The replaced results
*/
public function replacePropPhs($subject) {
$pattern = array(
'/\{core_path\}/',
'/\{base_path\}/',
'/\{assets_url\}/',
'/\{filemanager_path\}/',
'/\[\[\+\+core_path\]\]/',
'/\[\[\+\+base_path\]\]/'
);
$replacement = array(
$this->modx->getOption('core_path'),
$this->modx->getOption('base_path'),
$this->modx->getOption('assets_url'),
$this->modx->getOption('filemanager_path'),
$this->modx->getOption('core_path'),
$this->modx->getOption('base_path')
);
if (is_array($subject)) {
$parsedString = array();
foreach ($subject as $k => $s) {
if (is_array($s)) {
$s = $this->replacePropPhs($s);
}
$parsedString[$k] = preg_replace($pattern, $replacement, $s);
}
return $parsedString;
} else {
return preg_replace($pattern, $replacement, $subject);
}
}
/**
* Replacing MODX's getCount(), because it has bug on counting SQL with function.<br>
* Retrieves a count of xPDOObjects by the specified xPDOCriteria.
*
* @param string $className Class of xPDOObject to count instances of.
* @param mixed $criteria Any valid xPDOCriteria object or expression.
* @return integer The number of instances found by the criteria.
* @see xPDO::getCount()
* @link http://forums.modx.com/thread/88619/getcount-fails-if-the-query-has-aggregate-leaving-having-039-s-field-undefined The discussion for this
*/
public function getQueryCount($className, $criteria= null) {
$count= 0;
if ($query= $this->modx->newQuery($className, $criteria)) {
$expr= '*';
if ($pk= $this->modx->getPK($className)) {
if (!is_array($pk)) {
$pk= array ($pk);
}
$expr= $this->modx->getSelectColumns($className, 'alias', '', $pk);
}
$query->prepare();
$sql = $query->toSQL();
$stmt= $this->modx->query("SELECT COUNT($expr) FROM ($sql) alias");
if ($stmt) {
$tstart = microtime(true);
if ($stmt->execute()) {
$this->modx->queryTime += microtime(true) - $tstart;
$this->modx->executedQueries++;
if ($results= $stmt->fetchAll(PDO::FETCH_COLUMN)) {
$count= reset($results);
$count= intval($count);
}
} else {
$this->modx->queryTime += microtime(true) - $tstart;
$this->modx->executedQueries++;
$this->modx->log(modX::LOG_LEVEL_ERROR, "[" . __CLASS__ . "] Error " . $stmt->errorCode() . " executing statement: \n" . print_r($stmt->errorInfo(), true), '', __METHOD__, __FILE__, __LINE__);
}
}
}
return $count;
}
/**
* Returns select statement for easy reading
*
* @access public
* @param xPDOQuery $query The query to print
* @return string The select statement
* @author Coroico <[email protected]>
*/
public function niceQuery(xPDOQuery $query = null) {
$searched = array("SELECT", "GROUP_CONCAT", "LEFT JOIN", "INNER JOIN", "EXISTS", "LIMIT", "FROM",
"WHERE", "GROUP BY", "HAVING", "ORDER BY", "OR", "AND", "IFNULL", "ON", "MATCH", "AGAINST",
"COUNT");
$replace = array(" \r\nSELECT", " \r\nGROUP_CONCAT", " \r\nLEFT JOIN", " \r\nINNER JOIN", " \r\nEXISTS", " \r\nLIMIT", " \r\nFROM",
" \r\nWHERE", " \r\nGROUP BY", " \r\nHAVING", " ORDER BY", " \r\nOR", " \r\nAND", " \r\nIFNULL", " \r\nON", " \r\nMATCH", " \r\nAGAINST",
" \r\nCOUNT");
$output = '';
if (isset($query)) {
$query->prepare();
$output = str_replace($searched, $replace, " " . $query->toSQL());
}
return $output;
}
}