-
Notifications
You must be signed in to change notification settings - Fork 15
/
Savant3.php
executable file
·1337 lines (1143 loc) · 28.6 KB
/
Savant3.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
/**
*
* Provides an object-oriented template system for PHP5.
*
* @package Savant3
*
* @author Paul M. Jones <pmjones@ciaweb.net>
*
* @license http://www.gnu.org/copyleft/lesser.html LGPL
*
* @version $Id: Savant3.php,v 1.42 2006/01/01 18:31:00 pmjones Exp $
*
*/
/**
* Always have these classes available.
*/
include_once dirname(__FILE__) . '/Savant3/Filter.php';
include_once dirname(__FILE__) . '/Savant3/Plugin.php';
/**
*
* Provides an object-oriented template system for PHP5.
*
* Savant3 helps you separate business logic from presentation logic
* using PHP as the template language. By default, Savant3 does not
* compile templates. However, you may pass an optional compiler object
* to compile template source to include-able PHP code. It is E_STRICT
* compliant for PHP5.
*
* Please see the documentation at {@link http://phpsavant.com/}, and be
* sure to donate! :-)
*
* @author Paul M. Jones <pmjones@ciaweb.net>
*
* @package Savant3
*
* @version @package_version@
*
*/
class Savant3 {
/**
*
* Array of configuration parameters.
*
* @access protected
*
* @var array
*
*/
protected $__config = array(
'template_path' => array(),
'resource_path' => array(),
'error_text' => "\n\ntemplate error, examine fetch() result\n\n",
'exceptions' => false,
'autoload' => false,
'compiler' => null,
'filters' => array(),
'plugins' => array(),
'template' => null,
'plugin_conf' => array(),
'extract' => false,
'fetch' => null,
'escape' => array('htmlspecialchars'),
);
// -----------------------------------------------------------------
//
// Constructor and magic methods
//
// -----------------------------------------------------------------
/**
*
* Constructor.
*
* @access public
*
* @param array $config An associative array of configuration keys for
* the Savant3 object. Any, or none, of the keys may be set.
*
* @return object Savant3 A Savant3 instance.
*
*/
public function __construct($config = null)
{
// force the config to an array
settype($config, 'array');
// set the default template search path
if (isset($config['template_path'])) {
// user-defined dirs
$this->setPath('template', $config['template_path']);
} else {
// no directories set, use the
// default directory only
$this->setPath('template', null);
}
// set the default resource search path
if (isset($config['resource_path'])) {
// user-defined dirs
$this->setPath('resource', $config['resource_path']);
} else {
// no directories set, use the
// default directory only
$this->setPath('resource', null);
}
// set the error reporting text
if (isset($config['error_text'])) {
$this->setErrorText($config['error_text']);
}
// set the autoload flag
if (isset($config['autoload'])) {
$this->setAutoload($config['autoload']);
}
// set the extraction flag
if (isset($config['extract'])) {
$this->setExtract($config['extract']);
}
// set the exceptions flag
if (isset($config['exceptions'])) {
$this->setExceptions($config['exceptions']);
}
// set the template to use for output
if (isset($config['template'])) {
$this->setTemplate($config['template']);
}
// set the output escaping callbacks
if (isset($config['escape'])) {
$this->setEscape($config['escape']);
}
// set the default plugin configs
if (isset($config['plugin_conf']) && is_array($config['plugin_conf'])) {
foreach ($config['plugin_conf'] as $name => $opts) {
$this->setPluginConf($name, $opts);
}
}
// set the default filter callbacks
if (isset($config['filters'])) {
$this->addFilters($config['filters']);
}
}
/**
*
* Executes a main plugin method with arbitrary parameters.
*
* @access public
*
* @param string $func The plugin method name.
*
* @param array $args The parameters passed to the method.
*
* @return mixed The plugin output, or a Savant3_Error with an
* ERR_PLUGIN code if it can't find the plugin.
*
*/
public function __call($func, $args)
{
$plugin = $this->plugin($func);
if ($this->isError($plugin)) {
return $plugin;
}
// try to avoid the very-slow call_user_func_array()
// for plugins with very few parameters. thanks to
// Andreas Korthaus for profiling the code to find
// the slowdown.
switch (count($args)) {
case 0:
return $plugin->$func();
case 1:
return $plugin->$func($args[0]);
break;
case 2:
return $plugin->$func($args[0], $args[1]);
break;
case 3:
return $plugin->$func($args[0], $args[1], $args[2]);
break;
default:
return call_user_func_array(array($plugin, $func), $args);
break;
}
}
/**
*
* Magic method to echo this object as template output.
*
* Note that if there is an error, this will output a simple
* error text string and will not return an error object. Use
* fetch() to get an error object when errors occur.
*
* @access public
*
* @return string The template output.
*
*/
public function __toString()
{
return $this->getOutput();
}
/**
*
* Reports the API version for this class.
*
* @access public
*
* @return string A PHP-standard version number.
*
*/
public function apiVersion()
{
return '@package_version@';
}
/**
*
* Returns an internal plugin object; creates it as needed.
*
* @access public
*
* @param string $name The plugin name. If this plugin has not
* been created yet, this method creates it automatically.
*
* @return mixed The plugin object, or a Savant3_Error with an
* ERR_PLUGIN code if it can't find the plugin.
*
*/
public function plugin($name)
{
// shorthand reference
$plugins =& $this->__config['plugins'];
$autoload = $this->__config['autoload'];
// is the plugin method object already instantiated?
if (! array_key_exists($name, $plugins)) {
// not already instantiated, so load it up.
// set up the class name.
$class = "Savant3_Plugin_$name";
// has the class been loaded?
if (! class_exists($class, $autoload)) {
// class is not loaded, set up the file name.
$file = "$class.php";
// make sure the class file is available from the resource path.
$result = $this->findFile('resource', $file);
if (! $result) {
// not available, this is an error
return $this->error(
'ERR_PLUGIN',
array('method' => $name)
);
} else {
// available, load the class file
include_once $result;
}
}
// get the default configuration for the plugin.
$plugin_conf =& $this->__config['plugin_conf'];
if (! empty($plugin_conf[$name])) {
$opts = $plugin_conf[$name];
} else {
$opts = array();
}
// add the Savant reference
$opts['Savant'] = $this;
// instantiate the plugin with its options.
$plugins[$name] = new $class($opts);
}
// return the plugin object
return $plugins[$name];
}
// -----------------------------------------------------------------
//
// Public configuration management (getters and setters).
//
// -----------------------------------------------------------------
/**
*
* Returns a copy of the Savant3 configuration parameters.
*
* @access public
*
* @param string $key The specific configuration key to return. If null,
* returns the entire configuration array.
*
* @return mixed A copy of the $this->__config array.
*
*/
public function getConfig($key = null)
{
if (is_null($key)) {
// no key requested, return the entire config array
return $this->__config;
} elseif (empty($this->__config[$key])) {
// no such key
return null;
} else {
// return the requested key
return $this->__config[$key];
}
}
/**
*
* Sets __autoload() usage on or off.
*
* @access public
*
* @param bool $flag True to use __autoload(), false to not use it.
*
* @return void
*
*/
public function setAutoload($flag)
{
$this->__config['autoload'] = (bool) $flag;
}
/**
*
* Sets a custom compiler/pre-processor callback for template sources.
*
* By default, Savant3 does not use a compiler; use this to set your
* own custom compiler (pre-processor) for template sources.
*
* @access public
*
* @param mixed $compiler A compiler callback value suitable for the
* first parameter of call_user_func(). Set to null/false/empty to
* use PHP itself as the template markup (i.e., no compiling).
*
* @return void
*
*/
public function setCompiler($compiler)
{
$this->__config['compiler'] = $compiler;
}
/**
*
* Sets the custom error text for __toString().
*
* @access public
*
* @param string $text The error text when a template is echoed.
*
* @return void
*
*/
public function setErrorText($text)
{
$this->__config['error_text'] = $text;
}
/**
*
* Sets whether or not exceptions will be thrown.
*
* @access public
*
* @param bool $flag True to turn on exception throwing, false
* to turn it off.
*
* @return void
*
*/
public function setExceptions($flag)
{
$this->__config['exceptions'] = (bool) $flag;
}
/**
*
* Sets whether or not variables will be extracted.
*
* @access public
*
* @param bool $flag True to turn on variable extraction, false
* to turn it off.
*
* @return void
*
*/
public function setExtract($flag)
{
$this->__config['extract'] = (bool) $flag;
}
/**
*
* Sets config array for a plugin.
*
* @access public
*
* @param string $plugin The plugin to configure.
*
* @param array $config The configuration array for the plugin.
*
* @return void
*
*/
public function setPluginConf($plugin, $config = null)
{
$this->__config['plugin_conf'][$plugin] = $config;
}
/**
*
* Sets the template name to use.
*
* @access public
*
* @param string $template The template name.
*
* @return void
*
*/
public function setTemplate($template)
{
$this->__config['template'] = $template;
}
// -----------------------------------------------------------------
//
// Output escaping and management.
//
// -----------------------------------------------------------------
/**
*
* Clears then sets the callbacks to use when calling $this->escape().
*
* Each parameter passed to this function is treated as a separate
* callback. For example:
*
* <code>
* $savant->setEscape(
* 'stripslashes',
* 'htmlspecialchars',
* array('StaticClass', 'method'),
* array($object, $method)
* );
* </code>
*
* @access public
*
* @return void
*
*/
public function setEscape()
{
$this->__config['escape'] = (array) @func_get_args();
}
/**
*
* Adds to the callbacks used when calling $this->escape().
*
* Each parameter passed to this function is treated as a separate
* callback. For example:
*
* <code>
* $savant->addEscape(
* 'stripslashes',
* 'htmlspecialchars',
* array('StaticClass', 'method'),
* array($object, $method)
* );
* </code>
*
* @access public
*
* @return void
*
*/
public function addEscape()
{
$args = (array) @func_get_args();
$this->__config['escape'] = array_merge(
$this->__config['escape'], $args
);
}
/**
*
* Gets the array of output-escaping callbacks.
*
* @access public
*
* @return array The array of output-escaping callbacks.
*
*/
public function getEscape()
{
return $this->__config['escape'];
}
/**
*
* Applies escaping to a value.
*
* You can override the predefined escaping callbacks by passing
* added parameters as replacement callbacks.
*
* <code>
* // use predefined callbacks
* $result = $savant->escape($value);
*
* // use replacement callbacks
* $result = $savant->escape(
* $value,
* 'stripslashes',
* 'htmlspecialchars',
* array('StaticClass', 'method'),
* array($object, $method)
* );
* </code>
*
*
* Unfortunately, a call to "echo htmlspecialchars()" is twice
* as fast as a call to "echo $this->escape()" under the default
* escaping (which is htmlspecialchars). The benchmark showed
* 0.007 seconds for htmlspecialchars(), and 0.014 seconds for
* $this->escape(), on 300 calls each.
*
* @access public
*
* @param mixed $value The value to be escaped.
*
* @return mixed
*
*/
public function escape($value)
{
// were custom callbacks passed?
if (func_num_args() == 1) {
// no, only a value was passed.
// loop through the predefined callbacks.
foreach ($this->__config['escape'] as $func) {
// this if() shaves 0.001sec off of 300 calls.
if (is_string($func)) {
$value = $func($value);
} else {
$value = call_user_func($func, $value);
}
}
} else {
// yes, use the custom callbacks
$callbacks = func_get_args();
// drop $value
array_shift($callbacks);
// loop through custom callbacks.
foreach ($callbacks as $func) {
// this if() shaves 0.001sec off of 300 calls.
if (is_string($func)) {
$value = $func($value);
} else {
$value = call_user_func($func, $value);
}
}
}
return $value;
}
/**
*
* Prints a value after escaping it for output.
*
* You can override the predefined escaping callbacks by passing
* added parameters as replacement callbacks.
*
* <code>
* // use predefined callbacks
* $this->eprint($value);
*
* // use replacement callbacks
* $this->eprint(
* $value,
* 'stripslashes',
* 'htmlspecialchars',
* array('StaticClass', 'method'),
* array($object, $method)
* );
* </code>
*
* @access public
*
* @param mixed $value The value to be escaped and printed.
*
* @return void
*
*/
public function eprint($value)
{
// avoid the very slow call_user_func_array() when there
// are no custom escaping callbacks. thanks to
// Andreas Korthaus for profiling the code to find
// the slowdown.
$num = func_num_args();
if ($num == 1) {
echo $this->escape($value);
} else {
$args = func_get_args();
echo call_user_func_array(
array($this, 'escape'),
$args
);
}
}
// -----------------------------------------------------------------
//
// File management
//
// -----------------------------------------------------------------
/**
*
* Sets an entire array of search paths for templates or resources.
*
* @access public
*
* @param string $type The type of path to set, typically 'template'
* or 'resource'.
*
* @param string|array $path The new set of search paths. If null or
* false, resets to the current directory only.
*
* @return void
*
*/
public function setPath($type, $path)
{
// clear out the prior search dirs
$this->__config[$type . '_path'] = array();
// always add the fallback directories as last resort
switch (strtolower($type)) {
case 'template':
// the current directory
$this->addPath($type, '.');
break;
case 'resource':
// the Savant3 distribution resources
$this->addPath($type, dirname(__FILE__) . '/Savant3/resources/');
break;
}
// actually add the user-specified directories
$this->addPath($type, $path);
}
/**
*
* Adds to the search path for templates and resources.
*
* @access public
*
* @param string|array $path The directory or stream to search.
*
* @return void
*
*/
public function addPath($type, $path)
{
// convert from path string to array of directories
if (is_string($path) && ! strpos($path, '://')) {
// the path config is a string, and it's not a stream
// identifier (the "://" piece). add it as a path string.
$path = explode(PATH_SEPARATOR, $path);
// typically in path strings, the first one is expected
// to be searched first. however, Savant3 uses a stack,
// so the first would be last. reverse the path string
// so that it behaves as expected with path strings.
$path = array_reverse($path);
} else {
// just force to array
settype($path, 'array');
}
// loop through the path directories
foreach ($path as $dir) {
// no surrounding spaces allowed!
$dir = trim($dir);
// add trailing separators as needed
if (strpos($dir, '://') && substr($dir, -1) != '/') {
// stream
$dir .= '/';
} elseif (substr($dir, -1) != DIRECTORY_SEPARATOR) {
// directory
$dir .= DIRECTORY_SEPARATOR;
}
// add to the top of the search dirs
array_unshift(
$this->__config[$type . '_path'],
$dir
);
}
}
/**
*
* Searches the directory paths for a given file.
*
* @param array $type The type of path to search (template or resource).
*
* @param string $file The file name to look for.
*
* @return string|bool The full path and file name for the target file,
* or boolean false if the file is not found in any of the paths.
*
*/
protected function findFile($type, $file)
{
// get the set of paths
$set = $this->__config[$type . '_path'];
// start looping through the path set
foreach ($set as $path) {
// get the path to the file
$fullname = $path . $file;
// is the path based on a stream?
if (strpos($path, '://') === false) {
// not a stream, so do a realpath() to avoid
// directory traversal attempts on the local file
// system. Suggested by Ian Eure, initially
// rejected, but then adopted when the secure
// compiler was added.
$path = realpath($path); // needed for substr() later
$fullname = realpath($fullname);
}
// the substr() check added by Ian Eure to make sure
// that the realpath() results in a directory registered
// with Savant so that non-registered directores are not
// accessible via directory traversal attempts.
if (file_exists($fullname) && is_readable($fullname) &&
substr($fullname, 0, strlen($path)) == $path) {
return $fullname;
}
}
// could not find the file in the set of paths
return false;
}
// -----------------------------------------------------------------
//
// Variable and reference assignment
//
// -----------------------------------------------------------------
/**
*
* Sets variables for the template (by copy).
*
* This method is overloaded; you can assign all the properties of
* an object, an associative array, or a single value by name.
*
* You are not allowed to assign any variable named '__config' as
* it would conflict with internal configuration tracking.
*
* In the following examples, the template will have two variables
* assigned to it; the variables will be known inside the template as
* "$this->var1" and "$this->var2".
*
* <code>
* $Savant3 = new Savant3();
*
* // assign by object
* $obj = new stdClass;
* $obj->var1 = 'something';
* $obj->var2 = 'else';
* $Savant3->assign($obj);
*
* // assign by associative array
* $ary = array('var1' => 'something', 'var2' => 'else');
* $Savant3->assign($ary);
*
* // assign by name and value
* $Savant3->assign('var1', 'something');
* $Savant3->assign('var2', 'else');
*
* // assign directly
* $Savant3->var1 = 'something';
* $Savant3->var2 = 'else';
* </code>
*
* @access public
*
* @return bool True on success, false on failure.
*
*/
public function assign()
{
// get the arguments; there may be 1 or 2.
$arg0 = @func_get_arg(0);
$arg1 = @func_get_arg(1);
// assign from object
if (is_object($arg0)) {
// assign public properties
foreach (get_object_vars($arg0) as $key => $val) {
// can't assign to __config
if ($key != '__config') {
$this->$key = $val;
}
}
return true;
}
// assign from associative array
if (is_array($arg0)) {
foreach ($arg0 as $key => $val) {
// can't assign to __config
if ($key != '__config') {
$this->$key = $val;
}
}
return true;
}
// assign by name and value (can't assign to __config).
if (is_string($arg0) && func_num_args() > 1 && $arg0 != '__config') {
$this->$arg0 = $arg1;
return true;
}
// $arg0 was not object, array, or string.
return false;
}
/**
*
* Sets variables for the template (by reference).
*
* You are not allowed to assign any variable named '__config' as
* it would conflict with internal configuration tracking.
*
* <code>
* $Savant3 = new Savant3();
*
* // assign by name and value
* $Savant3->assignRef('var1', $ref);
*
* // assign directly
* $Savant3->ref =& $var1;
* </code>
*
* @access public
*
* @return bool True on success, false on failure.
*
*/
public function assignRef($key, &$val)
{
// assign by name and reference (can't assign to __config).
if ($key != '__config') {
$this->$key =& $val;
return true;
} else {
return false;
}
}
// -----------------------------------------------------------------
//
// Template processing
//
// -----------------------------------------------------------------
/**
*
* Displays a template directly (equivalent to <code>echo $tpl</code>).
*
* @access public
*
* @param string $tpl The template source to compile and display.
*
* @return void
*
*/
public function display($tpl = null)
{
echo $this->getOutput($tpl);
}
/**
* Returns output, including error_text if an error occurs.
*
* @param $tpl The template to process; if null, uses the
* default template set with setTemplate().