File: Template.php

package info (click to toggle)
imp4 4.2-4lenny3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 18,252 kB
  • ctags: 5,316
  • sloc: php: 21,340; xml: 19,302; makefile: 68; sql: 14
file content (509 lines) | stat: -rw-r--r-- 14,042 bytes parent folder | download
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
<?php
/**
 * Horde Template system. Adapted from bTemplate by Brian Lozier
 * <brian@massassi.net>.
 *
 * Horde_Template provides a basic template engine with tags, loops,
 * and if conditions. However, it is also a simple interface with
 * several essential functions: set(), fetch(), and
 * parse(). Subclasses or decorators can implement (or delegate) these
 * three methods, plus the options api, and easily implement other
 * template engines (PHP code, XSLT, etc.) without requiring usage
 * changes.
 *
 * Compilation code adapted from code written by Bruno Pedro <bpedro@ptm.pt>.
 *
 * $Horde: imp/lib/Template.php,v 1.9.2.2 2008/01/02 11:31:19 jan Exp $
 *
 * Copyright 2002-2008 The Horde Project (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @author  Michael Slusarz <slusarz@horde.org>
 * @since   Horde 3.0
 * @package Horde_Template
 */

/** The identifier to use for memory-only templates. */
define('IMP_TEMPLATE_STRING', '**string');

class IMP_Template {

    /**
     * The Horde_Cache object to use.
     *
     * @var Horde_Cache
     */
    var $_cache;

    /**
     * Option values.
     *
     * @var array
     */
    var $_options = array();

    /**
     * Directory that templates should be read from.
     *
     * @var string
     */
    var $_basepath = '';

    /**
     * Tag (scalar) values.
     *
     * @var array
     */
    var $_scalars = array();

    /**
     * Loop tag values.
     *
     * @var array
     */
    var $_arrays = array();

    /**
     * Path to template source.
     *
     * @var string
     */
    var $_templateFile = null;

    /**
     * Template source.
     *
     * @var string
     */
    var $_template = null;

    /**
     * Foreach variable mappings.
     *
     * @var array
     */
    var $_foreachMap = array();

    /**
     * Foreach variable incrementor.
     *
     * @var integer
     */
    var $_foreachVar = 0;

    /**
     * preg_match() cache.
     *
     * @var array
     */
    var $_pregcache = array();

    /**
     * Constructor.
     *
     * @param string $basepath  The directory where templates are read from.
     */
    function IMP_Template($basepath = null)
    {
        if (!is_null($basepath)) {
            $this->_basepath = $basepath;
        }

        require_once 'Horde/Cache.php';
        $this->_cache = &Horde_Cache::singleton($GLOBALS['conf']['cache']['driver'], Horde::getDriverConfig('cache', $GLOBALS['conf']['cache']['driver']));
    }

    /**
     * Sets an option.
     * Currently available options are:
     * <pre>
     * 'debug' - Output debugging information to screen
     * 'forcecompile' - Force a compilation on every page load
     * 'gettext' - Activate gettext detection
     * <pre>
     *
     * @param string $option  The option name.
     * @param mixed $val      The option's value.
     */
    function setOption($option, $val)
    {
        $this->_options[$option] = $val;
    }

    /**
     * Set the template contents to a string.
     *
     * @param string $template  The template text.
     */
    function setTemplate($template)
    {
        $this->_template = $template;
        $this->_parse();
        $this->_templateFile = IMP_TEMPLATE_STRING;
    }

    /**
     * Returns an option's value.
     *
     * @param string $option  The option name.
     *
     * @return mixed  The option's value.
     */
    function getOption($option)
    {
        return isset($this->_options[$option]) ? $this->_options[$option] : null;
    }

    /**
     * Sets a tag, loop, or if variable.
     *
     * @param string|array $tag   Either the tag name or a hash with tag names
     *                            as keys and tag values as values.
     * @param mixed        $var   The value to replace the tag with.
     */
    function set($tag, $var)
    {
        if (is_array($tag)) {
            foreach ($tag as $tTag => $tVar) {
                $this->set($tTag, $tVar);
            }
        } elseif (is_array($var) || is_object($var)) {
            $this->_arrays[$tag] = $var;
        } else {
            $this->_scalars[$tag] = $var;
        }
    }

    /**
     * Returns the value of a tag or loop.
     *
     * @param string $tag  The tag name.
     *
     * @return mixed  The tag value or null if the tag hasn't been set yet.
     */
    function get($tag)
    {
        if (isset($this->_arrays[$tag])) {
            return $this->_arrays[$tag];
        }
        if (isset($this->_scalars[$tag])) {
            return $this->_scalars[$tag];
        }
        return null;
    }

    /**
     * Fetches a template from the specified file and return the parsed
     * contents.
     *
     * @param string $filename  The file to fetch the template from.
     *
     * @return string  The parsed template.
     */
    function fetch($filename = null)
    {
        $file = $this->_basepath . $filename;
        $force = $this->getOption('forcecompile');

        if (!is_null($filename) && ($file != $this->_templateFile)) {
            $this->_template = $this->_templateFile = null;
        }

        /* First, check for a cached compiled version. */
        if (!$force && is_null($this->_template) && isset($this->_cache)) {
            $cacheid = 'horde_template|' . filemtime($file) . '|' . $file;
            $this->_template = $this->_cache->get($cacheid, 0);
            if ($this->_template === false) {
                $this->_template = null;
            }
        }

        /* Parse and compile the template. */
        if ($force || is_null($this->_template)) {
            $this->_template = str_replace("\n", " \n", file_get_contents($file));
            $this->_parse();
            if (isset($cacheid) &&
                !$this->_cache->set($cacheid, $this->_template)) {
                Horde::logMessage(sprintf(_("Could not save the compiled template file '%s'."), $file), __FILE__, __LINE__, PEAR_LOG_ERR);
            }
        }

        $this->_templateFile = $file;

        /* Template debugging. */
        if ($this->getOption('debug')) {
            echo '<pre>' . htmlspecialchars($this->_template) . '</pre>';
        }

        return $this->parse();
    }

    /**
     * Parses all variables/tags in the template.
     *
     * @param string $contents  The unparsed template.
     *
     * @return string  The parsed template.
     */
    function parse($contents = null)
    {
        if (!is_null($contents)) {
            $this->setTemplate(str_replace("\n", " \n", $contents));
        }

        /* Evaluate the compiled template and return the output. */
        ob_start();
        eval('?>' . $this->_template);
        return is_null($contents) ? ob_get_clean() : str_replace(" \n", "\n", ob_get_clean());
    }

    /**
     * Parses all variables/tags in the template.
     */
    function _parse()
    {
        // Escape XML instructions.
        $this->_template = preg_replace('/\?>|<\?/',
                                        '<?php echo \'$0\' ?>',
                                        $this->_template);

        // Parse gettext tags, if the option is enabled.
        if ($this->getOption('gettext')) {
            $this->_parseGettext();
        }

        // Process ifs.
        $this->_parseIf();

        // Process loops and arrays.
        $this->_parseLoop();

        // Process base scalar tags.  Needs to be after _parseLoop() as we
        // rely on _foreachMap().
        $this->_parseTags();

        // Finally, process any associative array scalar tags.
        $this->_parseAssociativeTags();
    }

    /**
     * Parses gettext tags.
     *
     * @access private
     */
    function _parseGettext()
    {
        if (preg_match_all("/<gettext>(.+?)<\/gettext>/s", $this->_template, $matches, PREG_SET_ORDER)) {
            $replace = array();
            foreach ($matches as $val) {
                $replace[$val[0]] = '<?php echo _(\'' . str_replace("'", "\\'", $val[1]) . '\'); ?>';
            }
            $this->_doReplace($replace);
        }
    }

    /**
     * Parses 'if' statements.
     *
     * @access private
     *
     * @param string $key  The key prefix to parse.
     */
    function _parseIf($key = null)
    {
        $replace = array();

        foreach ($this->_doSearch('if', $key) as $val) {
            $replace[$val[0]] = '<?php if (!empty(' . $this->_generatePHPVar('scalars', $val[1]) . ') || !empty(' . $this->_generatePHPVar('arrays', $val[1]) . ')): ?>';
            $replace[$val[2]] = '<?php endif; ?>';

            // Check for else statement.
            foreach ($this->_doSearch('else', $key) as $val2) {
                $replace[$val2[0]] = '<?php else: ?>';
                $replace[$val2[2]] = '';
            }
        }

        $this->_doReplace($replace);
    }

    /**
     * Parses the given array for any loops or other uses of the array.
     *
     * @access private
     *
     * @param string $key  The key prefix to parse.
     */
    function _parseLoop($key = null)
    {
        $replace = array();

        foreach ($this->_doSearch('loop', $key) as $val) {
            $divider = null;

            // See if we have a divider.
            if (preg_match("/<divider:" . $val[1] . ">(.*)<\/divider:" . $val[1] . ">/sU", $this->_template, $m)) {
                $divider = $m[1];
                $replace[$m[0]] = '';
            }

            if (!isset($this->_foreachMap[$val[1]])) {
                $this->_foreachMap[$val[1]] = ++$this->_foreachVar;
            }
            $varId = $this->_foreachMap[$val[1]];
            $var = $this->_generatePHPVar('arrays', $val[1]);

            $replace[$val[0]] = '<?php ' .
                (($divider) ? '$i' . $varId . ' = count(' . $var . '); ' : '') .
                'foreach (' . $this->_generatePHPVar('arrays', $val[1]) . ' as $k' . $varId . ' => $v' . $varId . '): ?>';
            $replace[$val[2]] = '<?php ' .
                (($divider) ? 'if (--$i' . $varId . ' != 0) { echo \'' . $divider . '\'; }; ' : '') .
                'endforeach; ?>';

            // Parse ifs.
            $this->_parseIf($val[1]);

            // Parse interior loops.
            $this->_parseLoop($val[1]);

            // Replace scalars.
            $this->_parseTags($val[1]);
        }

        $this->_doReplace($replace);
    }

    /**
     * Replaces 'tag' tags with their PHP equivalents.
     *
     * @access private
     *
     * @param string $key  The key prefix to parse.
     */
    function _parseTags($key = null)
    {
        $replace = array();

        foreach ($this->_doSearch('tag', $key, true) as $val) {
            $replace_text = '<?php ';
            if (isset($this->_foreachMap[$val[1]])) {
                $var = $this->_foreachMap[$val[1]];
                $replace_text .= 'if (isset($v' . $var . ')) { echo is_array($v' . $var . ') ? $k' . $var . ' : $v' . $var . '; } else';
            }
            $var = $this->_generatePHPVar('scalars', $val[1]);
            $replace[$val[0]] = $replace_text . 'if (isset(' . $var . ')) { echo ' . $var . '; } ?>';
        }

        $this->_doReplace($replace);
    }

    /**
     * Parse associative tags (i.e. <tag:foo.bar />).
     *
     * @access private
     */
    function _parseAssociativeTags()
    {
        $replace = array();

        foreach ($this->_pregcache['tag'] as $key => $val) {
            $parts = explode('.', $val[1]);
            $var = '$this->_arrays[\'' . $parts[0] . '\'][\'' . $parts[1] . '\']';
            $replace[$val[0]] = '<?php if (isset(' . $var . ')) { echo ' . $var . '; } ?>';
            unset($this->_pregcache['tag'][$key]);
        }

        $this->_doReplace($replace);
    }

    /**
     * Output the correct PHP variable string for use in template space.
     *
     * @access private
     */
    function _generatePHPVar($tag, $key)
    {
        $out = '';

        $a = explode('.', $key);
        $a_count = count($a);

        if ($a_count == 1) {
            switch ($tag) {
            case 'arrays':
                $out = '$this->_arrays';
                break;

            case 'scalars':
                $out = '$this->_scalars';
                break;
            }
        } else {
            $out = '$v' . $this->_foreachMap[implode('.', array_slice($a, 0, -1))];
        }

        return $out . '[\'' . end($a) . '\']';
    }

    /**
     * TODO
     *
     * @access private
     */
    function _doSearch($tag, $key, $noclose = false)
    {
        $out = array();
        $level = (is_null($key)) ? 0 : substr_count($key, '.') + 1;

        if (!isset($this->_pregcache[$key])) {
            $regex = ($noclose) ?
                "/<" . $tag . ":(.+?)\s\/>/" :
                "/<" . $tag . ":([^>]+)>/";
            preg_match_all($regex, $this->_template, $this->_pregcache[$tag], PREG_SET_ORDER);
        }

        foreach ($this->_pregcache[$tag] as $pkey => $val) {
            $val_level = substr_count($val[1], '.');
            $add = false;
            if (is_null($key)) {
                $add = !$val_level;
            } else {
                $add = (($val_level == $level) &&
                        (strpos($val[1], $key . '.') === 0));
            }
            if ($add) {
                if (!$noclose) {
                    $val[2] = '</' . $tag . ':' . $val[1] . '>';
                }
                $out[] = $val;
                unset($this->_pregcache[$tag][$pkey]);
            }
        }

        return $out;
    }

    /**
     * TODO
     *
     * @access private
     */
    function _doReplace($replace)
    {
        if (empty($replace)) {
            return;
        }

        $search = array();

        foreach (array_keys($replace) as $val) {
            $search[] = '/' . preg_quote($val, '/') . '/';
        }

        $this->_template = preg_replace($search, array_values($replace), $this->_template);
    }

}