-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOgerExtjs.class.php
More file actions
939 lines (743 loc) · 24.3 KB
/
OgerExtjs.class.php
File metadata and controls
939 lines (743 loc) · 24.3 KB
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
<?PHP
/*
#LICENSE BEGIN
**********************************************************************
* OgerArch - Archaeological Database is released under the GNU General Public License (GPL) <http://www.gnu.org/licenses>
* Copyright (C) Gerhard Öttl <gerhard.oettl@ogersoft.at>
**********************************************************************
#LICENSE END
*/
/*
* ATTENTION:
* The EXTJSQL PART is highly EXPERIMANTAL and INCOMPLETE.
* There is only implemented what is used currently.
* This EXTJSQL PART is OBSOLETED from 02/2015 and only maintaned for
* backward compability with legacy code.
* New features will not be added THERE. Use OgerExtjSqlTpl instead.
* ---
* Everything outside the
* // PREPARE SQL STATEMENT WITH VALUES FROM EXTJS REQUEST - PREG / STRREPL MODE
* enclosed part will be maintained normal.
*/
/**
* Some methods to simplify Extjs responses.
*/
class OgerExtjs {
/// Debug flag.
//public static $debug = true;
public static $debug = false;
/**
* Encode a php array into json.
* @param $arr The array with values.
* @param $success Boolean flag for the success property. Defaults to true.<br>
* - Null: Do not set a new and do not change an existing success property.
* @return Json encoded array.
* For content type see <http://www.ietf.org/rfc/rfc4627.txt>
* and <http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type>
* and <http://stackoverflow.com/questions/267546/correct-content-type-http-header-for-json>
* For JSON: header('Content-Type: application/json');
* For JSON-P: header('Content-Type: application/javascript');
*/
public static function enc($arr = array(), $success = true) {
if ($success !== null) {
$arr["success"] = (boolean)$success;
}
return json_encode($arr);
} // eo json encoded array
/**
* Encode data from a php array into json.
* @param $arr The array with the data values.
* @param $dataRoot Name of the data root property. Defaults to "data".
* @return Json encoded array.
*/
public static function encData($data = array(), $other = array(), $dataRoot = null, $totalName = null) {
if (!$dataRoot) {
$dataRoot = "data";
}
if (!$totalName) {
$totalName = "total";
}
if (!is_array($other)) {
// numeric primitive-type is reserved for total count in paging grids
if (is_numeric($other)) {
$other = array($totalName => intval($other));
}
else { // otherwise we ignore the more param if not an array
$other = array();
}
}
$all = array($dataRoot => $data);
$all = array_merge($other, $all);
return static::enc($all, true);
} // eo json encoded data array
/**
* Encode a message.
* @param $msg The error message.
* @param $usccess True for success messages otherwise false.
* @return Json encoded array.
*/
public static function msg($msg, $success = true) {
return static::enc(array("msg" => $msg), $success);
} // eo msg
/**
* Encode an error message.
* @param $msg The error message.
* @return Json encoded array.
*/
public static function errorMsg($msg) {
return static::msg($msg, false);
} // eo errorMsg
/**
* Get filter data from extjs request.
* @params $filterName: Name of the filter.
* $req: Request array.
*/
public static function getStoreFilter($filterName = null, $req = null) {
if ($filterName === null) {
$filterName = "filter";
}
if ($req === null) {
$req = $_REQUEST;
}
// no filter or filter is empty
if (!$req[$filterName]) {
return array();
}
// filter is already an array
if (is_array($req[$filterName])) {
return $req[$filterName];
}
// prepare filter
$filter = array();
$items = json_decode($req[$filterName], true);
foreach ((array)$items as $item) {
$filter[$item['property']] = $item['value'];
}
return $filter;
} // eo get ext filter
/**
* Get sort data from extjs request.
* @params $sortName: Name of the sort variable.
* $req: Request array.
*/
public static function getStoreSort($sortName = null, $req = null) {
if ($sortName === null) {
$sortName = "sort";
}
if ($req === null) {
$req = $_REQUEST;
}
// no sort or sort is empty
if (!$req[$sortName]) {
return array();
}
// sort is already an array
if (is_array($req[$sortName])) {
return $req[$sortName];
}
// prepare sort
$sort = array();
$items = json_decode($req[$sortName], true);
foreach ((array)$items as $item) {
$sort[$item['property']] = $item['direction'];
}
return $sort;
} // eo get ext sort
/**
* Get sql limit.
* @params $limitName: Name of the limit variable.
* $req: Request array.
*/
public static function getStoreLimit($limitName = null, $startName = null, $req = null) {
if ($limitName === null) {
$limitName = "limit";
}
if ($startName === null) {
$startName = "start";
}
if ($req === null) {
$req = $_REQUEST;
}
// no limit or limit is empty or non-numeric
if (!array_key_exists($limitName, $req) || !is_numeric($req[$limitName])) {
return "";
}
$limit = "" . intval($req[$limitName]);
// start only makes sense if limit is in prep
if (array_key_exists($startName, $req) && is_numeric($req[$startName])) {
$limit = "" . intval($req[$startName]) . ",$limit";
}
return $limit;
} // eo get limit
// #######################################################
// PREPARE SQL STATEMENT WITH VALUES FROM EXTJS REQUEST - PREG / STRREPL MODE
/**
* Prepare select statement with data from extjs request.
* WORK IN PROGRESS
* @params $tpl: The template containing special sql
* Variables are detectec by the colon (:) prefix.
*/
public static function extjSql($tpl, &$seleVals = array(), $req = null) {
if ($seleVals === null) {
$seleVals = array();
}
if ($req === null) {
$req = $_REQUEST;
}
// SELECT - obsoleted by now, only removes brackets
if (preg_match("/\{\s*SELECT\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = substr($ori, 1, -1);
$tpl = str_replace($ori, $prep, $tpl);
} // eo select
// WHERE
if (preg_match_all("/\{\s*WHERE\s.*?\}/is", $tpl, $matches)) {
foreach ($matches[0] as $ori) {
$prep = static::extjSqlWhere(substr($ori, 1, -1), $seleVals, $req);
$tpl = str_replace($ori, $prep, $tpl);
}
} // eo where
// GROUP BY
// ATTENTION: extjSqlGroupBy() is totaly untested, so disable by now !!!
/*
if (preg_match("/\{\s*GROUP\s+BY\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = static::extjSqlGroupBy(substr($ori, 1, -1));
$tpl = str_replace($ori, $prep, $tpl);
} // eo group by
*/
// HAVING
if (preg_match("/\{\s*HAVING\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = static::extjSqlWhere(substr($ori, 1, -1), $seleVals, $req);
$tpl = str_replace($ori, $prep, $tpl);
} // eo having
// ORDER BY
if (preg_match("/\{\s*ORDER\s+BY\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = static::extjSqlOrderBy(substr($ori, 1, -1), $req);
$tpl = str_replace($ori, $prep, $tpl);
} // eo order by
// LIMIT
$ori = "__EXTJS_LIMIT__";
if (strpos($tpl, $ori) !== false) {
$prep = static::extjSqlLimit($req);
$tpl = str_replace($ori, $prep, $tpl);
} // eo limit
return $tpl;
} // eo select with ext
/**
* Prepare WHERE (or HAVING) clause with data from extjs request.
* WORK IN PROGRESS
* Whitespaces are collapsed sometimes, so formating of sql will be lost.
* @params $tpl: The template containing special sql
* Variables are detectec by the colon (:) prefix.
*/
public static function extjSqlWhere($tpl, &$whereVals = array(), $req = null, $opts = array()) {
//Oger::debugFile("tpl=$tpl");
$tplOri = $tpl;
if ($whereVals === null) {
$whereVals = array();
}
if ($req === null) {
$req = $_REQUEST;
}
// get extjs filter from request
$req['filter'] = static::getStoreFilter(null, $req);
$extFilter = array();
foreach ((array)$req['filter'] as $colName => $value) {
$extFilter[$colName] = $value;
} // eo filter item loop
// detect and remove enclosing {}
$tpl = static::extjSqlStrip($tpl);
// detect, save and remove leading where keyword
if (preg_match("/^\s*(WHERE|HAVING)\s+/i", $tpl, $matches)) {
$kw = $matches[0];
$tpl = implode("", explode($kw, $tpl, 2));
} // keyword
// split at and/or boundery (TODO may be problems without leading whitespace)
$parts = preg_split("/(\s+OR\s+|\s+AND\s+)/i", $tpl, null, PREG_SPLIT_DELIM_CAPTURE);
while (count($parts)) { // we play with shift/unshift, so do not use foreach
$part = array_shift($parts);
// detect and/or glue and remember (and reset NOT keyword - detected later)
$tmp = strtoupper(trim($part));
if ($tmp == "OR" || $tmp == "AND") {
$andOrGlue = $part;
$kwNOT = "";
continue;
}
// detect leading NOT and remember
if (preg_match("/^\s*NOT\s+/i", $part, $matches)) {
$kwNOT = strtoupper(trim($matches[0]));
$part = implode("", explode($kwNOT, $part, 2));
}
$part = trim($part);
// handle grouping of conditions by parenthesis
// check for first opening parenthesis
// if the skipParenthesis parameter is given we have not a "full enclosed"
// WHERE clause but another term that starts with "("
// e.g. a subquery like "(SELECT * FROM ..." or something like that
if (substr(ltrim($part), 0, 1) == "(" && !$opts['skipParenthesis']) {
$parenthTpl = "";
// put current part back because it is called again
array_unshift($parts, $part);
// loop till closing parenthesis
while (count($parts)) {
$tmpPart = trim(array_shift($parts));
// add full part
$parenthTpl .= ($parenthTpl ? " " : "") . $tmpPart;
// check parenthesis balance
$parenthCount = 0;
$strDelimChar = "";
$litStr = "";
for ($i=0; $i < strlen($parenthTpl); $i++) {
$ch = $parenthTpl[$i];
// skip literal strings
if ($strDelimChar) { // we are inside a literal string
$litStr .= $ch; // collect string for possible error message
if ($ch == "\\") { // handle backslash escaping
$litStr .= $parenthTpl[$i + 1];
$i++; // skip next char - never mind which
continue;
}
if ($ch == $strDelimChar) { // end of string char detected
// handle escaping by duplicate delimiter
if ($parenthTpl[$i + 1] == $strDelimChar) {
$litStr .= $parenthTpl[$i + 1];
$i++; // skip duplicate-escaped delimiter
continue;
}
$strDelimChar = "";
$litStr = "";
} // eo final string char
continue;
} // eo inside literal string
if ($ch == '"' || $ch == "'") { // begin of string detected
$strDelimChar = $ch;
$litStr = $ch;
continue;
}
// count parenthesis +/-
if ($ch == "(") { $parenthCount++; }
if ($ch == ")") { $parenthCount--; }
} // eo parenthesis sum
// sanity check that all literal strings are closed
// or better say: that detection of litral strings worked fine
if ($strDelimChar) {
throw new Exception("Unterminated string '{$litStr}' in: $tplOri.");
}
// final closing parenthesis reached
if ($parenthCount <= 0) {
break;
}
} // eo loop till closing parenthesis
// sanity check that all parenthesis are closed
// or better say: that detection of parenthesis worked fine
if ($parenthCount != 0) {
throw new Exception("Missbalanced parenthesis ({$parenthCount}) part={$parenthTpl} in: $tplOri.");
}
// if we have a "full enclosed" part then we remove leading and trailing
// parenthesis (because of endless loop) and recurse
$hasInnerParenthesis = true;
$parenthTpl = trim($parenthTpl);
if (substr($parenthTpl, 0, 1) == "(" &&
substr($parenthTpl, -1) == ")") {
$parenthTpl = substr($parenthTpl, 1, -1);
$hasInnerParenthesis = false;
}
// process parenthesis template as separate template run
$part = trim(static::extjSqlWhere($parenthTpl, $whereVals, $req, array("skipParenthesis" => $hasInnerParenthesis)));
// if parentesis template processing is not empty
// then reassign parenthesis and add to sql
if ($part) {
if ( ! $hasInnerParenthesis) {
$part = "($part)"; // we removed enclosing () above, so we have to add back here
}
$sql .= ($sql ? " {$andOrGlue}" : "") . ($kwNOT ? " {$kwNOT}" : "") . " {$part}";
}
// handling of current parenthesis part finished
// continue with parts after closing parenthesis
continue;
} // parenthesis
if (static::$debug) { echo "part=$part<br>\n"; };
// check if all parameter names for this part are present
$usePart = false;
preg_match_all("/(:[\-\?\+!>@]*?[a-z_][a-z0-9_]+)/i", $part, $matches);
$pnams = $matches[1];
// if no pnames are present we use that part in any case
if (count($pnams) == 0) {
$usePart = true;
}
foreach ($pnams as $key => $pnamOri) {
// remove leading colon
$pnam = substr($pnamOri, 1);
// detect internal commands in first char
$doRemoveColon = false;
$doRemovePnam = false;
$isRequiredParam = false;
$doForceAddParam = false;
$isZombieParam = false;
$valueRequired = false;
//$trimmedValueRequired = false;
// loop over internal command prefix
$intCmdLoop = true;
while ($intCmdLoop) {
// remove colon in final where clause
if (substr($pnam, 0, 1) == "-") { // alternate: "="
$doRemoveColon = true;
$pnam = substr($pnam, 1);
continue;
}
// test if pnam exists and remove pnam afterwards
if (substr($pnam, 0, 1) == "?") { // alternate: "-"
$doRemovePnam = true;
$pnam = substr($pnam, 1);
continue;
}
// throw exption if pnam does not exist
if (substr($pnam, 0, 1) == "!") { // alternate: ":" ????
$isRequiredParam = true;
$pnam = substr($pnam, 1);
continue;
}
// add pnam even if not exits in value arra
if (substr($pnam, 0, 1) == "+") {
$doForceAddParam = true;
$pnam = substr($pnam, 1);
continue;
}
// use only if not empty (untrimmed)
// support ">" for backward compability
if (substr($pnam, 0, 1) == ">" ||
substr($pnam, 0, 1) == "@") { // alternate: "?"
$valueRequired = true;
$pnam = substr($pnam, 1);
continue;
}
$intCmdLoop = false;
} // eo internal cmd check
if (static::$debug) { echo "search for $pnam<br>\n"; };
// check if key exists and get value
//
// if pnam already in where vals, then this has peference
if (array_key_exists($pnam, $whereVals)) {
$value = $whereVals[$pnam];
$usePart = true;
}
// otherwise if pnam exists in extjs filter vals then we take this
elseif (array_key_exists($pnam, $extFilter)) {
$value = $extFilter[$pnam];
$usePart = true;
}
// otherwise if pnam elsewhere in values (request) then we take this
elseif (array_key_exists($pnam, $req)) {
$value = $req[$pnam];
$usePart = true;
}
if (static::$debug) { echo "use $pnam<br>\n"; };
// handle special internal commands and special cases
//
// if param is forced then add part even if pnam not present
// the user is responsible to provide the key and the value elsewhere
if ($doForceAddParam) {
$isZombieParam = true;
$usePart = true;
}
// otherwise check if it is a required param
// if not present till now throw an exeption
if ($isRequiredParam && !$usePart) {
throw new Exception("Required parameter '$pnam' not in value array for {$tpl}.");
}
// otherwise if value is required but not present
// then exlude if value is not present
if ($valueRequired && !$value) {
$usePart = false;
break;
}
// final test if part is used
if (!$usePart) {
break;
}
// write polished pnam out back to where part
if ($doRemoveColon) {
$pnamOut = $pnam;
}
elseif ($doRemovePnam) {
$pnamOut = "";
}
else {
$pnamOut = ":$pnam"; // reasign colon
}
$part = str_replace($pnamOri, $pnamOut, $part);
// remember pnam and value only if placeholder (:var) remains
// do not add zombie parameters - they come from elsewhere
if (substr($pnamOut, 0, 1) == ":" && !$isZombieParam) {
$whereVals[$pnam] = $value;
}
} // eo pnam loop
// do not use empty parts
if (!trim($part)) {
$usePart = false;
}
if (static::$debug) { echo "use=$usePart, usedPart=$part<br>\n"; };
// use part
if ($usePart) {
$sql .= ($sql ? " {$andOrGlue}" : "") . ($kwNOT ? " {$kwNOT}" : "") . " {$part}";
}
} // eo part loop
// if sql collected then prefix with keyword (and extrablanks to avoid collisions)
if ($sql) {
// replace escaped AND / OR part-delimiter
$sql = preg_replace("/\b\\\\AND\b/", "AND", $sql);
$sql = preg_replace("/\b\\\\OR\b/", "OR", $sql);
$sql = " {$kw} {$sql} ";
}
return $sql;
} // eo WHERE with ext
/**
* Prepare ORDER BY clause with data from extjs request.
* WORK IN PROGRESS
* @params $tpl: The template containing special sql
*/
public static function extjSqlOrderBy($tpl, $req = null) {
if ($whereVals === null) {
$whereVals = array();
}
if ($req === null) {
$req = $_REQUEST;
}
// detect, save and remove leading where keyword
if (preg_match("/^\s*ORDER\s+BY\s+/i", $tpl, $matches)) {
$kw = $matches[0];
$tpl = implode("", explode($kw, $tpl, 2));
}
// extract extra sort field info from template
$parts = explode(";", $tpl);
//@file_put_contents("debug.localonly", "tpl=$tpl => " . var_export($parts, true) . "\n\n", FILE_APPEND);
$tplSorter = array();
foreach ((array)$parts as $value) {
$value = trim($value);
if (!$value) {
continue;
}
if (strpos($value, "=") !== false) {
list($key, $value) = explode("=", $value, 2);
$key = trim($key);
$value = trim($value);
}
else { // for stand alone colnames sort expression is same as colname
$key = $value;
}
$tplSorter[$key] = $value;
}
// if no sort expression is present then fill with default sort
// if no default sort exists remove sort key
$defaultSort = $tplSorter[''];
foreach($tplSorter as $key => $value) {
if (!$value) {
if ($defaultSort) {
$tplSorter[$key] = $defaultSort;
}
else {
unset($tplSorter[$key]);
}
}
}
// convert sort info from json to array
$req['sort'] = static::getStoreSort(null, $req);
// loop over sort info from ext
foreach ((array)$req['sort'] as $colName => $direct) {
if ($direct && $direct != "ASC" && $direct != "DESC" && trim($direct) != "") {
throw new Exception("Invalid direction '$direct' for column name '$colName' in ExtJS sort.");
}
// apply sort expression from template when exists,
// otherwise ignore sort request
$sortExpr = trim($tplSorter[$colName]);
if (!$sortExpr) {
continue;
}
// compose sql
// if sort direction placeholder exists replace ALL placeholder
// otherwise append direction if given
$tmpSql = $sortExpr;
if (strpos($tmpSql, "__EXTJS_DIRECTION__") !== false) {
$tmpSql = str_replace("__EXTJS_DIRECTION__", $direct, $tmpSql);
}
elseif($direct) {
$tmpSql .= " $direct";
}
$sql .= ($sql ? "," : "") . $tmpSql;
} // eo ext sort item loop
$sql = trim($sql);
// if no order-by sql is composed, then use the template default sort
// but remove direction placeholder fist
if (!$sql && $defaultSort) {
$sql = str_replace("__EXTJS_DIRECTION__", "", $defaultSort);
}
// if sql collected then prefix with keyword
if ($sql) {
$sql = " {$kw} {$sql} ";
}
return $sql;
} // eo ORDER BY with ext
/**
* Prepare GROUP BY clause with data from extjs request.
* WORK IN PROGRESS
* @params $tpl: The template containing special sql
*/
public static function extjSqlGroupBy($tpl, $req = null) {
if ($whereVals === null) {
$whereVals = array();
}
if ($req === null) {
$req = $_REQUEST;
}
// detect, save and remove leading where keyword
if (preg_match("/^\s*GROUP\s+BY\s+/i", $tpl, $matches)) {
$kw = $matches[0];
$tpl = implode("", explode($kw, $tpl, 2));
}
// extract extra group field info from template
$parts = explode(";", $tpl);
$tplSorter = array();
foreach ((array)$parts as $value) {
$value = trim($value);
if (!$value) {
continue;
}
if (strpos($value, "=") !== false) {
list($key, $value) = explode("=", $value, 2);
$key = trim($key);
$value = trim($value);
}
else { // for stand alone colnames group expression is same as colname
$key = $value;
}
$tplSorter[$key] = $value;
}
// if no group expression is present then fill with default group
// if no default group exists remove group key
$defaultSort = $tplSorter[''];
foreach($tplSorter as $key => $value) {
if (!$value) {
if ($defaultSort) {
$tplSorter[$key] = $defaultSort;
}
else {
unset($tplSorter[$key]);
}
}
}
// convert sort info from json to array
$req['sort'] = static::getStoreSort(null, $req);
// loop over sort info from ext
foreach ((array)$req['sort'] as $colName => $direct) {
if ($direct && $direct != "ASC" && $direct != "DESC" && trim($direct) != "") {
throw new Exception("Invalid direction '$direct' for column name '$colName' in ExtJS sort.");
}
// apply sort expression from template when exists,
// otherwise ignore sort request
$sortExpr = trim($tplSorter[$colName]);
if (!$sortExpr) {
continue;
}
// compose sql
// if sort direction placeholder exists replace ALL placeholder
// otherwise append direction if given
$tmpSql = $sortExpr;
if (strpos($tmpSql, "__EXTJS_DIRECTION__") !== false) {
$tmpSql = str_replace("__EXTJS_DIRECTION__", $direct, $tmpSql);
}
elseif($direct) {
$tmpSql .= " $direct";
}
$sql .= ($sql ? "," : "") . $tmpSql;
} // eo ext sort item loop
$sql = trim($sql);
// if no order-by sql is composed, then use the template default sort
// but remove direction placeholder fist
if (!$sql && $defaultSort) {
$sql = str_replace("__EXTJS_DIRECTION__", "", $defaultSort);
}
// if sql collected then prefix with keyword
if ($sql) {
$sql = " {$kw} {$sql} ";
}
return $sql;
} // eo GROUP BY with ext
/**
* Prepare LIMIT clause with data from extjs request.
* Convenience method to complete the exjSql family.
*/
public static function extjSqlLimit($req = null) {
if ($req === null) {
$req = $_REQUEST;
}
$sql = static::getStoreLimit(null, null, $req);
if (strlen($sql) > 0) {
$sql = "LIMIT $sql";
}
return $sql;
} // eo
/**
* Strip opening and closing curly brackets.
* Preserve leading and trailing spaces.
*/
public static function extjSqlStrip($sql) {
if (substr(ltrim($sql), 0, 1) == "{") {
$pos = strpos($sql, "{");
$sql = substr($sql, 0, $pos) . substr($sql, $pos + 1);
}
if (substr(rtrim($sql), -1) == "}") {
$pos = strrpos($sql, "}");
$sql = substr($sql, 0, $pos) . substr($sql, $pos + 1);
}
return $sql;
} // eo
/**
* Remove clurly brackets from template.
* @params $tpl: The template containing special sql
*/
public static function extjSqlClearCurlyTags($tpl) {
// removes brackets from preg / str-repl mode templates
// SELECT
if (preg_match("/\{\s*SELECT\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = substr($ori, 1, -1);
$tpl = str_replace($ori, $prep, $tpl);
} // eo select
// WHERE
if (preg_match_all("/\{\s*WHERE\s.*?\}/is", $tpl, $matches)) {
foreach ($matches[0] as $ori) {
$prep = substr($ori, 1, -1);
$tpl = str_replace($ori, $prep, $tpl);
}
} // eo where
// GROUP BY
// ATTENTION: extjSqlGroupBy() is totaly untested, so disable by now !!!
/*
if (preg_match("/\{\s*GROUP\s+BY\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = static::extjSqlGroupBy(substr($ori, 1, -1));
$tpl = str_replace($ori, $prep, $tpl);
} // eo group by
*/
// HAVING
if (preg_match("/\{\s*HAVING\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = substr($ori, 1, -1);
$tpl = str_replace($ori, $prep, $tpl);
} // eo having
// ORDER BY
if (preg_match("/\{\s*ORDER\s+BY\s.*?\}/is", $tpl, $matches)) {
$ori = $matches[0];
$prep = substr($ori, 1, -1);
$tpl = str_replace($ori, $prep, $tpl);
} // eo order by
// real parsing
return $tpl;
} // eo remove curly brackets from template
// END OF PREPARE SQL STATEMENT WITH VALUES FROM EXTJS REQUEST - PREG / STR-REPL MODE
// #######################################################
} // end of class
?>