PageRenderTime 72ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/eztemplate/classes/eztemplate.php

https://github.com/aurelienRT1/ezpublish
PHP | 2702 lines | 1817 code | 229 blank | 656 comment | 258 complexity | c66ecac8902c70f99ed364aa4b2d2e3e MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  1. <?php
  2. //
  3. // Definition of eZTemplate class
  4. //
  5. // Created on: <01-Mar-2002 13:49:57 amos>
  6. //
  7. // ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
  8. // SOFTWARE NAME: eZ Publish
  9. // SOFTWARE RELEASE: 4.1.x
  10. // COPYRIGHT NOTICE: Copyright (C) 1999-2010 eZ Systems AS
  11. // SOFTWARE LICENSE: GNU General Public License v2.0
  12. // NOTICE: >
  13. // This program is free software; you can redistribute it and/or
  14. // modify it under the terms of version 2.0 of the GNU General
  15. // Public License as published by the Free Software Foundation.
  16. //
  17. // This program is distributed in the hope that it will be useful,
  18. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. // GNU General Public License for more details.
  21. //
  22. // You should have received a copy of version 2.0 of the GNU General
  23. // Public License along with this program; if not, write to the Free
  24. // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  25. // MA 02110-1301, USA.
  26. //
  27. //
  28. // ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
  29. //
  30. /*! \file
  31. Template system manager.
  32. */
  33. /*! \defgroup eZTemplate Template system */
  34. /*!
  35. \class eZTemplate eztemplate.php
  36. \ingroup eZTemplate
  37. \brief The main manager for templates
  38. The template systems allows for separation of code and
  39. layout by moving the layout part into template files. These
  40. template files are parsed and processed with template variables set
  41. by the PHP code.
  42. The template system in itself is does not do much, it parses template files
  43. according to a rule set sets up a tree hierarchy and process the data
  44. using functions and operators. The standard template system comes with only
  45. a few functions and no operators, it is meant for these functions and operators
  46. to be specified by the users of the template system. But for simplicity a few
  47. help classes is available which can be easily enabled.
  48. The classes are:
  49. - eZTemplateDelimitFunction - Inserts the left and right delimiter which are normally parsed.
  50. - eZTemplateSectionFunction - Allows for conditional blocks and loops.
  51. - eZTemplateIncludeFunction - Includes external templates
  52. - eZTemplateSequenceFunction - Creates sequences arrays
  53. - eZTemplateSwitchFunction - Conditional output of template
  54. - eZTemplatePHPOperator - Allows for easy redirection of operator names to PHP functions.
  55. - eZTemplateLocaleOperator - Allows for locale conversions.
  56. - eZTemplateArrayOperator - Creates arrays
  57. - eZTemplateAttributeOperator - Displays contents of template variables, useful for debugging
  58. - eZTemplateImageOperator - Converts text to image
  59. - eZTemplateLogicOperator - Various logical operators for boolean handling
  60. - eZTemplateUnitOperator - Unit conversion and display
  61. To enable these functions and operator use registerFunction and registerOperator.
  62. In keeping with the spirit of being simple the template system does not know how
  63. to get the template files itself. Instead it relies on resource handlers, these
  64. handlers fetches the template files using different kind of transport mechanism.
  65. For simplicity a default resource class is available, eZTemplateFileResource fetches
  66. templates from the filesystem.
  67. The parser process consists of three passes, each pass adds a new level of complexity.
  68. The first pass strips text from template blocks which starts with a left delimiter and
  69. ends with a right delimiter (default is { and } ), and places them in an array.
  70. The second pass iterates the text and block elements and removes newlines from
  71. text before function blocks and text after function blocks.
  72. The third pass builds the tree according the function rules.
  73. Processing is done by iterating over the root of the tree, if a text block is found
  74. the text is appended to the result text. If a variable or contant is it's data is extracted
  75. and any operators found are run on it before fetching the result and appending it to
  76. the result text. If a function is found the function is called with the parameters
  77. and it's up to the function handle children if any.
  78. Constants and template variables will usually be called variables since there's little
  79. difference. A template variable expression will start with a $ and consists of a
  80. namespace (optional) a name and attribues(optional). The variable expression
  81. \verbatim $root:var.attr1 \endverbatim exists in the "root" namespace, has the name "var" and uses the
  82. attribute "attr1". Some functions will create variables on demand, to avoid name conflicts
  83. namespaces were introduced, each function will place the new variables in a namespace
  84. specified in the template file. Attribues are used for fetching parts of the variable,
  85. for instance an element in an array or data in an object. Since the syntax is the
  86. same for arrays and objects the PHP code can use simple arrays when speed is required,
  87. the template code will not care.
  88. A different syntax is also available when you want to access an attribute using a variable.
  89. For instance \verbatim $root:var[$attr_var] \endverbatim, if the variable $attr_var contains "attr1" it would
  90. access the same attribute as in the first example.
  91. The syntax for operators is a | and a name, optionally parameters can be specified with
  92. ( and ) delimited with ,. Valid operators are \verbatim |upcase, |l10n(date) \endverbatim.
  93. Functions look a lot like HTML/XML tags. The function consists of a name and parameters
  94. which are assigned using the param=value syntax. Some parameters may be required while
  95. others may be optionally, the exact behaviour is specified by each function.
  96. Valid functions are \verbatim "section name=abc loop=4" \endverbatim
  97. Example of usage:
  98. \code
  99. // Init template
  100. $tpl = eZTemplate::instance();
  101. $tpl->registerOperators( new eZTemplatePHPOperator( array( "upcase" => "strtoupper",
  102. "reverse" => "strrev" ) ) );
  103. $tpl->registerOperators( new eZTemplateLocaleOperator() );
  104. $tpl->registerFunction( "section", new eZTemplateSectionFunction( "section" ) );
  105. $tpl->registerFunctions( new eZTemplateDelimitFunction() );
  106. $tpl->setVariable( "my_var", "{this value set by variable}", "test" );
  107. $tpl->setVariable( "my_arr", array( "1st", "2nd", "third", "fjerde" ) );
  108. $tpl->setVariable( "multidim", array( array( "a", "b" ),
  109. array( "c", "d" ),
  110. array( "e", "f" ),
  111. array( "g", "h" ) ) );
  112. class mytest
  113. {
  114. function mytest( $n, $s )
  115. {
  116. $this->n = $n;
  117. $this->s = $s;
  118. }
  119. function hasAttribute( $attr )
  120. {
  121. return ( $attr == "name" || $attr == "size" );
  122. }
  123. function attribute( $attr )
  124. {
  125. switch ( $attr )
  126. {
  127. case "name";
  128. return $this->n;
  129. case "size";
  130. return $this->s;
  131. default:
  132. $retAttr = null;
  133. return $retAttr;
  134. }
  135. }
  136. };
  137. $tpl->setVariable( "multidim_obj", array( new mytest( "jan", 200 ),
  138. new mytest( "feb", 200 ),
  139. new mytest( "john", 200 ),
  140. new mytest( "doe", 50 ) ) );
  141. $tpl->setVariable( "curdate", time() );
  142. $tpl->display( "lib/eztemplate/example/test.tpl" );
  143. // test.tpl
  144. {section name=outer loop=4}
  145. 123
  146. {delimit}::{/delimit}
  147. {/section}
  148. {literal test=1} This is some {blah arg1="" arg2="abc" /} {/literal}
  149. <title>This is a test</title>
  150. <table border="1">
  151. <tr><th>{$test:my_var}
  152. {"some text!!!"|upcase|reverse}</th></tr>
  153. {section name=abc loop=$my_arr}
  154. <tr><td>{$abc:item}</td></tr>
  155. {/section}
  156. </table>
  157. <table border="1">
  158. {section name=outer loop=$multidim}
  159. <tr>
  160. {section name=inner loop=$outer:item}
  161. <td>{$inner:item}</td>
  162. {/section}
  163. </tr>
  164. {/section}
  165. </table>
  166. <table border="1">
  167. {section name=outer loop=$multidim_obj}
  168. <tr>
  169. <td>{$outer:item.name}</td>
  170. <td>{$outer:item.size}</td>
  171. </tr>
  172. {/section}
  173. </table>
  174. {section name=outer loop=$nonexistingvar}
  175. <b><i>Dette skal ikke vises</b></i>
  176. {section-else}
  177. <b><i>This is shown when the {ldelim}$loop{rdelim} variable is non-existant</b></i>
  178. {/section}
  179. Denne koster {1.4|l10n(currency)}<br>
  180. {-123456789|l10n(number)}<br>
  181. {$curdate|l10n(date)}<br>
  182. {$curdate|l10n(shortdate)}<br>
  183. {$curdate|l10n(time)}<br>
  184. {$curdate|l10n(shorttime)}<br>
  185. {include file="test2.tpl"/}
  186. \endcode
  187. */
  188. class eZTemplate
  189. {
  190. const RESOURCE_FETCH = 1;
  191. const RESOURCE_QUERY = 2;
  192. const ELEMENT_TEXT = 1;
  193. const ELEMENT_SINGLE_TAG = 2;
  194. const ELEMENT_NORMAL_TAG = 3;
  195. const ELEMENT_END_TAG = 4;
  196. const ELEMENT_VARIABLE = 5;
  197. const ELEMENT_COMMENT = 6;
  198. const NODE_ROOT = 1;
  199. const NODE_TEXT = 2;
  200. const NODE_VARIABLE = 3;
  201. const NODE_FUNCTION = 4;
  202. const NODE_OPERATOR = 5;
  203. const NODE_INTERNAL = 100;
  204. const NODE_INTERNAL_CODE_PIECE = 101;
  205. const NODE_INTERNAL_VARIABLE_SET = 105;
  206. const NODE_INTERNAL_VARIABLE_UNSET = 102;
  207. const NODE_INTERNAL_NAMESPACE_CHANGE = 103;
  208. const NODE_INTERNAL_NAMESPACE_RESTORE = 104;
  209. const NODE_INTERNAL_WARNING = 120;
  210. const NODE_INTERNAL_ERROR = 121;
  211. const NODE_INTERNAL_RESOURCE_ACQUISITION = 140;
  212. const NODE_OPTIMIZED_RESOURCE_ACQUISITION = 141;
  213. const NODE_INTERNAL_OUTPUT_ASSIGN = 150;
  214. const NODE_INTERNAL_OUTPUT_READ = 151;
  215. const NODE_INTERNAL_OUTPUT_INCREASE = 152;
  216. const NODE_INTERNAL_OUTPUT_DECREASE = 153;
  217. const NODE_INTERNAL_OUTPUT_SPACING_INCREASE = 160;
  218. const NODE_INTERNAL_SPACING_DECREASE = 161;
  219. const NODE_OPTIMIZED_INIT = 201;
  220. const NODE_USER_CUSTOM = 1000;
  221. const TYPE_VOID = 0;
  222. const TYPE_STRING = 1;
  223. const TYPE_NUMERIC = 2;
  224. const TYPE_IDENTIFIER = 3;
  225. const TYPE_VARIABLE = 4;
  226. const TYPE_ATTRIBUTE = 5;
  227. const TYPE_OPERATOR = 6;
  228. const TYPE_BOOLEAN = 7;
  229. const TYPE_ARRAY = 8;
  230. const TYPE_DYNAMIC_ARRAY = 9;
  231. const TYPE_INTERNAL = 100;
  232. const TYPE_INTERNAL_CODE_PIECE = 101;
  233. const TYPE_PHP_VARIABLE = 102;
  234. const TYPE_OPTIMIZED_NODE = 201;
  235. const TYPE_OPTIMIZED_ARRAY_LOOKUP = 202;
  236. const TYPE_OPTIMIZED_CONTENT_CALL = 203;
  237. const TYPE_OPTIMIZED_ATTRIBUTE_LOOKUP = 204;
  238. const TYPE_INTERNAL_STOP = 999;
  239. const TYPE_STRING_BIT = 1;
  240. const TYPE_NUMERIC_BIT = 2;
  241. const TYPE_IDENTIFIER_BIT = 4;
  242. const TYPE_VARIABLE_BIT = 8;
  243. const TYPE_ATTRIBUTE_BIT = 16;
  244. const TYPE_OPERATOR_BIT = 32;
  245. const TYPE_NONE = 0;
  246. const TYPE_ALL = 63;
  247. const TYPE_BASIC = 47;
  248. const TYPE_MODIFIER_MASK = 48;
  249. const NAMESPACE_SCOPE_GLOBAL = 1;
  250. const NAMESPACE_SCOPE_LOCAL = 2;
  251. const NAMESPACE_SCOPE_RELATIVE = 3;
  252. const DEBUG_INTERNALS = false;
  253. const FILE_ERRORS = 1;
  254. /*!
  255. Intializes the template with left and right delimiters being { and },
  256. and a file resource. The literal tag "literal" is also registered.
  257. */
  258. function eZTemplate()
  259. {
  260. $this->Tree = array( eZTemplate::NODE_ROOT, false );
  261. $this->LDelim = "{";
  262. $this->RDelim = "}";
  263. $this->IncludeText = array();
  264. $this->IncludeOutput = array();
  265. $this->registerLiteral( "literal" );
  266. $res = new eZTemplateFileResource();
  267. $this->DefaultResource = $res;
  268. $this->registerResource( $res );
  269. $this->Resources = array();
  270. $this->Text = null;
  271. $this->IsCachingAllowed = true;
  272. $this->resetErrorLog();
  273. $this->AutoloadPathList = array( 'lib/eztemplate/classes/' );
  274. $this->Variables = array();
  275. $this->LocalVariablesNamesStack = array();
  276. $this->CurrentLocalVariablesNames = null;
  277. $this->Functions = array();
  278. $this->FunctionAttributes = array();
  279. $this->TestCompile = false;
  280. $ini = eZINI::instance( 'template.ini' );
  281. if ( $ini->hasVariable( 'ControlSettings', 'MaxLevel' ) )
  282. $this->MaxLevel = $ini->variable( 'ControlSettings', 'MaxLevel' );
  283. $this->MaxLevelWarning = ezpI18n::tr( 'lib/template',
  284. 'The maximum nesting level of %max has been reached. The execution is stopped to avoid infinite recursion.',
  285. '',
  286. array( '%max' => $this->MaxLevel ) );
  287. eZDebug::createAccumulatorGroup( 'template_total', 'Template Total' );
  288. $this->TemplatesUsageStatistics = array();
  289. // Array of templates which are used in a single fetch()
  290. $this->TemplateFetchList = array();
  291. $this->ForeachCounter = 0;
  292. $this->ForCounter = 0;
  293. $this->WhileCounter = 0;
  294. $this->DoCounter = 0;
  295. $this->ElseifCounter = 0;
  296. }
  297. /*!
  298. Returns the left delimiter being used.
  299. */
  300. function leftDelimiter()
  301. {
  302. return $this->LDelim;
  303. }
  304. /*!
  305. Returns the right delimiter being used.
  306. */
  307. function rightDelimiter()
  308. {
  309. return $this->RDelim;
  310. }
  311. /*!
  312. Sets the left delimiter.
  313. */
  314. function setLeftDelimiter( $delim )
  315. {
  316. $this->LDelim = $delim;
  317. }
  318. /*!
  319. Sets the right delimiter.
  320. */
  321. function setRightDelimiter( $delim )
  322. {
  323. $this->RDelim = $delim;
  324. }
  325. /*!
  326. Fetches the result of the template file and displays it.
  327. If $template is supplied it will load this template file first.
  328. */
  329. function display( $template = false, $extraParameters = false )
  330. {
  331. $output = $this->fetch( $template, $extraParameters );
  332. if ( $this->ShowDetails )
  333. {
  334. echo '<h1>Result:</h1>' . "\n";
  335. echo '<hr/>' . "\n";
  336. }
  337. echo "$output";
  338. if ( $this->ShowDetails )
  339. {
  340. echo '<hr/>' . "\n";
  341. }
  342. if ( $this->ShowDetails )
  343. {
  344. echo "<h1>Template data:</h1>";
  345. echo "<p class=\"filename\">" . $template . "</p>";
  346. echo "<pre class=\"example\">" . htmlspecialchars( $this->Text ) . "</pre>";
  347. reset( $this->IncludeText );
  348. while ( ( $key = key( $this->IncludeText ) ) !== null )
  349. {
  350. $item = $this->IncludeText[$key];
  351. echo "<p class=\"filename\">" . $key . "</p>";
  352. echo "<pre class=\"example\">" . htmlspecialchars( $item ) . "</pre>";
  353. next( $this->IncludeText );
  354. }
  355. echo "<h1>Result text:</h1>";
  356. echo "<p class=\"filename\">" . $template . "</p>";
  357. echo "<pre class=\"example\">" . htmlspecialchars( $output ) . "</pre>";
  358. reset( $this->IncludeOutput );
  359. while ( ( $key = key( $this->IncludeOutput ) ) !== null )
  360. {
  361. $item = $this->IncludeOutput[$key];
  362. echo "<p class=\"filename\">" . $key . "</p>";
  363. echo "<pre class=\"example\">" . htmlspecialchars( $item ) . "</pre>";
  364. next( $this->IncludeOutput );
  365. }
  366. }
  367. }
  368. /*!
  369. * Initialize list of local variables for the current template.
  370. * The list contains only names of variables.
  371. */
  372. function createLocalVariablesList()
  373. {
  374. $this->LocalVariablesNamesStack[] = array();
  375. $this->CurrentLocalVariablesNames =& $this->LocalVariablesNamesStack[ count( $this->LocalVariablesNamesStack ) - 1];
  376. }
  377. /*!
  378. * Check if the given local variable exists.
  379. */
  380. function hasLocalVariable( $varName, $rootNamespace )
  381. {
  382. return ( array_key_exists( $rootNamespace, $this->CurrentLocalVariablesNames ) &&
  383. array_key_exists( $varName, $this->CurrentLocalVariablesNames[$rootNamespace] ) );
  384. }
  385. /*!
  386. * Create a local variable.
  387. */
  388. function setLocalVariable( $varName, $varValue, $rootNamespace )
  389. {
  390. $this->CurrentLocalVariablesNames[$rootNamespace][$varName] = 1;
  391. $this->setVariable( $varName, $varValue, $rootNamespace );
  392. }
  393. /*!
  394. * Destroy a local variable.
  395. */
  396. function unsetLocalVariable( $varName, $rootNamespace )
  397. {
  398. if ( !$this->hasLocalVariable( $varName, $rootNamespace ) )
  399. return;
  400. $this->unsetVariable( $varName, $rootNamespace );
  401. unset( $this->CurrentLocalVariablesNames[$rootNamespace][$varName] );
  402. }
  403. /*!
  404. * Destroy all local variables defined in the current template.
  405. */
  406. function unsetLocalVariables()
  407. {
  408. foreach ( $this->CurrentLocalVariablesNames as $ns => $vars )
  409. {
  410. foreach ( $vars as $var => $val )
  411. $this->unsetLocalVariable( $var, $ns );
  412. }
  413. }
  414. /*!
  415. * Destroy list of local variables defined in the current (innermost) template.
  416. */
  417. function destroyLocalVariablesList()
  418. {
  419. array_pop( $this->LocalVariablesNamesStack );
  420. if ( $this->LocalVariablesNamesStack )
  421. $this->CurrentLocalVariablesNames =& $this->LocalVariablesNamesStack[ count( $this->LocalVariablesNamesStack ) - 1];
  422. else
  423. unset( $this->CurrentLocalVariablesNames );
  424. }
  425. /*!
  426. Tries to fetch the result of the template file and returns it.
  427. If $template is supplied it will load this template file first.
  428. */
  429. function fetch( $template = false, $extraParameters = false, $returnResourceData = false )
  430. {
  431. $this->resetErrorLog();
  432. // Reset fetch list when a new fetch is started
  433. $this->TemplateFetchList = array();
  434. eZDebug::accumulatorStart( 'template_total' );
  435. eZDebug::accumulatorStart( 'template_load', 'template_total', 'Template load' );
  436. $root = null;
  437. if ( is_string( $template ) )
  438. {
  439. $resourceData = $this->loadURIRoot( $template, true, $extraParameters );
  440. if ( $resourceData and
  441. $resourceData['root-node'] !== null )
  442. $root =& $resourceData['root-node'];
  443. }
  444. eZDebug::accumulatorStop( 'template_load' );
  445. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  446. {
  447. $savedLocale = setlocale( LC_CTYPE, null );
  448. setlocale( LC_CTYPE, $resourceData['locales'] );
  449. }
  450. $text = "";
  451. if ( $root !== null or
  452. $resourceData['compiled-template'] )
  453. {
  454. if ( $this->ShowDetails )
  455. eZDebug::addTimingPoint( "Process" );
  456. eZDebug::accumulatorStart( 'template_processing', 'template_total', 'Template processing' );
  457. $templateCompilationUsed = false;
  458. if ( $resourceData['compiled-template'] )
  459. {
  460. $textElements = array();
  461. if ( $this->executeCompiledTemplate( $resourceData, $textElements, "", "", $extraParameters ) )
  462. {
  463. $text = implode( '', $textElements );
  464. $templateCompilationUsed = true;
  465. }
  466. }
  467. if ( !$templateCompilationUsed )
  468. {
  469. if ( eZTemplate::isDebugEnabled() )
  470. {
  471. $fname = $resourceData['template-filename'];
  472. eZDebug::writeDebug( "FETCH START URI: $template, $fname" );
  473. }
  474. $this->process( $root, $text, "", "" );
  475. if ( eZTemplate::isDebugEnabled() )
  476. eZDebug::writeDebug( "FETCH END URI: $template, $fname" );
  477. }
  478. eZDebug::accumulatorStop( 'template_processing' );
  479. if ( $this->ShowDetails )
  480. eZDebug::addTimingPoint( "Process done" );
  481. }
  482. eZDebug::accumulatorStop( 'template_total' );
  483. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  484. {
  485. setlocale( LC_CTYPE, $savedLocale );
  486. }
  487. if ( $returnResourceData )
  488. {
  489. $resourceData['result_text'] = $text;
  490. return $resourceData;
  491. }
  492. return $text;
  493. }
  494. function process( $root, &$text, $rootNamespace, $currentNamespace )
  495. {
  496. $this->createLocalVariablesList();
  497. $textElements = array();
  498. $this->processNode( $root, $textElements, $rootNamespace, $currentNamespace );
  499. if ( is_array( $textElements ) )
  500. $text = implode( '', $textElements );
  501. else
  502. $text = $textElements;
  503. $this->unsetLocalVariables();
  504. $this->destroyLocalVariablesList();
  505. }
  506. function processNode( $node, &$textElements, $rootNamespace, $currentNamespace )
  507. {
  508. $rslt = null;
  509. $nodeType = $node[0];
  510. if ( $nodeType == eZTemplate::NODE_ROOT )
  511. {
  512. $children = $node[1];
  513. if ( $children )
  514. {
  515. foreach ( $children as $child )
  516. {
  517. $this->processNode( $child, $textElements, $rootNamespace, $currentNamespace );
  518. if ( !is_array( $textElements ) )
  519. eZDebug::writeError( "Textelements is no longer array: '$textElements'",
  520. 'eztemplate::processNode::root' );
  521. }
  522. }
  523. }
  524. else if ( $nodeType == eZTemplate::NODE_TEXT )
  525. {
  526. $textElements[] = $node[2];
  527. }
  528. else if ( $nodeType == eZTemplate::NODE_VARIABLE )
  529. {
  530. $variableData = $node[2];
  531. $variablePlacement = $node[3];
  532. $rslt = $this->processVariable( $textElements, $variableData, $variablePlacement, $rootNamespace, $currentNamespace );
  533. if ( !is_array( $textElements ) )
  534. eZDebug::writeError( "Textelements is no longer array: '$textElements'",
  535. 'eztemplate::processNode::variable' );
  536. }
  537. else if ( $nodeType == eZTemplate::NODE_FUNCTION )
  538. {
  539. $functionChildren = $node[1];
  540. $functionName = $node[2];
  541. $functionParameters = $node[3];
  542. $functionPlacement = $node[4];
  543. $rslt = $this->processFunction( $functionName, $textElements, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace );
  544. if ( !is_array( $textElements ) )
  545. eZDebug::writeError( "Textelements is no longer array: '$textElements'",
  546. "eztemplate::processNode::function( '$functionName' )" );
  547. }
  548. return $rslt;
  549. }
  550. function processVariable( &$textElements, $variableData, $variablePlacement, $rootNamespace, $currentNamespace )
  551. {
  552. $value = $this->elementValue( $variableData, $rootNamespace, $currentNamespace, $variablePlacement );
  553. $this->appendElementText( $textElements, $value, $rootNamespace, $currentNamespace );
  554. }
  555. function processFunction( $functionName, &$textElements, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace )
  556. {
  557. // Note: This code piece is replicated in the eZTemplateCompiler,
  558. // if this code is changed the replicated code must be updated as well.
  559. $func = $this->Functions[$functionName];
  560. if ( is_array( $func ) )
  561. {
  562. $this->loadAndRegisterFunctions( $this->Functions[$functionName] );
  563. $func = $this->Functions[$functionName];
  564. }
  565. if ( isset( $func ) and
  566. is_object( $func ) )
  567. {
  568. if ( eZTemplate::isMethodDebugEnabled() )
  569. eZDebug::writeDebug( "START FUNCTION: $functionName" );
  570. $value = $func->process( $this, $textElements, $functionName, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace );
  571. if ( eZTemplate::isMethodDebugEnabled() )
  572. eZDebug::writeDebug( "END FUNCTION: $functionName" );
  573. return $value;
  574. }
  575. else
  576. {
  577. $this->warning( "", "Function \"$functionName\" is not registered" );
  578. }
  579. }
  580. function fetchFunctionObject( $functionName )
  581. {
  582. $func = $this->Functions[$functionName];
  583. if ( is_array( $func ) )
  584. {
  585. $this->loadAndRegisterFunctions( $this->Functions[$functionName] );
  586. $func = $this->Functions[$functionName];
  587. }
  588. return $func;
  589. }
  590. /*!
  591. Loads the template using the URI $uri and parses it.
  592. \return The root node of the tree if \a $returnResourceData is false,
  593. if \c true the entire resource data structure.
  594. */
  595. function load( $uri, $extraParameters = false, $returnResourceData = false )
  596. {
  597. $resourceData = $this->loadURIRoot( $uri, true, $extraParameters );
  598. if ( !$resourceData or
  599. $resourceData['root-node'] === null )
  600. {
  601. $retValue = null;
  602. return $retValue;
  603. }
  604. else
  605. return $resourceData['root-node'];
  606. }
  607. function parse( $sourceText, &$rootElement, $rootNamespace, &$resourceData )
  608. {
  609. $parser = eZTemplateMultiPassParser::instance();
  610. $parser->parse( $this, $sourceText, $rootElement, $rootNamespace, $resourceData );
  611. }
  612. function loadURIData( $resourceObject, $uri, $resourceName, $template, &$extraParameters, $displayErrors = true )
  613. {
  614. $resourceData = $this->resourceData( $resourceObject, $uri, $resourceName, $template );
  615. $resourceData['text'] = null;
  616. $resourceData['root-node'] = null;
  617. $resourceData['compiled-template'] = false;
  618. $resourceData['time-stamp'] = null;
  619. $resourceData['key-data'] = null;
  620. $resourceData['locales'] = null;
  621. if ( !$resourceObject->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters ) )
  622. {
  623. $resourceData = null;
  624. if ( $displayErrors )
  625. $this->warning( "", "No template could be loaded for \"$template\" using resource \"$resourceName\"" );
  626. }
  627. return $resourceData;
  628. }
  629. /*!
  630. \static
  631. Creates a resource data structure of the parameters and returns it.
  632. This structure is passed to various parts of the template system.
  633. \note If you only have the URI you should call resourceFor() first to
  634. figure out the resource handler.
  635. */
  636. function resourceData( $resourceObject, $uri, $resourceName, $templateName )
  637. {
  638. $resourceData = array();
  639. $resourceData['uri'] = $uri;
  640. $resourceData['resource'] = $resourceName;
  641. $resourceData['template-name'] = $templateName;
  642. $resourceData['template-filename'] = $templateName;
  643. $resourceData['handler'] = $resourceObject;
  644. $resourceData['test-compile'] = $this->TestCompile;
  645. return $resourceData;
  646. }
  647. /*!
  648. Loads the template using the URI $uri and returns a structure with the text and timestamp,
  649. false otherwise.
  650. The structure keys are:
  651. - "text", the text.
  652. - "time-stamp", the timestamp.
  653. */
  654. function loadURIRoot( $uri, $displayErrors = true, &$extraParameters )
  655. {
  656. $res = "";
  657. $template = "";
  658. $resobj = $this->resourceFor( $uri, $res, $template );
  659. if ( !is_object( $resobj ) )
  660. {
  661. if ( $displayErrors )
  662. $this->warning( "", "No resource handler for \"$res\" and no default resource handler, aborting." );
  663. return null;
  664. }
  665. $canCache = true;
  666. if ( !$resobj->servesStaticData() )
  667. $canCache = false;
  668. if ( !$this->isCachingAllowed() )
  669. $canCache = false;
  670. $resourceData = $this->loadURIData( $resobj, $uri, $res, $template, $extraParameters, $displayErrors );
  671. if ( $resourceData )
  672. {
  673. $root = null;
  674. eZTemplate::appendTemplateToStatisticsIfNeeded( $resourceData['template-name'], $resourceData['template-filename'] );
  675. $this->appendTemplateFetch( $resourceData['template-filename'] );
  676. if ( !$resourceData['compiled-template'] and
  677. $resourceData['root-node'] === null )
  678. {
  679. $resourceData['root-node'] = array( eZTemplate::NODE_ROOT, false );
  680. $templateText = $resourceData["text"];
  681. $keyData = $resourceData['key-data'];
  682. $this->setIncludeText( $uri, $templateText );
  683. $rootNamespace = '';
  684. $this->parse( $templateText, $resourceData['root-node'], $rootNamespace, $resourceData );
  685. if ( eZTemplate::isDebugEnabled() )
  686. {
  687. $this->appendDebugNodes( $resourceData['root-node'], $resourceData );
  688. }
  689. if ( $canCache )
  690. $resobj->setCachedTemplateTree( $keyData, $uri, $res, $template, $extraParameters, $resourceData['root-node'] );
  691. }
  692. if ( !$resourceData['compiled-template'] and
  693. $canCache and
  694. $this->canCompileTemplate( $resourceData, $extraParameters ) )
  695. {
  696. $generateStatus = $this->compileTemplate( $resourceData, $extraParameters );
  697. if ( $generateStatus )
  698. $resourceData['compiled-template'] = true;
  699. }
  700. }
  701. return $resourceData;
  702. }
  703. function processURI( $uri, $displayErrors = true, &$extraParameters,
  704. &$textElements, $rootNamespace, $currentNamespace )
  705. {
  706. $this->Level++;
  707. if ( $this->Level > $this->MaxLevel )
  708. {
  709. eZDebug::writeError( $this->MaxLevelWarning, "eZTemplate:processURI Level: $this->Level @ $uri" );
  710. $textElements[] = $this->MaxLevelWarning;
  711. $this->Level--;
  712. return;
  713. }
  714. $resourceData = $this->loadURIRoot( $uri, $displayErrors, $extraParameters );
  715. if ( !$resourceData or
  716. ( !$resourceData['compiled-template'] and
  717. $resourceData['root-node'] === null ) )
  718. {
  719. $this->Level--;
  720. return;
  721. }
  722. $templateCompilationUsed = false;
  723. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  724. {
  725. $savedLocale = setlocale( LC_CTYPE, null );
  726. setlocale( LC_CTYPE, $resourceData['locales'] );
  727. }
  728. if ( $resourceData['compiled-template'] )
  729. {
  730. if ( $this->executeCompiledTemplate( $resourceData, $textElements, $rootNamespace, $currentNamespace, $extraParameters ) )
  731. $templateCompilationUsed = true;
  732. }
  733. if ( !$templateCompilationUsed )
  734. {
  735. $text = null;
  736. if ( eZTemplate::isDebugEnabled() )
  737. {
  738. $fname = $resourceData['template-filename'];
  739. eZDebug::writeDebug( "START URI: $uri, $fname" );
  740. }
  741. $this->process( $resourceData['root-node'], $text, $rootNamespace, $currentNamespace );
  742. if ( eZTemplate::isDebugEnabled() )
  743. eZDebug::writeDebug( "END URI: $uri, $fname" );
  744. $this->setIncludeOutput( $uri, $text );
  745. $textElements[] = $text;
  746. }
  747. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  748. {
  749. setlocale( LC_CTYPE, $savedLocale );
  750. }
  751. $this->Level--;
  752. }
  753. function canCompileTemplate( $resourceData, &$extraParameters )
  754. {
  755. $resourceObject = $resourceData['handler'];
  756. if ( !$resourceObject )
  757. return false;
  758. $canGenerate = $resourceObject->canCompileTemplate( $this, $resourceData, $extraParameters );
  759. return $canGenerate;
  760. }
  761. /*!
  762. Validates the template file \a $file and returns \c true if the file has correct syntax.
  763. \param $returnResourceData If \c true then the returned value will be the resourcedata structure
  764. \sa compileTemplateFile(), fetch()
  765. */
  766. function validateTemplateFile( $file, $returnResourceData = false )
  767. {
  768. $this->resetErrorLog();
  769. if ( !file_exists( $file ) )
  770. return false;
  771. $resourceHandler = $this->resourceFor( $file, $resourceName, $templateName );
  772. if ( !$resourceHandler )
  773. return false;
  774. $resourceData = $this->resourceData( $resourceHandler, $file, $resourceName, $templateName );
  775. $resourceData['key-data'] = "file:" . $file;
  776. $key = md5( $resourceData['key-data'] );
  777. $extraParameters = array();
  778. // Disable caching/compiling while fetchin the resource
  779. // It will be restored afterwards
  780. $isCachingAllowed = $this->IsCachingAllowed;
  781. $this->IsCachingAllowed = false;
  782. $resourceHandler->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters );
  783. // Restore previous caching flag
  784. $this->IsCachingAllowed = $isCachingAllowed;
  785. $root =& $resourceData['root-node'];
  786. $root = array( eZTemplate::NODE_ROOT, false );
  787. $templateText = $resourceData["text"];
  788. $rootNamespace = '';
  789. $this->parse( $templateText, $root, $rootNamespace, $resourceData );
  790. if ( eZTemplate::isDebugEnabled() )
  791. {
  792. $this->appendDebugNodes( $root, $resourceData );
  793. }
  794. $result = !$this->hasErrors() and !$this->hasWarnings();
  795. if ( $returnResourceData )
  796. {
  797. $resourceData['result'] = $result;
  798. return $resourceData;
  799. }
  800. return $result;
  801. }
  802. /*!
  803. Compiles the template file \a $file and returns \c true if the compilation was OK.
  804. \param $returnResourceData If \c true then the returned value will be the resourcedata structure
  805. \sa validateTemplateFile(), fetch()
  806. */
  807. function compileTemplateFile( $file, $returnResourceData = false )
  808. {
  809. $this->resetErrorLog();
  810. if ( !file_exists( $file ) )
  811. return false;
  812. $resourceHandler = $this->resourceFor( $file, $resourceName, $templateName );
  813. if ( !$resourceHandler )
  814. return false;
  815. $resourceData = $this->resourceData( $resourceHandler, $file, $resourceName, $templateName );
  816. $resourceData['key-data'] = "file:" . $file;
  817. $key = md5( $resourceData['key-data'] );
  818. $extraParameters = array();
  819. $resourceHandler->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters );
  820. $isCompiled = false;
  821. if ( isset( $resourceData['compiled-template'] ) )
  822. $isCompiled = $resourceData['compiled-template'];
  823. if ( !$isCompiled )
  824. {
  825. $root =& $resourceData['root-node'];
  826. $root = array( eZTemplate::NODE_ROOT, false );
  827. $templateText = $resourceData["text"];
  828. $rootNamespace = '';
  829. $this->parse( $templateText, $root, $rootNamespace, $resourceData );
  830. if ( eZTemplate::isDebugEnabled() )
  831. {
  832. $this->appendDebugNodes( $root, $resourceData );
  833. }
  834. $result = eZTemplateCompiler::compileTemplate( $this, $key, $resourceData );
  835. }
  836. else
  837. {
  838. $result = true;
  839. }
  840. if ( $returnResourceData )
  841. {
  842. $resourceData['result'] = $result;
  843. return $resourceData;
  844. }
  845. return $result;
  846. }
  847. function compileTemplate( &$resourceData, &$extraParameters )
  848. {
  849. $resourceObject = $resourceData['handler'];
  850. if ( !$resourceObject )
  851. return false;
  852. $keyData = $resourceData['key-data'];
  853. $uri = $resourceData['uri'];
  854. $resourceName = $resourceData['resource'];
  855. $templatePath = $resourceData['template-name'];
  856. return $resourceObject->compileTemplate( $this, $keyData, $uri, $resourceName, $templatePath, $extraParameters, $resourceData );
  857. }
  858. function executeCompiledTemplate( &$resourceData, &$textElements, $rootNamespace, $currentNamespace, &$extraParameters )
  859. {
  860. $resourceObject = $resourceData['handler'];
  861. if ( !$resourceObject )
  862. return false;
  863. $keyData = $resourceData['key-data'];
  864. $uri = $resourceData['uri'];
  865. $resourceName = $resourceData['resource'];
  866. $templatePath = $resourceData['template-name'];
  867. $timestamp = $resourceData['time-stamp'];
  868. return $resourceObject->executeCompiledTemplate( $this, $textElements,
  869. $keyData, $uri, $resourceData, $templatePath,
  870. $extraParameters, $timestamp,
  871. $rootNamespace, $currentNamespace );
  872. }
  873. /*!
  874. Returns the resource object for URI $uri. If a resource type is specified
  875. in the URI it is extracted and set in $res. The template name is set in $template
  876. without any resource specifier. To specify a resource the name and a ":" is
  877. prepended to the URI, for instance file:my.tpl.
  878. If no resource type is found the URI the default resource handler is used.
  879. */
  880. function resourceFor( $uri, &$res, &$template )
  881. {
  882. $args = explode( ":", $uri );
  883. if ( isset( $args[1] ) )
  884. {
  885. $res = $args[0];
  886. $template = $args[1];
  887. }
  888. else
  889. $template = $uri;
  890. if ( eZTemplate::isDebugEnabled() )
  891. {
  892. eZDebug::writeNotice( "eZTemplate: Loading template \"$template\" with resource \"$res\"" );
  893. }
  894. if ( isset( $this->Resources[$res] ) and is_object( $this->Resources[$res] ) )
  895. {
  896. return $this->Resources[$res];
  897. }
  898. return $this->DefaultResource;
  899. }
  900. /*!
  901. \return The resource handler object for resource name \a $resourceName.
  902. \sa resourceFor
  903. */
  904. function resourceHandler( $resourceName )
  905. {
  906. if ( isset( $this->Resources[$resourceName] ) &&
  907. is_object( $this->Resources[$resourceName] ) )
  908. {
  909. return $this->Resources[$resourceName];
  910. }
  911. return $this->DefaultResource;
  912. }
  913. function hasChildren( &$function, $functionName )
  914. {
  915. $hasChildren = $function->hasChildren();
  916. if ( is_array( $hasChildren ) )
  917. return $hasChildren[$functionName];
  918. else
  919. return $hasChildren;
  920. }
  921. /*!
  922. Returns the empty variable type.
  923. */
  924. function emptyVariable()
  925. {
  926. return array( "type" => "null" );
  927. }
  928. /*!
  929. \static
  930. */
  931. function mergeNamespace( $rootNamespace, $additionalNamespace )
  932. {
  933. $namespace = $rootNamespace;
  934. if ( $namespace == '' )
  935. $namespace = $additionalNamespace;
  936. else if ( $additionalNamespace != '' )
  937. $namespace = "$namespace:$additionalNamespace";
  938. return $namespace;
  939. }
  940. /*!
  941. Returns the actual value of a template type or null if an unknown type.
  942. */
  943. function elementValue( &$dataElements, $rootNamespace, $currentNamespace, $placement = false,
  944. $checkExistance = false, $checkForProxy = false )
  945. {
  946. /*
  947. * We use a small dirty hack in this function...
  948. * To help the caller to determine if the value was a proxy object,
  949. * we store boolean true to $dataElements['proxy-object-found'] in this case.
  950. * (it's up to caller to remove this garbage from $dataElements...)
  951. * This behaviour is enabled by $checkForProxy parameter.
  952. */
  953. $value = null;
  954. if ( !is_array( $dataElements ) )
  955. {
  956. $this->error( "elementValue",
  957. "Missing array data structure, got " . gettype( $dataElements ) );
  958. return null;
  959. }
  960. foreach ( $dataElements as $dataElement )
  961. {
  962. if ( $dataElement === null )
  963. {
  964. return null;
  965. }
  966. $dataType = $dataElement[0];
  967. switch ( $dataType )
  968. {
  969. case eZTemplate::TYPE_VOID:
  970. {
  971. if ( !$checkExistance )
  972. $this->warning( 'elementValue',
  973. 'Found void datatype, should not be used' );
  974. else
  975. {
  976. return null;
  977. }
  978. } break;
  979. case eZTemplate::TYPE_STRING:
  980. case eZTemplate::TYPE_NUMERIC:
  981. case eZTemplate::TYPE_IDENTIFIER:
  982. case eZTemplate::TYPE_BOOLEAN:
  983. case eZTemplate::TYPE_ARRAY:
  984. {
  985. $value = $dataElement[1];
  986. } break;
  987. case eZTemplate::TYPE_VARIABLE:
  988. {
  989. $variableData = $dataElement[1];
  990. $variableNamespace = $variableData[0];
  991. $variableNamespaceScope = $variableData[1];
  992. $variableName = $variableData[2];
  993. if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_GLOBAL )
  994. $namespace = $variableNamespace;
  995. else if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_LOCAL )
  996. $namespace = $this->mergeNamespace( $rootNamespace, $variableNamespace );
  997. else if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_RELATIVE )
  998. $namespace = $this->mergeNamespace( $currentNamespace, $variableNamespace );
  999. else
  1000. $namespace = false;
  1001. if ( $this->hasVariable( $variableName, $namespace ) )
  1002. {
  1003. $value = $this->variable( $variableName, $namespace );
  1004. }
  1005. else
  1006. {
  1007. if ( !$checkExistance )
  1008. $this->error( '', "Unknown template variable '$variableName' in namespace '$namespace'", $placement );
  1009. {
  1010. return null;
  1011. }
  1012. }
  1013. } break;
  1014. case eZTemplate::TYPE_ATTRIBUTE:
  1015. {
  1016. $attributeData = $dataElement[1];
  1017. $attributeValue = $this->elementValue( $attributeData, $rootNamespace, $currentNamespace, false, $checkExistance );
  1018. if ( $attributeValue !== null )
  1019. {
  1020. if ( !is_numeric( $attributeValue ) and
  1021. !is_string( $attributeValue ) and
  1022. !is_bool( $attributeValue ) )
  1023. {
  1024. if ( !$checkExistance )
  1025. $this->error( "",
  1026. "Cannot use type " . gettype( $attributeValue ) . " for attribute lookup", $placement );
  1027. {
  1028. return null;
  1029. }
  1030. }
  1031. if ( is_array( $value ) )
  1032. {
  1033. if ( array_key_exists( $attributeValue, $value ) )
  1034. {
  1035. $value = $value[$attributeValue];
  1036. }
  1037. else
  1038. {
  1039. if ( !$checkExistance )
  1040. {
  1041. $arrayAttributeList = array_keys( $value );
  1042. $arrayCount = count( $arrayAttributeList );
  1043. $errorMessage = "No such attribute for array($arrayCount): $attributeValue";
  1044. $chooseText = "Choose one of following: ";
  1045. $errorMessage .= "\n$chooseText";
  1046. $errorMessage .= $this->expandAttributes( $arrayAttributeList, $chooseText, 25 );
  1047. $this->error( "",
  1048. $errorMessage, $placement );
  1049. }
  1050. return null;
  1051. }
  1052. }
  1053. else if ( is_object( $value ) )
  1054. {
  1055. if ( method_exists( $value, "attribute" ) and
  1056. method_exists( $value, "hasattribute" ) )
  1057. {
  1058. if ( $value->hasAttribute( $attributeValue ) )
  1059. {
  1060. $value = $value->attribute( $attributeValue );
  1061. }
  1062. else
  1063. {
  1064. if ( !$checkExistance )
  1065. {
  1066. $objectAttributeList = array();
  1067. if ( method_exists( $value, 'attributes' ) )
  1068. $objectAttributeList = $value->attributes();
  1069. $objectClass= get_class( $value );
  1070. $errorMessage = "No such attribute for object($objectClass): $attributeValue";
  1071. $chooseText = "Choose one of following: ";
  1072. $errorMessage .= "\n$chooseText";
  1073. $errorMessage .= $this->expandAttributes( $objectAttributeList, $chooseText, 25 );
  1074. $this->error( "",
  1075. $errorMessage, $placement );
  1076. }
  1077. return null;
  1078. }
  1079. }
  1080. else
  1081. {
  1082. if ( !$checkExistance )
  1083. $this->error( "",
  1084. "Cannot retrieve attribute of object(" . get_class( $value ) .
  1085. "), no attribute functions available",
  1086. $placement );
  1087. return null;
  1088. }
  1089. }
  1090. else
  1091. {
  1092. if ( !$checkExistance )
  1093. $this->error( "",
  1094. "Cannot retrieve attribute of a " . gettype( $value ),
  1095. $placement );
  1096. return null;
  1097. }
  1098. }
  1099. else
  1100. {
  1101. if ( !$checkExistance )
  1102. $this->error( '',
  1103. 'Attribute value was null, cannot get attribute',
  1104. $placement );
  1105. return null;
  1106. }
  1107. } break;
  1108. case eZTemplate::TYPE_OPERATOR:
  1109. {
  1110. $operatorParameters = $dataElement[1];
  1111. $operatorName = $operatorParameters[0];
  1112. $operatorParameters = array_splice( $operatorParameters, 1 );
  1113. if ( is_object( $value ) and
  1114. method_exists( $value, 'templateValue' ) )
  1115. {
  1116. if ( $checkForProxy )
  1117. $dataElements['proxy-object-found'] = true;
  1118. $value = $value->templateValue();
  1119. }
  1120. $valueData = array( 'value' => $value );
  1121. $this->processOperator( $operatorName, $operatorParameters, $rootNamespace, $currentNamespace,
  1122. $valueData, $placement, $checkExistance );
  1123. $value = $valueData['value'];
  1124. } break;
  1125. default:
  1126. {
  1127. if ( !$checkExistance )
  1128. $this->error( "elementValue",
  1129. "Unknown data type: '$dataType'" );
  1130. return null;
  1131. }
  1132. }
  1133. }
  1134. if ( is_object( $value ) and
  1135. method_exists( $value, 'templateValue' ) )
  1136. {
  1137. if ( $checkForProxy )
  1138. $dataElements['proxy-object-found'] = true;
  1139. return $value->templateValue();
  1140. }
  1141. return $value;
  1142. }
  1143. function expandAttributes( $attributeList, $chooseText, $maxThreshold, $minThreshold = 1 )
  1144. {
  1145. $errorMessage = '';
  1146. $attributeCount = count( $attributeList );
  1147. if ( $attributeCount < $minThreshold )
  1148. return $errorMessage;
  1149. if ( $attributeCount < $maxThreshold )
  1150. {
  1151. $chooseLength = strlen( $chooseText );
  1152. $attributeText = '';
  1153. $i = 0;
  1154. foreach ( $attributeList as $attributeName )
  1155. {
  1156. if ( $i > 0 )
  1157. $attributeText .= ",";
  1158. if ( strlen( $attributeText ) > 40 )
  1159. {
  1160. $attributeText .= "\n";
  1161. $errorMessage .= $attributeText;
  1162. $errorMessage .= str_repeat( ' ', $chooseLength );
  1163. $attributeText = '';
  1164. }
  1165. else if ( $i > 0 )
  1166. $attributeText .= " ";
  1167. $attributeText .= $attributeName;
  1168. ++$i;
  1169. }
  1170. $errorMessage .= $attributeText;
  1171. }
  1172. return $errorMessage;
  1173. }
  1174. function processOperator( $operatorName, $operatorParameters, $rootNamespace, $currentNamespace,
  1175. &$valueData, $placement = false, $checkExistance = false )
  1176. {
  1177. $namedParameters = array();
  1178. $operatorParameterDefinition = $this->operatorParameterList( $operatorName );
  1179. $i = 0;
  1180. foreach ( $operatorParameterDefinition as $parameterName => $parameterType )
  1181. {
  1182. if ( !isset( $operatorParameters[$i] ) or
  1183. !isset( $operatorParameters[$i][0] ) or
  1184. $operatorParameters[$i][0] == eZTemplate::TYPE_VOID )
  1185. {
  1186. if ( $parameterType["required"] )
  1187. {
  1188. if ( !$checkExistance )
  1189. $this->warning( "eZTemplateOperatorElement", "Parameter '$parameterName' ($i) missing",
  1190. $placement );
  1191. $namedParameters[$parameterName] = $parameterType["default"];
  1192. }
  1193. else
  1194. {
  1195. $namedParameters[$parameterName] = $parameterType["default"];
  1196. }
  1197. }
  1198. else
  1199. {
  1200. $parameterData = $operatorParameters[$i];
  1201. $namedParameters[$parameterName] = $this->elementValue( $parameterData, $rootNamespace, $currentNamespace, false, $checkExistance );
  1202. }
  1203. ++$i;
  1204. }
  1205. if ( isset( $this->Operators[$operatorName] ) )
  1206. {
  1207. if ( is_array( $this->Operators[$operatorName] ) )
  1208. {
  1209. $this->loadAndRegisterOperators( $this->Operators[$operatorName] );
  1210. }
  1211. $op = $this->Operators[$operatorName];
  1212. if ( is_object( $op ) and method_exists( $op, 'modify' ) )
  1213. {
  1214. $value = $valueData['value'];
  1215. if ( eZTemplate::isMethodDebugEnabled() )
  1216. eZDebug::writeDebug( "START OPERATOR: $operatorName" );
  1217. $op->modify( $this, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, $value, $namedParameters,
  1218. $placement );
  1219. if ( eZTemplate::isMethodDebugEnabled() )
  1220. eZDebug::writeDebug( "END OPERATOR: $operatorName" );
  1221. $valueData['value'] = $value;
  1222. }
  1223. else
  1224. $this->error( '', "Object problem with operator '$operatorName' ",
  1225. $placement );
  1226. }
  1227. else if ( !$checkExistance )
  1228. $this->warning( "", "Operator '$operatorName' is not registered",
  1229. $placement );
  1230. }
  1231. /*!
  1232. Return the identifier used for attribute lookup.
  1233. */
  1234. function attributeValue( &$data, $nspace )
  1235. {
  1236. switch ( $data["type"] )
  1237. {
  1238. case "map":
  1239. {
  1240. return $data["content"];
  1241. } break;
  1242. case "index":
  1243. {
  1244. return $data["content"];
  1245. } break;
  1246. case "variable":
  1247. {
  1248. return $this->elementValue( $data["content"], $nspace );
  1249. } break;
  1250. default:
  1251. {
  1252. $this->error( "attributeValue()", "Unknown attribute type: " . $data["type"] );
  1253. return null;
  1254. }
  1255. }
  1256. }
  1257. /*!
  1258. Helper function for creating a displayable text for a variable.
  1259. */
  1260. function variableText( $var, $namespace = "", $attrs = array() )
  1261. {
  1262. $txt = "$";
  1263. if ( $namespace != "" )
  1264. $txt .= "$namespace:";
  1265. $txt .= $var;
  1266. if ( !empty( $attrs ) )
  1267. $txt .= "." . implode( ".", $attrs );
  1268. return $txt;
  1269. }
  1270. /*!
  1271. Returns the named parameter list for the operator $name.
  1272. */
  1273. function operatorParameterList( $name )
  1274. {
  1275. $param_list = array();
  1276. if ( !isset( $this->Operators[$name] ) )
  1277. {
  1278. return $param_list;
  1279. }
  1280. if ( is_array( $this->Operators[$name] ) )
  1281. {
  1282. $this->loadAndRegisterOperators( $this->Operators[$name] );
  1283. }
  1284. $op = $this->Operators[$name];
  1285. if ( isset( $op ) and
  1286. method_exists( $op, "namedparameterlist" ) )
  1287. {
  1288. $param_list = $op->namedParameterList();
  1289. if ( method_exists( $op, "namedparameterperoperator" ) and
  1290. $op->namedParameterPerOperator() )
  1291. {
  1292. if ( !isset( $param_list[$name] ) )
  1293. return array();
  1294. $param_list = $param_list[$name];
  1295. }
  1296. }
  1297. return $param_list;
  1298. }
  1299. /*!
  1300. Tries to run the operator $operatorName with parameters $operatorParameters
  1301. on the value $value.
  1302. */
  1303. function doOperator( $element, &$namespace, &$current_nspace, &$value, $operatorName, $operatorParameters, &$named_params )
  1304. {
  1305. if ( is_array( $this->Operators[$operatorName] ) )
  1306. {
  1307. $this->loadAndRegisterOperators( $this->Operators[$operatorName] );
  1308. }
  1309. $op = $this->Operators[$operatorName];
  1310. if ( isset( $op ) )
  1311. {
  1312. $op->modify( $element, $this, $operatorName, $operatorParameters, $namespace, $current_nspace, $value, $named_params );
  1313. }
  1314. else
  1315. $this->warning( "", "Operator \"$operatorName\" is not registered" );
  1316. }
  1317. /*!
  1318. Tries to run the function object $func_obj
  1319. */
  1320. function doFunction( $name, $func_obj, $nspace, $current_nspace )
  1321. {
  1322. $func = $this->Functions[$name];
  1323. if ( is_array( $func ) )
  1324. {
  1325. $this->loadAndRegisterFunctions( $this->Functions[$name] );
  1326. $func = $this->Functions[$name];
  1327. }
  1328. if ( isset( $func ) and
  1329. is_object( $func ) )
  1330. {
  1331. return $func->process( $this, $name, $func_obj, $nspace, $current_nspace );
  1332. }
  1333. else
  1334. {
  1335. $this->warning( "", "Function \"$name\" is not registered" );
  1336. return false;
  1337. }
  1338. }
  1339. /**
  1340. * Sets the template variable $var to the value $val.
  1341. *
  1342. * @param string $var
  1343. * @param string $val
  1344. * @param string $namespace (optional)
  1345. */
  1346. function setVariable( $var, $val, $namespace = '' )
  1347. {
  1348. $this->Variables[$namespace][$var] = $val;
  1349. }
  1350. /**
  1351. * Sets the template variable $var to the value $val by ref
  1352. *
  1353. * @deprecated Since 4.4, have not used references since 3.10
  1354. * @uses eZTemplate::setVariable()
  1355. *
  1356. * @param string $var
  1357. * @param string $val
  1358. * @param string $namespace (optional)
  1359. */
  1360. function setVariableRef( $var, $val, $namespace = '' )
  1361. {
  1362. $this->setVariable( $var, $val, $namespace );
  1363. }
  1364. /**
  1365. * Unsets the template variable $var.
  1366. *
  1367. * @param string $var
  1368. * @param string $namespace (optional)
  1369. */
  1370. function unsetVariable( $var, $namespace = '' )
  1371. {
  1372. if ( isset( $this->Variables[$namespace] ) &&
  1373. array_key_exists( $var, $this->Variables[$namespace] ) )
  1374. unset( $this->Variables[$namespace][$var] );
  1375. else
  1376. $this->warning( "unsetVariable()", "Undefined Variable: \$$namespace:$var, cannot unset" );
  1377. }
  1378. /**
  1379. * Returns true if the variable $var is set in namespace $namespace,
  1380. * if $attrs is supplied all attributes must exist for the function to return true.
  1381. *
  1382. * @param string $var
  1383. * @param string $namespace (optional)
  1384. * @param array $attrs (optional) Deprecated as of 4.4.
  1385. * @return bool
  1386. */
  1387. function hasVariable( $var, $namespace = '', $attrs = null )
  1388. {
  1389. $exists = ( isset( $this->Variables[$namespace] ) &&
  1390. array_key_exists( $var, $this->Variables[$namespace] ) );
  1391. if ( $exists && $attrs !== null && !empty( $attrs ) )
  1392. {
  1393. eZDebug::writeStrict( '$attrs parameter is deprecated as of 4.4', __METHOD__ );
  1394. $ptr =& $this->Variables[$namespace][$var];
  1395. foreach( $attrs as $attr )
  1396. {
  1397. unset( $tmp );
  1398. if ( is_object( $ptr ) )
  1399. {
  1400. if ( $ptr->hasAttribute( $attr ) )
  1401. $tmp = $ptr->attribute( $attr );
  1402. else
  1403. return false;
  1404. }
  1405. else if ( is_array( $ptr ) )
  1406. {
  1407. if ( array_key_exists( $attr, $ptr ) )
  1408. $tmp =& $ptr[$attr];
  1409. else
  1410. return false;
  1411. }
  1412. else
  1413. {
  1414. return false;
  1415. }
  1416. unset( $ptr );
  1417. $ptr =& $tmp;
  1418. }
  1419. }
  1420. return $exists;
  1421. }
  1422. /**
  1423. * Returns the content of the variable $var using namespace $namespace,
  1424. * if $attrs is supplied the result of the attributes is returned.
  1425. *
  1426. * @param string $var
  1427. * @param string $namespace (optional)
  1428. * @param array $attrs (optional) Deprecated as of 4.4
  1429. * @return string|array
  1430. */
  1431. function variable( $var, $namespace = '', $attrs = null )
  1432. {
  1433. $val = null;
  1434. $exists = ( isset( $this->Variables[$namespace] ) &&
  1435. array_key_exists( $var, $this->Variables[$namespace] ) );
  1436. if ( $exists )
  1437. {
  1438. if ( $attrs !== null && !empty( $attrs ) )
  1439. {
  1440. eZDebug::writeStrict( '$attrs parameter is deprecated as of 4.4', __METHOD__ );
  1441. $element = $this->Variables[$namespace][$var];
  1442. foreach( $attrs as $attr )
  1443. {
  1444. if ( is_object( $element ) )
  1445. {
  1446. if ( $element->hasAttribute( $attr ) )
  1447. {
  1448. $element = $element->attribute( $attr );
  1449. }
  1450. else
  1451. {
  1452. return $val;
  1453. }
  1454. }
  1455. else if ( is_array( $element ) )
  1456. {
  1457. if ( array_key_exists( $attr, $element ) )
  1458. {
  1459. $val = $element[$attr];
  1460. }
  1461. else
  1462. {
  1463. return $val;
  1464. }
  1465. }
  1466. else
  1467. {
  1468. return $val;
  1469. }
  1470. $val = $element;
  1471. }
  1472. }
  1473. else
  1474. {
  1475. $val = $this->Variables[$namespace][$var];
  1476. }
  1477. }
  1478. return $val;
  1479. }
  1480. /*!
  1481. Returns the attribute(s) of the template variable $var,
  1482. $attrs is an array of attribute names to use iteratively for each new variable returned.
  1483. */
  1484. function variableAttribute( $var, $attrs )
  1485. {
  1486. foreach( $attrs as $attr )
  1487. {
  1488. if ( is_object( $var ) )
  1489. {
  1490. if ( $var->hasAttribute( $attr ) )
  1491. {
  1492. $var = $var->attribute( $attr );
  1493. }
  1494. else
  1495. {
  1496. return null;
  1497. }
  1498. }
  1499. else if ( is_array( $var ) )
  1500. {
  1501. if ( isset( $var[$attr] ) )
  1502. {
  1503. $var = $var[$attr];
  1504. }
  1505. else
  1506. {
  1507. return null;
  1508. }
  1509. }
  1510. else
  1511. {
  1512. return null;
  1513. }
  1514. }
  1515. if ( isset( $var ) )
  1516. {
  1517. return $var;
  1518. }
  1519. return null;
  1520. }
  1521. function appendElement( &$text, $item, $nspace, $name )
  1522. {
  1523. $this->appendElementText( $textElements, $item, $nspace, $name );
  1524. $text .= implode( '', $textElements );
  1525. }
  1526. function appendElementText( &$textElements, $item, $nspace, $name )
  1527. {
  1528. if ( !is_array( $textElements ) )
  1529. $textElements = array();
  1530. if ( is_object( $item ) and
  1531. method_exists( $item, 'templateValue' ) )
  1532. {
  1533. $item = $item->templateValue();
  1534. $textElements[] = "$item";
  1535. }
  1536. else if ( is_object( $item ) )
  1537. {
  1538. $hasTemplateData = false;
  1539. if ( method_exists( $item, 'templateData' ) )
  1540. {
  1541. $templateData = $item->templateData();
  1542. if ( is_array( $templateData ) and
  1543. isset( $templateData['type'] ) )
  1544. {
  1545. if ( $templateData['type'] == 'template' and
  1546. isset( $templateData['uri'] ) and
  1547. isset( $templateData['template_variable_name'] ) )
  1548. {
  1549. $templateURI =& $templateData['uri'];
  1550. $templateVariableName =& $templateData['template_variable_name'];
  1551. $templateText = '';
  1552. $this->setVariable( $templateVariableName, $item, $name );
  1553. eZTemplateIncludeFunction::handleInclude( $textElements, $templateURI, $this, $nspace, $name );
  1554. $hasTemplateData = true;
  1555. }
  1556. }
  1557. }
  1558. if ( !$hasTemplateData )
  1559. $textElements[] = method_exists( $item, '__toString' ) ? (string)$item : 'Object(' . get_class( $item ) . ')';
  1560. }
  1561. else
  1562. $textElements[] = "$item";
  1563. return $textElements;
  1564. }
  1565. /*!
  1566. Creates some text nodes before and after the children of \a $root.
  1567. It will extract the current filename and uri and create some XHTML
  1568. comments and inline text.
  1569. \sa isXHTMLCodeIncluded
  1570. */
  1571. function appendDebugNodes( &$root, &$resourceData )
  1572. {
  1573. $path = $resourceData['template-filename'];
  1574. $uri = $resourceData['uri'];
  1575. $preText = "\n<!-- START: including template: $path ($uri) -->\n";
  1576. if ( eZTemplate::isXHTMLCodeIncluded() )
  1577. $preText .= "<p class=\"small\">$path</p><br/>\n";
  1578. $postText = "\n<!-- STOP: including template: $path ($uri) -->\n";
  1579. $root[1] = array_merge( array( eZTemplateNodeTool::createTextNode( $preText ) ), $root[1] );
  1580. $root[1][] = eZTemplateNodeTool::createTextNode( $postText );
  1581. }
  1582. /*!
  1583. Registers the functions supplied by the object $functionObject.
  1584. The object must have a function called functionList()
  1585. which returns an array of functions this object handles.
  1586. If the object has a function called attributeList()
  1587. it is used for registering function attributes.
  1588. The function returns an associative array with each key being
  1589. the name of the function and the value being a boolean.
  1590. If the boolean is true the function will have children.
  1591. */
  1592. function registerFunctions( &$functionObject )
  1593. {
  1594. $this->registerFunctionsInternal( $functionObject );
  1595. }
  1596. function registerAutoloadFunctions( $functionDefinition )
  1597. {
  1598. if ( ( ( isset( $functionDefinition['function'] ) ||
  1599. isset( $functionDefinition['class'] ) ) &&
  1600. ( isset( $functionDefinition['function_names_function'] ) ||
  1601. isset( $functionDefinition['function_names'] ) ) ) )
  1602. {
  1603. if ( isset( $functionDefinition['function_names_function'] ) )
  1604. {
  1605. $functionNamesFunction = $functionDefinition['function_names_function'];
  1606. if ( !function_exists( $functionNamesFunction ) )
  1607. {
  1608. $this->error( 'registerFunctions', "Cannot register function definition, missing function names function '$functionNamesFunction'" );
  1609. return;
  1610. }
  1611. $functionNames = $functionNamesFunction();
  1612. }
  1613. else
  1614. $functionNames = $functionDefinition['function_names'];
  1615. foreach ( $functionNames as $functionName )
  1616. {
  1617. $this->Functions[$functionName] = $functionDefinition;
  1618. }
  1619. if ( isset( $functionDefinition['function_attributes'] ) )
  1620. {
  1621. foreach ( $functionDefinition['function_attributes'] as $functionAttributeName )
  1622. {
  1623. $this->FunctionAttributes[$functionAttributeName] = $functionDefinition;
  1624. }
  1625. }
  1626. }
  1627. else
  1628. $this->error( 'registerFunctions', 'Cannot register function definition, missing data' );
  1629. }
  1630. function loadAndRegisterFunctions( $functionDefinition )
  1631. {
  1632. eZDebug::accumulatorStart( 'template_register_function', 'template_total', 'Template load and register function' );
  1633. $functionObject = null;
  1634. if ( isset( $functionDefinition['function'] ) )
  1635. {
  1636. $function = $functionDefinition['function'];
  1637. if ( function_exists( $function ) )
  1638. $functionObject = $function();
  1639. }
  1640. else
  1641. {
  1642. if ( !class_exists( $functionDefinition['class'], false )
  1643. && isset( $functionDefinition['script'] ) )
  1644. {
  1645. include_once( $functionDefinition['script'] );
  1646. }
  1647. $class = $functionDefinition['class'];
  1648. if ( class_exists( $class ) )
  1649. $functionObject = new $class();
  1650. }
  1651. eZDebug::accumulatorStop( 'template_register_function' );
  1652. if ( is_object( $functionObject ) )
  1653. {
  1654. $this->registerFunctionsInternal( $functionObject, true );
  1655. return true;
  1656. }
  1657. return false;
  1658. }
  1659. /*!
  1660. \private
  1661. */
  1662. function registerFunctionsInternal( $functionObject, $debug = false )
  1663. {
  1664. if ( !is_object( $functionObject ) or
  1665. !method_exists( $functionObject, 'functionList' ) )
  1666. return false;
  1667. foreach ( $functionObject->functionList() as $functionName )
  1668. {
  1669. $this->Functions[$functionName] = $functionObject;
  1670. }
  1671. if ( method_exists( $functionObject, "attributeList" ) )
  1672. {
  1673. $functionAttributes = $functionObject->attributeList();
  1674. foreach ( $functionAttributes as $attributeName => $hasChildren )
  1675. {
  1676. $this->FunctionAttributes[$attributeName] = $hasChildren;
  1677. }
  1678. }
  1679. return true;
  1680. }
  1681. /*!
  1682. Registers the function $func_name to be bound to object $func_obj.
  1683. If the object has a function called attributeList()
  1684. it is used for registering function attributes.
  1685. The function returns an associative array with each key being
  1686. the name of the function and the value being a boolean.
  1687. If the boolean is true the function will have children.
  1688. */
  1689. function registerFunction( $func_name, $func_obj )
  1690. {
  1691. $this->Functions[$func_name] = $func_obj;
  1692. if ( method_exists( $func_obj, "attributeList" ) )
  1693. {
  1694. $attrs = $func_obj->attributeList();
  1695. while ( list( $attr_name, $has_children ) = each( $attrs ) )
  1696. {
  1697. $this->FunctionAttributes[$attr_name] = $has_children;
  1698. }
  1699. }
  1700. }
  1701. /*!
  1702. Registers a new literal tag in which the tag will be transformed into
  1703. a text element.
  1704. */
  1705. function registerLiteral( $func_name )
  1706. {
  1707. $this->Literals[$func_name] = true;
  1708. }
  1709. /*!
  1710. Removes the literal tag $func_name.
  1711. */
  1712. function unregisterLiteral( $func_name )
  1713. {
  1714. unset( $this->Literals[$func_name] );
  1715. }
  1716. function registerAutoloadOperators( $operatorDefinition )
  1717. {
  1718. if ( ( ( isset( $operatorDefinition['function'] ) ||
  1719. isset( $operatorDefinition['class'] ) ) &&
  1720. ( isset( $operatorDefinition['operator_names_function'] ) ||
  1721. isset( $operatorDefinition['operator_names'] ) ) ) )
  1722. {
  1723. if ( isset( $operatorDefinition['operator_names_function'] ) )
  1724. {
  1725. $operatorNamesFunction = $operatorDefinition['operator_names_function'];
  1726. if ( !function_exists( $operatorNamesFunction ) )
  1727. {
  1728. $this->error( 'registerOperators', "Cannot register operator definition, missing operator names function '$operatorNamesFunction'" );
  1729. return;
  1730. }
  1731. $operatorNames = $operatorNamesFunction();
  1732. }
  1733. else
  1734. $operatorNames = $operatorDefinition['operator_names'];
  1735. foreach ( $operatorNames as $operatorName )
  1736. {
  1737. $this->Operators[$operatorName] = $operatorDefinition;
  1738. }
  1739. }
  1740. else
  1741. $this->error( 'registerOperators', 'Cannot register operator definition, missing data' );
  1742. }
  1743. function loadAndRegisterOperators( $operatorDefinition )
  1744. {
  1745. $operatorObject = null;
  1746. if ( isset( $operatorDefinition['function'] ) )
  1747. {
  1748. $function = $operatorDefinition['function'];
  1749. if ( function_exists( $function ) )
  1750. $operatorObject = $function();
  1751. }
  1752. else
  1753. {
  1754. $class = $operatorDefinition['class'];
  1755. if ( !class_exists( $class, false ) && isset( $operatorDefinition['script'] ) )
  1756. {
  1757. include_once( $operatorDefinition['script'] );
  1758. }
  1759. if ( class_exists( $class ) )
  1760. {
  1761. if ( isset( $operatorDefinition['class_parameter'] ) )
  1762. $operatorObject = new $class( $operatorDefinition['class_parameter'] );
  1763. else
  1764. $operatorObject = new $class();
  1765. }
  1766. }
  1767. if ( is_object( $operatorObject ) )
  1768. {
  1769. $this->registerOperatorsInternal( $operatorObject, true );
  1770. return true;
  1771. }
  1772. return false;
  1773. }
  1774. /*!
  1775. Registers the operators supplied by the object $operatorObject.
  1776. The function operatorList() must return an array of operator names.
  1777. */
  1778. function registerOperators( &$operatorObject )
  1779. {
  1780. $this->registerOperatorsInternal( $operatorObject );
  1781. }
  1782. function registerOperatorsInternal( $operatorObject, $debug = false )
  1783. {
  1784. if ( !is_object( $operatorObject ) or
  1785. !method_exists( $operatorObject, 'operatorList' ) )
  1786. return false;
  1787. foreach( $operatorObject->operatorList() as $operatorName )
  1788. {
  1789. $this->Operators[$operatorName] = $operatorObject;
  1790. }
  1791. }
  1792. /*!
  1793. Registers the operator $op_name to use the object $op_obj.
  1794. */
  1795. function registerOperator( $op_name, $op_obj )
  1796. {
  1797. $this->Operators[$op_name] = $op_obj;
  1798. }
  1799. /*!
  1800. Unregisters the operator $op_name.
  1801. */
  1802. function unregisterOperator( $op_name )
  1803. {
  1804. if ( is_array( $op_name ) )
  1805. {
  1806. foreach ( $op_name as $op )
  1807. {
  1808. $this->unregisterOperator( $op_name );
  1809. }
  1810. }
  1811. else if ( isset( $this->Operators ) )
  1812. unset( $this->Operators[$op_name] );
  1813. else
  1814. $this->warning( "unregisterOpearator()", "Operator $op_name is not registered, cannot unregister" );
  1815. }
  1816. /*!
  1817. Not implemented yet.
  1818. */
  1819. function registerFilter()
  1820. {
  1821. }
  1822. /*!
  1823. Registers a new resource object $res.
  1824. The resource object take care of fetching templates using an URI.
  1825. */
  1826. function registerResource( $res )
  1827. {
  1828. if ( is_object( $res ) )
  1829. $this->Resources[$res->resourceName()] =& $res;
  1830. else
  1831. $this->warning( "registerResource()", "Supplied argument is not a resource object" );
  1832. }
  1833. /*!
  1834. Unregisters the resource $res_name.
  1835. */
  1836. function unregisterResource( $res_name )
  1837. {
  1838. if ( is_array( $res_name ) )
  1839. {
  1840. foreach ( $res_name as $res )
  1841. {
  1842. $this->unregisterResource( $res );
  1843. }
  1844. }
  1845. else if ( isset( $this->Resources[$res_name] ) )
  1846. unset( $this->Resources[$res_name] );
  1847. else
  1848. $this->warning( "unregisterResource()", "Resource $res_name is not registered, cannot unregister" );
  1849. }
  1850. /*!
  1851. Sets whether detail output is used or not.
  1852. Detail output is useful for debug output where you want to examine the template
  1853. and the output text.
  1854. */
  1855. function setShowDetails( $show )
  1856. {
  1857. $this->ShowDetails = $show;
  1858. }
  1859. /*!
  1860. Outputs a warning about the parameter $param missing for function/operator $name.
  1861. */
  1862. function missingParameter( $name, $param )
  1863. {
  1864. $this->warning( $name, "Missing parameter $param" );
  1865. }
  1866. /*!
  1867. Outputs a warning about the parameter count being to high for function/operator $name.
  1868. */
  1869. function extraParameters( $name, $count, $maxCount )
  1870. {
  1871. $this->warning( $name, "Passed $count parameters but correct count is $maxCount" );
  1872. }
  1873. /*!
  1874. Outputs a warning about the variable $var being undefined.
  1875. */
  1876. function undefinedVariable( $name, $var )
  1877. {
  1878. $this->warning( $name, "Undefined variable: $var" );
  1879. }
  1880. /*!
  1881. Outputs an error about the template function $func_name being undefined.
  1882. */
  1883. function undefinedFunction( $func_name )
  1884. {
  1885. $this->error( "", "Undefined function: $func_name" );
  1886. }
  1887. /*!
  1888. Creates a string for the placement information and returns it.
  1889. \note The placement information can either be in indexed or associative
  1890. */
  1891. function placementText( $placement = false )
  1892. {
  1893. $placementText = false;
  1894. if ( $placement !== false )
  1895. {
  1896. if ( isset( $placement['start'] ) and
  1897. isset( $placement['stop'] ) and
  1898. isset( $placement['templatefile'] ) )
  1899. {
  1900. $line = $placement['start']['line'];
  1901. $column = $placement['start']['column'];
  1902. $templateFile = $placement['templatefile'];
  1903. }
  1904. else
  1905. {
  1906. $line = $placement[0][0];
  1907. $column = $placement[0][1];
  1908. $templateFile = $placement[2];
  1909. }
  1910. $placementText = " @ $templateFile:$line" . "[$column]";
  1911. }
  1912. return $placementText;
  1913. }
  1914. /*!
  1915. Displays a warning for the function/operator $name and text $txt.
  1916. */
  1917. function warning( $name, $txt, $placement = false )
  1918. {
  1919. $this->WarningLog[] = array( 'name' => $name,
  1920. 'text' => $txt,
  1921. 'placement' => $placement );
  1922. if ( !is_string( $placement ) )
  1923. $placementText = $this->placementText( $placement );
  1924. else
  1925. $placementText = $placement;
  1926. $placementText = $this->placementText( $placement );
  1927. if ( $name != "" )
  1928. eZDebug::writeWarning( $txt, "eZTemplate:$name" . $placementText );
  1929. else
  1930. eZDebug::writeWarning( $txt, "eZTemplate" . $placementText );
  1931. }
  1932. /*!
  1933. Displays an error for the function/operator $name and text $txt.
  1934. */
  1935. function error( $name, $txt, $placement = false )
  1936. {
  1937. $this->ErrorLog[] = array( 'name' => $name,
  1938. 'text' => $txt,
  1939. 'placement' => $placement );
  1940. if ( !is_string( $placement ) )
  1941. $placementText = $this->placementText( $placement );
  1942. else
  1943. $placementText = $placement;
  1944. if ( $name != "" )
  1945. $nameText = "eZTemplate:$name";
  1946. else
  1947. $nameText = "eZTemplate";
  1948. eZDebug::writeError( $txt, $nameText . $placementText );
  1949. $hasAppendWarning =& $GLOBALS['eZTemplateHasAppendWarning'];
  1950. $ini = $this->ini();
  1951. if ( $ini->variable( 'ControlSettings', 'DisplayWarnings' ) == 'enabled' )
  1952. {
  1953. if ( !isset( $hasAppendWarning ) or
  1954. !$hasAppendWarning )
  1955. {
  1956. if ( function_exists( 'eZAppendWarningItem' ) )
  1957. {
  1958. eZAppendWarningItem( array( 'error' => array( 'type' => 'template',
  1959. 'number' => eZTemplate::FILE_ERRORS ),
  1960. 'text' => ezpI18n::tr( 'lib/eztemplate', 'Some template errors occurred, see debug for more information.' ) ) );
  1961. $hasAppendWarning = true;
  1962. }
  1963. }
  1964. }
  1965. }
  1966. function operatorInputSupported( $operatorName )
  1967. {
  1968. }
  1969. /*!
  1970. Sets the original text for uri $uri to $text.
  1971. */
  1972. function setIncludeText( $uri, $text )
  1973. {
  1974. $this->IncludeText[$uri] = $text;
  1975. }
  1976. /*!
  1977. Sets the output for uri $uri to $output.
  1978. */
  1979. function setIncludeOutput( $uri, $output )
  1980. {
  1981. $this->IncludeOutput[$uri] = $output;
  1982. }
  1983. /*!
  1984. \return the path list which is used for autoloading functions and operators.
  1985. */
  1986. function autoloadPathList()
  1987. {
  1988. return $this->AutoloadPathList;
  1989. }
  1990. /*!
  1991. Sets the path list for autoloading.
  1992. */
  1993. function setAutoloadPathList( $pathList )
  1994. {
  1995. $this->AutoloadPathList = $pathList;
  1996. }
  1997. /*!
  1998. Looks trough the pathes specified in autoloadPathList() and fetches autoload
  1999. definition files used for autoloading functions and operators.
  2000. */
  2001. function autoload()
  2002. {
  2003. $pathList = $this->autoloadPathList();
  2004. foreach ( $pathList as $path )
  2005. {
  2006. $autoloadFile = $path . '/eztemplateautoload.php';
  2007. if ( file_exists( $autoloadFile ) )
  2008. {
  2009. unset( $eZTemplateOperatorArray );
  2010. unset( $eZTemplateFunctionArray );
  2011. include( $autoloadFile );
  2012. if ( isset( $eZTemplateOperatorArray ) and
  2013. is_array( $eZTemplateOperatorArray ) )
  2014. {
  2015. foreach ( $eZTemplateOperatorArray as $operatorDefinition )
  2016. {
  2017. $this->registerAutoloadOperators( $operatorDefinition );
  2018. }
  2019. }
  2020. if ( isset( $eZTemplateFunctionArray ) and
  2021. is_array( $eZTemplateFunctionArray ) )
  2022. {
  2023. foreach ( $eZTemplateFunctionArray as $functionDefinition )
  2024. {
  2025. $this->registerAutoloadFunctions( $functionDefinition );
  2026. }
  2027. }
  2028. }
  2029. }
  2030. }
  2031. /*!
  2032. Resets all template variables.
  2033. */
  2034. function resetVariables()
  2035. {
  2036. $this->Variables = array();
  2037. }
  2038. /*!
  2039. Resets all template functions and operators by calling the resetFunction and resetOperator
  2040. on all elements that supports it.
  2041. */
  2042. function resetElements()
  2043. {
  2044. foreach ( $this->Functions as $functionName => $functionObject )
  2045. {
  2046. if ( is_object( $functionObject ) and
  2047. method_exists( $functionObject, 'resetFunction' ) )
  2048. {
  2049. $functionObject->resetFunction( $functionName );
  2050. }
  2051. }
  2052. foreach ( $this->Operators as $operatorName => $operatorObject )
  2053. {
  2054. if ( is_object( $operatorObject ) and
  2055. method_exists( $operatorObject, 'resetOperator' ) )
  2056. {
  2057. $operatorObject->resetOperator( $operatorName );
  2058. }
  2059. }
  2060. }
  2061. /*!
  2062. Resets all template variables, functions, operators and error counts.
  2063. */
  2064. function reset()
  2065. {
  2066. $this->resetVariables();
  2067. $this->resetElements();
  2068. $this->IsCachingAllowed = true;
  2069. $this->resetErrorLog();
  2070. $this->TemplatesUsageStatistics = array();
  2071. $this->TemplateFetchList = array();
  2072. }
  2073. /*!
  2074. \return The number of errors that occured with the last fetch
  2075. \sa hasErrors()
  2076. */
  2077. function errorCount()
  2078. {
  2079. return count( $this->ErrorLog );
  2080. }
  2081. /*!
  2082. \return \ true if errors occured with the last fetch.
  2083. \sa errorCount()
  2084. */
  2085. function hasErrors()
  2086. {
  2087. return $this->errorCount() > 0;
  2088. }
  2089. /*!
  2090. \return error log.
  2091. \sa errorCount()
  2092. */
  2093. function errorLog()
  2094. {
  2095. return $this->ErrorLog;
  2096. }
  2097. /*!
  2098. \return The number of warnings that occured with the last fetch
  2099. \sa hasWarnings()
  2100. */
  2101. function warningCount()
  2102. {
  2103. return count( $this->WarningLog );
  2104. }
  2105. /*!
  2106. \return \ true if warnings occured with the last fetch.
  2107. \sa warningCount()
  2108. */
  2109. function hasWarnings()
  2110. {
  2111. return $this->warningCount() > 0;
  2112. }
  2113. /*!
  2114. \return waring log.
  2115. \sa warningCount()
  2116. */
  2117. function warningLog()
  2118. {
  2119. return $this->WarningLog;
  2120. }
  2121. /**
  2122. * Returns a shared instance of the eZTemplate class.
  2123. *
  2124. * @return eZTemplate
  2125. */
  2126. public static function instance()
  2127. {
  2128. if ( self::$instance === null )
  2129. {
  2130. self::$instance = new eZTemplate();
  2131. }
  2132. return self::$instance;
  2133. }
  2134. /**
  2135. * Returns a shared instance of the eZTemplate class with
  2136. * default settings applied, like:
  2137. * - Autoload operators loaded
  2138. * - Debug mode set
  2139. * - eZTemplateDesignResource::instance registered
  2140. *
  2141. * @since 4.3
  2142. * @return eZTemplate
  2143. */
  2144. public static function factory()
  2145. {
  2146. if ( self::$factory === false )
  2147. {
  2148. $instance = self::instance();
  2149. $ini = eZINI::instance();
  2150. if ( $ini->variable( 'TemplateSettings', 'Debug' ) == 'enabled' )
  2151. eZTemplate::setIsDebugEnabled( true );
  2152. $compatAutoLoadPath = $ini->variableArray( 'TemplateSettings', 'AutoloadPath' );
  2153. $autoLoadPathList = $ini->variable( 'TemplateSettings', 'AutoloadPathList' );
  2154. $extensionAutoloadPath = $ini->variable( 'TemplateSettings', 'ExtensionAutoloadPath' );
  2155. $extensionPathList = eZExtension::expandedPathList( $extensionAutoloadPath, 'autoloads' );
  2156. $autoLoadPathList = array_unique( array_merge( $compatAutoLoadPath, $autoLoadPathList, $extensionPathList ) );
  2157. $instance->setAutoloadPathList( $autoLoadPathList );
  2158. $instance->autoload();
  2159. $instance->registerResource( eZTemplateDesignResource::instance() );
  2160. self::$factory = true;
  2161. }
  2162. return self::instance();
  2163. }
  2164. /**
  2165. * Reset shared instance of the eZTemplate class and factory flag
  2166. * as used by {@see eZTemplate::instance()} and {@see eZTemplate::factory()}
  2167. *
  2168. * @since 4.3
  2169. */
  2170. public static function resetInstance()
  2171. {
  2172. self::$instance = null;
  2173. self::$factory = false;
  2174. }
  2175. /**
  2176. * Returns the eZINI object instance for the template.ini file.
  2177. *
  2178. * @return eZINI
  2179. */
  2180. public function ini()
  2181. {
  2182. return eZINI::instance( "template.ini" );
  2183. }
  2184. /*!
  2185. \static
  2186. \return true if special XHTML code should be included before the included template file.
  2187. This code will display the template filename in the browser but will eventually
  2188. break the design.
  2189. */
  2190. static function isXHTMLCodeIncluded()
  2191. {
  2192. if ( !isset( $GLOBALS['eZTemplateDebugXHTMLCodeEnabled'] ) )
  2193. {
  2194. $ini = eZINI::instance();
  2195. $GLOBALS['eZTemplateDebugXHTMLCodeEnabled'] = $ini->variable( 'TemplateSettings', 'ShowXHTMLCode' ) == 'enabled';
  2196. }
  2197. return $GLOBALS['eZTemplateDebugXHTMLCodeEnabled'];
  2198. }
  2199. /*!
  2200. \static
  2201. \return \c true if debug output of template functions and operators should be enabled.
  2202. */
  2203. static function isMethodDebugEnabled()
  2204. {
  2205. if ( !isset( $GLOBALS['eZTemplateDebugMethodEnabled'] ) )
  2206. {
  2207. $ini = eZINI::instance();
  2208. $GLOBALS['eZTemplateDebugMethodEnabled'] = $ini->variable( 'TemplateSettings', 'ShowMethodDebug' ) == 'enabled';
  2209. }
  2210. return $GLOBALS['eZTemplateDebugMethodEnabled'];
  2211. }
  2212. /*!
  2213. \static
  2214. \return true if debugging of internals is enabled, this will display
  2215. which files are loaded and when cache files are created.
  2216. Set the option with setIsDebugEnabled().
  2217. */
  2218. static function isDebugEnabled()
  2219. {
  2220. if ( !isset( $GLOBALS['eZTemplateDebugInternalsEnabled'] ) )
  2221. $GLOBALS['eZTemplateDebugInternalsEnabled'] = eZTemplate::DEBUG_INTERNALS;
  2222. return $GLOBALS['eZTemplateDebugInternalsEnabled'];
  2223. }
  2224. /*!
  2225. \static
  2226. Sets whether internal debugging is enabled or not.
  2227. */
  2228. static function setIsDebugEnabled( $debug )
  2229. {
  2230. $GLOBALS['eZTemplateDebugInternalsEnabled'] = $debug;
  2231. }
  2232. /*!
  2233. \return \c true if caching is allowed (default) or \c false otherwise.
  2234. This also affects template compiling.
  2235. \sa setIsCachingAllowed
  2236. */
  2237. function isCachingAllowed()
  2238. {
  2239. return $this->IsCachingAllowed;
  2240. }
  2241. /*!
  2242. Sets whether caching/compiling is allowed or not. This is useful
  2243. if you need to make sure templates are parsed and processed
  2244. without any caching mechanisms.
  2245. \note The default is to allow caching.
  2246. \sa isCachingAllowed
  2247. */
  2248. function setIsCachingAllowed( $allowed )
  2249. {
  2250. $this->IsCachingAllowed = $allowed;
  2251. }
  2252. /*!
  2253. \static
  2254. \return \c true if templates usage statistics should be enabled.
  2255. */
  2256. static function isTemplatesUsageStatisticsEnabled()
  2257. {
  2258. if ( !isset( $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] ) )
  2259. {
  2260. $ini = eZINI::instance();
  2261. $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] = $ini->variable( 'TemplateSettings', 'ShowUsedTemplates' ) == 'enabled';
  2262. }
  2263. return ( $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] );
  2264. }
  2265. /*!
  2266. \static
  2267. Sets whether templates usage statistics enabled or not.
  2268. \return \c true if templates usage statistics was enabled, otherwise \c false.
  2269. */
  2270. function setIsTemplatesUsageStatisticsEnabled( $enabled )
  2271. {
  2272. $wasEnabled = false;
  2273. if( isset( $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] ) )
  2274. $wasEnabled = $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'];
  2275. $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] = $enabled;
  2276. return $wasEnabled;
  2277. }
  2278. /*!
  2279. \static
  2280. Checks settings and if 'ShowUsedTemplates' is enabled appends template info to stats.
  2281. */
  2282. function appendTemplateToStatisticsIfNeeded( &$templateName, &$templateFileName )
  2283. {
  2284. if ( eZTemplate::isTemplatesUsageStatisticsEnabled() )
  2285. eZTemplate::appendTemplateToStatistics( $templateName, $templateFileName );
  2286. }
  2287. /*!
  2288. \static
  2289. Appends template info to stats.
  2290. */
  2291. function appendTemplateToStatistics( $templateName, $templateFileName )
  2292. {
  2293. $actualTemplateName = preg_replace( "#^[\w/]+templates/#", '', $templateFileName );
  2294. $requestedTemplateName = preg_replace( "#^[\w/]+templates/#", '', $templateName );
  2295. $tpl = eZTemplate::instance();
  2296. $needToAppend = true;
  2297. // don't add template info if it is a duplicate of previous.
  2298. $statsSize = count( $tpl->TemplatesUsageStatistics );
  2299. if ( $statsSize > 0 )
  2300. {
  2301. $lastTemplateInfo = $tpl->TemplatesUsageStatistics[$statsSize-1];
  2302. if ( $lastTemplateInfo['actual-template-name'] === $actualTemplateName &&
  2303. $lastTemplateInfo['requested-template-name'] === $requestedTemplateName &&
  2304. $lastTemplateInfo['template-filename'] === $templateFileName )
  2305. {
  2306. $needToAppend = false;
  2307. }
  2308. }
  2309. if ( $needToAppend )
  2310. {
  2311. $templateInfo = array( 'actual-template-name' => $actualTemplateName,
  2312. 'requested-template-name' => $requestedTemplateName,
  2313. 'template-filename' => $templateFileName );
  2314. $tpl->TemplatesUsageStatistics[] = $templateInfo;
  2315. }
  2316. }
  2317. /*!
  2318. Appends template info for current fetch.
  2319. */
  2320. function appendTemplateFetch( $actualTemplateName )
  2321. {
  2322. $this->TemplateFetchList[] = $actualTemplateName;
  2323. $this->TemplateFetchList = array_unique( $this->TemplateFetchList );
  2324. }
  2325. /*!
  2326. Reset error and warning logs
  2327. */
  2328. function resetErrorLog()
  2329. {
  2330. $this->ErrorLog = array();
  2331. $this->WarningLog = array();
  2332. }
  2333. /*!
  2334. \static
  2335. Returns template usage statistics
  2336. */
  2337. static function templatesUsageStatistics()
  2338. {
  2339. $tpl = eZTemplate::instance();
  2340. return $tpl->TemplatesUsageStatistics;
  2341. }
  2342. /*!
  2343. Returns template list for the last fetch.
  2344. */
  2345. function templateFetchList()
  2346. {
  2347. return $this->TemplateFetchList;
  2348. }
  2349. /*!
  2350. Set template compilation test mode.
  2351. \param true, will set template compilation in test mode ( no disc writes ).
  2352. false, will compile templates to disc
  2353. */
  2354. function setCompileTest( $val )
  2355. {
  2356. $this->TestCompile = $val;
  2357. }
  2358. /*!
  2359. Get if template session is test compile
  2360. */
  2361. function testCompile()
  2362. {
  2363. return $this->TestCompile;
  2364. }
  2365. /// \privatesection
  2366. /// Associative array of resource objects
  2367. public $Resources;
  2368. /// Reference to the default resource object
  2369. public $DefaultResource;
  2370. /// The original template text
  2371. public $Text;
  2372. /// Included texts, usually performed by custom functions
  2373. public $IncludeText;
  2374. /// Included outputs, usually performed by custom functions
  2375. public $IncludeOutput;
  2376. /// The timestamp of the template when it was last modified
  2377. public $TimeStamp;
  2378. /// The left delimiter used for parsing
  2379. public $LDelim;
  2380. /// The right delimiter used for parsing
  2381. public $RDelim;
  2382. /// The resulting object tree of the template
  2383. public $Tree;
  2384. /// An associative array of template variables
  2385. public $Variables;
  2386. /*!
  2387. Last element of this stack contains names of
  2388. all variables created in the innermost template, for them
  2389. to be destroyed after the template execution finishes.
  2390. */
  2391. public $LocalVariablesNamesStack;
  2392. // Reference to the last element of $LocalVariablesNamesStack.
  2393. public $CurrentLocalVariablesNames;
  2394. /// An associative array of operators
  2395. public $Operators;
  2396. /// An associative array of functions
  2397. public $Functions;
  2398. /// An associative array of function attributes
  2399. public $FunctionAttributes;
  2400. /// An associative array of literal tags
  2401. public $Literals;
  2402. /// True if output details is to be shown
  2403. public $ShowDetails = false;
  2404. /// \c true if caching is allowed
  2405. public $IsCachingAllowed;
  2406. /// Array containing all errors occured during a fetch
  2407. public $ErrorLog;
  2408. /// Array containing all warnings occured during a fetch
  2409. public $WarningLog;
  2410. public $AutoloadPathList;
  2411. /// include level
  2412. public $Level = 0;
  2413. public $MaxLevel = 40;
  2414. /// A list of templates used by a rendered page
  2415. public $TemplatesUsageStatistics;
  2416. // counter to make unique names for {foreach} loop variables in com
  2417. public $ForeachCounter;
  2418. public $ForCounter;
  2419. public $WhileCounter;
  2420. public $DoCounter;
  2421. public $ElseifCounter;
  2422. // Flag for setting compilation in test mode
  2423. public $TestCompile;
  2424. /**
  2425. * Singelton instance of eZTemplate used by {@see eZTemplate::instance()}
  2426. * Reset with {@see eZTemplate::resetInstance()}
  2427. *
  2428. * @var null|eZTemplate
  2429. */
  2430. protected static $instance;
  2431. /**
  2432. * Factory flag as used by {@see eZTemplate::factory()}
  2433. * Reset with {@see eZTemplate::resetInstance()}
  2434. *
  2435. * @var bool
  2436. */
  2437. protected static $factory = false;
  2438. // public $CurrentRelatedResource;
  2439. // public $CurrentRelatedTemplateName;
  2440. }
  2441. ?>