forked from givanz/vtpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Psttt.php
executable file
·692 lines (604 loc) · 19.6 KB
/
Psttt.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
<?php
/**
* Psttt!
* What is this? check this http://www.codeassembly.com/Psttt!-I-am-a-different-php-templating-system
* Full documentation http://www.codeassembly.com/Psttt!-full-documentation
* Copyright (C) 2010 Ziadin Givan www.CodeAssembly.com
*
* 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 3 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, see http://www.gnu.org/licenses/
*/
define('PSTTT_DEBUG', false); #Change to true to enable debugging. (liquibyte)
define('PSTTT_TYPE_LOAD',1);
define('PSTTT_TYPE_SAVE',2);
define('PSTTT_TYPE_SELECTOR',3);
define('PSTTT_TYPE_SELECTOR_STRING',4);
define('PSTTT_TYPE_SELECTOR_PHP',5);
define('PSTTT_TYPE_SELECTOR_VARIABLE',6);
define('PSTTT_TYPE_SELECTOR_FROM',7);
define('PSTTT_CSS_XPATH_TRANSFORM',8);
define('PSTTT_IMPORT_FILE_NOT_EXIST', 9);
define('PSTTT_DEBUG_SHOW_XPATH', false);
define('PSTTT_DEBUG_JQUERY', 'http://code.jquery.com/jquery-1.4.2.min.js');
class Psttt
{
var $template;
var $extension = 'pst';
var $debug = false;
var $debug_log;
//var debug_html; added by liquibyte to instantiate a property being called but not defined.
var $debug_html;
var $_modifiers = array('outerHTML','before','after','deleteAllButFirst','delete','if_exists','hide');
function debug_type_to_string($type)
{
}
function Psttt()
{
if ('PSTTT_DEBUG')
{
$this->debug = true;
}
$this->document = new DomDocument();
}
function debug($type,$message)
{
if ($this->debug)
{
$this->debug_log[][$type]= $message;
}
}
function add_debug_html_line($command, $parameters, $break = '<br/>')
{
$this->debug_html .= "<span> <b>$command</b> $parameters</span>$break";
}
function debug_log_to_html()
{
foreach ($this->debug_log as $line)
{
$type = key($line);
$message = $line[$type];
switch ($type)
{
case PSTTT_TYPE_LOAD:
$this->add_debug_html_line('LOAD',$message);
break;
case PSTTT_TYPE_SAVE:
$this->add_debug_html_line('SAVE',$message);
break;
case PSTTT_TYPE_SELECTOR:
$this->add_debug_html_line('SELECTOR',
"<a href='#'
onclick=\"return psttt_selector_click('$message')\"
onmouseover=\"return psttt_selector_over('$message')\"
onmouseout=\"return psttt_selector_out('$message')\">
$message</a>", '');
break;
case PSTTT_TYPE_SELECTOR_STRING:
$this->add_debug_html_line('INJECT STRING',$message);
break;
case PSTTT_TYPE_SELECTOR_PHP:
$this->add_debug_html_line('INJECT PHP',htmlentities($message));
break;
case PSTTT_TYPE_SELECTOR_VARIABLE:
$this->add_debug_html_line('INJECT VARIABLE',$message);
break;
case PSTTT_TYPE_SELECTOR_FROM:
$this->add_debug_html_line('EXTERNAL HTML',$message);
break;
case PSTTT_CSS_XPATH_TRANSFORM:
if (PSTTT_DEBUG_SHOW_XPATH)
$this->add_debug_html_line('RESULTED XPATH',
"<a href='#'
onclick=\"return psttt_selector_click('$message')\"
onmouseover=\"return psttt_selector_over('$message')\"
onmouseout=\"return psttt_selector_out('$message')\">
$message</a>");
break;
default:
$this->add_debug_html_line('',$message);
break;
}
}
}
function load_template_file($template_file)
{
$this->debug(PSTTT_TYPE_LOAD, $this->template_path . $template_file);
$this->template = @file_get_contents($this->template_path . $template_file);
if (!$this->template) return false;
//echo '<pre>' . htmlentities($this->template) .'</pre>';
/*
* imports
*
* */
$found_imports = true;
//expand imports
while ($found_imports)
{
$found_imports = preg_match_all("/import\(([^\&%'`\@{}~!#\(\)&\^\+,=\[\]]*?\.$this->extension)\)/", $this->template, $imports);
for ($i=0;$i<count($imports[0]);$i++)
{
if (file_exists($this->template_path . $imports[1][$i]))
{
$this->template = str_replace($imports[0][$i], file_get_contents($this->template_path . $imports[1][$i]), $this->template);
} else
{
$this->template = str_replace($imports[0][$i], '', $this->template);
$this->debug(PSTTT_IMPORT_FILE_NOT_EXIST, $this->template_path . $imports[1][$i]);
}
}
}
/**
* placeholders
*
*/
preg_match_all("/(?<![\"'])\/\*.*?\*\/|\s*(?<![\"'])\/\/[^\n]*/s", $this->template, $comments);
preg_match_all("/(?<![\"'])<\?php(.*?)\?>/s", $this->template, $php_code);
preg_match_all("/[\"'][^\"'\\\r\n]*(?:\\.[^\"'\\\r\n]*)*[\"']/s", $this->template, $strings);
//preg_match_all("/([\"'])[^\\\\]*?(\\\\.[^\\\\]*?)*?\\1/s", $str, $matches);
$strings[0] = array_values( array_unique($strings[0]) );
for ($i=0;$i<count($strings[0]);$i++)
{
$patterns_strings[] = "/".preg_quote($strings[0][$i], '/')."/";
// $patterns[] = preg_quote($matches[0][$i], '/');
$placeholders_strings[]="replace_string-$i";
// double backslashes must be escaped if we want to use them in the replacement argument
$strings[0][$i] = str_replace('\\\\', '\\\\\\\\', $strings[0][$i]);
}
$comments[0] = array_values( array_unique($comments[0]) );
$placeholders_comments = array();
for ($i=0;$i<count($comments[0]);$i++)
{
$patterns_comments[] = "/".preg_quote($comments[0][$i], '/')."/";
$placeholders_comments[]="\nreplacecomments-$i\n";
// double backslashes must be escaped if we want to use them in the replacement argument
$comments[0][$i] = str_replace('\\\\', '\\\\\\\\', $comments[0][$i]);
}
$php_code[0] = array_values( $php_code[0] );
for ($i=0;$i<count($php_code[1]);$i++)
{
$patterns_php[] = "/".preg_quote($php_code[0][$i], '/')."/";
// $patterns[] = preg_quote($matches[0][$i], '/');
$placeholders_php[]="replace_php_code-$i";
// double backslashes must be escaped if we want to use them in the replacement argument
$php_code[0][$i] = str_replace('\\\\', '\\\\\\\\', $php_code[1][$i]);
}
if (isset($placeholders_php))
{
$this->template = preg_replace($patterns_php, $placeholders_php, $this->template);
}
if ( $strings[0] )
{
$this->template = preg_replace($patterns_strings, $placeholders_strings, $this->template);
}
/*
*Variables
*/
preg_match_all("/(?<![\"'])(\\$[a-zA-Z0-9->\\[\\]\\']*)/s", $this->template, $variables);
$variables[0] = array_values( $variables[0] );
for ($i=0;$i<count($variables[1]);$i++)
{
$patterns_variables[] = "/".preg_quote($variables[0][$i], '/')."/";
// $patterns[] = preg_quote($matches[0][$i], '/');
$placeholders_variables[]="replace_variable-$i";
// double backslashes must be escaped if we want to use them in the replacement argument
$variables[0][$i] = str_replace('\\\\', '\\\\\\\\', $variables[1][$i]);
}
if ( $variables[0] )
{
$this->template = preg_replace($patterns_variables, $placeholders_variables, $this->template);
}
/*
*Froms
*/
preg_match_all('/from\(([^\|\)]*)(|[^\)]*)?\)/s', $this->template, $froms);
$froms[0] = array_values($froms[0]);
for ($i=0;$i<count($froms[1]);$i++)
{
$patterns_froms[] = "/".preg_quote($froms[0][$i], '/')."/";
// $patterns[] = preg_quote($matches[0][$i], '/');
$placeholders_froms[]="replace_from-$i";
// double backslashes must be escaped if we want to use them in the replacement argument
$froms[0][$i] = str_replace('\\\\', '\\\\\\\\', $froms[1][$i]);
}
if ($froms[0])
{
$this->template = preg_replace($patterns_froms, $placeholders_froms, $this->template);
}
//remove comments
$this->template = preg_replace("/(?<![\"'])\/\*.*?\*\/|\s*(?<![\"'])\/\/[^\n]*/s", '', $this->template);
$this->template = preg_replace('/\n+/',"\n", $this->template);
$this->template = preg_replace('/(?<=\=)\s*\n/','', $this->template);
$this->strings = $strings[0];
$this->php_code = $php_code[0];
$this->variables = $variables[0];
$this->froms = $froms;
$lines = explode("\n",$this->template);
foreach ($lines as $line)
{
$arr = explode('=', trim($line));
if ($arr[0])
{
$this->selectors[] = $arr;
}
}
//echo '<hr/><pre>' . htmlentities($this->template) .'</pre>';
//die();
}
/**
* Convert a CSS-selector into an xPath-query
*
* @return string
* @param string $selector The CSS-selector
*/
function css_to_xpath($selector)
{
$selector = (string) $selector;
$css_selector = array(
// E > F: Matches any F element that is a child of an element E
'/([a-zA-Z#._-])\s*>\s*([a-zA-Z#._-])/',
// E + F: Matches any F element immediately preceded by an element
'/([a-zA-Z#._-])\s*\+\s*([a-zA-Z#._-])/',
// E F: Matches any F element that is a descendant of an E element
'/([a-zA-Z#._-])\s+([a-zA-Z#._-])/',
// E:first-child: Matches element E when E is the first child of its parent
'/(\w):first-child/',
// E[foo]: Matches any E element with the "foo" attribute set (whatever the value)
'/(\w)\[([\w\-]+)]/',
// E[foo="warning"]: Matches any E element whose "foo" attribute value is exactly equal to "warning"
'/(\w)\[([\w\-]+)\=\"(.*)\"]/',
// [foo]: Matches any element with the "foo" attribute set (whatever the value)
'/\[([\w\-]+)]/',
// [foo="warning"]: Matches any element whose "foo" attribute value is exactly equal to "warning"
'/\[([\w\-]+)\=\"(.*)\"]/',
// div.warning: HTML only. The same as DIV[class~="warning"]
'/(\w+|\*)\.([\w\-]+)+/',
// .warning: HTML only. The same as [class~="warning"]
'/\.([\w\-]+)+/',
// E#myid: Matches any E element with id-attribute equal to "myid"
'/(\w+)+\#([\w\-]+)/',
// #myid: Matches any E element with id-attribute equal to "myid"
'/\#([\w\-]+)/'
);
$xpath_query = array(
'\1/\2',
'\1/following-sibling::*[1]/self::\2',
'\1//\2',
'*[1]/self::\1',
'\1 [ @\2 ]',
'\1[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]',
'* [ @\2 ]',
'*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]',
'\1[ contains( concat( " ", @class, " " ), concat( " ", "\2", " " ) ) ]',
'*[ contains( concat( " ", @class, " " ), concat( " ", "\1", " " ) ) ]',
'\1[ @id = "\2" ]',
'*[ @id = "\1" ]'
);
$result = (string) '//'. preg_replace($css_selector, $xpath_query, $selector);
$this->debug(PSTTT_CSS_XPATH_TRANSFORM, $result);
return $result;
}
//function
function _process_template()
{
if ($this->selectors)
foreach($this->selectors as $data)
{
$selector = trim($data[0]);
$selector_components = explode('|', $selector);
$selector = $selector_components[0];
$modifier = (isset($selector_components[1])) ? trim($selector_components[1]) : '';
$value = (isset($data[1])) ? trim($data[1]) : '';
//enable disable debugging
if (!$selector) continue;
$this->debug(PSTTT_TYPE_SELECTOR, $selector);
if ($selector == 'debug') $this->debug = ($value=='true') ? true:false;else
{
$value_elements = explode('-', $value);
switch($value_elements[0])
{
case 'replace_string':
$val = trim($this->strings[(int) $value_elements[1]],'"\'');
$this->debug(PSTTT_TYPE_SELECTOR_STRING, $this->strings[(int) $value_elements[1]]);
break;
case 'replace_php_code':
if ($modifier && !in_array($modifier, $this->_modifiers))
{
$val = '<script language="php">' . $this->php_code[(int) $value_elements[1]] . '</script>';
} else
{
$val = '<script language="php"><![CDATA[' . $this->php_code[(int) $value_elements[1]] . ']]></script>';
}
$this->debug(PSTTT_TYPE_SELECTOR_PHP, $this->php_code[(int) $value_elements[1]]);
break;
case 'replace_variable':
if ($modifier)
{
if ($modifier == 'if_exists' || $modifier == 'hide')
{
$val = $this->variables[(int) $value_elements[1]];
} else if (!in_array($modifier, $this->_modifiers))
{
$val = '<script language="php"> echo ' . $this->variables[(int) $value_elements[1]] . ';</script>';
}
} else
{
$val = '<script language="php"><![CDATA[ echo ' . $this->variables[(int) $value_elements[1]] . ';]]></script>';
}
$this->debug(PSTTT_TYPE_SELECTOR_VARIABLE, $this->variables[(int) $value_elements[1]]);
break;
case 'replace_from':
$from = $this->froms[0][(int) $value_elements[1]];//external html file
$from_selector = substr($this->froms[2][(int) $value_elements[1]],1);
//load specified selector if available otherwise load html with the same selector
if (empty($from_selector))
{
//override default selector with the provided one
$from_selector = $selector;
}
//get html
$this->debug(PSTTT_TYPE_SELECTOR_FROM,$from);
$val = $this->load_from_external_html($from, $from_selector);
break;
}
$elements = $this->xpath->query($this->css_to_xpath($selector));
switch ($modifier)
{
case 'outerHTML':
$this->outerHTML($elements, $val);
break;
case 'before':
$this->insertBefore($elements, $val);
break;
case 'after':
$this->insertAfter($elements, $val);
break;
case 'deleteAllButFirst':
$this->deleteAllButFirst($elements, $val);
break;
case 'delete':
$this->delete($elements, $val);
case 'if_exists':
$this->if_exists($elements, $val);
break;
case 'hide':
$this->hide($elements, $val);
break;
case '':
$this->innerHTML($elements, $val);
break;
default:
$this->setAttribute($elements, $modifier, $val);
break;
}
}
}
}
function remove_children($node)
{
while ($node->firstChild)
{
while ($node->firstChild->firstChild)
{
$this->remove_children($node->firstChild);
}
$node->removeChild($node->firstChild);
}
}
function innerHTML($node_list, $html = false)
{
foreach ($node_list as $node)
{
if($html === false)
{
$doc = new DOMDocument();
foreach ($node->childNodes as $child)
$doc->appendChild($doc->importNode($child, true));
return $doc->saveHTML();
} else
{
$this->remove_children($node);
if($html == '') continue;
$f = $this->document->createDocumentFragment();
$f->appendXML($html);
$node->appendChild($f);
}
}
}
function if_exists($node_list, $variable = false)
{
foreach ($node_list as $node)
{
if($variable == '') continue;
//before
$html = "<script language=\"php\">if ($variable) {</script>";
$f = $this->document->createDocumentFragment();
$f->appendXML($html);
$node->parentNode->insertBefore( $f, $node);
//after
$html = "<script language=\"php\">}</script>";
$f = $this->document->createDocumentFragment();
$f->appendXML($html);
//$node->parentNode->appendChild( $f );
$node->parentNode->insertBefore( $f, $node->nextSibling);
}
}
function hide($node_list, $variable = false)
{
foreach ($node_list as $node)
{
if($variable == '') continue;
//before
$html = "<script language=\"php\">if (!$variable) {</script>";
$f = $this->document->createDocumentFragment();
$f->appendXML($html);
$node->parentNode->insertBefore( $f, $node);
//after
$html = "<script language=\"php\">}</script>";
$f = $this->document->createDocumentFragment();
$f->appendXML($html);
//$node->parentNode->appendChild( $f );
$node->parentNode->insertBefore( $f, $node->nextSibling);
}
}
function insertBefore($node_list, $html = false)
{
foreach ($node_list as $node)
{
if($html == '') continue;
$f = $this->document->createDocumentFragment();
$f->appendXML($html);
$node->parentNode->insertBefore( $f, $node);
}
}
function insertAfter($node_list, $html = false)
{
foreach ($node_list as $node)
{
if($html == '') continue;
$f = $this->document->createDocumentFragment();
$f->appendXML($html);
//$node->parentNode->appendChild( $f );
$node->parentNode->insertBefore( $f, $node->nextSibling);
}
}
function deleteAllButFirst($node_list, $html = false)
{
$first = true;
foreach ($node_list as $node)
{
if (!$first)
{
$this->remove_children($node);
$node->parentNode->removeChild($node);
}
$first = false;
}
}
function delete($node_list, $html = false)
{
foreach ($node_list as $node)
{
$this->remove_children($node);
$node->parentNode->removeChild($node);
}
}
function setAttribute($node_list, $attribute, $val)
{
foreach ($node_list as $node)
{
$node->setAttribute($attribute,$val);
}
}
function get_inner_html($element)
{
$innerHTML = "";
$tmp_dom = new DOMDocument();
$tmp_dom->appendChild($tmp_dom->importNode($element, true));
$innerHTML.=trim($tmp_dom->saveHTML());
return '<![CDATA[' . $innerHTML . ']]>';
}
function load_from_external_html($from, $selector)
{
$document = new DomDocument();
@$document->loadHTMLFile($this->html_path . $from);
$xpath = new DOMXpath($document);
$elements = $xpath->query($this->css_to_xpath($selector));
return $this->get_inner_html($elements->item(0));
}
function load_html_template($html_file)
{
$this->debug(PSTTT_TYPE_LOAD, $this->html_path . $html_file);
@$this->document->loadHTMLFile($this->html_path . $html_file);
//original document used to extract selectors
$this->original_document = clone($this->document);
$this->xpath = new DOMXpath($this->document );
}
function save_compiled_template($compiled_file)
{
$this->_process_template();
$html = $this->document ->saveHTML();
$html = preg_replace_callback('@<script(%20|\s)language=(%22|")php(%22|")>.*?</script>@s',
create_function(
'$matches',
'return urldecode(html_entity_decode($matches[0]));'
), $html);//sad hack :(
$this->debug(PSTTT_TYPE_SAVE, $compiled_file);
//show debug console if needed
if ($this->debug_log)
{
$this->debug_log_to_html();
$PSTTT_DEBUG_JQUERY = PSTTT_DEBUG_JQUERY;
echo <<<HTML
<script src="$PSTTT_DEBUG_JQUERY"></script>
<script>
function psttt_selector_over(selector)
{
jQuery(selector).addClass('pstt_selected');
return false;
}
function psttt_selector_out(selector)
{
jQuery(selector).removeClass('pstt_selected');
return false;
}
//this needs firebug or equivalent
function psttt_selector_click(selector)
{
console.log(jQuery(selector));
return false;
}
function psttt_hide(selector)
{
if (jQuery(".psttt_console_log_content").css('display') == 'none')
{
jQuery(".psttt_console_log").css({height:"350px"});
} else
{
jQuery(".psttt_console_log").css({height:"30px"});
}
jQuery(".psttt_console_log_content").toggle("slow");
return false;
}
function psttt_close()
{
jQuery(".psttt_console_log").remove()
return false;
}
</script>
<style>
.pstt_selected
{
border:5px solid red !important;
}
html
{
padding-bottom:350px;
}
.psttt_console_log
{
background:#fff;z-index:10000;position:fixed;bottom:0;width:100%;height:300px;overflow:auto;border:1px solid #000;
}
</style>
<div class="psttt_console_log">
<a href="..//pst/doc/index.html">Psttt!</a>
<a href="#" onclick="psttt_hide()">Toggle</a>
<a href="#" onclick="psttt_close()">Close</a>
<div class="psttt_console_log_content">
$this->debug_html;
</div>
</div>
HTML;
}
return file_put_contents($compiled_file, $html);
}
}