PageRenderTime 56ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/eztemplate/classes/eztemplate.php

https://github.com/StephanBoganskyXrow/ezpublish
PHP | 2707 lines | 1820 code | 229 blank | 658 comment | 262 complexity | df4ebd9eaf52cf3767eaaaff2330b425 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  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-2011 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'", __METHOD__ . '::root' );
  520. }
  521. }
  522. }
  523. else if ( $nodeType == eZTemplate::NODE_TEXT )
  524. {
  525. $textElements[] = $node[2];
  526. }
  527. else if ( $nodeType == eZTemplate::NODE_VARIABLE )
  528. {
  529. $variableData = $node[2];
  530. $variablePlacement = $node[3];
  531. $rslt = $this->processVariable( $textElements, $variableData, $variablePlacement, $rootNamespace, $currentNamespace );
  532. if ( !is_array( $textElements ) )
  533. eZDebug::writeError( "Textelements is no longer array: '$textElements'", __METHOD__ . '::variable' );
  534. }
  535. else if ( $nodeType == eZTemplate::NODE_FUNCTION )
  536. {
  537. $functionChildren = $node[1];
  538. $functionName = $node[2];
  539. $functionParameters = $node[3];
  540. $functionPlacement = $node[4];
  541. $rslt = $this->processFunction( $functionName, $textElements, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace );
  542. if ( !is_array( $textElements ) )
  543. eZDebug::writeError( "Textelements is no longer array: '$textElements'", __METHOD__ . "::function( '$functionName' )" );
  544. }
  545. return $rslt;
  546. }
  547. function processVariable( &$textElements, $variableData, $variablePlacement, $rootNamespace, $currentNamespace )
  548. {
  549. $value = $this->elementValue( $variableData, $rootNamespace, $currentNamespace, $variablePlacement );
  550. $this->appendElementText( $textElements, $value, $rootNamespace, $currentNamespace );
  551. }
  552. function processFunction( $functionName, &$textElements, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace )
  553. {
  554. // Note: This code piece is replicated in the eZTemplateCompiler,
  555. // if this code is changed the replicated code must be updated as well.
  556. $func = $this->Functions[$functionName];
  557. if ( is_array( $func ) )
  558. {
  559. $this->loadAndRegisterFunctions( $this->Functions[$functionName] );
  560. $func = $this->Functions[$functionName];
  561. }
  562. if ( isset( $func ) and
  563. is_object( $func ) )
  564. {
  565. if ( eZTemplate::isMethodDebugEnabled() )
  566. eZDebug::writeDebug( "START FUNCTION: $functionName" );
  567. $value = $func->process( $this, $textElements, $functionName, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace );
  568. if ( eZTemplate::isMethodDebugEnabled() )
  569. eZDebug::writeDebug( "END FUNCTION: $functionName" );
  570. return $value;
  571. }
  572. else
  573. {
  574. $this->warning( "", "Function \"$functionName\" is not registered" );
  575. }
  576. }
  577. function fetchFunctionObject( $functionName )
  578. {
  579. $func = $this->Functions[$functionName];
  580. if ( is_array( $func ) )
  581. {
  582. $this->loadAndRegisterFunctions( $this->Functions[$functionName] );
  583. $func = $this->Functions[$functionName];
  584. }
  585. return $func;
  586. }
  587. /*!
  588. Loads the template using the URI $uri and parses it.
  589. \return The root node of the tree if \a $returnResourceData is false,
  590. if \c true the entire resource data structure.
  591. */
  592. function load( $uri, $extraParameters = false, $returnResourceData = false )
  593. {
  594. $resourceData = $this->loadURIRoot( $uri, true, $extraParameters );
  595. if ( !$resourceData or
  596. $resourceData['root-node'] === null )
  597. {
  598. $retValue = null;
  599. return $retValue;
  600. }
  601. else
  602. return $resourceData['root-node'];
  603. }
  604. function parse( $sourceText, &$rootElement, $rootNamespace, &$resourceData )
  605. {
  606. $parser = eZTemplateMultiPassParser::instance();
  607. $parser->parse( $this, $sourceText, $rootElement, $rootNamespace, $resourceData );
  608. }
  609. function loadURIData( $resourceObject, $uri, $resourceName, $template, &$extraParameters, $displayErrors = true )
  610. {
  611. $resourceData = $this->resourceData( $resourceObject, $uri, $resourceName, $template );
  612. $resourceData['text'] = null;
  613. $resourceData['root-node'] = null;
  614. $resourceData['compiled-template'] = false;
  615. $resourceData['time-stamp'] = null;
  616. $resourceData['key-data'] = null;
  617. $resourceData['locales'] = null;
  618. if ( !$resourceObject->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters ) )
  619. {
  620. $resourceData = null;
  621. if ( $displayErrors )
  622. $this->warning( "", "No template could be loaded for \"$template\" using resource \"$resourceName\"" );
  623. }
  624. return $resourceData;
  625. }
  626. /*!
  627. \static
  628. Creates a resource data structure of the parameters and returns it.
  629. This structure is passed to various parts of the template system.
  630. \note If you only have the URI you should call resourceFor() first to
  631. figure out the resource handler.
  632. */
  633. function resourceData( $resourceObject, $uri, $resourceName, $templateName )
  634. {
  635. $resourceData = array();
  636. $resourceData['uri'] = $uri;
  637. $resourceData['resource'] = $resourceName;
  638. $resourceData['template-name'] = $templateName;
  639. $resourceData['template-filename'] = $templateName;
  640. $resourceData['handler'] = $resourceObject;
  641. $resourceData['test-compile'] = $this->TestCompile;
  642. return $resourceData;
  643. }
  644. /*!
  645. Loads the template using the URI $uri and returns a structure with the text and timestamp,
  646. false otherwise.
  647. The structure keys are:
  648. - "text", the text.
  649. - "time-stamp", the timestamp.
  650. */
  651. function loadURIRoot( $uri, $displayErrors = true, &$extraParameters )
  652. {
  653. $res = "";
  654. $template = "";
  655. $resobj = $this->resourceFor( $uri, $res, $template );
  656. if ( !is_object( $resobj ) )
  657. {
  658. if ( $displayErrors )
  659. $this->warning( "", "No resource handler for \"$res\" and no default resource handler, aborting." );
  660. return null;
  661. }
  662. $canCache = true;
  663. if ( !$resobj->servesStaticData() )
  664. $canCache = false;
  665. if ( !$this->isCachingAllowed() )
  666. $canCache = false;
  667. $resourceData = $this->loadURIData( $resobj, $uri, $res, $template, $extraParameters, $displayErrors );
  668. if ( $resourceData )
  669. {
  670. eZTemplate::appendTemplateToStatisticsIfNeeded( $resourceData['template-name'], $resourceData['template-filename'] );
  671. $this->appendTemplateFetch( $resourceData['template-filename'] );
  672. if ( !$resourceData['compiled-template'] and
  673. $resourceData['root-node'] === null )
  674. {
  675. $resourceData['root-node'] = array( eZTemplate::NODE_ROOT, false );
  676. $templateText = $resourceData["text"];
  677. $keyData = $resourceData['key-data'];
  678. $this->setIncludeText( $uri, $templateText );
  679. $rootNamespace = '';
  680. $this->parse( $templateText, $resourceData['root-node'], $rootNamespace, $resourceData );
  681. if ( eZTemplate::isDebugEnabled() )
  682. {
  683. $this->appendDebugNodes( $resourceData['root-node'], $resourceData );
  684. }
  685. if ( $canCache )
  686. $resobj->setCachedTemplateTree( $keyData, $uri, $res, $template, $extraParameters, $resourceData['root-node'] );
  687. }
  688. if ( !$resourceData['compiled-template'] and
  689. $canCache and
  690. $this->canCompileTemplate( $resourceData, $extraParameters ) )
  691. {
  692. $generateStatus = $this->compileTemplate( $resourceData, $extraParameters );
  693. if ( $generateStatus )
  694. $resourceData['compiled-template'] = true;
  695. }
  696. }
  697. return $resourceData;
  698. }
  699. function processURI( $uri, $displayErrors = true, &$extraParameters,
  700. &$textElements, $rootNamespace, $currentNamespace )
  701. {
  702. $this->Level++;
  703. if ( $this->Level > $this->MaxLevel )
  704. {
  705. eZDebug::writeError( $this->MaxLevelWarning, __METHOD__ . " Level: $this->Level @ $uri" );
  706. $textElements[] = $this->MaxLevelWarning;
  707. $this->Level--;
  708. return;
  709. }
  710. $resourceData = $this->loadURIRoot( $uri, $displayErrors, $extraParameters );
  711. if ( !$resourceData or
  712. ( !$resourceData['compiled-template'] and
  713. $resourceData['root-node'] === null ) )
  714. {
  715. $this->Level--;
  716. return;
  717. }
  718. $templateCompilationUsed = false;
  719. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  720. {
  721. $savedLocale = setlocale( LC_CTYPE, null );
  722. setlocale( LC_CTYPE, $resourceData['locales'] );
  723. }
  724. if ( $resourceData['compiled-template'] )
  725. {
  726. if ( $this->executeCompiledTemplate( $resourceData, $textElements, $rootNamespace, $currentNamespace, $extraParameters ) )
  727. $templateCompilationUsed = true;
  728. }
  729. if ( !$templateCompilationUsed )
  730. {
  731. $text = null;
  732. if ( eZTemplate::isDebugEnabled() )
  733. {
  734. $fname = $resourceData['template-filename'];
  735. eZDebug::writeDebug( "START URI: $uri, $fname" );
  736. }
  737. $this->process( $resourceData['root-node'], $text, $rootNamespace, $currentNamespace );
  738. if ( eZTemplate::isDebugEnabled() )
  739. eZDebug::writeDebug( "END URI: $uri, $fname" );
  740. $this->setIncludeOutput( $uri, $text );
  741. $textElements[] = $text;
  742. }
  743. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  744. {
  745. setlocale( LC_CTYPE, $savedLocale );
  746. }
  747. $this->Level--;
  748. }
  749. function canCompileTemplate( $resourceData, &$extraParameters )
  750. {
  751. $resourceObject = $resourceData['handler'];
  752. if ( !$resourceObject )
  753. return false;
  754. $canGenerate = $resourceObject->canCompileTemplate( $this, $resourceData, $extraParameters );
  755. return $canGenerate;
  756. }
  757. /*!
  758. Validates the template file \a $file and returns \c true if the file has correct syntax.
  759. \param $returnResourceData If \c true then the returned value will be the resourcedata structure
  760. \sa compileTemplateFile(), fetch()
  761. */
  762. function validateTemplateFile( $file, $returnResourceData = false )
  763. {
  764. $this->resetErrorLog();
  765. if ( !file_exists( $file ) )
  766. return false;
  767. $resourceHandler = $this->resourceFor( $file, $resourceName, $templateName );
  768. if ( !$resourceHandler )
  769. return false;
  770. $resourceData = $this->resourceData( $resourceHandler, $file, $resourceName, $templateName );
  771. $resourceData['key-data'] = "file:" . $file;
  772. $extraParameters = array();
  773. // Disable caching/compiling while fetchin the resource
  774. // It will be restored afterwards
  775. $isCachingAllowed = $this->IsCachingAllowed;
  776. $this->IsCachingAllowed = false;
  777. $resourceHandler->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters );
  778. // Restore previous caching flag
  779. $this->IsCachingAllowed = $isCachingAllowed;
  780. $root =& $resourceData['root-node'];
  781. $root = array( eZTemplate::NODE_ROOT, false );
  782. $templateText = $resourceData["text"];
  783. $rootNamespace = '';
  784. $this->parse( $templateText, $root, $rootNamespace, $resourceData );
  785. if ( eZTemplate::isDebugEnabled() )
  786. {
  787. $this->appendDebugNodes( $root, $resourceData );
  788. }
  789. $result = !$this->hasErrors() and !$this->hasWarnings();
  790. if ( $returnResourceData )
  791. {
  792. $resourceData['result'] = $result;
  793. return $resourceData;
  794. }
  795. return $result;
  796. }
  797. /*!
  798. Compiles the template file \a $file and returns \c true if the compilation was OK.
  799. \param $returnResourceData If \c true then the returned value will be the resourcedata structure
  800. \sa validateTemplateFile(), fetch()
  801. */
  802. function compileTemplateFile( $file, $returnResourceData = false )
  803. {
  804. $this->resetErrorLog();
  805. if ( !file_exists( $file ) )
  806. return false;
  807. $resourceHandler = $this->resourceFor( $file, $resourceName, $templateName );
  808. if ( !$resourceHandler )
  809. return false;
  810. $resourceData = $this->resourceData( $resourceHandler, $file, $resourceName, $templateName );
  811. $resourceData['key-data'] = "file:" . $file;
  812. $key = md5( $resourceData['key-data'] );
  813. $extraParameters = array();
  814. $resourceHandler->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters );
  815. $isCompiled = false;
  816. if ( isset( $resourceData['compiled-template'] ) )
  817. $isCompiled = $resourceData['compiled-template'];
  818. if ( !$isCompiled )
  819. {
  820. $root =& $resourceData['root-node'];
  821. $root = array( eZTemplate::NODE_ROOT, false );
  822. $templateText = $resourceData["text"];
  823. $rootNamespace = '';
  824. $this->parse( $templateText, $root, $rootNamespace, $resourceData );
  825. if ( eZTemplate::isDebugEnabled() )
  826. {
  827. $this->appendDebugNodes( $root, $resourceData );
  828. }
  829. $result = eZTemplateCompiler::compileTemplate( $this, $key, $resourceData );
  830. }
  831. else
  832. {
  833. $result = true;
  834. }
  835. if ( $returnResourceData )
  836. {
  837. $resourceData['result'] = $result;
  838. return $resourceData;
  839. }
  840. return $result;
  841. }
  842. function compileTemplate( &$resourceData, &$extraParameters )
  843. {
  844. $resourceObject = $resourceData['handler'];
  845. if ( !$resourceObject )
  846. return false;
  847. $keyData = $resourceData['key-data'];
  848. $uri = $resourceData['uri'];
  849. $resourceName = $resourceData['resource'];
  850. $templatePath = $resourceData['template-name'];
  851. return $resourceObject->compileTemplate( $this, $keyData, $uri, $resourceName, $templatePath, $extraParameters, $resourceData );
  852. }
  853. function executeCompiledTemplate( &$resourceData, &$textElements, $rootNamespace, $currentNamespace, &$extraParameters )
  854. {
  855. $resourceObject = $resourceData['handler'];
  856. if ( !$resourceObject )
  857. return false;
  858. $keyData = $resourceData['key-data'];
  859. $uri = $resourceData['uri'];
  860. $resourceName = $resourceData['resource'];
  861. $templatePath = $resourceData['template-name'];
  862. $timestamp = $resourceData['time-stamp'];
  863. return $resourceObject->executeCompiledTemplate( $this, $textElements,
  864. $keyData, $uri, $resourceData, $templatePath,
  865. $extraParameters, $timestamp,
  866. $rootNamespace, $currentNamespace );
  867. }
  868. /*!
  869. Returns the resource object for URI $uri. If a resource type is specified
  870. in the URI it is extracted and set in $res. The template name is set in $template
  871. without any resource specifier. To specify a resource the name and a ":" is
  872. prepended to the URI, for instance file:my.tpl.
  873. If no resource type is found the URI the default resource handler is used.
  874. */
  875. function resourceFor( $uri, &$res, &$template )
  876. {
  877. $args = explode( ":", $uri );
  878. if ( isset( $args[1] ) )
  879. {
  880. $res = $args[0];
  881. $template = $args[1];
  882. }
  883. else
  884. $template = $uri;
  885. if ( eZTemplate::isDebugEnabled() )
  886. {
  887. eZDebug::writeNotice( "eZTemplate: Loading template \"$template\" with resource \"$res\"" );
  888. }
  889. if ( isset( $this->Resources[$res] ) and is_object( $this->Resources[$res] ) )
  890. {
  891. return $this->Resources[$res];
  892. }
  893. return $this->DefaultResource;
  894. }
  895. /*!
  896. \return The resource handler object for resource name \a $resourceName.
  897. \sa resourceFor
  898. */
  899. function resourceHandler( $resourceName )
  900. {
  901. if ( isset( $this->Resources[$resourceName] ) &&
  902. is_object( $this->Resources[$resourceName] ) )
  903. {
  904. return $this->Resources[$resourceName];
  905. }
  906. return $this->DefaultResource;
  907. }
  908. function hasChildren( &$function, $functionName )
  909. {
  910. $hasChildren = $function->hasChildren();
  911. if ( is_array( $hasChildren ) )
  912. return $hasChildren[$functionName];
  913. else
  914. return $hasChildren;
  915. }
  916. /*!
  917. Returns the empty variable type.
  918. */
  919. function emptyVariable()
  920. {
  921. return array( "type" => "null" );
  922. }
  923. /*!
  924. \static
  925. */
  926. function mergeNamespace( $rootNamespace, $additionalNamespace )
  927. {
  928. $namespace = $rootNamespace;
  929. if ( $namespace == '' )
  930. $namespace = $additionalNamespace;
  931. else if ( $additionalNamespace != '' )
  932. $namespace = "$namespace:$additionalNamespace";
  933. return $namespace;
  934. }
  935. /*!
  936. Returns the actual value of a template type or null if an unknown type.
  937. */
  938. function elementValue( &$dataElements, $rootNamespace, $currentNamespace, $placement = false,
  939. $checkExistance = false, $checkForProxy = false )
  940. {
  941. /*
  942. * We use a small dirty hack in this function...
  943. * To help the caller to determine if the value was a proxy object,
  944. * we store boolean true to $dataElements['proxy-object-found'] in this case.
  945. * (it's up to caller to remove this garbage from $dataElements...)
  946. * This behaviour is enabled by $checkForProxy parameter.
  947. */
  948. $value = null;
  949. if ( !is_array( $dataElements ) )
  950. {
  951. $this->error( "elementValue",
  952. "Missing array data structure, got " . gettype( $dataElements ) );
  953. return null;
  954. }
  955. foreach ( $dataElements as $dataElement )
  956. {
  957. if ( $dataElement === null )
  958. {
  959. return null;
  960. }
  961. $dataType = $dataElement[0];
  962. switch ( $dataType )
  963. {
  964. case eZTemplate::TYPE_VOID:
  965. {
  966. if ( !$checkExistance )
  967. $this->warning( 'elementValue',
  968. 'Found void datatype, should not be used' );
  969. else
  970. {
  971. return null;
  972. }
  973. } break;
  974. case eZTemplate::TYPE_STRING:
  975. case eZTemplate::TYPE_NUMERIC:
  976. case eZTemplate::TYPE_IDENTIFIER:
  977. case eZTemplate::TYPE_BOOLEAN:
  978. case eZTemplate::TYPE_ARRAY:
  979. {
  980. $value = $dataElement[1];
  981. } break;
  982. case eZTemplate::TYPE_VARIABLE:
  983. {
  984. $variableData = $dataElement[1];
  985. $variableNamespace = $variableData[0];
  986. $variableNamespaceScope = $variableData[1];
  987. $variableName = $variableData[2];
  988. if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_GLOBAL )
  989. $namespace = $variableNamespace;
  990. else if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_LOCAL )
  991. $namespace = $this->mergeNamespace( $rootNamespace, $variableNamespace );
  992. else if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_RELATIVE )
  993. $namespace = $this->mergeNamespace( $currentNamespace, $variableNamespace );
  994. else
  995. $namespace = false;
  996. if ( $this->hasVariable( $variableName, $namespace ) )
  997. {
  998. $value = $this->variable( $variableName, $namespace );
  999. }
  1000. else
  1001. {
  1002. if ( !$checkExistance )
  1003. $this->error( '', "Unknown template variable '$variableName' in namespace '$namespace'", $placement );
  1004. {
  1005. return null;
  1006. }
  1007. }
  1008. } break;
  1009. case eZTemplate::TYPE_ATTRIBUTE:
  1010. {
  1011. $attributeData = $dataElement[1];
  1012. $attributeValue = $this->elementValue( $attributeData, $rootNamespace, $currentNamespace, false, $checkExistance );
  1013. if ( $attributeValue !== null )
  1014. {
  1015. if ( !is_numeric( $attributeValue ) and
  1016. !is_string( $attributeValue ) and
  1017. !is_bool( $attributeValue ) )
  1018. {
  1019. if ( !$checkExistance )
  1020. $this->error( "",
  1021. "Cannot use type " . gettype( $attributeValue ) . " for attribute lookup", $placement );
  1022. {
  1023. return null;
  1024. }
  1025. }
  1026. if ( is_array( $value ) )
  1027. {
  1028. if ( array_key_exists( $attributeValue, $value ) )
  1029. {
  1030. $value = $value[$attributeValue];
  1031. }
  1032. else
  1033. {
  1034. if ( !$checkExistance )
  1035. {
  1036. $arrayAttributeList = array_keys( $value );
  1037. $arrayCount = count( $arrayAttributeList );
  1038. $errorMessage = "No such attribute for array($arrayCount): $attributeValue";
  1039. $chooseText = "Choose one of following: ";
  1040. $errorMessage .= "\n$chooseText";
  1041. $errorMessage .= $this->expandAttributes( $arrayAttributeList, $chooseText, 25 );
  1042. $this->error( "",
  1043. $errorMessage, $placement );
  1044. }
  1045. return null;
  1046. }
  1047. }
  1048. else if ( is_object( $value ) )
  1049. {
  1050. if ( method_exists( $value, "attribute" ) and
  1051. method_exists( $value, "hasAttribute" ) )
  1052. {
  1053. if ( $value->hasAttribute( $attributeValue ) )
  1054. {
  1055. $value = $value->attribute( $attributeValue );
  1056. }
  1057. else
  1058. {
  1059. if ( !$checkExistance )
  1060. {
  1061. $objectAttributeList = array();
  1062. if ( method_exists( $value, 'attributes' ) )
  1063. $objectAttributeList = $value->attributes();
  1064. $objectClass= get_class( $value );
  1065. $errorMessage = "No such attribute for object($objectClass): $attributeValue";
  1066. $chooseText = "Choose one of following: ";
  1067. $errorMessage .= "\n$chooseText";
  1068. $errorMessage .= $this->expandAttributes( $objectAttributeList, $chooseText, 25 );
  1069. $this->error( "",
  1070. $errorMessage, $placement );
  1071. }
  1072. return null;
  1073. }
  1074. }
  1075. else
  1076. {
  1077. if ( !$checkExistance )
  1078. $this->error( "",
  1079. "Cannot retrieve attribute of object(" . get_class( $value ) .
  1080. "), no attribute functions available",
  1081. $placement );
  1082. return null;
  1083. }
  1084. }
  1085. else
  1086. {
  1087. if ( !$checkExistance )
  1088. $this->error( "",
  1089. "Cannot retrieve attribute of a " . gettype( $value ),
  1090. $placement );
  1091. return null;
  1092. }
  1093. }
  1094. else
  1095. {
  1096. if ( !$checkExistance )
  1097. $this->error( '',
  1098. 'Attribute value was null, cannot get attribute',
  1099. $placement );
  1100. return null;
  1101. }
  1102. } break;
  1103. case eZTemplate::TYPE_OPERATOR:
  1104. {
  1105. $operatorParameters = $dataElement[1];
  1106. $operatorName = $operatorParameters[0];
  1107. $operatorParameters = array_splice( $operatorParameters, 1 );
  1108. if ( is_object( $value ) and
  1109. method_exists( $value, 'templateValue' ) )
  1110. {
  1111. if ( $checkForProxy )
  1112. $dataElements['proxy-object-found'] = true;
  1113. $value = $value->templateValue();
  1114. }
  1115. $valueData = array( 'value' => $value );
  1116. $this->processOperator( $operatorName, $operatorParameters, $rootNamespace, $currentNamespace,
  1117. $valueData, $placement, $checkExistance );
  1118. $value = $valueData['value'];
  1119. } break;
  1120. default:
  1121. {
  1122. if ( !$checkExistance )
  1123. $this->error( "elementValue",
  1124. "Unknown data type: '$dataType'" );
  1125. return null;
  1126. }
  1127. }
  1128. }
  1129. if ( is_object( $value ) and
  1130. method_exists( $value, 'templateValue' ) )
  1131. {
  1132. if ( $checkForProxy )
  1133. $dataElements['proxy-object-found'] = true;
  1134. return $value->templateValue();
  1135. }
  1136. return $value;
  1137. }
  1138. function expandAttributes( $attributeList, $chooseText, $maxThreshold, $minThreshold = 1 )
  1139. {
  1140. $errorMessage = '';
  1141. $attributeCount = count( $attributeList );
  1142. if ( $attributeCount < $minThreshold )
  1143. return $errorMessage;
  1144. if ( $attributeCount < $maxThreshold )
  1145. {
  1146. $chooseLength = strlen( $chooseText );
  1147. $attributeText = '';
  1148. $i = 0;
  1149. foreach ( $attributeList as $attributeName )
  1150. {
  1151. if ( $i > 0 )
  1152. $attributeText .= ",";
  1153. if ( strlen( $attributeText ) > 40 )
  1154. {
  1155. $attributeText .= "\n";
  1156. $errorMessage .= $attributeText;
  1157. $errorMessage .= str_repeat( ' ', $chooseLength );
  1158. $attributeText = '';
  1159. }
  1160. else if ( $i > 0 )
  1161. $attributeText .= " ";
  1162. $attributeText .= $attributeName;
  1163. ++$i;
  1164. }
  1165. $errorMessage .= $attributeText;
  1166. }
  1167. return $errorMessage;
  1168. }
  1169. function processOperator( $operatorName, $operatorParameters, $rootNamespace, $currentNamespace,
  1170. &$valueData, $placement = false, $checkExistance = false )
  1171. {
  1172. $namedParameters = array();
  1173. $operatorParameterDefinition = $this->operatorParameterList( $operatorName );
  1174. $i = 0;
  1175. foreach ( $operatorParameterDefinition as $parameterName => $parameterType )
  1176. {
  1177. if ( !isset( $operatorParameters[$i] ) or
  1178. !isset( $operatorParameters[$i][0] ) or
  1179. $operatorParameters[$i][0] == eZTemplate::TYPE_VOID )
  1180. {
  1181. if ( $parameterType["required"] )
  1182. {
  1183. if ( !$checkExistance )
  1184. $this->warning( "eZTemplateOperatorElement", "Parameter '$parameterName' ($i) missing",
  1185. $placement );
  1186. $namedParameters[$parameterName] = $parameterType["default"];
  1187. }
  1188. else
  1189. {
  1190. $namedParameters[$parameterName] = $parameterType["default"];
  1191. }
  1192. }
  1193. else
  1194. {
  1195. $parameterData = $operatorParameters[$i];
  1196. $namedParameters[$parameterName] = $this->elementValue( $parameterData, $rootNamespace, $currentNamespace, false, $checkExistance );
  1197. }
  1198. ++$i;
  1199. }
  1200. if ( isset( $this->Operators[$operatorName] ) )
  1201. {
  1202. if ( is_array( $this->Operators[$operatorName] ) )
  1203. {
  1204. $this->loadAndRegisterOperators( $this->Operators[$operatorName] );
  1205. }
  1206. $op = $this->Operators[$operatorName];
  1207. if ( is_object( $op ) and method_exists( $op, 'modify' ) )
  1208. {
  1209. $value = $valueData['value'];
  1210. if ( eZTemplate::isMethodDebugEnabled() )
  1211. eZDebug::writeDebug( "START OPERATOR: $operatorName" );
  1212. $op->modify( $this, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, $value, $namedParameters,
  1213. $placement );
  1214. if ( eZTemplate::isMethodDebugEnabled() )
  1215. eZDebug::writeDebug( "END OPERATOR: $operatorName" );
  1216. $valueData['value'] = $value;
  1217. }
  1218. else
  1219. $this->error( '', "Object problem with operator '$operatorName' ",
  1220. $placement );
  1221. }
  1222. else if ( !$checkExistance )
  1223. $this->warning( "", "Operator '$operatorName' is not registered",
  1224. $placement );
  1225. }
  1226. /*!
  1227. Return the identifier used for attribute lookup.
  1228. */
  1229. function attributeValue( &$data, $nspace )
  1230. {
  1231. switch ( $data["type"] )
  1232. {
  1233. case "map":
  1234. {
  1235. return $data["content"];
  1236. } break;
  1237. case "index":
  1238. {
  1239. return $data["content"];
  1240. } break;
  1241. case "variable":
  1242. {
  1243. return $this->elementValue( $data["content"], $nspace );
  1244. } break;
  1245. default:
  1246. {
  1247. $this->error( "attributeValue()", "Unknown attribute type: " . $data["type"] );
  1248. return null;
  1249. }
  1250. }
  1251. }
  1252. /*!
  1253. Helper function for creating a displayable text for a variable.
  1254. */
  1255. function variableText( $var, $namespace = "", $attrs = array() )
  1256. {
  1257. $txt = "$";
  1258. if ( $namespace != "" )
  1259. $txt .= "$namespace:";
  1260. $txt .= $var;
  1261. if ( !empty( $attrs ) )
  1262. $txt .= "." . implode( ".", $attrs );
  1263. return $txt;
  1264. }
  1265. /*!
  1266. Returns the named parameter list for the operator $name.
  1267. */
  1268. function operatorParameterList( $name )
  1269. {
  1270. $param_list = array();
  1271. if ( !isset( $this->Operators[$name] ) )
  1272. {
  1273. return $param_list;
  1274. }
  1275. if ( is_array( $this->Operators[$name] ) )
  1276. {
  1277. $this->loadAndRegisterOperators( $this->Operators[$name] );
  1278. }
  1279. $op = $this->Operators[$name];
  1280. if ( isset( $op ) and
  1281. method_exists( $op, "namedParameterList" ) )
  1282. {
  1283. $param_list = $op->namedParameterList();
  1284. if ( method_exists( $op, "namedParameterPerOperator" ) and
  1285. $op->namedParameterPerOperator() )
  1286. {
  1287. if ( !isset( $param_list[$name] ) )
  1288. return array();
  1289. $param_list = $param_list[$name];
  1290. }
  1291. }
  1292. return $param_list;
  1293. }
  1294. /*!
  1295. Tries to run the operator $operatorName with parameters $operatorParameters
  1296. on the value $value.
  1297. */
  1298. function doOperator( $element, &$namespace, &$current_nspace, &$value, $operatorName, $operatorParameters, &$named_params )
  1299. {
  1300. if ( is_array( $this->Operators[$operatorName] ) )
  1301. {
  1302. $this->loadAndRegisterOperators( $this->Operators[$operatorName] );
  1303. }
  1304. $op = $this->Operators[$operatorName];
  1305. if ( isset( $op ) )
  1306. {
  1307. $op->modify( $element, $this, $operatorName, $operatorParameters, $namespace, $current_nspace, $value, $named_params );
  1308. }
  1309. else
  1310. $this->warning( "", "Operator \"$operatorName\" is not registered" );
  1311. }
  1312. /*!
  1313. Tries to run the function object $func_obj
  1314. */
  1315. function doFunction( $name, $func_obj, $nspace, $current_nspace )
  1316. {
  1317. $func = $this->Functions[$name];
  1318. if ( is_array( $func ) )
  1319. {
  1320. $this->loadAndRegisterFunctions( $this->Functions[$name] );
  1321. $func = $this->Functions[$name];
  1322. }
  1323. if ( isset( $func ) and
  1324. is_object( $func ) )
  1325. {
  1326. return $func->process( $this, $name, $func_obj, $nspace, $current_nspace );
  1327. }
  1328. else
  1329. {
  1330. $this->warning( "", "Function \"$name\" is not registered" );
  1331. return false;
  1332. }
  1333. }
  1334. /**
  1335. * Sets the template variable $var to the value $val.
  1336. *
  1337. * @param string $var
  1338. * @param string $val
  1339. * @param string $namespace (optional)
  1340. */
  1341. function setVariable( $var, $val, $namespace = '' )
  1342. {
  1343. $this->Variables[$namespace][$var] = $val;
  1344. }
  1345. /**
  1346. * Sets the template variable $var to the value $val by ref
  1347. *
  1348. * @deprecated Since 4.4, have not used references since 3.10
  1349. * @uses eZTemplate::setVariable()
  1350. *
  1351. * @param string $var
  1352. * @param string $val
  1353. * @param string $namespace (optional)
  1354. */
  1355. function setVariableRef( $var, $val, $namespace = '' )
  1356. {
  1357. $this->setVariable( $var, $val, $namespace );
  1358. }
  1359. /**
  1360. * Unsets the template variable $var.
  1361. *
  1362. * @param string $var
  1363. * @param string $namespace (optional)
  1364. */
  1365. function unsetVariable( $var, $namespace = '' )
  1366. {
  1367. if ( isset( $this->Variables[$namespace] ) &&
  1368. array_key_exists( $var, $this->Variables[$namespace] ) )
  1369. unset( $this->Variables[$namespace][$var] );
  1370. else
  1371. $this->warning( "unsetVariable()", "Undefined Variable: \$$namespace:$var, cannot unset" );
  1372. }
  1373. /**
  1374. * Returns true if the variable $var is set in namespace $namespace,
  1375. * if $attrs is supplied all attributes must exist for the function to return true.
  1376. *
  1377. * @param string $var
  1378. * @param string $namespace (optional)
  1379. * @param array $attrs (optional) Deprecated as of 4.4.
  1380. * @return bool
  1381. */
  1382. function hasVariable( $var, $namespace = '', $attrs = null )
  1383. {
  1384. $exists = ( isset( $this->Variables[$namespace] ) &&
  1385. array_key_exists( $var, $this->Variables[$namespace] ) );
  1386. if ( $exists && $attrs !== null && !empty( $attrs ) )
  1387. {
  1388. eZDebug::writeStrict( '$attrs parameter is deprecated as of 4.4', __METHOD__ );
  1389. $ptr =& $this->Variables[$namespace][$var];
  1390. foreach( $attrs as $attr )
  1391. {
  1392. unset( $tmp );
  1393. if ( is_object( $ptr ) )
  1394. {
  1395. if ( $ptr->hasAttribute( $attr ) )
  1396. $tmp = $ptr->attribute( $attr );
  1397. else
  1398. return false;
  1399. }
  1400. else if ( is_array( $ptr ) )
  1401. {
  1402. if ( array_key_exists( $attr, $ptr ) )
  1403. $tmp =& $ptr[$attr];
  1404. else
  1405. return false;
  1406. }
  1407. else
  1408. {
  1409. return false;
  1410. }
  1411. unset( $ptr );
  1412. $ptr =& $tmp;
  1413. }
  1414. }
  1415. return $exists;
  1416. }
  1417. /**
  1418. * Returns the content of the variable $var using namespace $namespace,
  1419. * if $attrs is supplied the result of the attributes is returned.
  1420. *
  1421. * @param string $var
  1422. * @param string $namespace (optional)
  1423. * @param array $attrs (optional) Deprecated as of 4.4
  1424. * @return string|array
  1425. */
  1426. function variable( $var, $namespace = '', $attrs = null )
  1427. {
  1428. $val = null;
  1429. $exists = ( isset( $this->Variables[$namespace] ) &&
  1430. array_key_exists( $var, $this->Variables[$namespace] ) );
  1431. if ( $exists )
  1432. {
  1433. if ( $attrs !== null && !empty( $attrs ) )
  1434. {
  1435. eZDebug::writeStrict( '$attrs parameter is deprecated as of 4.4', __METHOD__ );
  1436. $element = $this->Variables[$namespace][$var];
  1437. foreach( $attrs as $attr )
  1438. {
  1439. if ( is_object( $element ) )
  1440. {
  1441. if ( $element->hasAttribute( $attr ) )
  1442. {
  1443. $element = $element->attribute( $attr );
  1444. }
  1445. else
  1446. {
  1447. return $val;
  1448. }
  1449. }
  1450. else if ( is_array( $element ) )
  1451. {
  1452. if ( array_key_exists( $attr, $element ) )
  1453. {
  1454. $val = $element[$attr];
  1455. }
  1456. else
  1457. {
  1458. return $val;
  1459. }
  1460. }
  1461. else
  1462. {
  1463. return $val;
  1464. }
  1465. $val = $element;
  1466. }
  1467. }
  1468. else
  1469. {
  1470. $val = $this->Variables[$namespace][$var];
  1471. }
  1472. }
  1473. return $val;
  1474. }
  1475. /*!
  1476. Returns the attribute(s) of the template variable $var,
  1477. $attrs is an array of attribute names to use iteratively for each new variable returned.
  1478. */
  1479. function variableAttribute( $var, $attrs )
  1480. {
  1481. foreach( $attrs as $attr )
  1482. {
  1483. if ( is_object( $var ) )
  1484. {
  1485. if ( $var->hasAttribute( $attr ) )
  1486. {
  1487. $var = $var->attribute( $attr );
  1488. }
  1489. else
  1490. {
  1491. return null;
  1492. }
  1493. }
  1494. else if ( is_array( $var ) )
  1495. {
  1496. if ( isset( $var[$attr] ) )
  1497. {
  1498. $var = $var[$attr];
  1499. }
  1500. else
  1501. {
  1502. return null;
  1503. }
  1504. }
  1505. else
  1506. {
  1507. return null;
  1508. }
  1509. }
  1510. if ( isset( $var ) )
  1511. {
  1512. return $var;
  1513. }
  1514. return null;
  1515. }
  1516. function appendElement( &$text, $item, $nspace, $name )
  1517. {
  1518. $this->appendElementText( $textElements, $item, $nspace, $name );
  1519. $text .= implode( '', $textElements );
  1520. }
  1521. function appendElementText( &$textElements, $item, $nspace, $name )
  1522. {
  1523. if ( !is_array( $textElements ) )
  1524. $textElements = array();
  1525. if ( is_object( $item ) and
  1526. method_exists( $item, 'templateValue' ) )
  1527. {
  1528. $item = $item->templateValue();
  1529. $textElements[] = "$item";
  1530. }
  1531. else if ( is_object( $item ) )
  1532. {
  1533. $hasTemplateData = false;
  1534. if ( method_exists( $item, 'templateData' ) )
  1535. {
  1536. $templateData = $item->templateData();
  1537. if ( is_array( $templateData ) and
  1538. isset( $templateData['type'] ) )
  1539. {
  1540. if ( $templateData['type'] == 'template' and
  1541. isset( $templateData['uri'] ) and
  1542. isset( $templateData['template_variable_name'] ) )
  1543. {
  1544. $templateURI =& $templateData['uri'];
  1545. $templateVariableName =& $templateData['template_variable_name'];
  1546. $templateText = '';
  1547. $this->setVariable( $templateVariableName, $item, $name );
  1548. eZTemplateIncludeFunction::handleInclude( $textElements, $templateURI, $this, $nspace, $name );
  1549. $hasTemplateData = true;
  1550. }
  1551. }
  1552. }
  1553. if ( !$hasTemplateData )
  1554. $textElements[] = method_exists( $item, '__toString' ) ? (string)$item : 'Object(' . get_class( $item ) . ')';
  1555. }
  1556. else
  1557. $textElements[] = "$item";
  1558. return $textElements;
  1559. }
  1560. /*!
  1561. Creates some text nodes before and after the children of \a $root.
  1562. It will extract the current filename and uri and create some XHTML
  1563. comments and inline text.
  1564. \sa isXHTMLCodeIncluded
  1565. */
  1566. function appendDebugNodes( &$root, &$resourceData )
  1567. {
  1568. $path = $resourceData['template-filename'];
  1569. // Do not ouput debug on pagelayout templates to avoid trigering
  1570. // browser quirks mode
  1571. if ( isset( $root[1][0][2] ) && is_string( $root[1][0][2] ) && strpos( $root[1][0][2], '<!DOCTYPE' ) === 0 )
  1572. return;
  1573. $uri = $resourceData['uri'];
  1574. $preText = "\n<!-- START: including template: $path ($uri) -->\n";
  1575. if ( eZTemplate::isXHTMLCodeIncluded() )
  1576. $preText .= "<p class=\"small\">$path</p><br/>\n";
  1577. $postText = "\n<!-- STOP: including template: $path ($uri) -->\n";
  1578. $root[1] = array_merge( array( eZTemplateNodeTool::createTextNode( $preText ) ), $root[1] );
  1579. $root[1][] = eZTemplateNodeTool::createTextNode( $postText );
  1580. }
  1581. /*!
  1582. Registers the functions supplied by the object $functionObject.
  1583. The object must have a function called functionList()
  1584. which returns an array of functions this object handles.
  1585. If the object has a function called attributeList()
  1586. it is used for registering function attributes.
  1587. The function returns an associative array with each key being
  1588. the name of the function and the value being a boolean.
  1589. If the boolean is true the function will have children.
  1590. */
  1591. function registerFunctions( &$functionObject )
  1592. {
  1593. $this->registerFunctionsInternal( $functionObject );
  1594. }
  1595. function registerAutoloadFunctions( $functionDefinition )
  1596. {
  1597. if ( ( ( isset( $functionDefinition['function'] ) ||
  1598. isset( $functionDefinition['class'] ) ) &&
  1599. ( isset( $functionDefinition['function_names_function'] ) ||
  1600. isset( $functionDefinition['function_names'] ) ) ) )
  1601. {
  1602. if ( isset( $functionDefinition['function_names_function'] ) )
  1603. {
  1604. $functionNamesFunction = $functionDefinition['function_names_function'];
  1605. if ( !function_exists( $functionNamesFunction ) )
  1606. {
  1607. $this->error( 'registerFunctions', "Cannot register function definition, missing function names function '$functionNamesFunction'" );
  1608. return;
  1609. }
  1610. $functionNames = $functionNamesFunction();
  1611. }
  1612. else
  1613. $functionNames = $functionDefinition['function_names'];
  1614. foreach ( $functionNames as $functionName )
  1615. {
  1616. $this->Functions[$functionName] = $functionDefinition;
  1617. }
  1618. if ( isset( $functionDefinition['function_attributes'] ) )
  1619. {
  1620. foreach ( $functionDefinition['function_attributes'] as $functionAttributeName )
  1621. {
  1622. $this->FunctionAttributes[$functionAttributeName] = $functionDefinition;
  1623. }
  1624. }
  1625. }
  1626. else
  1627. $this->error( 'registerFunctions', 'Cannot register function definition, missing data' );
  1628. }
  1629. function loadAndRegisterFunctions( $functionDefinition )
  1630. {
  1631. eZDebug::accumulatorStart( 'template_register_function', 'template_total', 'Template load and register function' );
  1632. $functionObject = null;
  1633. if ( isset( $functionDefinition['function'] ) )
  1634. {
  1635. $function = $functionDefinition['function'];
  1636. if ( function_exists( $function ) )
  1637. $functionObject = $function();
  1638. }
  1639. else
  1640. {
  1641. if ( !class_exists( $functionDefinition['class'], false )
  1642. && isset( $functionDefinition['script'] ) )
  1643. {
  1644. include_once( $functionDefinition['script'] );
  1645. }
  1646. $class = $functionDefinition['class'];
  1647. if ( class_exists( $class ) )
  1648. $functionObject = new $class();
  1649. }
  1650. eZDebug::accumulatorStop( 'template_register_function' );
  1651. if ( is_object( $functionObject ) )
  1652. {
  1653. $this->registerFunctionsInternal( $functionObject, true );
  1654. return true;
  1655. }
  1656. return false;
  1657. }
  1658. /*!
  1659. \private
  1660. */
  1661. function registerFunctionsInternal( $functionObject, $debug = false )
  1662. {
  1663. if ( !is_object( $functionObject ) or
  1664. !method_exists( $functionObject, 'functionList' ) )
  1665. return false;
  1666. foreach ( $functionObject->functionList() as $functionName )
  1667. {
  1668. $this->Functions[$functionName] = $functionObject;
  1669. }
  1670. if ( method_exists( $functionObject, "attributeList" ) )
  1671. {
  1672. $functionAttributes = $functionObject->attributeList();
  1673. foreach ( $functionAttributes as $attributeName => $hasChildren )
  1674. {
  1675. $this->FunctionAttributes[$attributeName] = $hasChildren;
  1676. }
  1677. }
  1678. return true;
  1679. }
  1680. /*!
  1681. Registers the function $func_name to be bound to object $func_obj.
  1682. If the object has a function called attributeList()
  1683. it is used for registering function attributes.
  1684. The function returns an associative array with each key being
  1685. the name of the function and the value being a boolean.
  1686. If the boolean is true the function will have children.
  1687. */
  1688. function registerFunction( $func_name, $func_obj )
  1689. {
  1690. $this->Functions[$func_name] = $func_obj;
  1691. if ( method_exists( $func_obj, "attributeList" ) )
  1692. {
  1693. $attrs = $func_obj->attributeList();
  1694. while ( list( $attr_name, $has_children ) = each( $attrs ) )
  1695. {
  1696. $this->FunctionAttributes[$attr_name] = $has_children;
  1697. }
  1698. }
  1699. }
  1700. /*!
  1701. Registers a new literal tag in which the tag will be transformed into
  1702. a text element.
  1703. */
  1704. function registerLiteral( $func_name )
  1705. {
  1706. $this->Literals[$func_name] = true;
  1707. }
  1708. /*!
  1709. Removes the literal tag $func_name.
  1710. */
  1711. function unregisterLiteral( $func_name )
  1712. {
  1713. unset( $this->Literals[$func_name] );
  1714. }
  1715. function registerAutoloadOperators( $operatorDefinition )
  1716. {
  1717. if ( ( ( isset( $operatorDefinition['function'] ) ||
  1718. isset( $operatorDefinition['class'] ) ) &&
  1719. ( isset( $operatorDefinition['operator_names_function'] ) ||
  1720. isset( $operatorDefinition['operator_names'] ) ) ) )
  1721. {
  1722. if ( isset( $operatorDefinition['operator_names_function'] ) )
  1723. {
  1724. $operatorNamesFunction = $operatorDefinition['operator_names_function'];
  1725. if ( !function_exists( $operatorNamesFunction ) )
  1726. {
  1727. $this->error( 'registerOperators', "Cannot register operator definition, missing operator names function '$operatorNamesFunction'" );
  1728. return;
  1729. }
  1730. $operatorNames = $operatorNamesFunction();
  1731. }
  1732. else
  1733. $operatorNames = $operatorDefinition['operator_names'];
  1734. foreach ( $operatorNames as $operatorName )
  1735. {
  1736. $this->Operators[$operatorName] = $operatorDefinition;
  1737. }
  1738. }
  1739. else
  1740. $this->error( 'registerOperators', 'Cannot register operator definition, missing data' );
  1741. }
  1742. function loadAndRegisterOperators( $operatorDefinition )
  1743. {
  1744. $operatorObject = null;
  1745. if ( isset( $operatorDefinition['function'] ) )
  1746. {
  1747. $function = $operatorDefinition['function'];
  1748. if ( function_exists( $function ) )
  1749. $operatorObject = $function();
  1750. }
  1751. else
  1752. {
  1753. $class = $operatorDefinition['class'];
  1754. if ( !class_exists( $class, false ) && isset( $operatorDefinition['script'] ) )
  1755. {
  1756. include_once( $operatorDefinition['script'] );
  1757. }
  1758. if ( class_exists( $class ) )
  1759. {
  1760. if ( isset( $operatorDefinition['class_parameter'] ) )
  1761. $operatorObject = new $class( $operatorDefinition['class_parameter'] );
  1762. else
  1763. $operatorObject = new $class();
  1764. }
  1765. }
  1766. if ( is_object( $operatorObject ) )
  1767. {
  1768. $this->registerOperatorsInternal( $operatorObject, true );
  1769. return true;
  1770. }
  1771. return false;
  1772. }
  1773. /*!
  1774. Registers the operators supplied by the object $operatorObject.
  1775. The function operatorList() must return an array of operator names.
  1776. */
  1777. function registerOperators( &$operatorObject )
  1778. {
  1779. $this->registerOperatorsInternal( $operatorObject );
  1780. }
  1781. function registerOperatorsInternal( $operatorObject, $debug = false )
  1782. {
  1783. if ( !is_object( $operatorObject ) or
  1784. !method_exists( $operatorObject, 'operatorList' ) )
  1785. return false;
  1786. foreach( $operatorObject->operatorList() as $operatorName )
  1787. {
  1788. $this->Operators[$operatorName] = $operatorObject;
  1789. }
  1790. }
  1791. /*!
  1792. Registers the operator $op_name to use the object $op_obj.
  1793. */
  1794. function registerOperator( $op_name, $op_obj )
  1795. {
  1796. $this->Operators[$op_name] = $op_obj;
  1797. }
  1798. /*!
  1799. Unregisters the operator $op_name.
  1800. */
  1801. function unregisterOperator( $op_name )
  1802. {
  1803. if ( is_array( $op_name ) )
  1804. {
  1805. foreach ( $op_name as $op )
  1806. {
  1807. $this->unregisterOperator( $op_name );
  1808. }
  1809. }
  1810. else if ( isset( $this->Operators ) )
  1811. unset( $this->Operators[$op_name] );
  1812. else
  1813. $this->warning( "unregisterOpearator()", "Operator $op_name is not registered, cannot unregister" );
  1814. }
  1815. /*!
  1816. Not implemented yet.
  1817. */
  1818. function registerFilter()
  1819. {
  1820. }
  1821. /*!
  1822. Registers a new resource object $res.
  1823. The resource object take care of fetching templates using an URI.
  1824. */
  1825. function registerResource( $res )
  1826. {
  1827. if ( is_object( $res ) )
  1828. $this->Resources[$res->resourceName()] =& $res;
  1829. else
  1830. $this->warning( "registerResource()", "Supplied argument is not a resource object" );
  1831. }
  1832. /*!
  1833. Unregisters the resource $res_name.
  1834. */
  1835. function unregisterResource( $res_name )
  1836. {
  1837. if ( is_array( $res_name ) )
  1838. {
  1839. foreach ( $res_name as $res )
  1840. {
  1841. $this->unregisterResource( $res );
  1842. }
  1843. }
  1844. else if ( isset( $this->Resources[$res_name] ) )
  1845. unset( $this->Resources[$res_name] );
  1846. else
  1847. $this->warning( "unregisterResource()", "Resource $res_name is not registered, cannot unregister" );
  1848. }
  1849. /*!
  1850. Sets whether detail output is used or not.
  1851. Detail output is useful for debug output where you want to examine the template
  1852. and the output text.
  1853. */
  1854. function setShowDetails( $show )
  1855. {
  1856. $this->ShowDetails = $show;
  1857. }
  1858. /*!
  1859. Outputs a warning about the parameter $param missing for function/operator $name.
  1860. */
  1861. function missingParameter( $name, $param )
  1862. {
  1863. $this->warning( $name, "Missing parameter $param" );
  1864. }
  1865. /*!
  1866. Outputs a warning about the parameter count being to high for function/operator $name.
  1867. */
  1868. function extraParameters( $name, $count, $maxCount )
  1869. {
  1870. $this->warning( $name, "Passed $count parameters but correct count is $maxCount" );
  1871. }
  1872. /*!
  1873. Outputs a warning about the variable $var being undefined.
  1874. */
  1875. function undefinedVariable( $name, $var )
  1876. {
  1877. $this->warning( $name, "Undefined variable: $var" );
  1878. }
  1879. /*!
  1880. Outputs an error about the template function $func_name being undefined.
  1881. */
  1882. function undefinedFunction( $func_name )
  1883. {
  1884. $this->error( "", "Undefined function: $func_name" );
  1885. }
  1886. /*!
  1887. Creates a string for the placement information and returns it.
  1888. \note The placement information can either be in indexed or associative
  1889. */
  1890. function placementText( $placement = false )
  1891. {
  1892. $placementText = false;
  1893. if ( $placement !== false )
  1894. {
  1895. if ( isset( $placement['start'] ) and
  1896. isset( $placement['stop'] ) and
  1897. isset( $placement['templatefile'] ) )
  1898. {
  1899. $line = $placement['start']['line'];
  1900. $column = $placement['start']['column'];
  1901. $templateFile = $placement['templatefile'];
  1902. }
  1903. else
  1904. {
  1905. $line = $placement[0][0];
  1906. $column = $placement[0][1];
  1907. $templateFile = $placement[2];
  1908. }
  1909. $placementText = " @ $templateFile:$line" . "[$column]";
  1910. }
  1911. return $placementText;
  1912. }
  1913. /*!
  1914. Displays a warning for the function/operator $name and text $txt.
  1915. */
  1916. function warning( $name, $txt, $placement = false )
  1917. {
  1918. $this->WarningLog[] = array( 'name' => $name,
  1919. 'text' => $txt,
  1920. 'placement' => $placement );
  1921. if ( !is_string( $placement ) )
  1922. $placementText = $this->placementText( $placement );
  1923. else
  1924. $placementText = $placement;
  1925. $placementText = $this->placementText( $placement );
  1926. if ( $name != "" )
  1927. eZDebug::writeWarning( $txt, "eZTemplate:$name" . $placementText );
  1928. else
  1929. eZDebug::writeWarning( $txt, "eZTemplate" . $placementText );
  1930. }
  1931. /*!
  1932. Displays an error for the function/operator $name and text $txt.
  1933. */
  1934. function error( $name, $txt, $placement = false )
  1935. {
  1936. $this->ErrorLog[] = array( 'name' => $name,
  1937. 'text' => $txt,
  1938. 'placement' => $placement );
  1939. if ( !is_string( $placement ) )
  1940. $placementText = $this->placementText( $placement );
  1941. else
  1942. $placementText = $placement;
  1943. if ( $name != "" )
  1944. $nameText = "eZTemplate:$name";
  1945. else
  1946. $nameText = "eZTemplate";
  1947. eZDebug::writeError( $txt, $nameText . $placementText );
  1948. $hasAppendWarning =& $GLOBALS['eZTemplateHasAppendWarning'];
  1949. $ini = $this->ini();
  1950. if ( $ini->variable( 'ControlSettings', 'DisplayWarnings' ) == 'enabled' )
  1951. {
  1952. if ( !isset( $hasAppendWarning ) or
  1953. !$hasAppendWarning )
  1954. {
  1955. if ( function_exists( 'eZAppendWarningItem' ) )
  1956. {
  1957. eZAppendWarningItem( array( 'error' => array( 'type' => 'template',
  1958. 'number' => eZTemplate::FILE_ERRORS ),
  1959. 'text' => ezpI18n::tr( 'lib/eztemplate', 'Some template errors occurred, see debug for more information.' ) ) );
  1960. $hasAppendWarning = true;
  1961. }
  1962. }
  1963. }
  1964. }
  1965. function operatorInputSupported( $operatorName )
  1966. {
  1967. }
  1968. /*!
  1969. Sets the original text for uri $uri to $text.
  1970. */
  1971. function setIncludeText( $uri, $text )
  1972. {
  1973. $this->IncludeText[$uri] = $text;
  1974. }
  1975. /*!
  1976. Sets the output for uri $uri to $output.
  1977. */
  1978. function setIncludeOutput( $uri, $output )
  1979. {
  1980. $this->IncludeOutput[$uri] = $output;
  1981. }
  1982. /*!
  1983. \return the path list which is used for autoloading functions and operators.
  1984. */
  1985. function autoloadPathList()
  1986. {
  1987. return $this->AutoloadPathList;
  1988. }
  1989. /*!
  1990. Sets the path list for autoloading.
  1991. */
  1992. function setAutoloadPathList( $pathList )
  1993. {
  1994. $this->AutoloadPathList = $pathList;
  1995. }
  1996. /*!
  1997. Looks trough the pathes specified in autoloadPathList() and fetches autoload
  1998. definition files used for autoloading functions and operators.
  1999. */
  2000. function autoload()
  2001. {
  2002. $pathList = $this->autoloadPathList();
  2003. foreach ( $pathList as $path )
  2004. {
  2005. $autoloadFile = $path . 'eztemplateautoload.php';
  2006. if ( file_exists( $autoloadFile ) )
  2007. {
  2008. unset( $eZTemplateOperatorArray );
  2009. unset( $eZTemplateFunctionArray );
  2010. include( $autoloadFile );
  2011. if ( isset( $eZTemplateOperatorArray ) &&
  2012. is_array( $eZTemplateOperatorArray ) )
  2013. {
  2014. foreach ( $eZTemplateOperatorArray as $operatorDefinition )
  2015. {
  2016. $this->registerAutoloadOperators( $operatorDefinition );
  2017. }
  2018. }
  2019. if ( isset( $eZTemplateFunctionArray ) &&
  2020. is_array( $eZTemplateFunctionArray ) )
  2021. {
  2022. foreach ( $eZTemplateFunctionArray as $functionDefinition )
  2023. {
  2024. $this->registerAutoloadFunctions( $functionDefinition );
  2025. }
  2026. }
  2027. }
  2028. else
  2029. {
  2030. eZDebug::writeWarning( "Path '$path' does not have the file 'eztemplateautoload.php' allthough it reported it had one.\n" .
  2031. "Looked for file '" . $autoloadFile . "'\n" .
  2032. "Check the setting [TemplateSettings]/ExtensionAutoloadPath or AutoloadPathList in your site.ini settings." );
  2033. }
  2034. }
  2035. }
  2036. /*!
  2037. Resets all template variables.
  2038. */
  2039. function resetVariables()
  2040. {
  2041. $this->Variables = array();
  2042. }
  2043. /*!
  2044. Resets all template functions and operators by calling the resetFunction and resetOperator
  2045. on all elements that supports it.
  2046. */
  2047. function resetElements()
  2048. {
  2049. foreach ( $this->Functions as $functionName => $functionObject )
  2050. {
  2051. if ( is_object( $functionObject ) and
  2052. method_exists( $functionObject, 'resetFunction' ) )
  2053. {
  2054. $functionObject->resetFunction( $functionName );
  2055. }
  2056. }
  2057. foreach ( $this->Operators as $operatorName => $operatorObject )
  2058. {
  2059. if ( is_object( $operatorObject ) and
  2060. method_exists( $operatorObject, 'resetOperator' ) )
  2061. {
  2062. $operatorObject->resetOperator( $operatorName );
  2063. }
  2064. }
  2065. }
  2066. /*!
  2067. Resets all template variables, functions, operators and error counts.
  2068. */
  2069. function reset()
  2070. {
  2071. $this->resetVariables();
  2072. $this->resetElements();
  2073. $this->IsCachingAllowed = true;
  2074. $this->resetErrorLog();
  2075. $this->TemplatesUsageStatistics = array();
  2076. $this->TemplateFetchList = array();
  2077. }
  2078. /*!
  2079. \return The number of errors that occured with the last fetch
  2080. \sa hasErrors()
  2081. */
  2082. function errorCount()
  2083. {
  2084. return count( $this->ErrorLog );
  2085. }
  2086. /*!
  2087. \return \ true if errors occured with the last fetch.
  2088. \sa errorCount()
  2089. */
  2090. function hasErrors()
  2091. {
  2092. return $this->errorCount() > 0;
  2093. }
  2094. /*!
  2095. \return error log.
  2096. \sa errorCount()
  2097. */
  2098. function errorLog()
  2099. {
  2100. return $this->ErrorLog;
  2101. }
  2102. /*!
  2103. \return The number of warnings that occured with the last fetch
  2104. \sa hasWarnings()
  2105. */
  2106. function warningCount()
  2107. {
  2108. return count( $this->WarningLog );
  2109. }
  2110. /*!
  2111. \return \ true if warnings occured with the last fetch.
  2112. \sa warningCount()
  2113. */
  2114. function hasWarnings()
  2115. {
  2116. return $this->warningCount() > 0;
  2117. }
  2118. /*!
  2119. \return waring log.
  2120. \sa warningCount()
  2121. */
  2122. function warningLog()
  2123. {
  2124. return $this->WarningLog;
  2125. }
  2126. /**
  2127. * Returns a shared instance of the eZTemplate class.
  2128. *
  2129. * @return eZTemplate
  2130. */
  2131. public static function instance()
  2132. {
  2133. if ( self::$instance === null )
  2134. {
  2135. self::$instance = new eZTemplate();
  2136. }
  2137. return self::$instance;
  2138. }
  2139. /**
  2140. * Returns a shared instance of the eZTemplate class with
  2141. * default settings applied, like:
  2142. * - Autoload operators loaded
  2143. * - Debug mode set
  2144. * - eZTemplateDesignResource::instance registered
  2145. *
  2146. * @since 4.3
  2147. * @return eZTemplate
  2148. */
  2149. public static function factory()
  2150. {
  2151. if ( self::$factory === false )
  2152. {
  2153. $instance = self::instance();
  2154. $ini = eZINI::instance();
  2155. if ( $ini->variable( 'TemplateSettings', 'Debug' ) == 'enabled' )
  2156. eZTemplate::setIsDebugEnabled( true );
  2157. $compatAutoLoadPath = $ini->variableArray( 'TemplateSettings', 'AutoloadPath' );
  2158. $autoLoadPathList = $ini->variable( 'TemplateSettings', 'AutoloadPathList' );
  2159. $extensionAutoloadPath = $ini->variable( 'TemplateSettings', 'ExtensionAutoloadPath' );
  2160. $extensionPathList = eZExtension::expandedPathList( $extensionAutoloadPath, 'autoloads/' );
  2161. $autoLoadPathList = array_unique( array_merge( $compatAutoLoadPath, $autoLoadPathList, $extensionPathList ) );
  2162. $instance->setAutoloadPathList( $autoLoadPathList );
  2163. $instance->autoload();
  2164. $instance->registerResource( eZTemplateDesignResource::instance() );
  2165. self::$factory = true;
  2166. }
  2167. return self::instance();
  2168. }
  2169. /**
  2170. * Reset shared instance of the eZTemplate class and factory flag
  2171. * as used by {@link eZTemplate::instance()} and {@link eZTemplate::factory()}
  2172. *
  2173. * @since 4.3
  2174. */
  2175. public static function resetInstance()
  2176. {
  2177. self::$instance = null;
  2178. self::$factory = false;
  2179. }
  2180. /**
  2181. * Returns the eZINI object instance for the template.ini file.
  2182. *
  2183. * @return eZINI
  2184. */
  2185. public function ini()
  2186. {
  2187. return eZINI::instance( "template.ini" );
  2188. }
  2189. /*!
  2190. \static
  2191. \return true if special XHTML code should be included before the included template file.
  2192. This code will display the template filename in the browser but will eventually
  2193. break the design.
  2194. */
  2195. static function isXHTMLCodeIncluded()
  2196. {
  2197. if ( !isset( $GLOBALS['eZTemplateDebugXHTMLCodeEnabled'] ) )
  2198. {
  2199. $ini = eZINI::instance();
  2200. $GLOBALS['eZTemplateDebugXHTMLCodeEnabled'] = $ini->variable( 'TemplateSettings', 'ShowXHTMLCode' ) == 'enabled';
  2201. }
  2202. return $GLOBALS['eZTemplateDebugXHTMLCodeEnabled'];
  2203. }
  2204. /*!
  2205. \static
  2206. \return \c true if debug output of template functions and operators should be enabled.
  2207. */
  2208. static function isMethodDebugEnabled()
  2209. {
  2210. if ( !isset( $GLOBALS['eZTemplateDebugMethodEnabled'] ) )
  2211. {
  2212. $ini = eZINI::instance();
  2213. $GLOBALS['eZTemplateDebugMethodEnabled'] = $ini->variable( 'TemplateSettings', 'ShowMethodDebug' ) == 'enabled';
  2214. }
  2215. return $GLOBALS['eZTemplateDebugMethodEnabled'];
  2216. }
  2217. /*!
  2218. \static
  2219. \return true if debugging of internals is enabled, this will display
  2220. which files are loaded and when cache files are created.
  2221. Set the option with setIsDebugEnabled().
  2222. */
  2223. static function isDebugEnabled()
  2224. {
  2225. if ( !isset( $GLOBALS['eZTemplateDebugInternalsEnabled'] ) )
  2226. $GLOBALS['eZTemplateDebugInternalsEnabled'] = eZTemplate::DEBUG_INTERNALS;
  2227. return $GLOBALS['eZTemplateDebugInternalsEnabled'];
  2228. }
  2229. /*!
  2230. \static
  2231. Sets whether internal debugging is enabled or not.
  2232. */
  2233. static function setIsDebugEnabled( $debug )
  2234. {
  2235. $GLOBALS['eZTemplateDebugInternalsEnabled'] = $debug;
  2236. }
  2237. /*!
  2238. \return \c true if caching is allowed (default) or \c false otherwise.
  2239. This also affects template compiling.
  2240. \sa setIsCachingAllowed
  2241. */
  2242. function isCachingAllowed()
  2243. {
  2244. return $this->IsCachingAllowed;
  2245. }
  2246. /*!
  2247. Sets whether caching/compiling is allowed or not. This is useful
  2248. if you need to make sure templates are parsed and processed
  2249. without any caching mechanisms.
  2250. \note The default is to allow caching.
  2251. \sa isCachingAllowed
  2252. */
  2253. function setIsCachingAllowed( $allowed )
  2254. {
  2255. $this->IsCachingAllowed = $allowed;
  2256. }
  2257. /*!
  2258. \static
  2259. \return \c true if templates usage statistics should be enabled.
  2260. */
  2261. static function isTemplatesUsageStatisticsEnabled()
  2262. {
  2263. if ( !isset( $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] ) )
  2264. {
  2265. $ini = eZINI::instance();
  2266. $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] = $ini->variable( 'TemplateSettings', 'ShowUsedTemplates' ) == 'enabled';
  2267. }
  2268. return ( $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] );
  2269. }
  2270. /*!
  2271. \static
  2272. Sets whether templates usage statistics enabled or not.
  2273. \return \c true if templates usage statistics was enabled, otherwise \c false.
  2274. */
  2275. function setIsTemplatesUsageStatisticsEnabled( $enabled )
  2276. {
  2277. $wasEnabled = false;
  2278. if( isset( $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] ) )
  2279. $wasEnabled = $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'];
  2280. $GLOBALS['eZTemplateDebugTemplatesUsageStatisticsEnabled'] = $enabled;
  2281. return $wasEnabled;
  2282. }
  2283. /*!
  2284. \static
  2285. Checks settings and if 'ShowUsedTemplates' is enabled appends template info to stats.
  2286. */
  2287. function appendTemplateToStatisticsIfNeeded( &$templateName, &$templateFileName )
  2288. {
  2289. if ( eZTemplate::isTemplatesUsageStatisticsEnabled() )
  2290. eZTemplate::appendTemplateToStatistics( $templateName, $templateFileName );
  2291. }
  2292. /*!
  2293. \static
  2294. Appends template info to stats.
  2295. */
  2296. function appendTemplateToStatistics( $templateName, $templateFileName )
  2297. {
  2298. $actualTemplateName = preg_replace( "#^[\w/]+templates/#", '', $templateFileName );
  2299. $requestedTemplateName = preg_replace( "#^[\w/]+templates/#", '', $templateName );
  2300. $tpl = eZTemplate::instance();
  2301. $needToAppend = true;
  2302. // don't add template info if it is a duplicate of previous.
  2303. $statsSize = count( $tpl->TemplatesUsageStatistics );
  2304. if ( $statsSize > 0 )
  2305. {
  2306. $lastTemplateInfo = $tpl->TemplatesUsageStatistics[$statsSize-1];
  2307. if ( $lastTemplateInfo['actual-template-name'] === $actualTemplateName &&
  2308. $lastTemplateInfo['requested-template-name'] === $requestedTemplateName &&
  2309. $lastTemplateInfo['template-filename'] === $templateFileName )
  2310. {
  2311. $needToAppend = false;
  2312. }
  2313. }
  2314. if ( $needToAppend )
  2315. {
  2316. $templateInfo = array( 'actual-template-name' => $actualTemplateName,
  2317. 'requested-template-name' => $requestedTemplateName,
  2318. 'template-filename' => $templateFileName );
  2319. $tpl->TemplatesUsageStatistics[] = $templateInfo;
  2320. }
  2321. }
  2322. /*!
  2323. Appends template info for current fetch.
  2324. */
  2325. function appendTemplateFetch( $actualTemplateName )
  2326. {
  2327. $this->TemplateFetchList[] = $actualTemplateName;
  2328. $this->TemplateFetchList = array_unique( $this->TemplateFetchList );
  2329. }
  2330. /*!
  2331. Reset error and warning logs
  2332. */
  2333. function resetErrorLog()
  2334. {
  2335. $this->ErrorLog = array();
  2336. $this->WarningLog = array();
  2337. }
  2338. /*!
  2339. \static
  2340. Returns template usage statistics
  2341. */
  2342. static function templatesUsageStatistics()
  2343. {
  2344. $tpl = eZTemplate::instance();
  2345. return $tpl->TemplatesUsageStatistics;
  2346. }
  2347. /*!
  2348. Returns template list for the last fetch.
  2349. */
  2350. function templateFetchList()
  2351. {
  2352. return $this->TemplateFetchList;
  2353. }
  2354. /*!
  2355. Set template compilation test mode.
  2356. \param true, will set template compilation in test mode ( no disc writes ).
  2357. false, will compile templates to disc
  2358. */
  2359. function setCompileTest( $val )
  2360. {
  2361. $this->TestCompile = $val;
  2362. }
  2363. /*!
  2364. Get if template session is test compile
  2365. */
  2366. function testCompile()
  2367. {
  2368. return $this->TestCompile;
  2369. }
  2370. /// \privatesection
  2371. /// Associative array of resource objects
  2372. public $Resources;
  2373. /// Reference to the default resource object
  2374. public $DefaultResource;
  2375. /// The original template text
  2376. public $Text;
  2377. /// Included texts, usually performed by custom functions
  2378. public $IncludeText;
  2379. /// Included outputs, usually performed by custom functions
  2380. public $IncludeOutput;
  2381. /// The timestamp of the template when it was last modified
  2382. public $TimeStamp;
  2383. /// The left delimiter used for parsing
  2384. public $LDelim;
  2385. /// The right delimiter used for parsing
  2386. public $RDelim;
  2387. /// The resulting object tree of the template
  2388. public $Tree;
  2389. /// An associative array of template variables
  2390. public $Variables;
  2391. /*!
  2392. Last element of this stack contains names of
  2393. all variables created in the innermost template, for them
  2394. to be destroyed after the template execution finishes.
  2395. */
  2396. public $LocalVariablesNamesStack;
  2397. // Reference to the last element of $LocalVariablesNamesStack.
  2398. public $CurrentLocalVariablesNames;
  2399. /// An associative array of operators
  2400. public $Operators;
  2401. /// An associative array of functions
  2402. public $Functions;
  2403. /// An associative array of function attributes
  2404. public $FunctionAttributes;
  2405. /// An associative array of literal tags
  2406. public $Literals;
  2407. /// True if output details is to be shown
  2408. public $ShowDetails = false;
  2409. /// \c true if caching is allowed
  2410. public $IsCachingAllowed;
  2411. /// Array containing all errors occured during a fetch
  2412. public $ErrorLog;
  2413. /// Array containing all warnings occured during a fetch
  2414. public $WarningLog;
  2415. public $AutoloadPathList;
  2416. /// include level
  2417. public $Level = 0;
  2418. public $MaxLevel = 40;
  2419. /// A list of templates used by a rendered page
  2420. public $TemplatesUsageStatistics;
  2421. // counter to make unique names for {foreach} loop variables in com
  2422. public $ForeachCounter;
  2423. public $ForCounter;
  2424. public $WhileCounter;
  2425. public $DoCounter;
  2426. public $ElseifCounter;
  2427. // Flag for setting compilation in test mode
  2428. public $TestCompile;
  2429. /**
  2430. * Singelton instance of eZTemplate used by {@link eZTemplate::instance()}
  2431. * Reset with {@link eZTemplate::resetInstance()}
  2432. *
  2433. * @var null|eZTemplate
  2434. */
  2435. protected static $instance;
  2436. /**
  2437. * Factory flag as used by {@link eZTemplate::factory()}
  2438. * Reset with {@link eZTemplate::resetInstance()}
  2439. *
  2440. * @var bool
  2441. */
  2442. protected static $factory = false;
  2443. // public $CurrentRelatedResource;
  2444. // public $CurrentRelatedTemplateName;
  2445. }
  2446. ?>