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