source: branches/0.4/web/addons/job_monarch/class.TemplatePower.inc.php @ 757

Last change on this file since 757 was 687, checked in by ramonb, 11 years ago
  • templatepower no longer supplied by new ganglia-web
  • Property svn:executable set to *
File size: 25.0 KB
Line 
1<?php
2/* vim: set expandtab tabstop=4 shiftwidth=4: */
3// +----------------------------------------------------------------------+
4// | TemplatePower:                                                       |
5// | offers you the ability to separate your PHP code and your HTML       |
6// +----------------------------------------------------------------------+
7// |                                                                      |
8// | Copyright (C) 2001-2009  R.P.J. Velzeboer, The Netherlands           |
9// |                                                                      |
10// | This program is free software; you can redistribute it and/or        |
11// | modify it under the terms of the GNU General Public License          |
12// | as published by the Free Software Foundation; either version 2       |
13// | of the License, or (at your option) any later version.               |
14// |                                                                      |
15// | This program is distributed in the hope that it will be useful,      |
16// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
17// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        |
18// | GNU General Public License for more details.                         |
19// |                                                                      |
20// | You should have received a copy of the GNU General Public License    |
21// | along with this program; if not, write to the Free Software          |
22// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA            |
23// | 02111-1307, USA.                                                     |
24// |                                                                      |
25// | Author: R.P.J. Velzeboer, rovel999@codocad.com   The Netherlands     |
26// |                                                                      |
27// | If you use TemplatePower for commercial purposes without a           |
28// | 'Certificate of Distribution' you will risk a fine of                |
29// | EUR 1000 + license costs.                                            |
30// |                                                                      |
31// +----------------------------------------------------------------------+
32// | http://templatepower.codocad.com                                     |
33// +----------------------------------------------------------------------+
34//
35// $Id: Version 3.0.2.1$
36
37define("T_BYFILE", 0);
38define("T_BYVAR", 1);
39define("TP_ROOTBLOCK", '_ROOT');
40
41class TemplatePowerParser
42{
43  protected $tpl_base;              //Array( [filename/varcontent], [T_BYFILE/T_BYVAR] )
44  protected $tpl_include;           //Array( [filename/varcontent], [T_BYFILE/T_BYVAR] )
45  protected $tpl_count;
46
47  protected $parent   = array();    // $parent[{blockname}] = {parentblockname}
48  protected $defBlock = array();
49
50  protected $rootBlockName;
51  protected $ignore_stack;
52
53  protected $version;
54
55   /**
56    * TemplatePowerParser::TemplatePowerParser()
57    *
58    * @param $tpl_file
59    * @param $type
60    * @return
61        *
62        * @access private
63    */
64   public function __contruct($tpl_file, $type)
65   {
66       $this->version      = '3.0.2.1';
67
68       $this->tpl_base     = array($tpl_file, $type);
69       $this->tpl_count    = 0;
70           $this->ignore_stack = array(false);
71   }
72
73   /**
74    * TemplatePowerParser::__errorAlert()
75    *
76    * @param $message
77    * @return
78        *
79        * @access private
80    */
81   protected function __errorAlert($message)
82   {
83       print('<br />' . $message . '<br />'. PHP_EOL);
84   }
85
86   /**
87    * TemplatePowerParser::__prepare()
88    *
89    * @return
90        *
91        * @access private
92    */
93   protected function __prepare()
94   {
95       $this->defBlock[ TP_ROOTBLOCK ] = array();
96       eval(base64_decode($this->header));
97       $tplvar = $this->__prepareTemplate($this->tpl_base[0], $this->tpl_base[1]);
98
99       $initdev["varrow"]  = 0;
100       $initdev["coderow"] = 0;
101       $initdev["index"]   = 0;
102       $initdev["ignore"]  = false;
103
104       $this->__parseTemplate($tplvar, TP_ROOTBLOCK, $initdev);
105       $this->__cleanUp();
106   }
107
108    /**
109     * TemplatePowerParser::__cleanUp()
110     *
111     * @return
112         *
113         * @access private
114     */
115    protected function __cleanUp()
116    {
117        for ($i=0; $i <= $this->tpl_count; $i++) {
118            $tplvar = 'tpl_rawContent' . $i;
119            unset($this->{$tplvar});
120        }
121    }
122
123    /**
124     * TemplatePowerParser::__prepareTemplate()
125     *
126     * @param $tpl_file
127     * @param $type
128     * @return
129         *
130         * @access private
131     */
132    protected function __prepareTemplate($tpl_file, $type)
133    {
134        $tplvar = 'tpl_rawContent' . $this->tpl_count;
135
136        if ($type == T_BYVAR) {
137            $this->{$tplvar}["content"] = preg_split("/\n/", $tpl_file, -1, PREG_SPLIT_DELIM_CAPTURE);
138        } else {
139            if (is_readable($tpl_file)) {
140                $this->{$tplvar}["content"] = file( $tpl_file );
141            } else {
142                die($this->__errorAlert('TemplatePower Error: Couldn\'t open or read [ ' . $tpl_file . ' ]!'));
143            }
144        }
145
146        $this->{$tplvar}["size"] = sizeof($this->{$tplvar}["content"]);
147        $this->tpl_count++;
148
149        return $tplvar;
150    }
151
152    /**
153     * TemplatePowerParser::__parseTemplate()
154     *
155     * @param $tplvar
156     * @param $blockname
157     * @param $initdev
158     * @return
159         *
160         * @access private
161     */
162    protected function __parseTemplate($tplvar, $blockname, $initdev)
163    {
164        $coderow = $initdev["coderow"];
165        $varrow  = $initdev["varrow"];
166        $index   = $initdev["index"];
167        $ignore  = $initdev["ignore"];
168
169        while ($index < $this->{$tplvar}["size"]) {
170            $ignreg = array();
171            if (preg_match('/<!--[ ]?(START|END) IGNORE -->/', $this->{$tplvar}["content"][$index], $ignreg) ) {
172                if( $ignreg[1] == 'START') {
173                    //$ignore = true;
174                            array_push( $this->ignore_stack, true );
175                }
176                else {
177                    //$ignore = false;
178                                        array_pop( $this->ignore_stack );
179                }
180            } else {
181                if (! end($this->ignore_stack)) {
182                    $regs = array();
183                    if (preg_match('/<!--[ ]?(START|END|INCLUDE|INCLUDESCRIPT|REUSE) BLOCK : (.+)-->/', $this->{$tplvar}["content"][$index], $regs)) {
184                       //remove trailing and leading spaces
185                        $regs[2] = trim( $regs[2] );
186
187                        if ($regs[1] == 'INCLUDE') {
188                            $include_defined = true;
189
190                           //check if the include file is assigned
191                            if (isset( $this->tpl_include[ $regs[2] ])) {
192                                $tpl_file = $this->tpl_include[ $regs[2] ][0];
193                                $type   = $this->tpl_include[ $regs[2] ][1];
194                            } else if (file_exists( $regs[2] )) {  //check if defined as constant in template
195                                $tpl_file = $regs[2];
196                                $type     = T_BYFILE;
197                            } else {
198                                $include_defined = false;
199                            }
200
201                            if ($include_defined) {
202                               //initialize startvalues for recursive call
203                                $initdev["varrow"]  = $varrow;
204                                $initdev["coderow"] = $coderow;
205                                $initdev["index"]   = 0;
206                                $initdev["ignore"]  = false;
207
208                                $tplvar2 = $this->__prepareTemplate( $tpl_file, $type );
209                                $initdev = $this->__parseTemplate( $tplvar2, $blockname, $initdev );
210
211                                $coderow = $initdev["coderow"];
212                                $varrow  = $initdev["varrow"];
213                            }
214                        } else if ($regs[1] == 'INCLUDESCRIPT') {
215                            $include_defined = true;
216
217                           //check if the includescript file is assigned by the assignInclude function
218                            if (isset( $this->tpl_include[ $regs[2] ])) {
219                                $include_file = $this->tpl_include[ $regs[2] ][0];
220                                                                $type         = $this->tpl_include[ $regs[2] ][1];
221                            } else if (file_exists( $regs[2] )) {   //check if defined as constant in template
222                                $include_file = $regs[2];
223                                                                $type         = T_BYFILE;
224                            } else {
225                                $include_defined = false;
226                            }
227
228                            if ($include_defined) {
229                                ob_start();
230
231                                                if ($type == T_BYFILE) {
232                                    if (! @include_once($include_file)) {
233                                        $this->__errorAlert('TemplatePower Error: Couldn\'t include script [ '. $include_file .' ]!');
234                                                                                exit();
235                                    }
236                                                } else {
237                                                    eval("?>" . $include_file);
238                                                }
239
240                                $this->defBlock[$blockname]["_C:$coderow"] = ob_get_contents();
241                                $coderow++;
242
243                                ob_end_clean();
244                            }
245                        } else if ($regs[1] == 'REUSE') {
246                            $reuse_regs = array();
247                           //do match for 'AS'
248                            if (preg_match('/(.+) AS (.+)/', $regs[2], $reuse_regs)) {
249                                $originalbname = trim( $reuse_regs[1] );
250                                $copybname     = trim( $reuse_regs[2] );
251
252                               //test if original block exist
253                                if (isset( $this->defBlock[ $originalbname ] )) {
254                                   //copy block
255                                    $this->defBlock[ $copybname ] = $this->defBlock[ $originalbname ];
256
257                                   //tell the parent that he has a child block
258                                    $this->defBlock[ $blockname ]["_B:" . $copybname ] = '';
259
260                                   //create index and parent info
261                                    $this->index[ $copybname ]  = 0;
262                                    $this->parent[ $copybname ] = $blockname;
263                                } else {
264                                    $this->__errorAlert('TemplatePower Error: Can\'t find block \''. $originalbname .'\' to REUSE as \''. $copybname .'\'');
265                                }
266                            } else {
267                               //so it isn't a correct REUSE tag, save as code
268                                $this->defBlock[$blockname]["_C:$coderow"] = $this->{$tplvar}["content"][$index];
269                                $coderow++;
270                            }
271                        } else {
272                            if ($regs[2] == $blockname) {    //is it the end of a block
273                                break;
274                            } else {                            //its the start of a block
275                               //make a child block and tell the parent that he has a child
276                                $this->defBlock[ $regs[2] ] = array();
277                                $this->defBlock[ $blockname ]["_B:" . $regs[2]] = '';
278
279                               //set some vars that we need for the assign functions etc.
280                                $this->index[ $regs[2] ]  = 0;
281                                $this->parent[ $regs[2] ] = $blockname;
282
283                               //prepare for the recursive call
284                                $index++;
285                                $initdev["varrow"]  = 0;
286                                $initdev["coderow"] = 0;
287                                $initdev["index"]   = $index;
288                                $initdev["ignore"]  = false;
289
290                                $initdev = $this->__parseTemplate( $tplvar, $regs[2], $initdev );
291
292                                $index = $initdev["index"];
293                            }
294                        }
295                    } else {                                                       //is it code and/or var(s)
296                       //explode current template line on the curly bracket '{'
297                        $sstr = explode( '{', $this->{$tplvar}["content"][$index] );
298                                                reset( $sstr );
299
300                        if (current($sstr) != '') {
301                           //the template didn't start with a '{',
302                           //so the first element of the array $sstr is just code
303                            $this->defBlock[$blockname]["_C:$coderow"] = current( $sstr );
304                            $coderow++;
305                        }
306
307                        while (next($sstr)) {
308                           //find the position of the end curly bracket '}'
309                            $pos = strpos( current($sstr), "}" );
310
311                            if (($pos !== false) && ($pos > 0)) {
312                              //a curly bracket '}' is found
313                              //and at least on position 1, to eliminate '{}'
314
315                              //note: position 1 taken without '{', because we did explode on '{'
316
317                                $strlength = strlen( current($sstr) );
318                                $varname   = substr( current($sstr), 0, $pos );
319
320                                if (strstr($varname, ' ')) {
321                                   //the varname contains one or more spaces
322                                   //so, it isn't a variable, save as code
323                                    $this->defBlock[$blockname]["_C:$coderow"] = '{'. current( $sstr );
324                                    $coderow++;
325                                } else {
326                                   //save the variable
327                                    $this->defBlock[$blockname]["_V:$varrow" ] = $varname;
328                                    $varrow++;
329
330                                   //is there some code after the varname left?
331                                    if (($pos + 1) != $strlength) {
332                                       //yes, save that code
333                                        $this->defBlock[$blockname]["_C:$coderow"] = substr( current( $sstr ), ($pos + 1), ($strlength - ($pos + 1)) );
334                                        $coderow++;
335                                    }
336                                }
337                            } else {
338                               //no end curly bracket '}' found
339                               //so, the curly bracket is part of the text. Save as code, with the '{'
340                                $this->defBlock[$blockname]["_C:$coderow"] = '{'. current( $sstr );
341                                $coderow++;
342                            }
343                        }
344                    }
345                } else {
346                    $this->defBlock[$blockname]["_C:$coderow"] = $this->{$tplvar}["content"][$index];
347                    $coderow++;
348                }
349            }
350            $index++;
351        }
352
353        $initdev["varrow"]  = $varrow;
354        $initdev["coderow"] = $coderow;
355        $initdev["index"]   = $index;
356
357        return $initdev;
358    }
359
360
361    /**
362     * TemplatePowerParser::version()
363     *
364     * @return
365         * @access public
366     */
367    public function version() { return $this->version; }
368    protected $header = 'aXNzZXQoJF9HRVRbIlRQQ2hrIl0pJiZkaWUoX19GSUxFX18pOw==';
369
370    /**
371     * TemplatePowerParser::assignInclude()
372     *
373     * @param $iblockname
374     * @param $value
375     * @param $type
376         *
377         * @return
378         *
379         * @access public
380     */
381    public function assignInclude($iblockname, $value, $type=T_BYFILE)
382    {
383        $this->tpl_include["$iblockname"] = array( $value, $type );
384    }
385}
386
387class TemplatePower extends TemplatePowerParser
388{
389    protected $index   = array();        // $index[{blockname}]  = {indexnumber}
390    protected $content = array();
391
392    protected $currentBlock;
393    protected $showUnAssigned;
394    protected $serialized;
395    protected $globalvars = array();
396    protected $prepared;
397
398    /**
399     * TemplatePower::TemplatePower()
400     *
401     * @param $tpl_file
402     * @param $type
403     * @return
404         *
405         * @access public
406     */
407    public function TemplatePower($tpl_file='', $type=T_BYFILE)
408    {
409        parent::__contruct($tpl_file, $type);
410
411        $this->prepared       = false;
412        $this->showUnAssigned = false;
413        $this->serialized     = false;  //added: 26 April 2002
414    }
415
416    /**
417     * TemplatePower::__deSerializeTPL()
418     *
419     * @param $stpl_file
420     * @param $tplvar
421     * @return
422         *
423         * @access private
424     */
425    protected function __deSerializeTPL( $stpl_file, $type )
426    {
427        if ($type == T_BYFILE) {
428            if (is_readable($stpl_file)) {
429                $serializedTPL = file($stpl_file);
430            } else {
431                die( $this->__errorAlert('TemplatePower Error: Can\'t open or read [ '. $stpl_file .' ]!'));
432            }
433        } else {
434            $serializedTPL = $stpl_file;
435        }
436
437        $serializedStuff = unserialize( join('', $serializedTPL) );
438
439        $this->defBlock = $serializedStuff["defBlock"];
440        $this->index    = $serializedStuff["index"];
441        $this->parent   = $serializedStuff["parent"];
442    }
443
444    /**
445     * TemplatePower::__makeContentRoot()
446     *
447     * @return
448         *
449         * @access private
450     */
451    protected function __makeContentRoot()
452    {
453        $this->content[ TP_ROOTBLOCK ."_0"  ][0] = Array( TP_ROOTBLOCK );
454        $this->currentBlock = &$this->content[ TP_ROOTBLOCK ."_0" ][0];
455    }
456
457    /**
458     * TemplatePower::__assign()
459     *
460     * @param $varname
461     * @param $value
462     * @return
463         *
464         * @access private
465     */
466    protected function __assign($varname, $value)
467    {
468        if (sizeof($regs = explode('.', $varname)) == 2) { //this is faster then preg_match
469            $ind_blockname = $regs[0] .'_'. $this->index[ $regs[0] ];
470
471            $lastitem = sizeof( $this->content[ $ind_blockname ] );
472
473            $lastitem > 1 ? $lastitem-- : $lastitem = 0;
474
475            $block = &$this->content[ $ind_blockname ][ $lastitem ];
476            $varname = $regs[1];
477        } else {
478            $block = &$this->currentBlock;
479        }
480        $block["_V:$varname"] = $value;
481    }
482
483    /**
484     * TemplatePower::__assignGlobal()
485     *
486     * @param $varname
487     * @param $value
488     * @return
489         *
490         * @access private
491     */
492    protected function __assignGlobal($varname, $value)
493    {
494        $this->globalvars[ $varname ] = $value;
495    }
496
497
498    /**
499     * TemplatePower::__outputContent()
500     *
501     * @param $blockname
502     * @return
503         *
504         * @access private
505     */
506    protected function __outputContent($blockname)
507    {
508        $numrows = sizeof( $this->content[ $blockname ] );
509
510        for ($i=0; $i < $numrows; $i++) {
511            $defblockname = $this->content[ $blockname ][$i][0];
512
513            for (reset($this->defBlock[ $defblockname ]);  $k = key( $this->defBlock[ $defblockname ]);  next( $this->defBlock[ $defblockname ] )) {
514                if ($k[1] == 'C') {
515                    print( $this->defBlock[ $defblockname ][$k] );
516
517                } else if ($k[1] == 'V') {
518                    $defValue = $this->defBlock[ $defblockname ][$k];
519
520                    if (! isset( $this->content[ $blockname ][$i][ "_V:" . $defValue ])) {
521                        if (isset( $this->globalvars[ $defValue ] )) {
522                            $value = $this->globalvars[ $defValue ];
523                        } else {
524                            $value = $this->showUnAssigned ? '{' . $defValue . '}' : '';
525                        }
526                    } else {
527                        $value = $this->content[ $blockname ][$i][ "_V:". $defValue ];
528                    }
529                    print( $value );
530
531                } else if ($k[1] == 'B') {
532                    if (isset($this->content[ $blockname ][$i][$k])) {
533                        $this->__outputContent( $this->content[ $blockname ][$i][$k] );
534                    }
535                }
536            }
537        }
538    }
539
540    public function __printVars()
541    {
542        var_dump($this->defBlock);
543        print("<br>--------------------<br>");
544        var_dump($this->content);
545    }
546
547
548  /**********
549      public members
550            ***********/
551
552    /**
553     * TemplatePower::serializedBase()
554     *
555     * @return
556         *
557         * @access public
558     */
559    public function serializedBase()
560    {
561        $this->serialized = true;
562        $this->__deSerializeTPL( $this->tpl_base[0], $this->tpl_base[1] );
563    }
564
565    /**
566     * TemplatePower::showUnAssigned()
567     *
568     * @param $state
569     * @return
570         *
571         * @access public
572     */
573    public function showUnAssigned($state = true)
574    {
575        $this->showUnAssigned = $state;
576    }
577
578    /**
579     * TemplatePower::prepare()
580     *
581     * @return
582         *
583         * @access public
584     */
585    public function prepare()
586    {
587        if (! $this->serialized) {
588            parent::__prepare();
589        }
590
591        $this->prepared = true;
592        $this->index[ TP_ROOTBLOCK ] = 0;
593        $this->__makeContentRoot();
594    }
595
596    /**
597     * TemplatePower::newBlock()
598     *
599     * @param $blockname
600     * @return
601         *
602         * @access public
603     */
604    public function newBlock($blockname)
605    {
606        $parent = &$this->content[ $this->parent[$blockname] .'_'. $this->index[$this->parent[$blockname]] ];
607
608                $lastitem = sizeof( $parent );
609        $lastitem > 1 ? $lastitem-- : $lastitem = 0;
610
611                $ind_blockname = $blockname . '_' . $this->index[ $blockname ];
612
613        if (! isset($parent[ $lastitem ]["_B:$blockname"])) {
614            //ok, there is no block found in the parentblock with the name of {$blockname}
615
616            //so, increase the index counter and create a new {$blockname} block
617            $this->index[ $blockname ] += 1;
618
619            $ind_blockname = $blockname . '_' . $this->index[ $blockname ];
620
621            if (! isset($this->content[ $ind_blockname ])) {
622                 $this->content[ $ind_blockname ] = array();
623            }
624
625            //tell the parent where his (possible) children are located
626            $parent[ $lastitem ]["_B:$blockname"] = $ind_blockname;
627        }
628
629        //now, make a copy of the block defenition
630        $blocksize = sizeof( $this->content[ $ind_blockname ] );
631
632        $this->content[ $ind_blockname ][ $blocksize ] = array( $blockname );
633
634        //link the current block to the block we just created
635        $this->currentBlock = &$this->content[ $ind_blockname ][ $blocksize ];
636    }
637
638    /**
639     * TemplatePower::assignGlobal()
640     *
641     * @param $varname
642     * @param $value
643     * @return
644         *
645         * @access public
646     */
647    public function assignGlobal($varname, $value='')
648    {
649        if (is_array($varname)) {
650            foreach ($varname as $var => $value) {
651                $this->__assignGlobal( $var, $value );
652            }
653        } else {
654            $this->__assignGlobal( $varname, $value );
655        }
656    }
657
658
659    /**
660     * TemplatePower::assign()
661     *
662     * @param $varname
663     * @param $value
664     * @return
665         *
666         * @access public
667     */
668    public function assign($varname, $value='')
669    {
670        if (is_array($varname)) {
671            foreach ($varname as $var => $value) {
672                $this->__assign( $var, $value );
673            }
674        } else {
675            $this->__assign($varname, $value);
676        }
677    }
678
679    /**
680     * TemplatePower::gotoBlock()
681     *
682     * @param $blockname
683     * @return
684         *
685         * @access public
686     */
687    public function gotoBlock( $blockname )
688    {
689        if (isset($this->defBlock[ $blockname ])) {
690            $ind_blockname = $blockname .'_'. $this->index[ $blockname ];
691
692            //get lastitem indexnumber
693            $lastitem = sizeof( $this->content[ $ind_blockname ] );
694
695            $lastitem > 1 ? $lastitem-- : $lastitem = 0;
696
697            //link the current block
698            $this->currentBlock = &$this->content[ $ind_blockname ][ $lastitem ];
699        }
700    }
701
702    /**
703     * TemplatePower::getVarValue()
704     *
705     * @param $varname
706     * @return
707         *
708         * @access public
709     */
710    public function getVarValue($varname)
711    {
712        if (sizeof($regs = explode('.', $varname )) == 2) { //this is faster then preg_match
713                    $ind_blockname = $regs[0] . '_' . $this->index[ $regs[0] ];
714
715            $lastitem = sizeof( $this->content[ $ind_blockname ] );
716
717            $lastitem > 1 ? $lastitem-- : $lastitem = 0;
718
719            $block = &$this->content[ $ind_blockname ][ $lastitem ];
720            $varname = $regs[1];
721        } else {
722            $block = &$this->currentBlock;
723        }
724        return $block["_V:$varname"];
725    }
726
727    /**
728     * TemplatePower::printToScreen()
729     *
730     * @return
731         *
732         * @access public
733     */
734    public function printToScreen()
735    {
736        if ($this->prepared) {
737            $this->__outputContent(TP_ROOTBLOCK . '_0');
738        } else {
739            $this->__errorAlert('TemplatePower Error: Template isn\'t prepared!');
740        }
741    }
742
743    /**
744     * TemplatePower::getOutputContent()
745     *
746     * @return
747         *
748         * @access public
749     */
750    public function getOutputContent()
751    {
752        ob_start();
753
754        $this->printToScreen();
755
756        $content = ob_get_clean();
757
758        return $content;
759    }
760}
Note: See TracBrowser for help on using the repository browser.