Source for file LatteFilter.php

Documentation is available at LatteFilter.php

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * Nette Framework
  5. 5:  *
  6. 6:  * Copyright (c) 2004, 2009 David Grudl (http://davidgrudl.com)
  7. 7:  *
  8. 8:  * This source file is subject to the "Nette license" that is bundled
  9. 9:  * with this package in the file license.txt.
  10. 10:  *
  11. 11:  * For more information please see http://nettephp.com
  12. 12:  *
  13. 13:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  14. 14:  * @license    http://nettephp.com/license  Nette license
  15. 15:  * @link       http://nettephp.com
  16. 16:  * @category   Nette
  17. 17:  * @package    Nette\Templates
  18. 18:  */
  19. 19:  
  20. 20:  
  21. 21:  
  22. 22: require_once dirname(__FILE__'/../../Object.php';
  23. 23:  
  24. 24:  
  25. 25:  
  26. 26: /**
  27. 27:  * Compile-time filter Latte.
  28. 28:  *
  29. 29:  * @author     David Grudl
  30. 30:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  31. 31:  * @package    Nette\Templates
  32. 32:  */
  33. 33: class LatteFilter extends Object
  34. 34: {
  35. 35:     /** @ignore internal single & double quoted PHP string */
  36. 36:     const RE_STRING '\'(?:\\\\.|[^\'\\\\])*\'|"(?:\\\\.|[^"\\\\])*"';
  37. 37:  
  38. 38:     /** @ignore internal PHP identifier */
  39. 39:     const RE_IDENTIFIER '[_a-zA-Z\x7F-\xFF][_a-zA-Z0-9\x7F-\xFF]*';
  40. 40:  
  41. 41:     /** @ignore internal special HTML tag or attribute prefix */
  42. 42:     const HTML_PREFIX 'n:';
  43. 43:  
  44. 44:     /** @var ILatteHandler */
  45. 45:     private $handler;
  46. 46:  
  47. 47:     /** @var string */
  48. 48:     private $macroRe;
  49. 49:  
  50. 50:     /** @var string */
  51. 51:     private $input$output;
  52. 52:  
  53. 53:     /** @var int */
  54. 54:     private $offset;
  55. 55:  
  56. 56:     /** @var strng (for CONTEXT_ATTRIBUTE) */
  57. 57:     private $quote;
  58. 58:  
  59. 59:     /** @var array */
  60. 60:     private $tags;
  61. 61:  
  62. 62:     /** @var string */
  63. 63:     public $context$escape;
  64. 64:  
  65. 65:     /**#@+ @ignore internal Context-aware escaping states */
  66. 66:     const CONTEXT_TEXT 'text';
  67. 67:     const CONTEXT_CDATA 'cdata';
  68. 68:     const CONTEXT_TAG 'tag';
  69. 69:     const CONTEXT_ATTRIBUTE 'attribute';
  70. 70:     const CONTEXT_NONE 'none';
  71. 71:     const CONTEXT_COMMENT 'comment';
  72. 72:     /**#@-*/
  73. 73:  
  74. 74:  
  75. 75:  
  76. 76:     /**
  77. 77:      * Sets a macro handler.
  78. 78:      * @param  ILatteHandler 
  79. 79:      * @return LatteFilter  provides a fluent interface
  80. 80:      */
  81. 81:     public function setHandler($handler)
  82. 82:     {
  83. 83:         $this->handler $handler;
  84. 84:         return $this;
  85. 85:     }
  86. 86:  
  87. 87:  
  88. 88:  
  89. 89:     /**
  90. 90:      * Returns macro handler.
  91. 91:      * @return ILatteHandler 
  92. 92:      */
  93. 93:     public function getHandler()
  94. 94:     {
  95. 95:         if ($this->handler === NULL{
  96. 96:             $this->handler new LatteMacros;
  97. 97:         }
  98. 98:         return $this->handler;
  99. 99:     }
  100. 100:  
  101. 101:  
  102. 102:  
  103. 103:     /**
  104. 104:      * Invokes filter.
  105. 105:      * @param  string 
  106. 106:      * @return string 
  107. 107:      */
  108. 108:     public function __invoke($s)
  109. 109:     {
  110. 110:         if (!$this->macroRe{
  111. 111:             $this->setDelimiters('\\{(?![\\s\'"{}])''\\}');
  112. 112:         }
  113. 113:  
  114. 114:         // context-aware escaping
  115. 115:         $this->context = LatteFilter::CONTEXT_NONE;
  116. 116:         $this->escape = '$template->escape';
  117. 117:  
  118. 118:         // initialize handlers
  119. 119:         $this->getHandler()->initialize($this$s);
  120. 120:  
  121. 121:         // process all {tags} and <tags/>
  122. 122:         $s $this->parse("\n" $s);
  123. 123:  
  124. 124:         $this->getHandler()->finalize($s);
  125. 125:  
  126. 126:         return $s;
  127. 127:     }
  128. 128:  
  129. 129:  
  130. 130:  
  131. 131:     /**
  132. 132:      * Searches for curly brackets, HTML tags and attributes.
  133. 133:      * @param  string 
  134. 134:      * @return string 
  135. 135:      */
  136. 136:     private function parse($s)
  137. 137:     {
  138. 138:         $this->input $s;
  139. 139:         $this->offset 0;
  140. 140:         $this->output '';
  141. 141:         $this->tags array();
  142. 142:         $len strlen($s);
  143. 143:  
  144. 144:         while ($this->offset $len{
  145. 145:             $matches $this->{"context$this->context"}();
  146. 146:  
  147. 147:             if (!$matches// EOF
  148. 148:                 break;
  149. 149:  
  150. 150:             elseif (!empty($matches['macro'])) // {macro|modifiers}
  151. 151:                 preg_match('#^(/?[a-z]+)?(.*?)(\\|[a-z](?:'.self::RE_STRING.'|[^\'"\s]+)*)?$()#is'$matches['macro']$m2);
  152. 152:                 list($macro$value$modifiers$m2;
  153. 153:                 $code $this->handler->macro($macrotrim($value)isset($modifiers$modifiers '');
  154. 154:                 if ($code === NULL{
  155. 155:                     throw new InvalidStateException("Unknown macro {{$matches['macro']}} on line $this->line.");
  156. 156:                 }
  157. 157:                 $nl isset($matches['newline']"\n" ''// double newline
  158. 158:                 if ($nl && $matches['indent'&& strncmp($code'<?php echo '11)) {
  159. 159:                     $this->output .= "\n" $code// remove indent, single newline
  160. 160:                 else {
  161. 161:                     $this->output .= $matches['indent'$code (substr($code-2=== '?>' $nl '');
  162. 162:                 }
  163. 163:  
  164. 164:             else // common behaviour
  165. 165:                 $this->output .= $matches[0];
  166. 166:             }
  167. 167:         }
  168. 168:  
  169. 169:         foreach ($this->tags as $tag{
  170. 170:             if (!$tag->isMacro && !empty($tag->attrs)) {
  171. 171:                 throw new InvalidStateException("Missing end tag </$tag->name> for macro-attribute self::HTML_PREFIX implode(' and ' self::HTML_PREFIXarray_keys($tag->attrs)) ".");
  172. 172:             }
  173. 173:         }
  174. 174:  
  175. 175:         return $this->output substr($this->input$this->offset);
  176. 176:     }
  177. 177:  
  178. 178:  
  179. 179:  
  180. 180:     /**
  181. 181:      * Handles CONTEXT_TEXT.
  182. 182:      */
  183. 183:     private function contextText()
  184. 184:     {
  185. 185:         $matches $this->match('~
  186. 186:             (?:\n[ \t]*)?<(?P<closing>/?)(?P<tag>[a-z0-9:]+)|  ##  begin of HTML tag <tag </tag - ignores <!DOCTYPE
  187. 187:             <(?P<comment>!--)|           ##  begin of HTML comment <!--
  188. 188:             '.$this->macroRe.'           ##  curly tag
  189. 189:         ~xsi');
  190. 190:  
  191. 191:         if (!$matches || !empty($matches['macro'])) // EOF or {macro}
  192. 192:  
  193. 193:         elseif (!empty($matches['comment'])) // <!--
  194. 194:             $this->context self::CONTEXT_COMMENT;
  195. 195:             $this->escape 'TemplateHelpers::escapeHtmlComment';
  196. 196:  
  197. 197:         elseif (empty($matches['closing'])) // <tag
  198. 198:             $tag $this->tags[= (object) NULL;
  199. 199:             $tag->name $matches['tag'];
  200. 200:             $tag->closing FALSE;
  201. 201:             $tag->isMacro String::startsWith($tag->nameself::HTML_PREFIX);
  202. 202:             $tag->attrs array();
  203. 203:             $tag->pos = strlen($this->output);
  204. 204:             $this->context self::CONTEXT_TAG;
  205. 205:             $this->escape 'TemplateHelpers::escapeHtml';
  206. 206:  
  207. 207:         else // </tag
  208. 208:             do {
  209. 209:                 $tag array_pop($this->tags);
  210. 210:                 if (!$tag{
  211. 211:                     //throw new InvalidStateException("End tag for element '$matches[tag]' which is not open on line $this->line.");
  212. 212:                     $tag = (object) NULL;
  213. 213:                     $tag->name $matches['tag'];
  214. 214:                     $tag->isMacro String::startsWith($tag->nameself::HTML_PREFIX);
  215. 215:                 }
  216. 216:             while (strcasecmp($tag->name$matches['tag']));
  217. 217:             $this->tags[$tag;
  218. 218:             $tag->closing TRUE;
  219. 219:             $tag->pos = strlen($this->output);
  220. 220:             $this->context self::CONTEXT_TAG;
  221. 221:             $this->escape 'TemplateHelpers::escapeHtml';
  222. 222:         }
  223. 223:         return $matches;
  224. 224:     }
  225. 225:  
  226. 226:  
  227. 227:  
  228. 228:     /**
  229. 229:      * Handles CONTEXT_CDATA.
  230. 230:      */
  231. 231:     private function contextCData()
  232. 232:     {
  233. 233:         $tag end($this->tags);
  234. 234:         $matches $this->match('~
  235. 235:             </'.$tag->name.'(?![a-z0-9:])| ##  end HTML tag </tag
  236. 236:             '.$this->macroRe.'           ##  curly tag
  237. 237:         ~xsi');
  238. 238:  
  239. 239:         if ($matches && empty($matches['macro'])) // </tag
  240. 240:             $tag->closing TRUE;
  241. 241:             $tag->pos = strlen($this->output);
  242. 242:             $this->context self::CONTEXT_TAG;
  243. 243:             $this->escape 'TemplateHelpers::escapeHtml';
  244. 244:         }
  245. 245:         return $matches;
  246. 246:     }
  247. 247:  
  248. 248:  
  249. 249:  
  250. 250:     /**
  251. 251:      * Handles CONTEXT_TAG.
  252. 252:      */
  253. 253:     private function contextTag()
  254. 254:     {
  255. 255:         $matches $this->match('~
  256. 256:             (?P<end>/?>)(?P<tagnewline>[\ \t]*(?=\r|\n))?|  ##  end of HTML tag
  257. 257:             '.$this->macroRe.'|          ##  curly tag
  258. 258:             \s*(?P<attr>[^\s/>={]+)(?:\s*=\s*(?P<value>["\']|[^\s/>{]+))? ## begin of HTML attribute
  259. 259:         ~xsi');
  260. 260:  
  261. 261:         if (!$matches || !empty($matches['macro'])) // EOF or {macro}
  262. 262:  
  263. 263:         elseif (!empty($matches['end'])) // end of HTML tag />
  264. 264:             $tag end($this->tags);
  265. 265:             $isEmpty !$tag->closing && ($matches['end'][0=== '/' || isset(Html::$emptyElements[strtolower($tag->name)]));
  266. 266:  
  267. 267:             if ($tag->isMacro || !empty($tag->attrs)) {
  268. 268:                 if ($tag->isMacro{
  269. 269:                     $code $this->handler->tagMacro(substr($tag->namestrlen(self::HTML_PREFIX))$tag->attrs$tag->closing);
  270. 270:                     if ($code === NULL{
  271. 271:                         throw new InvalidStateException("Unknown tag-macro <$tag->name> on line $this->line.");
  272. 272:                     }
  273. 273:                     if ($isEmpty{
  274. 274:                         $code .= $this->handler->tagMacro(substr($tag->namestrlen(self::HTML_PREFIX))$tag->attrsTRUE);
  275. 275:                     }
  276. 276:                 else {
  277. 277:                     $code substr($this->output$tag->pos$matches[0(isset($matches['tagnewline']"\n" '');
  278. 278:                     $code $this->handler->attrsMacro($code$tag->attrs$tag->closing);
  279. 279:                     if ($code === NULL{
  280. 280:                         throw new InvalidStateException("Unknown macro-attribute " self::HTML_PREFIX implode(' or ' self::HTML_PREFIXarray_keys($tag->attrs)) " on line $this->line.");
  281. 281:                     }
  282. 282:                     if ($isEmpty{
  283. 283:                         $code $this->handler->attrsMacro($code$tag->attrsTRUE);
  284. 284:                     }
  285. 285:                 }
  286. 286:                 $this->output substr_replace($this->output$code$tag->pos);
  287. 287:                 $matches[0''// remove from output
  288. 288:             }
  289. 289:  
  290. 290:             if ($isEmpty{
  291. 291:                 $tag->closing TRUE;
  292. 292:             }
  293. 293:  
  294. 294:             if (!$tag->closing && (strcasecmp($tag->name'script'=== || strcasecmp($tag->name'style'=== 0)) {
  295. 295:                 $this->context self::CONTEXT_CDATA;
  296. 296:                 $this->escape strcasecmp($tag->name'style''TemplateHelpers::escapeJs' 'TemplateHelpers::escapeCss';
  297. 297:             else {
  298. 298:                 $this->context self::CONTEXT_TEXT;
  299. 299:                 $this->escape 'TemplateHelpers::escapeHtml';
  300. 300:                 if ($tag->closingarray_pop($this->tags);
  301. 301:             }
  302. 302:  
  303. 303:         else // HTML attribute
  304. 304:             $name $matches['attr'];
  305. 305:             $value empty($matches['value']TRUE $matches['value'];
  306. 306:  
  307. 307:             // special attribute?
  308. 308:             if ($isSpecial String::startsWith($nameself::HTML_PREFIX)) {
  309. 309:                 $name substr($namestrlen(self::HTML_PREFIX));
  310. 310:             }
  311. 311:             $tag end($this->tags);
  312. 312:             if ($isSpecial || $tag->isMacro{
  313. 313:                 if ($value === '"' || $value === "'"{
  314. 314:                     if ($matches $this->match('~(.*?)' $value '~xsi')) // overwrites $matches
  315. 315:                         $value $matches[1];
  316. 316:                     }
  317. 317:                 }
  318. 318:                 $tag->attrs[$name$value;
  319. 319:                 $matches[0''// remove from output
  320. 320:  
  321. 321:             elseif ($value === '"' || $value === "'"// attribute = "'
  322. 322:                 $this->context self::CONTEXT_ATTRIBUTE;
  323. 323:                 $this->quote $value;
  324. 324:                 $this->escape strncasecmp($name'on'2)
  325. 325:                     ? (strcasecmp($name'style''TemplateHelpers::escapeHtml' 'TemplateHelpers::escapeHtmlCss')
  326. 326:                     : 'TemplateHelpers::escapeHtmlJs';
  327. 327:             }
  328. 328:         }
  329. 329:         return $matches;
  330. 330:     }
  331. 331:  
  332. 332:  
  333. 333:  
  334. 334:     /**
  335. 335:      * Handles CONTEXT_ATTRIBUTE.
  336. 336:      */
  337. 337:     private function contextAttribute()
  338. 338:     {
  339. 339:         $matches $this->match('~
  340. 340:             (' $this->quote ')|      ##  1) end of HTML attribute
  341. 341:             '.$this->macroRe.'           ##  curly tag
  342. 342:         ~xsi');
  343. 343:  
  344. 344:         if ($matches && empty($matches['macro'])) // (attribute end) '"
  345. 345:             $this->context self::CONTEXT_TAG;
  346. 346:             $this->escape 'TemplateHelpers::escapeHtml';
  347. 347:         }
  348. 348:         return $matches;
  349. 349:     }
  350. 350:  
  351. 351:  
  352. 352:  
  353. 353:     /**
  354. 354:      * Handles CONTEXT_COMMENT.
  355. 355:      */
  356. 356:     private function contextComment()
  357. 357:     {
  358. 358:         $matches $this->match('~
  359. 359:             (--\s*>)|                    ##  1) end of HTML comment
  360. 360:             '.$this->macroRe.'           ##  curly tag
  361. 361:         ~xsi');
  362. 362:  
  363. 363:         if ($matches && empty($matches['macro'])) // --\s*>
  364. 364:             $this->context self::CONTEXT_TEXT;
  365. 365:             $this->escape 'TemplateHelpers::escapeHtml';
  366. 366:         }
  367. 367:         return $matches;
  368. 368:     }
  369. 369:  
  370. 370:  
  371. 371:  
  372. 372:     /**
  373. 373:      * Handles CONTEXT_NONE.
  374. 374:      */
  375. 375:     private function contextNone()
  376. 376:     {
  377. 377:         $matches $this->match('~
  378. 378:             '.$this->macroRe.'           ##  curly tag
  379. 379:         ~xsi');
  380. 380:         return $matches;
  381. 381:     }
  382. 382:  
  383. 383:  
  384. 384:  
  385. 385:     /**
  386. 386:      * Matches next token.
  387. 387:      * @param  string 
  388. 388:      * @return array 
  389. 389:      */
  390. 390:     private function match($re)
  391. 391:     {
  392. 392:         if (preg_match($re$this->input$matchesPREG_OFFSET_CAPTURE$this->offset)) {
  393. 393:             $this->output .= substr($this->input$this->offset$matches[0][1$this->offset);
  394. 394:             $this->offset $matches[0][1strlen($matches[0][0]);
  395. 395:             foreach ($matches as $k => $v$matches[$k$v[0];
  396. 396:         }
  397. 397:         return $matches;
  398. 398:     }
  399. 399:  
  400. 400:  
  401. 401:  
  402. 402:     /**
  403. 403:      * Returns current line number.
  404. 404:      * @return int 
  405. 405:      */
  406. 406:     public function getLine()
  407. 407:     {
  408. 408:         return substr_count($this->input"\n"0$this->offset);
  409. 409:     }
  410. 410:  
  411. 411:  
  412. 412:  
  413. 413:     /**
  414. 414:      * Changes macro delimiters.
  415. 415:      * @param  string  left regular expression
  416. 416:      * @param  string  right regular expression
  417. 417:      * @return LatteFilter  provides a fluent interface
  418. 418:      */
  419. 419:     public function setDelimiters($left$right)
  420. 420:     {
  421. 421:         $this->macroRe '
  422. 422:             (?P<indent>\n[\ \t]*)?
  423. 423:             ' $left '
  424. 424:                 (?P<macro>(?:' self::RE_STRING '|[^\'"]+?)*?)
  425. 425:             ' $right '
  426. 426:             (?P<newline>[\ \t]*(?=\r|\n))?
  427. 427:         ';
  428. 428:         return $this;
  429. 429:     }
  430. 430:  
  431. 431:  
  432. 432:  
  433. 433:     /********************* compile-time helpers ****************d*g**/
  434. 434:  
  435. 435:  
  436. 436:  
  437. 437:     /**
  438. 438:      * Applies modifiers.
  439. 439:      * @param  string 
  440. 440:      * @param  string 
  441. 441:      * @return string 
  442. 442:      */
  443. 443:     public static function formatModifiers($var$modifiers)
  444. 444:     {
  445. 445:         if (!$modifiersreturn $var;
  446. 446:         preg_match_all(
  447. 447:             '~
  448. 448:                 '.self::RE_STRING.'|  ## single or double quoted string
  449. 449:                 [^\'"|:,]+|           ## symbol
  450. 450:                 [|:,]                 ## separator
  451. 451:             ~xs',
  452. 452:             $modifiers '|',
  453. 453:             $tokens
  454. 454:         );
  455. 455:         $inside FALSE;
  456. 456:         $prev '';
  457. 457:         foreach ($tokens[0as $token{
  458. 458:             if ($token === '|' || $token === ':' || $token === ','{
  459. 459:                 if ($prev === ''{
  460. 460:  
  461. 461:                 elseif (!$inside{
  462. 462:                     if (!preg_match('#^'.self::RE_IDENTIFIER.'$#'$prev)) {
  463. 463:                         throw new InvalidStateException("Modifier name must be alphanumeric string, '$prev' given.");
  464. 464:                     }
  465. 465:                     $var "\$template->$prev($var";
  466. 466:                     $prev '';
  467. 467:                     $inside TRUE;
  468. 468:  
  469. 469:                 else {
  470. 470:                     $var .= ', ' self::formatString($prev);
  471. 471:                     $prev '';
  472. 472:                 }
  473. 473:  
  474. 474:                 if ($token === '|' && $inside{
  475. 475:                     $var .= ')';
  476. 476:                     $inside FALSE;
  477. 477:                 }
  478. 478:             else {
  479. 479:                 $prev .= $token;
  480. 480:             }
  481. 481:         }
  482. 482:         return $var;
  483. 483:     }
  484. 484:  
  485. 485:  
  486. 486:  
  487. 487:     /**
  488. 488:      * Reads single token (optionally delimited by comma) from string.
  489. 489:      * @param  string 
  490. 490:      * @return string 
  491. 491:      */
  492. 492:     public static function fetchToken($s)
  493. 493:     {
  494. 494:         if (preg_match('#^((?>'.self::RE_STRING.'|[^\'"\s,]+)+)\s*,?\s*(.*)$#'$s$matches)) // token [,] tail
  495. 495:             $s $matches[2];
  496. 496:             return $matches[1];
  497. 497:         }
  498. 498:         return NULL;
  499. 499:     }
  500. 500:  
  501. 501:  
  502. 502:  
  503. 503:     /**
  504. 504:      * Formats parameters to PHP array.
  505. 505:      * @param  string 
  506. 506:      * @param  string 
  507. 507:      * @return string 
  508. 508:      */
  509. 509:     public static function formatArray($s$prefix '')
  510. 510:     {
  511. 511:         $s preg_replace_callback(
  512. 512:             '~
  513. 513:                 '.self::RE_STRING.'|                          ## single or double quoted string
  514. 514:                 (?<=[,=(]|=>|^)\s*([a-z\d_]+)(?=\s*[,=)]|$)   ## 1) symbol
  515. 515:             ~xi',
  516. 516:             array(__CLASS__'cbArgs'),
  517. 517:             trim($s)
  518. 518:         );
  519. 519:         return $s === '' '' $prefix "array($s)";
  520. 520:     }
  521. 521:  
  522. 522:  
  523. 523:  
  524. 524:     /**
  525. 525:      * Callback for formatArgs().
  526. 526:      */
  527. 527:     private static function cbArgs($matches)
  528. 528:     {
  529. 529:         //    [1] => symbol
  530. 530:  
  531. 531:         if (!empty($matches[1])) // symbol
  532. 532:             list($symbol$matches;
  533. 533:             static $keywords array('true'=>1'false'=>1'null'=>1'and'=>1'or'=>1'xor'=>1'clone'=>1'new'=>1);
  534. 534:             return is_numeric($symbol|| isset($keywords[strtolower($symbol)]$matches[0"'$symbol'";
  535. 535:  
  536. 536:         else {
  537. 537:             return $matches[0];
  538. 538:         }
  539. 539:     }
  540. 540:  
  541. 541:  
  542. 542:  
  543. 543:     /**
  544. 544:      * Formats parameter to PHP string.
  545. 545:      * @param  string 
  546. 546:      * @return string 
  547. 547:      */
  548. 548:     public static function formatString($s)
  549. 549:     {
  550. 550:         return (is_numeric($s|| strspn($s'\'"$')) $s '"' $s '"';
  551. 551:     }
  552. 552:  
  553. 553:  
  554. 554:  
  555. 555:     /**
  556. 556:      * Invokes filter.
  557. 557:      * @deprecated
  558. 558:      */
  559. 559:     public static function invoke($s)
  560. 560:     {
  561. 561:         $filter new self;
  562. 562:         return $filter->__invoke($s);
  563. 563:     }
  564. 564:  
  565. 566:  
  566. 567:  
  567. 568:  
  568. 569: /** @deprecated */
  569. 570: class CurlyBracketsFilter extends LatteFilter {}
  570. 571: class CurlyBracketsMacros extends LatteMacros {}