2 rcs_id('$Id: Template.php,v 1.73 2005-04-08 05:41:00 rurban Exp $');
4 require_once("lib/ErrorManager.php");
12 * name optionally of form "theme/template" to include parent templates in children
14 function Template ($name, &$request, $args = false) {
17 $this->_request =& $request;
18 $this->_basepage = $request->getArg('pagename');
20 if (strstr($name, "/")) {
21 $oldname = $WikiTheme->_name;
22 $oldtheme = $WikiTheme->_theme;
23 list($themename, $name) = explode("/", $name);
24 $WikiTheme->_theme = "themes/$themename";
27 $file = $WikiTheme->findTemplate($name);
29 trigger_error("no template for $name found.", E_USER_WARNING);
32 if (isset($oldname)) {
33 $WikiTheme->_name = $oldname;
34 $WikiTheme->_theme = $oldtheme;
36 $fp = fopen($file, "rb");
38 trigger_error("$file not found", E_USER_WARNING);
41 $request->_TemplatesProcessed[$name] = 1;
42 $this->_tmpl = fread($fp, filesize($file));
44 //$userid = $request->_user->_userid;
46 $this->_locals = $args;
48 $this->_locals = array('CONTENT' => $args);
50 $this->_locals = array();
53 function _munge_input($template) {
55 // Convert < ?plugin expr ? > to < ?php $this->_printPluginPI("expr"); ? >
56 $orig[] = '/<\?plugin.*?\?>/se';
57 $repl[] = "\$this->_mungePlugin('\\0')";
59 // Convert < ?= expr ? > to < ?php $this->_print(expr); ? >
60 $orig[] = '/<\?=(.*?)\?>/s';
61 $repl[] = '<?php $this->_print(\1);?>';
63 return preg_replace($orig, $repl, $template);
66 function _mungePlugin($pi) {
67 // HACK ALERT: PHP's preg_replace, with the /e option seems to
68 // escape both single and double quotes with backslashes.
69 // So we need to unescape the double quotes here...
71 $pi = preg_replace('/(?!<\\\\)\\\\"/x', '"', $pi);
72 return sprintf('<?php $this->_printPlugin(%s); ?>',
73 "'" . str_replace("'", "\'", $pi) . "'");
76 function _printPlugin ($pi) {
77 include_once("lib/WikiPlugin.php");
81 $loader = new WikiPluginLoader;
83 $this->_print($loader->expandPI($pi, $this->_request, $this, $this->_basepage));
86 function _print ($val) {
87 if (isa($val, 'Template')) {
88 $this->_expandSubtemplate($val);
94 function _expandSubtemplate (&$template) {
96 //if (!$template->_request)
97 // $template->_request = &$this->_request;
99 echo "<!-- Begin $template->_name -->\n";
101 // Expand sub-template with defaults from this template.
102 $template->printExpansion($this->_vars);
104 echo "<!-- End $template->_name -->\n";
109 * Substitute HTML replacement text for tokens in template.
111 * Constructs a new WikiTemplate based upon the named template.
115 * @param $token string Name of token to substitute for.
117 * @param $replacement string Replacement HTML text.
119 function replace($varname, $value) {
120 $this->_locals[$varname] = $value;
124 function printExpansion ($defaults = false) {
125 if (!is_array($defaults)) // HTML object or template object
126 $defaults = array('CONTENT' => $defaults);
127 $this->_vars = array_merge($defaults, $this->_locals);
128 extract($this->_vars);
132 $user = $request->getUser();
134 $page = $request->getPage();
136 global $WikiTheme, $RCS_IDS, $charset;
137 //$this->_dump_template();
138 $SEP = $WikiTheme->getButtonSeparator();
140 global $ErrorManager;
141 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_errorHandler'));
143 eval('?>' . $this->_munge_input($this->_tmpl));
145 $ErrorManager->popErrorHandler();
149 // Find a way to do template expansion less memory intensive and faster.
150 // 1.3.4 needed no memory at all for dumphtml, now it needs +15MB.
151 // Smarty? As before?
152 function getExpansion ($defaults = false) {
154 $this->printExpansion($defaults);
155 $xml = ob_get_contents();
156 ob_end_clean(); // PHP problem: Doesn't release its memory?
160 function printXML () {
161 $this->printExpansion();
165 return $this->getExpansion();
170 function _dump_template () {
171 $lines = explode("\n", $this->_munge_input($this->_tmpl));
174 foreach ($lines as $line)
175 $pre->pushContent(fmt("%4d %s\n", $n++, $line));
179 function _errorHandler($error) {
180 //if (!preg_match('/: eval\(\)\'d code$/', $error->errfile))
183 if (preg_match('/: eval\(\)\'d code$/', $error->errfile)) {
184 $error->errfile = "In template '$this->_name'";
185 // Hack alert: Ignore 'undefined variable' messages for variables
186 // whose names are ALL_CAPS.
187 if (preg_match('/Undefined variable:\s*[_A-Z]+\s*$/', $error->errstr))
190 // ignore recursively nested htmldump loop: browse -> body -> htmldump -> browse -> body ...
191 // FIXME for other possible loops also
192 elseif (strstr($error->errfile, "In template 'htmldump'")) {
195 elseif (strstr($error->errfile, "In template '")) { // merge
196 $error->errfile = preg_replace("/'(\w+)'\)$/", "'\\1' < '$this->_name')", $error->errfile);
199 $error->errfile .= " (In template '$this->_name')";
202 if (!empty($this->_tmpl)) {
203 $lines = explode("\n", $this->_tmpl);
204 if (isset($lines[$error->errline - 1]))
205 $error->errstr .= ":\n\t" . $lines[$error->errline - 1];
214 * This is a convenience function and is equivalent to:
219 function Template($name, $args = false) {
221 return new Template($name, $request, $args);
224 function alreadyTemplateProcessed($name) {
226 return !empty($request->_TemplatesProcessed[$name]) ? true : false;
229 * Make and expand the top-level template.
232 * @param $content mixed html content to put into the page
233 * @param $title string page title
234 * @param $page_revision object A WikiDB_PageRevision object
235 * @param $args hash Extract args for top-level template
237 * @return string HTML expansion of template.
239 function GeneratePage($content, $title, $page_revision = false, $args = false) {
242 if (!is_array($args))
245 $args['CONTENT'] = $content;
246 $args['TITLE'] = $title;
247 $args['revision'] = $page_revision;
249 if (!isset($args['HEADER']))
250 $args['HEADER'] = $title;
252 printXML(new Template('html', $request, $args));
257 * For dumping pages as html to a file.
259 function GeneratePageasXML($content, $title, $page_revision = false, $args = false) {
262 if (!is_array($args))
265 $content->_basepage = $title;
266 $args['CONTENT'] = $content;
267 $args['TITLE'] = SplitPagename($title);
268 $args['revision'] = $page_revision;
270 if (!isset($args['HEADER']))
271 $args['HEADER'] = SplitPagename($title);
273 global $HIDE_TOOLBARS, $NO_BASEHREF, $HTML_DUMP;
274 $HIDE_TOOLBARS = true;
277 $html = asXML(new Template('htmldump', $request, $args));
279 $HIDE_TOOLBARS = false;
284 // $Log: not supported by cvs2svn $
285 // Revision 1.72 2005/02/02 20:35:41 rurban
288 // Revision 1.71 2005/02/02 19:29:30 rurban
289 // support theme overrides
291 // Revision 1.70 2005/01/25 07:01:26 rurban
292 // update comments about future plans
294 // Revision 1.69 2004/11/17 20:07:17 rurban
297 // Revision 1.68 2004/11/09 17:11:04 rurban
298 // * revert to the wikidb ref passing. there's no memory abuse there.
299 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
300 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
301 // are also needed at the rendering for linkExistingWikiWord().
302 // pass options to pageiterator.
303 // use this cache also for _get_pageid()
304 // This saves about 8 SELECT count per page (num all pagelinks).
305 // * fix passing of all page fields to the pageiterator.
306 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
308 // Revision 1.67 2004/11/05 18:03:35 rurban
309 // shorten the template chain in errmsg
311 // Revision 1.66 2004/11/01 10:43:55 rurban
312 // seperate PassUser methods into seperate dir (memory usage)
313 // fix WikiUser (old) overlarge data session
314 // remove wikidb arg from various page class methods, use global ->_dbi instead
317 // Revision 1.65 2004/10/07 16:08:58 rurban
318 // fixed broken FileUser session handling.
319 // thanks to Arnaud Fontaine for detecting this.
320 // enable file user Administrator membership.
322 // Revision 1.64 2004/10/04 23:40:35 rurban
323 // fix nested loops on htmldump errors
325 // Revision 1.63 2004/09/06 08:22:33 rurban
326 // prevent errorhandler to fail on empty templates
328 // Revision 1.62 2004/06/28 15:39:27 rurban
329 // fixed endless recursion in WikiGroup: isAdmin()
331 // Revision 1.61 2004/06/25 14:29:18 rurban
332 // WikiGroup refactoring:
333 // global group attached to user, code for not_current user.
334 // improved helpers for special groups (avoid double invocations)
335 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
336 // fixed a XHTML validation error on userprefs.tmpl
338 // Revision 1.60 2004/06/14 11:31:36 rurban
339 // renamed global $Theme to $WikiTheme (gforge nameclash)
340 // inherit PageList default options from PageList
341 // default sortby=pagename
342 // use options in PageList_Selectable (limit, sortby, ...)
343 // added action revert, with button at action=diff
344 // added option regex to WikiAdminSearchReplace
346 // Revision 1.59 2004/05/18 16:23:39 rurban
347 // rename split_pagename to SplitPagename
349 // Revision 1.58 2004/05/15 19:48:33 rurban
350 // fix some too loose PagePerms for signed, but not authenticated users
351 // (admin, owner, creator)
352 // no double login page header, better login msg.
353 // moved action_pdf to lib/pdf.php
355 // Revision 1.57 2004/05/01 18:20:05 rurban
356 // Add $charset to template locals (instead of constant CHARSET)
358 // Revision 1.56 2004/04/12 13:04:50 rurban
359 // added auth_create: self-registering Db users
361 // removed rating recommendations
362 // ziplib reformatting
364 // Revision 1.55 2004/04/02 15:06:55 rurban
365 // fixed a nasty ADODB_mysql session update bug
366 // improved UserPreferences layout (tabled hints)
367 // fixed UserPreferences auth handling
368 // improved auth stability
369 // improved old cookie handling: fixed deletion of old cookies with paths
371 // Revision 1.54 2004/03/02 18:11:39 rurban
372 // CreateToc support: Pass the preparsed markup to each plugin as $dbi->_markup
373 // to be able to know about its context, and even let the plugin change it.
376 // Revision 1.53 2004/02/22 23:20:31 rurban
377 // fixed DumpHtmlToDir,
378 // enhanced sortby handling in PageList
379 // new button_heading th style (enabled),
380 // added sortby and limit support to the db backends and plugins
381 // for paging support (<<prev, next>> links on long lists)
383 // Revision 1.52 2003/12/20 23:59:19 carstenklapp
384 // Internal change: Added rcs Log tag & emacs php mode tag (sorry, forgot
385 // this in the last commit).
392 // c-hanging-comment-ender-p: nil
393 // indent-tabs-mode: nil