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