PageRenderTime 67ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/eztemplate/classes/eztemplate.php

http://github.com/ezsystems/ezpublish
PHP | 2720 lines | 1862 code | 229 blank | 629 comment | 266 complexity | 066270e1b01b7237178b8dde811833f7 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * File containing the eZTemplate class.
  4. *
  5. * @copyright Copyright (C) eZ Systems AS. All rights reserved.
  6. * @license For full copyright and license information view LICENSE file distributed with this source code.
  7. * @version //autogentag//
  8. * @package lib
  9. */
  10. /*! \defgroup eZTemplate Template system */
  11. /*!
  12. \class eZTemplate eztemplate.php
  13. \ingroup eZTemplate
  14. \brief The main manager for templates
  15. The template systems allows for separation of code and
  16. layout by moving the layout part into template files. These
  17. template files are parsed and processed with template variables set
  18. by the PHP code.
  19. The template system in itself is does not do much, it parses template files
  20. according to a rule set sets up a tree hierarchy and process the data
  21. using functions and operators. The standard template system comes with only
  22. a few functions and no operators, it is meant for these functions and operators
  23. to be specified by the users of the template system. But for simplicity a few
  24. help classes is available which can be easily enabled.
  25. The classes are:
  26. - eZTemplateDelimitFunction - Inserts the left and right delimiter which are normally parsed.
  27. - eZTemplateSectionFunction - Allows for conditional blocks and loops.
  28. - eZTemplateIncludeFunction - Includes external templates
  29. - eZTemplateSequenceFunction - Creates sequences arrays
  30. - eZTemplateSwitchFunction - Conditional output of template
  31. - eZTemplatePHPOperator - Allows for easy redirection of operator names to PHP functions.
  32. - eZTemplateLocaleOperator - Allows for locale conversions.
  33. - eZTemplateArrayOperator - Creates arrays
  34. - eZTemplateAttributeOperator - Displays contents of template variables, useful for debugging
  35. - eZTemplateImageOperator - Converts text to image
  36. - eZTemplateLogicOperator - Various logical operators for boolean handling
  37. - eZTemplateUnitOperator - Unit conversion and display
  38. To enable these functions and operator use registerFunction and registerOperator.
  39. In keeping with the spirit of being simple the template system does not know how
  40. to get the template files itself. Instead it relies on resource handlers, these
  41. handlers fetches the template files using different kind of transport mechanism.
  42. For simplicity a default resource class is available, eZTemplateFileResource fetches
  43. templates from the filesystem.
  44. The parser process consists of three passes, each pass adds a new level of complexity.
  45. The first pass strips text from template blocks which starts with a left delimiter and
  46. ends with a right delimiter (default is { and } ), and places them in an array.
  47. The second pass iterates the text and block elements and removes newlines from
  48. text before function blocks and text after function blocks.
  49. The third pass builds the tree according the function rules.
  50. Processing is done by iterating over the root of the tree, if a text block is found
  51. the text is appended to the result text. If a variable or contant is it's data is extracted
  52. and any operators found are run on it before fetching the result and appending it to
  53. the result text. If a function is found the function is called with the parameters
  54. and it's up to the function handle children if any.
  55. Constants and template variables will usually be called variables since there's little
  56. difference. A template variable expression will start with a $ and consists of a
  57. namespace (optional) a name and attribues(optional). The variable expression
  58. \verbatim $root:var.attr1 \endverbatim exists in the "root" namespace, has the name "var" and uses the
  59. attribute "attr1". Some functions will create variables on demand, to avoid name conflicts
  60. namespaces were introduced, each function will place the new variables in a namespace
  61. specified in the template file. Attribues are used for fetching parts of the variable,
  62. for instance an element in an array or data in an object. Since the syntax is the
  63. same for arrays and objects the PHP code can use simple arrays when speed is required,
  64. the template code will not care.
  65. A different syntax is also available when you want to access an attribute using a variable.
  66. For instance \verbatim $root:var[$attr_var] \endverbatim, if the variable $attr_var contains "attr1" it would
  67. access the same attribute as in the first example.
  68. The syntax for operators is a | and a name, optionally parameters can be specified with
  69. ( and ) delimited with ,. Valid operators are \verbatim |upcase, |l10n(date) \endverbatim.
  70. Functions look a lot like HTML/XML tags. The function consists of a name and parameters
  71. which are assigned using the param=value syntax. Some parameters may be required while
  72. others may be optionally, the exact behaviour is specified by each function.
  73. Valid functions are \verbatim "section name=abc loop=4" \endverbatim
  74. Example of usage:
  75. \code
  76. // Init template
  77. $tpl = eZTemplate::instance();
  78. $tpl->registerOperators( new eZTemplatePHPOperator( array( "upcase" => "strtoupper",
  79. "reverse" => "strrev" ) ) );
  80. $tpl->registerOperators( new eZTemplateLocaleOperator() );
  81. $tpl->registerFunction( "section", new eZTemplateSectionFunction( "section" ) );
  82. $tpl->registerFunctions( new eZTemplateDelimitFunction() );
  83. $tpl->setVariable( "my_var", "{this value set by variable}", "test" );
  84. $tpl->setVariable( "my_arr", array( "1st", "2nd", "third", "fjerde" ) );
  85. $tpl->setVariable( "multidim", array( array( "a", "b" ),
  86. array( "c", "d" ),
  87. array( "e", "f" ),
  88. array( "g", "h" ) ) );
  89. class mytest
  90. {
  91. function mytest( $n, $s )
  92. {
  93. $this->n = $n;
  94. $this->s = $s;
  95. }
  96. function hasAttribute( $attr )
  97. {
  98. return ( $attr == "name" || $attr == "size" );
  99. }
  100. function attribute( $attr )
  101. {
  102. switch ( $attr )
  103. {
  104. case "name";
  105. return $this->n;
  106. case "size";
  107. return $this->s;
  108. default:
  109. $retAttr = null;
  110. return $retAttr;
  111. }
  112. }
  113. }
  114. $tpl->setVariable( "multidim_obj", array( new mytest( "jan", 200 ),
  115. new mytest( "feb", 200 ),
  116. new mytest( "john", 200 ),
  117. new mytest( "doe", 50 ) ) );
  118. $tpl->setVariable( "curdate", time() );
  119. $tpl->display( "lib/eztemplate/example/test.tpl" );
  120. // test.tpl
  121. {section name=outer loop=4}
  122. 123
  123. {delimit}::{/delimit}
  124. {/section}
  125. {literal test=1} This is some {blah arg1="" arg2="abc" /} {/literal}
  126. <title>This is a test</title>
  127. <table border="1">
  128. <tr><th>{$test:my_var}
  129. {"some text!!!"|upcase|reverse}</th></tr>
  130. {section name=abc loop=$my_arr}
  131. <tr><td>{$abc:item}</td></tr>
  132. {/section}
  133. </table>
  134. <table border="1">
  135. {section name=outer loop=$multidim}
  136. <tr>
  137. {section name=inner loop=$outer:item}
  138. <td>{$inner:item}</td>
  139. {/section}
  140. </tr>
  141. {/section}
  142. </table>
  143. <table border="1">
  144. {section name=outer loop=$multidim_obj}
  145. <tr>
  146. <td>{$outer:item.name}</td>
  147. <td>{$outer:item.size}</td>
  148. </tr>
  149. {/section}
  150. </table>
  151. {section name=outer loop=$nonexistingvar}
  152. <b><i>Dette skal ikke vises</b></i>
  153. {section-else}
  154. <b><i>This is shown when the {ldelim}$loop{rdelim} variable is non-existant</b></i>
  155. {/section}
  156. Denne koster {1.4|l10n(currency)}<br>
  157. {-123456789|l10n(number)}<br>
  158. {$curdate|l10n(date)}<br>
  159. {$curdate|l10n(shortdate)}<br>
  160. {$curdate|l10n(time)}<br>
  161. {$curdate|l10n(shorttime)}<br>
  162. {include file="test2.tpl"/}
  163. \endcode
  164. */
  165. class eZTemplate
  166. {
  167. const RESOURCE_FETCH = 1;
  168. const RESOURCE_QUERY = 2;
  169. const ELEMENT_TEXT = 1;
  170. const ELEMENT_SINGLE_TAG = 2;
  171. const ELEMENT_NORMAL_TAG = 3;
  172. const ELEMENT_END_TAG = 4;
  173. const ELEMENT_VARIABLE = 5;
  174. const ELEMENT_COMMENT = 6;
  175. const NODE_ROOT = 1;
  176. const NODE_TEXT = 2;
  177. const NODE_VARIABLE = 3;
  178. const NODE_FUNCTION = 4;
  179. const NODE_OPERATOR = 5;
  180. const NODE_INTERNAL = 100;
  181. const NODE_INTERNAL_CODE_PIECE = 101;
  182. const NODE_INTERNAL_VARIABLE_SET = 105;
  183. const NODE_INTERNAL_VARIABLE_UNSET = 102;
  184. const NODE_INTERNAL_NAMESPACE_CHANGE = 103;
  185. const NODE_INTERNAL_NAMESPACE_RESTORE = 104;
  186. const NODE_INTERNAL_WARNING = 120;
  187. const NODE_INTERNAL_ERROR = 121;
  188. const NODE_INTERNAL_RESOURCE_ACQUISITION = 140;
  189. const NODE_OPTIMIZED_RESOURCE_ACQUISITION = 141;
  190. const NODE_INTERNAL_OUTPUT_ASSIGN = 150;
  191. const NODE_INTERNAL_OUTPUT_READ = 151;
  192. const NODE_INTERNAL_OUTPUT_INCREASE = 152;
  193. const NODE_INTERNAL_OUTPUT_DECREASE = 153;
  194. const NODE_INTERNAL_OUTPUT_SPACING_INCREASE = 160;
  195. const NODE_INTERNAL_SPACING_DECREASE = 161;
  196. const NODE_OPTIMIZED_INIT = 201;
  197. const NODE_USER_CUSTOM = 1000;
  198. const TYPE_VOID = 0;
  199. const TYPE_STRING = 1;
  200. const TYPE_NUMERIC = 2;
  201. const TYPE_IDENTIFIER = 3;
  202. const TYPE_VARIABLE = 4;
  203. const TYPE_ATTRIBUTE = 5;
  204. const TYPE_OPERATOR = 6;
  205. const TYPE_BOOLEAN = 7;
  206. const TYPE_ARRAY = 8;
  207. const TYPE_DYNAMIC_ARRAY = 9;
  208. const TYPE_INTERNAL = 100;
  209. const TYPE_INTERNAL_CODE_PIECE = 101;
  210. const TYPE_PHP_VARIABLE = 102;
  211. const TYPE_OPTIMIZED_NODE = 201;
  212. const TYPE_OPTIMIZED_ARRAY_LOOKUP = 202;
  213. const TYPE_OPTIMIZED_CONTENT_CALL = 203;
  214. const TYPE_OPTIMIZED_ATTRIBUTE_LOOKUP = 204;
  215. const TYPE_INTERNAL_STOP = 999;
  216. const TYPE_STRING_BIT = 1;
  217. const TYPE_NUMERIC_BIT = 2;
  218. const TYPE_IDENTIFIER_BIT = 4;
  219. const TYPE_VARIABLE_BIT = 8;
  220. const TYPE_ATTRIBUTE_BIT = 16;
  221. const TYPE_OPERATOR_BIT = 32;
  222. const TYPE_NONE = 0;
  223. const TYPE_ALL = 63;
  224. const TYPE_BASIC = 47;
  225. const TYPE_MODIFIER_MASK = 48;
  226. const NAMESPACE_SCOPE_GLOBAL = 1;
  227. const NAMESPACE_SCOPE_LOCAL = 2;
  228. const NAMESPACE_SCOPE_RELATIVE = 3;
  229. const DEBUG_INTERNALS = false;
  230. const FILE_ERRORS = 1;
  231. /**
  232. * Intializes the template with left and right delimiters being { and }, and a file resource.
  233. * The literal tag "literal" is also registered.
  234. */
  235. public function __construct()
  236. {
  237. $this->Tree = array( eZTemplate::NODE_ROOT, false );
  238. $this->LDelim = "{";
  239. $this->RDelim = "}";
  240. $this->IncludeText = array();
  241. $this->IncludeOutput = array();
  242. $this->registerLiteral( "literal" );
  243. $res = new eZTemplateFileResource();
  244. $this->DefaultResource = $res;
  245. $this->registerResource( $res );
  246. $this->Resources = array();
  247. $this->Text = null;
  248. $this->IsCachingAllowed = true;
  249. $this->resetErrorLog();
  250. $this->AutoloadPathList = array( 'lib/eztemplate/classes/' );
  251. $this->Variables = array();
  252. $this->LocalVariablesNamesStack = array();
  253. $this->CurrentLocalVariablesNames = null;
  254. $this->Functions = array();
  255. $this->FunctionAttributes = array();
  256. $this->TestCompile = false;
  257. $ini = eZINI::instance( 'template.ini' );
  258. if ( $ini->hasVariable( 'ControlSettings', 'MaxLevel' ) )
  259. $this->MaxLevel = $ini->variable( 'ControlSettings', 'MaxLevel' );
  260. $this->MaxLevelWarning = ezpI18n::tr( 'lib/template',
  261. 'The maximum nesting level of %max has been reached. The execution is stopped to avoid infinite recursion.',
  262. '',
  263. array( '%max' => $this->MaxLevel ) );
  264. eZDebug::createAccumulatorGroup( 'template_total', 'Template Total' );
  265. $this->TemplatesUsageStatistics = array();
  266. // Array of templates which are used in a single fetch()
  267. $this->TemplateFetchList = array();
  268. $this->ForeachCounter = 0;
  269. $this->ForCounter = 0;
  270. $this->WhileCounter = 0;
  271. $this->DoCounter = 0;
  272. $this->ElseifCounter = 0;
  273. }
  274. /*!
  275. Returns the left delimiter being used.
  276. */
  277. function leftDelimiter()
  278. {
  279. return $this->LDelim;
  280. }
  281. /*!
  282. Returns the right delimiter being used.
  283. */
  284. function rightDelimiter()
  285. {
  286. return $this->RDelim;
  287. }
  288. /*!
  289. Sets the left delimiter.
  290. */
  291. function setLeftDelimiter( $delim )
  292. {
  293. $this->LDelim = $delim;
  294. }
  295. /*!
  296. Sets the right delimiter.
  297. */
  298. function setRightDelimiter( $delim )
  299. {
  300. $this->RDelim = $delim;
  301. }
  302. /*!
  303. Fetches the result of the template file and displays it.
  304. If $template is supplied it will load this template file first.
  305. */
  306. function display( $template = false, $extraParameters = false )
  307. {
  308. $output = $this->fetch( $template, $extraParameters );
  309. if ( $this->ShowDetails )
  310. {
  311. echo '<h1>Result:</h1>' . "\n";
  312. echo '<hr/>' . "\n";
  313. }
  314. echo "$output";
  315. if ( $this->ShowDetails )
  316. {
  317. echo '<hr/>' . "\n";
  318. }
  319. if ( $this->ShowDetails )
  320. {
  321. echo "<h1>Template data:</h1>";
  322. echo "<p class=\"filename\">" . $template . "</p>";
  323. echo "<pre class=\"example\">" . htmlspecialchars( $this->Text ) . "</pre>";
  324. reset( $this->IncludeText );
  325. while ( ( $key = key( $this->IncludeText ) ) !== null )
  326. {
  327. $item = $this->IncludeText[$key];
  328. echo "<p class=\"filename\">" . $key . "</p>";
  329. echo "<pre class=\"example\">" . htmlspecialchars( $item ) . "</pre>";
  330. next( $this->IncludeText );
  331. }
  332. echo "<h1>Result text:</h1>";
  333. echo "<p class=\"filename\">" . $template . "</p>";
  334. echo "<pre class=\"example\">" . htmlspecialchars( $output ) . "</pre>";
  335. reset( $this->IncludeOutput );
  336. while ( ( $key = key( $this->IncludeOutput ) ) !== null )
  337. {
  338. $item = $this->IncludeOutput[$key];
  339. echo "<p class=\"filename\">" . $key . "</p>";
  340. echo "<pre class=\"example\">" . htmlspecialchars( $item ) . "</pre>";
  341. next( $this->IncludeOutput );
  342. }
  343. }
  344. }
  345. /*!
  346. * Initialize list of local variables for the current template.
  347. * The list contains only names of variables.
  348. */
  349. function createLocalVariablesList()
  350. {
  351. $this->LocalVariablesNamesStack[] = array();
  352. $this->CurrentLocalVariablesNames =& $this->LocalVariablesNamesStack[ count( $this->LocalVariablesNamesStack ) - 1];
  353. }
  354. /*!
  355. * Check if the given local variable exists.
  356. */
  357. function hasLocalVariable( $varName, $rootNamespace )
  358. {
  359. return ( array_key_exists( $rootNamespace, $this->CurrentLocalVariablesNames ) &&
  360. array_key_exists( $varName, $this->CurrentLocalVariablesNames[$rootNamespace] ) );
  361. }
  362. /*!
  363. * Create a local variable.
  364. */
  365. function setLocalVariable( $varName, $varValue, $rootNamespace )
  366. {
  367. $this->CurrentLocalVariablesNames[$rootNamespace][$varName] = 1;
  368. $this->setVariable( $varName, $varValue, $rootNamespace );
  369. }
  370. /*!
  371. * Destroy a local variable.
  372. */
  373. function unsetLocalVariable( $varName, $rootNamespace )
  374. {
  375. if ( !$this->hasLocalVariable( $varName, $rootNamespace ) )
  376. return;
  377. $this->unsetVariable( $varName, $rootNamespace );
  378. unset( $this->CurrentLocalVariablesNames[$rootNamespace][$varName] );
  379. }
  380. /*!
  381. * Destroy all local variables defined in the current template.
  382. */
  383. function unsetLocalVariables()
  384. {
  385. foreach ( $this->CurrentLocalVariablesNames as $ns => $vars )
  386. {
  387. foreach ( $vars as $var => $val )
  388. $this->unsetLocalVariable( $var, $ns );
  389. }
  390. }
  391. /*!
  392. * Destroy list of local variables defined in the current (innermost) template.
  393. */
  394. function destroyLocalVariablesList()
  395. {
  396. array_pop( $this->LocalVariablesNamesStack );
  397. if ( $this->LocalVariablesNamesStack )
  398. $this->CurrentLocalVariablesNames =& $this->LocalVariablesNamesStack[ count( $this->LocalVariablesNamesStack ) - 1];
  399. else
  400. unset( $this->CurrentLocalVariablesNames );
  401. }
  402. /*!
  403. Tries to fetch the result of the template file and returns it.
  404. If $template is supplied it will load this template file first.
  405. */
  406. function fetch( $template = false, $extraParameters = false, $returnResourceData = false )
  407. {
  408. $this->resetErrorLog();
  409. // Reset fetch list when a new fetch is started
  410. $this->TemplateFetchList = array();
  411. eZDebug::accumulatorStart( 'template_total' );
  412. eZDebug::accumulatorStart( 'template_load', 'template_total', 'Template load' );
  413. $root = null;
  414. if ( is_string( $template ) )
  415. {
  416. $resourceData = $this->loadURIRoot( $template, true, $extraParameters );
  417. if ( $resourceData and
  418. $resourceData['root-node'] !== null )
  419. $root =& $resourceData['root-node'];
  420. }
  421. eZDebug::accumulatorStop( 'template_load' );
  422. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  423. {
  424. $savedLocale = setlocale( LC_CTYPE, null );
  425. setlocale( LC_CTYPE, $resourceData['locales'] );
  426. }
  427. $text = "";
  428. if ( $root !== null or
  429. $resourceData['compiled-template'] )
  430. {
  431. if ( $this->ShowDetails )
  432. eZDebug::addTimingPoint( "Process" );
  433. eZDebug::accumulatorStart( 'template_processing', 'template_total', 'Template processing' );
  434. $templateCompilationUsed = false;
  435. if ( $resourceData['compiled-template'] )
  436. {
  437. $textElements = array();
  438. if ( $this->executeCompiledTemplate( $resourceData, $textElements, "", "", $extraParameters ) )
  439. {
  440. $text = implode( '', $textElements );
  441. $templateCompilationUsed = true;
  442. }
  443. }
  444. if ( !$templateCompilationUsed )
  445. {
  446. if ( eZTemplate::isDebugEnabled() )
  447. {
  448. $fname = $resourceData['template-filename'];
  449. eZDebug::writeDebug( "FETCH START URI: $template, $fname" );
  450. }
  451. $this->process( $root, $text, "", "" );
  452. if ( eZTemplate::isDebugEnabled() )
  453. eZDebug::writeDebug( "FETCH END URI: $template, $fname" );
  454. }
  455. eZDebug::accumulatorStop( 'template_processing' );
  456. if ( $this->ShowDetails )
  457. eZDebug::addTimingPoint( "Process done" );
  458. }
  459. eZDebug::accumulatorStop( 'template_total' );
  460. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  461. {
  462. setlocale( LC_CTYPE, $savedLocale );
  463. }
  464. if ( $returnResourceData )
  465. {
  466. $resourceData['result_text'] = $text;
  467. return $resourceData;
  468. }
  469. return $text;
  470. }
  471. function process( $root, &$text, $rootNamespace, $currentNamespace )
  472. {
  473. $this->createLocalVariablesList();
  474. $textElements = array();
  475. $this->processNode( $root, $textElements, $rootNamespace, $currentNamespace );
  476. if ( is_array( $textElements ) )
  477. $text = implode( '', $textElements );
  478. else
  479. $text = $textElements;
  480. $this->unsetLocalVariables();
  481. $this->destroyLocalVariablesList();
  482. }
  483. function processNode( $node, &$textElements, $rootNamespace, $currentNamespace )
  484. {
  485. $rslt = null;
  486. $nodeType = $node[0];
  487. if ( $nodeType == eZTemplate::NODE_ROOT )
  488. {
  489. $children = $node[1];
  490. if ( $children )
  491. {
  492. foreach ( $children as $child )
  493. {
  494. $this->processNode( $child, $textElements, $rootNamespace, $currentNamespace );
  495. if ( !is_array( $textElements ) )
  496. eZDebug::writeError( "Textelements is no longer array: '$textElements'", __METHOD__ . '::root' );
  497. }
  498. }
  499. }
  500. else if ( $nodeType == eZTemplate::NODE_TEXT )
  501. {
  502. $textElements[] = $node[2];
  503. }
  504. else if ( $nodeType == eZTemplate::NODE_VARIABLE )
  505. {
  506. $variableData = $node[2];
  507. $variablePlacement = $node[3];
  508. $this->processVariable( $textElements, $variableData, $variablePlacement, $rootNamespace, $currentNamespace );
  509. if ( !is_array( $textElements ) )
  510. eZDebug::writeError( "Textelements is no longer array: '$textElements'", __METHOD__ . '::variable' );
  511. }
  512. else if ( $nodeType == eZTemplate::NODE_FUNCTION )
  513. {
  514. $functionChildren = $node[1];
  515. $functionName = $node[2];
  516. $functionParameters = $node[3];
  517. $functionPlacement = $node[4];
  518. $rslt = $this->processFunction( $functionName, $textElements, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace );
  519. if ( !is_array( $textElements ) )
  520. eZDebug::writeError( "Textelements is no longer array: '$textElements'", __METHOD__ . "::function( '$functionName' )" );
  521. }
  522. return $rslt;
  523. }
  524. function processVariable( &$textElements, $variableData, $variablePlacement, $rootNamespace, $currentNamespace )
  525. {
  526. $value = $this->elementValue( $variableData, $rootNamespace, $currentNamespace, $variablePlacement );
  527. $this->appendElementText( $textElements, $value, $rootNamespace, $currentNamespace );
  528. }
  529. function processFunction( $functionName, &$textElements, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace )
  530. {
  531. // Note: This code piece is replicated in the eZTemplateCompiler,
  532. // if this code is changed the replicated code must be updated as well.
  533. $func = $this->Functions[$functionName];
  534. if ( is_array( $func ) )
  535. {
  536. $this->loadAndRegisterFunctions( $this->Functions[$functionName] );
  537. $func = $this->Functions[$functionName];
  538. }
  539. if ( isset( $func ) and
  540. is_object( $func ) )
  541. {
  542. if ( eZTemplate::isMethodDebugEnabled() )
  543. eZDebug::writeDebug( "START FUNCTION: $functionName" );
  544. $value = $func->process( $this, $textElements, $functionName, $functionChildren, $functionParameters, $functionPlacement, $rootNamespace, $currentNamespace );
  545. if ( eZTemplate::isMethodDebugEnabled() )
  546. eZDebug::writeDebug( "END FUNCTION: $functionName" );
  547. return $value;
  548. }
  549. else
  550. {
  551. $this->warning( "", "Function \"$functionName\" is not registered" );
  552. return null;
  553. }
  554. }
  555. function fetchFunctionObject( $functionName )
  556. {
  557. $func = $this->Functions[$functionName];
  558. if ( is_array( $func ) )
  559. {
  560. $this->loadAndRegisterFunctions( $this->Functions[$functionName] );
  561. $func = $this->Functions[$functionName];
  562. }
  563. return $func;
  564. }
  565. /*!
  566. Loads the template using the URI $uri and parses it.
  567. \return The root node of the tree if \a $returnResourceData is false,
  568. if \c true the entire resource data structure.
  569. */
  570. function load( $uri, $extraParameters = false, $returnResourceData = false )
  571. {
  572. $resourceData = $this->loadURIRoot( $uri, true, $extraParameters );
  573. if ( !$resourceData or
  574. $resourceData['root-node'] === null )
  575. {
  576. $retValue = null;
  577. return $retValue;
  578. }
  579. else
  580. return $resourceData['root-node'];
  581. }
  582. function parse( $sourceText, &$rootElement, $rootNamespace, &$resourceData )
  583. {
  584. $parser = eZTemplateMultiPassParser::instance();
  585. $parser->parse( $this, $sourceText, $rootElement, $rootNamespace, $resourceData );
  586. }
  587. function loadURIData( $resourceObject, $uri, $resourceName, $template, &$extraParameters, $displayErrors = true )
  588. {
  589. $resourceData = $this->resourceData( $resourceObject, $uri, $resourceName, $template );
  590. $resourceData['text'] = null;
  591. $resourceData['root-node'] = null;
  592. $resourceData['compiled-template'] = false;
  593. $resourceData['time-stamp'] = null;
  594. $resourceData['key-data'] = null;
  595. $resourceData['locales'] = null;
  596. if ( !$resourceObject->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters ) )
  597. {
  598. $resourceData = null;
  599. if ( $displayErrors )
  600. $this->warning( "", "No template could be loaded for \"$template\" using resource \"$resourceName\"" );
  601. }
  602. return $resourceData;
  603. }
  604. /*!
  605. \static
  606. Creates a resource data structure of the parameters and returns it.
  607. This structure is passed to various parts of the template system.
  608. \note If you only have the URI you should call resourceFor() first to
  609. figure out the resource handler.
  610. */
  611. function resourceData( $resourceObject, $uri, $resourceName, $templateName )
  612. {
  613. $resourceData = array();
  614. $resourceData['uri'] = $uri;
  615. $resourceData['resource'] = $resourceName;
  616. $resourceData['template-name'] = $templateName;
  617. $resourceData['template-filename'] = $templateName;
  618. $resourceData['handler'] = $resourceObject;
  619. $resourceData['test-compile'] = $this->TestCompile;
  620. return $resourceData;
  621. }
  622. /*!
  623. Loads the template using the URI $uri and returns a structure with the text and timestamp,
  624. false otherwise.
  625. The structure keys are:
  626. - "text", the text.
  627. - "time-stamp", the timestamp.
  628. */
  629. function loadURIRoot( $uri, $displayErrors = true, &$extraParameters )
  630. {
  631. $res = "";
  632. $template = "";
  633. $resobj = $this->resourceFor( $uri, $res, $template );
  634. if ( !is_object( $resobj ) )
  635. {
  636. if ( $displayErrors )
  637. $this->warning( "", "No resource handler for \"$res\" and no default resource handler, aborting." );
  638. return null;
  639. }
  640. $canCache = true;
  641. if ( !$resobj->servesStaticData() )
  642. $canCache = false;
  643. if ( !$this->isCachingAllowed() )
  644. $canCache = false;
  645. $resourceData = $this->loadURIData( $resobj, $uri, $res, $template, $extraParameters, $displayErrors );
  646. if ( $resourceData )
  647. {
  648. eZTemplate::appendTemplateToStatisticsIfNeeded( $resourceData['template-name'], $resourceData['template-filename'] );
  649. $this->appendTemplateFetch( $resourceData['template-filename'] );
  650. if ( !$resourceData['compiled-template'] and
  651. $resourceData['root-node'] === null )
  652. {
  653. $resourceData['root-node'] = array( eZTemplate::NODE_ROOT, false );
  654. $templateText = $resourceData["text"];
  655. $keyData = $resourceData['key-data'];
  656. $this->setIncludeText( $uri, $templateText );
  657. $rootNamespace = '';
  658. $this->parse( $templateText, $resourceData['root-node'], $rootNamespace, $resourceData );
  659. if ( eZTemplate::isDebugEnabled() )
  660. {
  661. $this->appendDebugNodes( $resourceData['root-node'], $resourceData );
  662. }
  663. if ( $canCache )
  664. $resobj->setCachedTemplateTree( $keyData, $uri, $res, $template, $extraParameters, $resourceData['root-node'] );
  665. }
  666. if ( !$resourceData['compiled-template'] and
  667. $canCache and
  668. $this->canCompileTemplate( $resourceData, $extraParameters ) )
  669. {
  670. $generateStatus = $this->compileTemplate( $resourceData, $extraParameters );
  671. if ( $generateStatus )
  672. $resourceData['compiled-template'] = true;
  673. }
  674. }
  675. return $resourceData;
  676. }
  677. function processURI( $uri, $displayErrors = true, &$extraParameters,
  678. &$textElements, $rootNamespace, $currentNamespace )
  679. {
  680. $this->Level++;
  681. if ( $this->Level > $this->MaxLevel )
  682. {
  683. eZDebug::writeError( $this->MaxLevelWarning, __METHOD__ . " Level: $this->Level @ $uri" );
  684. $textElements[] = $this->MaxLevelWarning;
  685. $this->Level--;
  686. return;
  687. }
  688. $resourceData = $this->loadURIRoot( $uri, $displayErrors, $extraParameters );
  689. if ( !$resourceData or
  690. ( !$resourceData['compiled-template'] and
  691. $resourceData['root-node'] === null ) )
  692. {
  693. $this->Level--;
  694. return;
  695. }
  696. $templateCompilationUsed = false;
  697. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  698. {
  699. $savedLocale = setlocale( LC_CTYPE, null );
  700. setlocale( LC_CTYPE, $resourceData['locales'] );
  701. }
  702. if ( $resourceData['compiled-template'] )
  703. {
  704. if ( $this->executeCompiledTemplate( $resourceData, $textElements, $rootNamespace, $currentNamespace, $extraParameters ) )
  705. $templateCompilationUsed = true;
  706. }
  707. if ( !$templateCompilationUsed )
  708. {
  709. $text = null;
  710. if ( eZTemplate::isDebugEnabled() )
  711. {
  712. $fname = $resourceData['template-filename'];
  713. eZDebug::writeDebug( "START URI: $uri, $fname" );
  714. }
  715. $this->process( $resourceData['root-node'], $text, $rootNamespace, $currentNamespace );
  716. if ( eZTemplate::isDebugEnabled() )
  717. eZDebug::writeDebug( "END URI: $uri, $fname" );
  718. $this->setIncludeOutput( $uri, $text );
  719. $textElements[] = $text;
  720. }
  721. if ( $resourceData['locales'] && !empty( $resourceData['locales'] ) )
  722. {
  723. setlocale( LC_CTYPE, $savedLocale );
  724. }
  725. $this->Level--;
  726. }
  727. function canCompileTemplate( $resourceData, &$extraParameters )
  728. {
  729. $resourceObject = $resourceData['handler'];
  730. if ( !$resourceObject )
  731. return false;
  732. $canGenerate = $resourceObject->canCompileTemplate( $this, $resourceData, $extraParameters );
  733. return $canGenerate;
  734. }
  735. /*!
  736. Validates the template file \a $file and returns \c true if the file has correct syntax.
  737. \param $returnResourceData If \c true then the returned value will be the resourcedata structure
  738. \sa compileTemplateFile(), fetch()
  739. */
  740. function validateTemplateFile( $file, $returnResourceData = false )
  741. {
  742. $this->resetErrorLog();
  743. if ( !file_exists( $file ) )
  744. return false;
  745. $resourceHandler = $this->resourceFor( $file, $resourceName, $templateName );
  746. if ( !$resourceHandler )
  747. return false;
  748. $resourceData = $this->resourceData( $resourceHandler, $file, $resourceName, $templateName );
  749. $resourceData['key-data'] = "file:" . $file;
  750. $extraParameters = array();
  751. // Disable caching/compiling while fetchin the resource
  752. // It will be restored afterwards
  753. $isCachingAllowed = $this->IsCachingAllowed;
  754. $this->IsCachingAllowed = false;
  755. $resourceHandler->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters );
  756. // Restore previous caching flag
  757. $this->IsCachingAllowed = $isCachingAllowed;
  758. $root =& $resourceData['root-node'];
  759. $root = array( eZTemplate::NODE_ROOT, false );
  760. $templateText = $resourceData["text"];
  761. $rootNamespace = '';
  762. $this->parse( $templateText, $root, $rootNamespace, $resourceData );
  763. if ( eZTemplate::isDebugEnabled() )
  764. {
  765. $this->appendDebugNodes( $root, $resourceData );
  766. }
  767. $result = !$this->hasErrors() and !$this->hasWarnings();
  768. if ( $returnResourceData )
  769. {
  770. $resourceData['result'] = $result;
  771. $resourceData['errors'] = $this->ErrorLog();
  772. $resourceData['warnings'] = $this->WarningLog();
  773. return $resourceData;
  774. }
  775. return $result;
  776. }
  777. /*!
  778. Compiles the template file \a $file and returns \c true if the compilation was OK.
  779. \param $returnResourceData If \c true then the returned value will be the resourcedata structure
  780. \sa validateTemplateFile(), fetch()
  781. */
  782. function compileTemplateFile( $file, $returnResourceData = false )
  783. {
  784. $this->resetErrorLog();
  785. if ( !file_exists( $file ) )
  786. return false;
  787. $resourceHandler = $this->resourceFor( $file, $resourceName, $templateName );
  788. if ( !$resourceHandler )
  789. return false;
  790. $resourceData = $this->resourceData( $resourceHandler, $file, $resourceName, $templateName );
  791. $resourceData['key-data'] = "file:" . $file;
  792. $key = md5( $resourceData['key-data'] );
  793. $extraParameters = array();
  794. $resourceHandler->handleResource( $this, $resourceData, eZTemplate::RESOURCE_FETCH, $extraParameters );
  795. $isCompiled = false;
  796. if ( isset( $resourceData['compiled-template'] ) )
  797. $isCompiled = $resourceData['compiled-template'];
  798. if ( !$isCompiled )
  799. {
  800. $root =& $resourceData['root-node'];
  801. $root = array( eZTemplate::NODE_ROOT, false );
  802. $templateText = $resourceData["text"];
  803. $rootNamespace = '';
  804. $this->parse( $templateText, $root, $rootNamespace, $resourceData );
  805. if ( eZTemplate::isDebugEnabled() )
  806. {
  807. $this->appendDebugNodes( $root, $resourceData );
  808. }
  809. $result = eZTemplateCompiler::compileTemplate( $this, $key, $resourceData );
  810. }
  811. else
  812. {
  813. $result = true;
  814. }
  815. if ( $returnResourceData )
  816. {
  817. $resourceData['result'] = $result;
  818. return $resourceData;
  819. }
  820. return $result;
  821. }
  822. function compileTemplate( &$resourceData, &$extraParameters )
  823. {
  824. $resourceObject = $resourceData['handler'];
  825. if ( !$resourceObject )
  826. return false;
  827. $keyData = $resourceData['key-data'];
  828. $uri = $resourceData['uri'];
  829. $resourceName = $resourceData['resource'];
  830. $templatePath = $resourceData['template-name'];
  831. return $resourceObject->compileTemplate( $this, $keyData, $uri, $resourceName, $templatePath, $extraParameters, $resourceData );
  832. }
  833. function executeCompiledTemplate( &$resourceData, &$textElements, $rootNamespace, $currentNamespace, &$extraParameters )
  834. {
  835. $resourceObject = $resourceData['handler'];
  836. if ( !$resourceObject )
  837. return false;
  838. $keyData = $resourceData['key-data'];
  839. $uri = $resourceData['uri'];
  840. $resourceName = $resourceData['resource'];
  841. $templatePath = $resourceData['template-name'];
  842. $timestamp = $resourceData['time-stamp'];
  843. return $resourceObject->executeCompiledTemplate( $this, $textElements,
  844. $keyData, $uri, $resourceData, $templatePath,
  845. $extraParameters, $timestamp,
  846. $rootNamespace, $currentNamespace );
  847. }
  848. /*!
  849. Returns the resource object for URI $uri. If a resource type is specified
  850. in the URI it is extracted and set in $res. The template name is set in $template
  851. without any resource specifier. To specify a resource the name and a ":" is
  852. prepended to the URI, for instance file:my.tpl.
  853. If no resource type is found the URI the default resource handler is used.
  854. */
  855. function resourceFor( $uri, &$res, &$template )
  856. {
  857. $args = explode( ":", $uri );
  858. if ( isset( $args[1] ) )
  859. {
  860. $res = $args[0];
  861. $template = $args[1];
  862. }
  863. else
  864. $template = $uri;
  865. if ( eZTemplate::isDebugEnabled() )
  866. {
  867. eZDebug::writeNotice( "eZTemplate: Loading template \"$template\" with resource \"$res\"" );
  868. }
  869. if ( isset( $this->Resources[$res] ) and is_object( $this->Resources[$res] ) )
  870. {
  871. return $this->Resources[$res];
  872. }
  873. return $this->DefaultResource;
  874. }
  875. /*!
  876. \return The resource handler object for resource name \a $resourceName.
  877. \sa resourceFor
  878. */
  879. function resourceHandler( $resourceName )
  880. {
  881. if ( isset( $this->Resources[$resourceName] ) &&
  882. is_object( $this->Resources[$resourceName] ) )
  883. {
  884. return $this->Resources[$resourceName];
  885. }
  886. return $this->DefaultResource;
  887. }
  888. function hasChildren( &$function, $functionName )
  889. {
  890. $hasChildren = $function->hasChildren();
  891. if ( is_array( $hasChildren ) )
  892. return $hasChildren[$functionName];
  893. else
  894. return $hasChildren;
  895. }
  896. /*!
  897. Returns the empty variable type.
  898. */
  899. function emptyVariable()
  900. {
  901. return array( "type" => "null" );
  902. }
  903. /*!
  904. \static
  905. */
  906. function mergeNamespace( $rootNamespace, $additionalNamespace )
  907. {
  908. $namespace = $rootNamespace;
  909. if ( $namespace == '' )
  910. $namespace = $additionalNamespace;
  911. else if ( $additionalNamespace != '' )
  912. $namespace = "$namespace:$additionalNamespace";
  913. return $namespace;
  914. }
  915. /*!
  916. Returns the actual value of a template type or null if an unknown type.
  917. */
  918. function elementValue( &$dataElements, $rootNamespace, $currentNamespace, $placement = false,
  919. $checkExistance = false, $checkForProxy = false )
  920. {
  921. /*
  922. * We use a small dirty hack in this function...
  923. * To help the caller to determine if the value was a proxy object,
  924. * we store boolean true to $dataElements['proxy-object-found'] in this case.
  925. * (it's up to caller to remove this garbage from $dataElements...)
  926. * This behaviour is enabled by $checkForProxy parameter.
  927. */
  928. $value = null;
  929. if ( !is_array( $dataElements ) )
  930. {
  931. $this->error( "elementValue",
  932. "Missing array data structure, got " . gettype( $dataElements ),
  933. $placement );
  934. return null;
  935. }
  936. foreach ( $dataElements as $dataElement )
  937. {
  938. if ( $dataElement === null )
  939. {
  940. return null;
  941. }
  942. $dataType = $dataElement[0];
  943. switch ( $dataType )
  944. {
  945. case eZTemplate::TYPE_VOID:
  946. {
  947. if ( !$checkExistance )
  948. $this->warning( 'elementValue',
  949. 'Found void datatype, should not be used' );
  950. else
  951. {
  952. return null;
  953. }
  954. } break;
  955. case eZTemplate::TYPE_STRING:
  956. case eZTemplate::TYPE_NUMERIC:
  957. case eZTemplate::TYPE_IDENTIFIER:
  958. case eZTemplate::TYPE_BOOLEAN:
  959. case eZTemplate::TYPE_ARRAY:
  960. {
  961. $value = $dataElement[1];
  962. } break;
  963. case eZTemplate::TYPE_VARIABLE:
  964. {
  965. $variableData = $dataElement[1];
  966. $variableNamespace = $variableData[0];
  967. $variableNamespaceScope = $variableData[1];
  968. $variableName = $variableData[2];
  969. if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_GLOBAL )
  970. $namespace = $variableNamespace;
  971. else if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_LOCAL )
  972. $namespace = $this->mergeNamespace( $rootNamespace, $variableNamespace );
  973. else if ( $variableNamespaceScope == eZTemplate::NAMESPACE_SCOPE_RELATIVE )
  974. $namespace = $this->mergeNamespace( $currentNamespace, $variableNamespace );
  975. else
  976. $namespace = false;
  977. if ( $this->hasVariable( $variableName, $namespace ) )
  978. {
  979. $value = $this->variable( $variableName, $namespace );
  980. }
  981. else
  982. {
  983. if ( !$checkExistance )
  984. $this->error( '', "Unknown template variable '$variableName' in namespace '$namespace'", $placement );
  985. {
  986. return null;
  987. }
  988. }
  989. } break;
  990. case eZTemplate::TYPE_ATTRIBUTE:
  991. {
  992. $attributeData = $dataElement[1];
  993. $attributeValue = $this->elementValue( $attributeData, $rootNamespace, $currentNamespace, $placement, $checkExistance );
  994. if ( $attributeValue !== null )
  995. {
  996. if ( !is_numeric( $attributeValue ) and
  997. !is_string( $attributeValue ) and
  998. !is_bool( $attributeValue ) )
  999. {
  1000. if ( !$checkExistance )
  1001. $this->error( "",
  1002. "Cannot use type " . gettype( $attributeValue ) . " for attribute lookup", $placement );
  1003. {
  1004. return null;
  1005. }
  1006. }
  1007. if ( is_array( $value ) )
  1008. {
  1009. if ( array_key_exists( $attributeValue, $value ) )
  1010. {
  1011. $value = $value[$attributeValue];
  1012. }
  1013. else
  1014. {
  1015. if ( !$checkExistance )
  1016. {
  1017. $arrayAttributeList = array_keys( $value );
  1018. $arrayCount = count( $arrayAttributeList );
  1019. $errorMessage = "No such attribute for array($arrayCount): $attributeValue";
  1020. $chooseText = "Choose one of following: ";
  1021. $errorMessage .= "\n$chooseText";
  1022. $errorMessage .= $this->expandAttributes( $arrayAttributeList, $chooseText, 25 );
  1023. $this->error( "",
  1024. $errorMessage, $placement );
  1025. }
  1026. return null;
  1027. }
  1028. }
  1029. else if ( is_object( $value ) )
  1030. {
  1031. if ( method_exists( $value, "attribute" ) and
  1032. method_exists( $value, "hasAttribute" ) )
  1033. {
  1034. if ( $value->hasAttribute( $attributeValue ) )
  1035. {
  1036. $value = $value->attribute( $attributeValue );
  1037. }
  1038. else
  1039. {
  1040. if ( !$checkExistance )
  1041. {
  1042. $objectAttributeList = array();
  1043. if ( method_exists( $value, 'attributes' ) )
  1044. $objectAttributeList = $value->attributes();
  1045. $objectClass= get_class( $value );
  1046. $errorMessage = "No such attribute for object($objectClass): $attributeValue";
  1047. $chooseText = "Choose one of following: ";
  1048. $errorMessage .= "\n$chooseText";
  1049. $errorMessage .= $this->expandAttributes( $objectAttributeList, $chooseText, 25 );
  1050. $this->error( "",
  1051. $errorMessage, $placement );
  1052. }
  1053. return null;
  1054. }
  1055. }
  1056. else
  1057. {
  1058. if ( !$checkExistance )
  1059. $this->error( "",
  1060. "Cannot retrieve attribute of object(" . get_class( $value ) .
  1061. "), no attribute functions available",
  1062. $placement );
  1063. return null;
  1064. }
  1065. }
  1066. else
  1067. {
  1068. if ( !$checkExistance )
  1069. $this->error( "",
  1070. "Cannot retrieve attribute of a " . gettype( $value ),
  1071. $placement );
  1072. return null;
  1073. }
  1074. }
  1075. else
  1076. {
  1077. if ( !$checkExistance )
  1078. $this->error( '',
  1079. 'Attribute value was null, cannot get attribute',
  1080. $placement );
  1081. return null;
  1082. }
  1083. } break;
  1084. case eZTemplate::TYPE_OPERATOR:
  1085. {
  1086. $operatorParameters = $dataElement[1];
  1087. $operatorName = $operatorParameters[0];
  1088. $operatorParameters = array_splice( $operatorParameters, 1 );
  1089. if ( is_object( $value ) and
  1090. method_exists( $value, 'templateValue' ) )
  1091. {
  1092. if ( $checkForProxy )
  1093. $dataElements['proxy-object-found'] = true;
  1094. $value = $value->templateValue();
  1095. }
  1096. $valueData = array( 'value' => $value );
  1097. $this->processOperator( $operatorName, $operatorParameters, $rootNamespace, $currentNamespace,
  1098. $valueData, $placement, $checkExistance );
  1099. $value = $valueData['value'];
  1100. } break;
  1101. default:
  1102. {
  1103. if ( !$checkExistance )
  1104. $this->error( "elementValue",
  1105. "Unknown data type: '$dataType'",
  1106. $placement );
  1107. return null;
  1108. }
  1109. }
  1110. }
  1111. if ( is_object( $value ) and
  1112. method_exists( $value, 'templateValue' ) )
  1113. {
  1114. if ( $checkForProxy )
  1115. $dataElements['proxy-object-found'] = true;
  1116. return $value->templateValue();
  1117. }
  1118. return $value;
  1119. }
  1120. function expandAttributes( $attributeList, $chooseText, $maxThreshold, $minThreshold = 1 )
  1121. {
  1122. $errorMessage = '';
  1123. $attributeCount = count( $attributeList );
  1124. if ( $attributeCount < $minThreshold )
  1125. return $errorMessage;
  1126. if ( $attributeCount < $maxThreshold )
  1127. {
  1128. $chooseLength = strlen( $chooseText );
  1129. $attributeText = '';
  1130. $i = 0;
  1131. foreach ( $attributeList as $attributeName )
  1132. {
  1133. if ( $i > 0 )
  1134. $attributeText .= ",";
  1135. if ( strlen( $attributeText ) > 40 )
  1136. {
  1137. $attributeText .= "\n";
  1138. $errorMessage .= $attributeText;
  1139. $errorMessage .= str_repeat( ' ', $chooseLength );
  1140. $attributeText = '';
  1141. }
  1142. else if ( $i > 0 )
  1143. $attributeText .= " ";
  1144. $attributeText .= $attributeName;
  1145. ++$i;
  1146. }
  1147. $errorMessage .= $attributeText;
  1148. }
  1149. return $errorMessage;
  1150. }
  1151. function processOperator( $operatorName, $operatorParameters, $rootNamespace, $currentNamespace,
  1152. &$valueData, $placement = false, $checkExistance = false )
  1153. {
  1154. $namedParameters = array();
  1155. $operatorParameterDefinition = $this->operatorParameterList( $operatorName );
  1156. $i = 0;
  1157. foreach ( $operatorParameterDefinition as $parameterName => $parameterType )
  1158. {
  1159. if ( !isset( $operatorParameters[$i] ) or
  1160. !isset( $operatorParameters[$i][0] ) or
  1161. $operatorParameters[$i][0] == eZTemplate::TYPE_VOID )
  1162. {
  1163. if ( $parameterType["required"] )
  1164. {
  1165. if ( !$checkExistance )
  1166. $this->warning( "eZTemplateOperatorElement", "Par…

Large files files are truncated, but you can click here to view the full file