Subversion Repositories svnkaklik

Rev

Go to most recent revision | Details | Last modification | View Log

Rev Author Line No. Line
6 kaklik 1
<?php
2
// +-----------------------------------------------------------------------+
3
// | PhpWebGallery - a PHP based picture gallery                           |
4
// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5
// | Copyright (C) 2003-2005 PhpWebGallery Team - http://phpwebgallery.net |
6
// +-----------------------------------------------------------------------+
7
// | branch        : BSF (Best So Far)
8
// | file          : $RCSfile: template.php,v $
9
// | last update   : $Date: 2005/03/12 10:51:08 $
10
// | last modifier : $Author: plg $
11
// | revision      : $Revision: 1.8 $
12
// +-----------------------------------------------------------------------+
13
// | This program is free software; you can redistribute it and/or modify  |
14
// | it under the terms of the GNU General Public License as published by  |
15
// | the Free Software Foundation                                          |
16
// |                                                                       |
17
// | This program is distributed in the hope that it will be useful, but   |
18
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20
// | General Public License for more details.                              |
21
// |                                                                       |
22
// | You should have received a copy of the GNU General Public License     |
23
// | along with this program; if not, write to the Free Software           |
24
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25
// | USA.                                                                  |
26
// +-----------------------------------------------------------------------+
27
 
28
/**
29
 * Template class. By Nathan Codding of the phpBB group. The interface was
30
 * originally inspired by PHPLib templates, and the template file formats
31
 * are quite similar.
32
 */
33
 
34
class Template {
35
 
36
  var $classname = "Template";
37
 
38
  // variable that holds all the data we'll be substituting into
39
  // the compiled templates.
40
  // ...
41
  // This will end up being a multi-dimensional array like this :
42
  // $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value
43
  // if it's a root-level variable, it'll be like this:
44
  // $this->_tpldata[.][0][varname] == value
45
  var $_tpldata = array();
46
 
47
  // Hash of filenames for each template handle.
48
  var $files = array();
49
 
50
  // Root template directory.
51
  var $root = "";
52
 
53
  // this will hash handle names to the compiled code for that handle.
54
  var $compiled_code = array();
55
 
56
  // This will hold the uncompiled code for that handle.
57
  var $uncompiled_code = array();
58
 
59
  // output
60
  var $output = '';
61
 
62
  /**
63
   * Constructor. Simply sets the root dir.
64
   *
65
   */
66
  function Template($root = ".")
67
    {
68
      $this->set_rootdir($root);
69
    }
70
 
71
  /**
72
   * Destroys this template object. Should be called when you're done with
73
   * it, in order to clear out the template data so you can load/parse a new
74
   * template set.
75
   */
76
  function destroy()
77
    {
78
      $this->_tpldata = array();
79
    }
80
 
81
  /**
82
   * Sets the template root directory for this Template object.
83
   */
84
  function set_rootdir($dir)
85
    {
86
      if (!is_dir($dir))
87
      {
88
        return false;
89
      }
90
 
91
      $this->root = $dir;
92
      return true;
93
    }
94
 
95
  /**
96
   * Sets the template filenames for handles. $filename_array should be a
97
   * hash of handle => filename pairs.
98
   */
99
  function set_filenames($filename_array)
100
    {
101
      if (!is_array($filename_array))
102
      {
103
        return false;
104
      }
105
 
106
      reset($filename_array);
107
      while(list($handle, $filename) = each($filename_array))
108
      {
109
        $this->files[$handle] = $this->make_filename($filename);
110
      }
111
 
112
      return true;
113
    }
114
 
115
 
116
  /**
117
   * Load the file for the handle, compile the file, and run the compiled
118
   * code. This will print out the results of executing the template.
119
   */
120
  function pparse($handle)
121
    {
122
      if (!$this->loadfile($handle))
123
      {
124
        die("Template->pparse(): Couldn't load template file for handle $handle");
125
      }
126
 
127
      // actually compile the template now.
128
      if (!isset($this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
129
      {
130
        // Actually compile the code now.
131
        $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle]);
132
      }
133
 
134
      // Run the compiled code.
135
      //echo ("<!-- ".$this->compiled_code[$handle]." -->");
136
      eval($this->compiled_code[$handle]);
137
      return true;
138
    }
139
 
140
  /**
141
   * fills $output template var
142
   */
143
  function parse($handle)
144
    {
145
      if (!$this->loadfile($handle))
146
      {
147
        die("Template->pparse(): Couldn't load template file for handle $handle");
148
      }
149
 
150
      // actually compile the template now.
151
      if (!isset($this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
152
      {
153
        // Actually compile the code now.
154
        $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle], true, '_str');
155
      }
156
 
157
      // Run the compiled code.
158
      $_str = '';
159
      eval($this->compiled_code[$handle]);
160
      $this->output.= $_str;
161
 
162
      return true;
163
    }
164
 
165
  /**
166
   * prints $output template var
167
   */
168
  function p()
169
    {
170
      echo $this->output;
171
    }
172
 
173
  /**
174
   * Inserts the uncompiled code for $handle as the value of $varname in the
175
   * root-level. This can be used to effectively include a template in the
176
   * middle of another template.
177
   *
178
   * Note that all desired assignments to the variables in $handle should be
179
   * done BEFORE calling this function.
180
   */
181
  function assign_var_from_handle($varname, $handle)
182
    {
183
      if (!$this->loadfile($handle))
184
      {
185
        die("Template->assign_var_from_handle(): Couldn't load template file for handle $handle");
186
      }
187
 
188
      // Compile it, with the "no echo statements" option on.
189
      $_str = "";
190
      $code = $this->compile($this->uncompiled_code[$handle], true, '_str');
191
 
192
      // evaluate the variable assignment.
193
      eval($code);
194
      // assign the value of the generated variable to the given varname.
195
      $this->assign_var($varname, $_str);
196
 
197
      return true;
198
    }
199
 
200
  /**
201
   * Block-level variable assignment. Adds a new block iteration with the
202
   * given variable assignments. Note that this should only be called once
203
   * per block iteration.
204
   */
205
  function assign_block_vars($blockname, $vararray)
206
    {
207
      if (strstr($blockname, '.'))
208
      {
209
        // Nested block.
210
        $blocks = explode('.', $blockname);
211
        $blockcount = sizeof($blocks) - 1;
212
        $str = '$this->_tpldata';
213
        for ($i = 0; $i < $blockcount; $i++)
214
        {
215
          $str .= '[\'' . $blocks[$i] . '.\']';
216
          eval('$lastiteration = sizeof(' . $str . ') - 1;');
217
          $str .= '[' . $lastiteration . ']';
218
        }
219
        // Now we add the block that we're actually assigning to.
220
        // We're adding a new iteration to this block with the given
221
        // variable assignments.
222
        $str .= '[\'' . $blocks[$blockcount] . '.\'][] = $vararray;';
223
 
224
        // Now we evaluate this assignment we've built up.
225
        eval($str);
226
      }
227
      else
228
      {
229
        // Top-level block. Add a new iteration to this block with the
230
        // variable assignments we were given.
231
        $this->_tpldata[$blockname . '.'][] = $vararray;
232
      }
233
 
234
      return true;
235
    }
236
 
237
  /**
238
   * Root-level variable assignment. Adds to current assignments, overriding
239
   * any existing variable assignment with the same name.
240
   */
241
  function assign_vars($vararray)
242
    {
243
      reset ($vararray);
244
      while (list($key, $val) = each($vararray))
245
      {
246
        $this->_tpldata['.'][0][$key] = $val;
247
      }
248
 
249
      return true;
250
    }
251
 
252
  /**
253
   * Root-level variable assignment. Adds to current assignments, overriding
254
   * any existing variable assignment with the same name.
255
   */
256
  function assign_var($varname, $varval)
257
    {
258
      $this->_tpldata['.'][0][$varname] = $varval;
259
 
260
      return true;
261
    }
262
 
263
 
264
  /**
265
   * Generates a full path+filename for the given filename, which can either
266
   * be an absolute name, or a name relative to the rootdir for this
267
   * Template object.
268
   */
269
  function make_filename($filename)
270
    {
271
      // Check if it's an absolute or relative path.
272
      if (substr($filename, 0, 1) != '/')
273
      {
274
        $filename = $this->root.'/'.$filename;
275
      }
276
 
277
      if (!file_exists($filename))
278
      {
279
        die("Template->make_filename(): Error - file $filename does not exist");
280
      }
281
 
282
      return $filename;
283
    }
284
 
285
 
286
  /**
287
   * If not already done, load the file for the given handle and populate
288
   * the uncompiled_code[] hash with its code. Do not compile.
289
   */
290
  function loadfile($handle)
291
    {
292
      // If the file for this handle is already loaded and compiled, do
293
      // nothing.
294
      if (isset($this->uncompiled_code[$handle])
295
          and !empty($this->uncompiled_code[$handle]))
296
      {
297
        return true;
298
      }
299
 
300
      // If we don't have a file assigned to this handle, die.
301
      if (!isset($this->files[$handle]))
302
      {
303
        die("Template->loadfile(): No file specified for handle $handle");
304
      }
305
 
306
      $filename = $this->files[$handle];
307
 
308
      $str = implode("", @file($filename));
309
      if (empty($str))
310
      {
311
        die("Template->loadfile(): File $filename for handle $handle is empty");
312
      }
313
 
314
      $this->uncompiled_code[$handle] = $str;
315
 
316
      return true;
317
    }
318
 
319
 
320
 
321
  /**
322
   * Compiles the given string of code, and returns the result in a string.
323
   *
324
   * If "do_not_echo" is true, the returned code will not be directly
325
   * executable, but can be used as part of a variable assignment for use in
326
   * assign_code_from_handle().
327
   */
328
  function compile($code, $do_not_echo = false, $retvar = '')
329
    {
330
      // replace \ with \\ and then ' with \'.
331
      $code = str_replace('\\', '\\\\', $code);
332
      $code = str_replace('\'', '\\\'', $code);
333
 
334
      // change template varrefs into PHP varrefs
335
 
336
      // This one will handle varrefs WITH namespaces
337
      $varrefs = array();
338
      preg_match_all('#\{(([a-z0-9\-_]+?\.)+?)([a-z0-9\-_]+?)\}#is', $code, $varrefs);
339
      $varcount = sizeof($varrefs[1]);
340
      for ($i = 0; $i < $varcount; $i++)
341
      {
342
        $namespace = $varrefs[1][$i];
343
        $varname = $varrefs[3][$i];
344
        $new = $this->generate_block_varref($namespace, $varname);
345
 
346
        $code = str_replace($varrefs[0][$i], $new, $code);
347
      }
348
 
349
      // This will handle the remaining root-level varrefs
350
      $code = preg_replace('#\{([a-z0-9\-_]*?)\}#is', '\' . ( ( isset($this->_tpldata[\'.\'][0][\'\1\']) ) ? $this->_tpldata[\'.\'][0][\'\1\'] : \'\' ) . \'', $code);
351
 
352
      // Break it up into lines.
353
      $code_lines = explode("\n", $code);
354
 
355
      $block_nesting_level = 0;
356
      $block_names = array();
357
      $block_names[0] = ".";
358
 
359
      // Second: prepend echo ', append ' . "\n"; to each line.
360
      $line_count = sizeof($code_lines);
361
      for ($i = 0; $i < $line_count; $i++)
362
      {
363
        $code_lines[$i] = chop($code_lines[$i]);
364
        if (preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m))
365
        {
366
          $n[0] = $m[0];
367
          $n[1] = $m[1];
368
 
369
          // Added: dougk_ff7-Keeps templates from bombing if begin is on
370
          // the same line as end.. I think. :)
371
          if ( preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n) )
372
          {
373
            $block_nesting_level++;
374
            $block_names[$block_nesting_level] = $m[1];
375
            if ($block_nesting_level < 2)
376
            {
377
              // Block is not nested.
378
              $code_lines[$i] = '$_' . $n[1] . '_count = ( isset($this->_tpldata[\'' . $n[1] . '.\']) ) ?  sizeof($this->_tpldata[\'' . $n[1] . '.\']) : 0;';
379
              $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
380
              $code_lines[$i] .= "\n" . '{';
381
            }
382
            else
383
            {
384
              // This block is nested.
385
 
386
              // Generate a namespace string for this block.
387
              $namespace = implode('.', $block_names);
388
              // strip leading period from root level..
389
              $namespace = substr($namespace, 2);
390
              // Get a reference to the data array for this block that depends on the
391
              // current indices of all parent blocks.
392
              $varref = $this->generate_block_data_ref($namespace, false);
393
              // Create the for loop code to iterate over this block.
394
              $code_lines[$i] = '$_' . $n[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
395
              $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
396
              $code_lines[$i] .= "\n" . '{';
397
            }
398
 
399
            // We have the end of a block.
400
            unset($block_names[$block_nesting_level]);
401
            $block_nesting_level--;
402
            $code_lines[$i] .= '} // END ' . $n[1];
403
            $m[0] = $n[0];
404
            $m[1] = $n[1];
405
          }
406
          else
407
          {
408
            // We have the start of a block.
409
            $block_nesting_level++;
410
            $block_names[$block_nesting_level] = $m[1];
411
            if ($block_nesting_level < 2)
412
            {
413
              // Block is not nested.
414
              $code_lines[$i] = '$_' . $m[1] . '_count = ( isset($this->_tpldata[\'' . $m[1] . '.\']) ) ? sizeof($this->_tpldata[\'' . $m[1] . '.\']) : 0;';
415
              $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
416
              $code_lines[$i] .= "\n" . '{';
417
            }
418
            else
419
            {
420
              // This block is nested.
421
 
422
              // Generate a namespace string for this block.
423
              $namespace = implode('.', $block_names);
424
              // strip leading period from root level..
425
              $namespace = substr($namespace, 2);
426
              // Get a reference to the data array for this block that
427
              // depends on the current indices of all parent blocks.
428
              $varref = $this->generate_block_data_ref($namespace, false);
429
              // Create the for loop code to iterate over this block.
430
              $code_lines[$i] = '$_' . $m[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
431
              $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
432
              $code_lines[$i] .= "\n" . '{';
433
            }
434
          }
435
        }
436
        else if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m))
437
        {
438
          // We have the end of a block.
439
          unset($block_names[$block_nesting_level]);
440
          $block_nesting_level--;
441
          $code_lines[$i] = '} // END ' . $m[1];
442
        }
443
        else
444
        {
445
          // We have an ordinary line of code.
446
          if (!$do_not_echo)
447
          {
448
            $code_lines[$i] = 'echo \'' . $code_lines[$i] . '\' . "\\n";';
449
          }
450
          else
451
          {
452
            $code_lines[$i] = '$' . $retvar . '.= \'' . $code_lines[$i] . '\' . "\\n";'; 
453
          }
454
        }
455
      }
456
 
457
      // Bring it back into a single string of lines of code.
458
      $code = implode("\n", $code_lines);
459
      return $code	;
460
 
461
    }
462
 
463
 
464
  /**
465
   * Generates a reference to the given variable inside the given (possibly
466
   * nested) block namespace. This is a string of the form: '
467
   * . $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['varname']
468
   * . ' It's ready to be inserted into an "echo" line in one of the
469
   * templates.  NOTE: expects a trailing "." on the namespace.
470
   */
471
  function generate_block_varref($namespace, $varname)
472
    {
473
      // Strip the trailing period.
474
      $namespace = substr($namespace, 0, strlen($namespace) - 1);
475
 
476
      // Get a reference to the data block for this namespace.
477
      $varref = $this->generate_block_data_ref($namespace, true);
478
      // Prepend the necessary code to stick this in an echo line.
479
 
480
      // Append the variable reference.
481
      $varref .= '[\'' . $varname . '\']';
482
 
483
      $varref = '\' . ( ( isset(' . $varref . ') ) ? ' . $varref . ' : \'\' ) . \'';
484
 
485
      return $varref;
486
 
487
    }
488
 
489
 
490
  /**
491
   * Generates a reference to the array of data values for the given
492
   * (possibly nested) block namespace. This is a string of the form:
493
   * $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['$childN']
494
   *
495
   * If $include_last_iterator is true, then [$_childN_i] will be appended
496
   * to the form shown above.  NOTE: does not expect a trailing "." on the
497
   * blockname.
498
   */
499
  function generate_block_data_ref($blockname, $include_last_iterator)
500
    {
501
      // Get an array of the blocks involved.
502
      $blocks = explode(".", $blockname);
503
      $blockcount = sizeof($blocks) - 1;
504
      $varref = '$this->_tpldata';
505
      // Build up the string with everything but the last child.
506
      for ($i = 0; $i < $blockcount; $i++)
507
      {
508
        $varref .= '[\'' . $blocks[$i] . '.\'][$_' . $blocks[$i] . '_i]';
509
      }
510
      // Add the block reference for the last child.
511
      $varref .= '[\'' . $blocks[$blockcount] . '.\']';
512
      // Add the iterator for the last child if requried.
513
      if ($include_last_iterator)
514
      {
515
              $varref .= '[$_' . $blocks[$blockcount] . '_i]';
516
      }
517
 
518
      return $varref;
519
    }
520
 
521
}
522
 
523
?>