]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Template.php
rcs_id no longer makes sense with Subversion global version number
[SourceForge/phpwiki.git] / lib / Template.php
1 <?php //-*-php-*-
2 // rcs_id('$Id$');
3
4 require_once("lib/ErrorManager.php");
5
6
7 /** An HTML template.
8  */
9 class Template
10 {
11     /**
12      * name optionally of form "theme/template" to include parent templates in children
13      */
14     function Template ($name, &$request, $args = false) {
15         global $WikiTheme;
16
17         $this->_request =& $request;
18         $this->_basepage = $request->getArg('pagename');
19
20         if (strstr($name, "/")) {
21             $oldname = $WikiTheme->_name;
22             $oldtheme = $WikiTheme->_theme;
23             list($themename, $name) = explode("/", $name);
24             $WikiTheme->_theme = "themes/$themename";
25             $WikiTheme->_name = $name;
26         }
27         $this->_name = $name;
28         $file = $WikiTheme->findTemplate($name);
29         if (!$file) {
30             trigger_error("no template for $name found.", E_USER_WARNING);
31             return;
32         }
33         if (isset($oldname)) { 
34             $WikiTheme->_name = $oldname; 
35             $WikiTheme->_theme = $oldtheme; 
36         }
37         $fp = fopen($file, "rb");
38         if (!$fp) {
39             trigger_error("$file not found", E_USER_WARNING);
40             return;
41         }
42         $request->_TemplatesProcessed[$name] = 1;
43         $this->_tmpl = fread($fp, filesize($file));
44         if ($fp) fclose($fp);
45         //$userid = $request->_user->_userid;
46         if (is_array($args))
47             $this->_locals = $args;
48         elseif ($args)
49             $this->_locals = array('CONTENT' => $args);
50         else
51             $this->_locals = array();
52     }
53
54     function _munge_input($template) {
55
56         // Convert < ?plugin expr ? > to < ?php $this->_printPluginPI("expr"); ? >
57         $orig[] = '/<\?plugin.*?\?>/se';
58         $repl[] = "\$this->_mungePlugin('\\0')";
59         
60         // Convert < ?= expr ? > to < ?php $this->_print(expr); ? >
61         $orig[] = '/<\?=(.*?)\?>/s';
62         $repl[] = '<?php $this->_print(\1);?>';
63         
64         return preg_replace($orig, $repl, $template);
65     }
66
67     function _mungePlugin($pi) {
68         // HACK ALERT: PHP's preg_replace, with the /e option seems to
69         // escape both single and double quotes with backslashes.
70         // So we need to unescape the double quotes here...
71
72         $pi = preg_replace('/(?!<\\\\)\\\\"/x', '"', $pi);
73         return sprintf('<?php $this->_printPlugin(%s); ?>',
74                        "'" . str_replace("'", "\'", $pi) . "'");
75     }
76     
77     function _printPlugin ($pi) {
78         include_once("lib/WikiPlugin.php");
79         static $loader;
80
81         if (empty($loader))
82             $loader = new WikiPluginLoader;
83         
84         $this->_print($loader->expandPI($pi, $this->_request, $this, $this->_basepage));
85     }
86     
87     function _print ($val) {
88         if (isa($val, 'Template')) {
89             $this->_expandSubtemplate($val);
90         } else {
91             PrintXML($val);
92         }
93     }
94
95     function _expandSubtemplate (&$template) {
96         // FIXME: big hack!        
97         //if (!$template->_request)
98         //    $template->_request = &$this->_request;
99         if (DEBUG) {
100             echo "<!-- Begin $template->_name -->\n";
101         }
102         // Expand sub-template with defaults from this template.
103         $template->printExpansion($this->_vars);
104         if (DEBUG) {
105             echo "<!-- End $template->_name -->\n";
106         }
107     }
108         
109     /**
110      * Substitute HTML replacement text for tokens in template. 
111      *
112      * Constructs a new WikiTemplate based upon the named template.
113      *
114      * @access public
115      *
116      * @param $token string Name of token to substitute for.
117      *
118      * @param $replacement string Replacement HTML text.
119      */
120     function replace($varname, $value) {
121         $this->_locals[$varname] = $value;
122     }
123
124     
125     function printExpansion ($defaults = false) {
126         if (!is_array($defaults)) // HTML object or template object
127             $defaults = array('CONTENT' => $defaults);
128         $this->_vars = array_merge($defaults, $this->_locals);
129         extract($this->_vars);
130
131         global $request;
132         if (!isset($user))
133             $user = $request->getUser();
134         if (!isset($page))
135             $page = $request->getPage();
136         // Speedup. I checked all templates
137         if (!isset($revision)) 
138             $revision = false;
139
140         global $WikiTheme, $charset; 
141         //$this->_dump_template();
142         $SEP = $WikiTheme->getButtonSeparator();
143
144         global $ErrorManager;
145         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_errorHandler'));
146
147         eval('?>' . $this->_munge_input($this->_tmpl));
148
149         $ErrorManager->popErrorHandler();
150     }
151
152     // FIXME (1.3.12)
153     // Find a way to do template expansion less memory intensive and faster.
154     // 1.3.4 needed no memory at all for dumphtml, now it needs +15MB.
155     // Smarty? As before?
156     function getExpansion ($defaults = false) {
157         ob_start();
158         $this->printExpansion($defaults);
159         $xml = ob_get_contents();
160         ob_end_clean();         // PHP problem: Doesn't release its memory?
161         return $xml;
162     }
163
164     function printXML () {
165         $this->printExpansion();
166     }
167
168     function asXML () {
169         return $this->getExpansion();
170     }
171     
172             
173     // Debugging:
174     function _dump_template () {
175         $lines = explode("\n", $this->_munge_input($this->_tmpl));
176         $pre = HTML::pre();
177         $n = 1;
178         foreach ($lines as $line)
179             $pre->pushContent(fmt("%4d  %s\n", $n++, $line));
180         $pre->printXML();
181     }
182
183     function _errorHandler($error) {
184         //if (!preg_match('/: eval\(\)\'d code$/', $error->errfile))
185         //    return false;
186
187         if (preg_match('/: eval\(\)\'d code$/', $error->errfile)) {
188             $error->errfile = "In template '$this->_name'";
189             // Hack alert: Ignore 'undefined variable' messages for variables
190             //  whose names are ALL_CAPS.
191             if (preg_match('/Undefined variable:\s*[_A-Z]+\s*$/', $error->errstr))
192                 return true;
193         }
194         // ignore recursively nested htmldump loop: browse -> body -> htmldump -> browse -> body ...
195         // FIXME for other possible loops also
196         elseif (strstr($error->errfile, "In template 'htmldump'")) {
197             ; //return $error;
198         }
199         elseif (strstr($error->errfile, "In template '")) { // merge
200             $error->errfile = preg_replace("/'(\w+)'\)$/", "'\\1' < '$this->_name')", $error->errfile);
201         }
202         else {
203             $error->errfile .= " (In template '$this->_name')";
204         }
205
206         if (!empty($this->_tmpl)) {
207             $lines = explode("\n", $this->_tmpl);
208             if (isset($lines[$error->errline - 1]))
209                 $error->errstr .= ":\n\t" . $lines[$error->errline - 1];
210         }
211         return $error;
212     }
213 };
214
215 /**
216  * Get a templates
217  *
218  * This is a convenience function and is equivalent to:
219  * <pre>
220  *   new Template(...)
221  * </pre>
222  */
223 function Template($name, $args = false) {
224     global $request;
225     return new Template($name, $request, $args);
226 }
227
228 function alreadyTemplateProcessed($name) {
229     global $request;
230     return !empty($request->_TemplatesProcessed[$name]) ? true : false;
231 }
232 /**
233  * Make and expand the top-level template. 
234  *
235  *
236  * @param $content mixed html content to put into the page
237  * @param $title string page title
238  * @param $page_revision object A WikiDB_PageRevision object or false
239  * @param $args hash Extract args for top-level template
240  *
241  * @return string HTML expansion of template.
242  */
243 function GeneratePage($content, $title, $page_revision = false, $args = false) {
244     global $request;
245     
246     if (!is_array($args))
247         $args = array();
248
249     $args['CONTENT'] = $content;
250     $args['TITLE'] = $title;
251     $args['revision'] = $page_revision;
252     
253     if (!isset($args['HEADER']))
254         $args['HEADER'] = $title;
255     
256     printXML(new Template('html', $request, $args));
257 }
258
259
260 /**
261  * For dumping pages as html to a file.
262  * Used for action=dumphtml,action=ziphtml,format=pdf,format=xml
263  */
264 function GeneratePageasXML($content, $title, $page_revision = false, $args = false) {
265     global $request;
266     
267     if (!is_array($args))
268         $args = array();
269
270     $content->_basepage = $title;
271     $args['CONTENT'] = $content;
272     $args['TITLE'] = SplitPagename($title);
273     $args['revision'] = $page_revision;
274     
275     if (!isset($args['HEADER']))
276         $args['HEADER'] = SplitPagename($title);
277     
278     global $HIDE_TOOLBARS, $NO_BASEHREF, $WikiTheme;
279     $HIDE_TOOLBARS = true;
280     if (!$WikiTheme->DUMP_MODE)
281         $WikiTheme->DUMP_MODE = 'HTML';
282
283     // FIXME: unfatal errors and login requirements
284     $html = asXML(new Template('htmldump', $request, $args));
285     
286     $HIDE_TOOLBARS = false;
287     //$WikiTheme->DUMP_MODE = false;
288     return $html;
289 }
290
291 // Local Variables:
292 // mode: php
293 // tab-width: 8
294 // c-basic-offset: 4
295 // c-hanging-comment-ender-p: nil
296 // indent-tabs-mode: nil
297 // End:   
298 ?>