1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Latte;
9:
10: use Nette,
11: Nette\Utils\Strings;
12:
13:
14: 15: 16: 17: 18:
19: class Compiler extends Nette\Object
20: {
21:
22: public $defaultContentType = self::CONTENT_HTML;
23:
24:
25: private $tokens;
26:
27:
28: private $output;
29:
30:
31: private $position;
32:
33:
34: private $macros;
35:
36:
37: private $macroHandlers;
38:
39:
40: private $htmlNode;
41:
42:
43: private $macroNode;
44:
45:
46: private $attrCodes = array();
47:
48:
49: private $contentType;
50:
51:
52: private $context;
53:
54:
55: private $templateId;
56:
57:
58: const CONTENT_HTML = 'html',
59: CONTENT_XHTML = 'xhtml',
60: CONTENT_XML = 'xml',
61: CONTENT_JS = 'js',
62: CONTENT_CSS = 'css',
63: CONTENT_URL = 'url',
64: CONTENT_ICAL = 'ical',
65: CONTENT_TEXT = 'text';
66:
67:
68: const = 'comment',
69: CONTEXT_SINGLE_QUOTED_ATTR = "'",
70: CONTEXT_DOUBLE_QUOTED_ATTR = '"',
71: CONTEXT_UNQUOTED_ATTR = '=';
72:
73:
74: public function __construct()
75: {
76: $this->macroHandlers = new \SplObjectStorage;
77: }
78:
79:
80: 81: 82: 83: 84:
85: public function addMacro($name, IMacro $macro)
86: {
87: $this->macros[$name][] = $macro;
88: $this->macroHandlers->attach($macro);
89: return $this;
90: }
91:
92:
93: 94: 95: 96: 97:
98: public function compile(array $tokens)
99: {
100: $this->templateId = Strings::random();
101: $this->tokens = $tokens;
102: $output = '';
103: $this->output = & $output;
104: $this->htmlNode = $this->macroNode = NULL;
105: $this->setContentType($this->defaultContentType);
106:
107: foreach ($this->macroHandlers as $handler) {
108: $handler->initialize($this);
109: }
110:
111: try {
112: foreach ($tokens as $this->position => $token) {
113: $this->{"process$token->type"}($token);
114: }
115: } catch (CompileException $e) {
116: $e->sourceLine = $token->line;
117: throw $e;
118: }
119:
120: while ($this->htmlNode) {
121: if (!empty($this->htmlNode->macroAttrs)) {
122: throw new CompileException('Missing ' . self::printEndTag($this->macroNode), 0, $token->line);
123: }
124: $this->htmlNode = $this->htmlNode->parentNode;
125: }
126:
127: $prologs = $epilogs = '';
128: foreach ($this->macroHandlers as $handler) {
129: $res = $handler->finalize();
130: $handlerName = get_class($handler);
131: $prologs .= empty($res[0]) ? '' : "<?php\n// prolog $handlerName\n$res[0]\n?>";
132: $epilogs = (empty($res[1]) ? '' : "<?php\n// epilog $handlerName\n$res[1]\n?>") . $epilogs;
133: }
134: $output = ($prologs ? $prologs . "<?php\n//\n// main template\n//\n?>\n" : '') . $output . $epilogs;
135:
136: if ($this->macroNode) {
137: throw new CompileException('Missing ' . self::printEndTag($this->macroNode), 0, $token->line);
138: }
139:
140: $output = $this->expandTokens($output);
141: return $output;
142: }
143:
144:
145: 146: 147:
148: public function setContentType($type)
149: {
150: $this->contentType = $type;
151: $this->context = NULL;
152: return $this;
153: }
154:
155:
156: 157: 158:
159: public function getContentType()
160: {
161: return $this->contentType;
162: }
163:
164:
165: 166: 167:
168: public function setContext($context, $sub = NULL)
169: {
170: $this->context = array($context, $sub);
171: return $this;
172: }
173:
174:
175: 176: 177:
178: public function getContext()
179: {
180: return $this->context;
181: }
182:
183:
184: 185: 186:
187: public function getTemplateId()
188: {
189: return $this->templateId;
190: }
191:
192:
193: 194: 195:
196: public function getMacroNode()
197: {
198: return $this->macroNode;
199: }
200:
201:
202: 203: 204: 205:
206: public function getLine()
207: {
208: return $this->tokens ? $this->tokens[$this->position]->line : NULL;
209: }
210:
211:
212: public function expandTokens($s)
213: {
214: return strtr($s, $this->attrCodes);
215: }
216:
217:
218: private function processText(Token $token)
219: {
220: if (($this->context[0] === self::CONTEXT_SINGLE_QUOTED_ATTR || $this->context[0] === self::CONTEXT_DOUBLE_QUOTED_ATTR)
221: && $token->text === $this->context[0]
222: ) {
223: $this->setContext(self::CONTEXT_UNQUOTED_ATTR);
224: }
225: $this->output .= $token->text;
226: }
227:
228:
229: private function processMacroTag(Token $token)
230: {
231: $isRightmost = !isset($this->tokens[$this->position + 1])
232: || substr($this->tokens[$this->position + 1]->text, 0, 1) === "\n";
233:
234: if ($token->name[0] === '/') {
235: $this->closeMacro((string) substr($token->name, 1), $token->value, $token->modifiers, $isRightmost);
236: } else {
237: $this->openMacro($token->name, $token->value, $token->modifiers, $isRightmost && !$token->empty);
238: if ($token->empty) {
239: $this->closeMacro($token->name, NULL, NULL, $isRightmost);
240: }
241: }
242: }
243:
244:
245: private function processHtmlTagBegin(Token $token)
246: {
247: if ($token->closing) {
248: while ($this->htmlNode) {
249: if (strcasecmp($this->htmlNode->name, $token->name) === 0) {
250: break;
251: }
252: if ($this->htmlNode->macroAttrs) {
253: throw new CompileException("Unexpected </$token->name>, expecting " . self::printEndTag($this->macroNode));
254: }
255: $this->htmlNode = $this->htmlNode->parentNode;
256: }
257: if (!$this->htmlNode) {
258: $this->htmlNode = new HtmlNode($token->name);
259: }
260: $this->htmlNode->closing = TRUE;
261: $this->htmlNode->offset = strlen($this->output);
262: $this->setContext(NULL);
263:
264: } elseif ($token->text === '<!--') {
265: $this->setContext(self::CONTEXT_COMMENT);
266:
267: } else {
268: $this->htmlNode = new HtmlNode($token->name, $this->htmlNode);
269: $this->htmlNode->isEmpty = in_array($this->contentType, array(self::CONTENT_HTML, self::CONTENT_XHTML))
270: && isset(Nette\Utils\Html::$emptyElements[strtolower($token->name)]);
271: $this->htmlNode->offset = strlen($this->output);
272: $this->setContext(self::CONTEXT_UNQUOTED_ATTR);
273: }
274: $this->output .= $token->text;
275: }
276:
277:
278: private function processHtmlTagEnd(Token $token)
279: {
280: if ($token->text === '-->') {
281: $this->output .= $token->text;
282: $this->setContext(NULL);
283: return;
284: }
285:
286: $htmlNode = $this->htmlNode;
287: $isEmpty = !$htmlNode->closing && (Strings::contains($token->text, '/') || $htmlNode->isEmpty);
288: $end = '';
289:
290: if ($isEmpty && in_array($this->contentType, array(self::CONTENT_HTML, self::CONTENT_XHTML))) {
291: $token->text = preg_replace('#^.*>#', $htmlNode->isEmpty && $this->contentType === self::CONTENT_XHTML ? ' />' : '>', $token->text);
292: if (!$htmlNode->isEmpty) {
293: $end = "</$htmlNode->name>";
294: }
295: }
296:
297: if (empty($htmlNode->macroAttrs)) {
298: $this->output .= $token->text . $end;
299: } else {
300: $code = substr($this->output, $htmlNode->offset) . $token->text;
301: $this->output = substr($this->output, 0, $htmlNode->offset);
302: $this->writeAttrsMacro($code);
303: if ($isEmpty) {
304: $htmlNode->closing = TRUE;
305: $this->writeAttrsMacro($end);
306: }
307: }
308:
309: if ($isEmpty) {
310: $htmlNode->closing = TRUE;
311: }
312:
313: $lower = strtolower($htmlNode->name);
314: if (!$htmlNode->closing && ($lower === 'script' || $lower === 'style')) {
315: $this->setContext($lower === 'script' ? self::CONTENT_JS : self::CONTENT_CSS);
316: } else {
317: $this->setContext(NULL);
318: if ($htmlNode->closing) {
319: $this->htmlNode = $this->htmlNode->parentNode;
320: }
321: }
322: }
323:
324:
325: private function processHtmlAttribute(Token $token)
326: {
327: if (Strings::startsWith($token->name, Parser::N_PREFIX)) {
328: $name = substr($token->name, strlen(Parser::N_PREFIX));
329: if (isset($this->htmlNode->macroAttrs[$name])) {
330: throw new CompileException("Found multiple macro-attributes $token->name.");
331:
332: } elseif ($this->macroNode && $this->macroNode->htmlNode === $this->htmlNode) {
333: throw new CompileException("Macro-attributes must not appear inside macro; found $token->name inside {{$this->macroNode->name}}.");
334: }
335: $this->htmlNode->macroAttrs[$name] = $token->value;
336: return;
337: }
338:
339: $this->htmlNode->attrs[$token->name] = TRUE;
340: $this->output .= $token->text;
341:
342: $context = NULL;
343: if (in_array($this->contentType, array(self::CONTENT_HTML, self::CONTENT_XHTML))) {
344: $lower = strtolower($token->name);
345: if (substr($lower, 0, 2) === 'on') {
346: $context = self::CONTENT_JS;
347: } elseif ($lower === 'style') {
348: $context = self::CONTENT_CSS;
349: } elseif (in_array($lower, array('href', 'src', 'action', 'formaction'))
350: || ($lower === 'data' && strtolower($this->htmlNode->name) === 'object')
351: ) {
352: $context = self::CONTENT_URL;
353: }
354: }
355: $this->setContext($token->value ?: self::CONTEXT_UNQUOTED_ATTR, $context);
356: }
357:
358:
359: private function (Token $token)
360: {
361: $isLeftmost = trim(substr($this->output, strrpos("\n$this->output", "\n"))) === '';
362: if (!$isLeftmost) {
363: $this->output .= substr($token->text, strlen(rtrim($token->text, "\n")));
364: }
365: }
366:
367:
368:
369:
370:
371: 372: 373: 374: 375: 376: 377: 378:
379: public function openMacro($name, $args = NULL, $modifiers = NULL, $isRightmost = FALSE, $nPrefix = NULL)
380: {
381: $node = $this->expandMacro($name, $args, $modifiers, $nPrefix);
382: if ($node->isEmpty) {
383: $this->writeCode($node->openingCode, $this->output, $isRightmost);
384: } else {
385: $this->macroNode = $node;
386: $node->saved = array(& $this->output, $isRightmost);
387: $this->output = & $node->content;
388: }
389: return $node;
390: }
391:
392:
393: 394: 395: 396: 397: 398: 399: 400:
401: public function closeMacro($name, $args = NULL, $modifiers = NULL, $isRightmost = FALSE, $nPrefix = NULL)
402: {
403: $node = $this->macroNode;
404:
405: if (!$node || ($node->name !== $name && '' !== $name) || $modifiers
406: || ($args && $node->args && !Strings::startsWith("$node->args ", "$args "))
407: || $nPrefix !== $node->prefix
408: ) {
409: $name = $nPrefix
410: ? "</{$this->htmlNode->name}> for macro-attribute " . Parser::N_PREFIX . implode(' and ' . Parser::N_PREFIX, array_keys($this->htmlNode->macroAttrs))
411: : '{/' . $name . ($args ? ' ' . $args : '') . $modifiers . '}';
412: throw new CompileException("Unexpected $name" . ($node ? ', expecting ' . self::printEndTag($node) : ''));
413: }
414:
415: $this->macroNode = $node->parentNode;
416: if (!$node->args) {
417: $node->setArgs($args);
418: }
419:
420: $isLeftmost = $node->content ? trim(substr($this->output, strrpos("\n$this->output", "\n"))) === '' : FALSE;
421:
422: $node->closing = TRUE;
423: $node->macro->nodeClosed($node);
424:
425: $this->output = & $node->saved[0];
426: $this->writeCode($node->openingCode, $this->output, $node->saved[1]);
427: $this->writeCode($node->closingCode, $node->content, $isRightmost, $isLeftmost);
428: $this->output .= $node->content;
429: return $node;
430: }
431:
432:
433: private function writeCode($code, & $output, $isRightmost, $isLeftmost = NULL)
434: {
435: if ($isRightmost) {
436: $leftOfs = strrpos("\n$output", "\n");
437: $isLeftmost = $isLeftmost === NULL ? trim(substr($output, $leftOfs)) === '' : $isLeftmost;
438: if ($isLeftmost && substr($code, 0, 11) !== '<?php echo ') {
439: $output = substr($output, 0, $leftOfs);
440: } elseif (substr($code, -2) === '?>') {
441: $code .= "\n";
442: }
443: }
444: $output .= $code;
445: }
446:
447:
448: 449: 450: 451: 452:
453: public function writeAttrsMacro($code)
454: {
455: $attrs = $this->htmlNode->macroAttrs;
456: $left = $right = array();
457:
458: foreach ($this->macros as $name => $foo) {
459: $attrName = MacroNode::PREFIX_INNER . "-$name";
460: if (isset($attrs[$attrName])) {
461: if ($this->htmlNode->closing) {
462: $left[] = array('closeMacro', $name, '', MacroNode::PREFIX_INNER);
463: } else {
464: array_unshift($right, array('openMacro', $name, $attrs[$attrName], MacroNode::PREFIX_INNER));
465: }
466: unset($attrs[$attrName]);
467: }
468: }
469:
470: foreach (array_reverse($this->macros) as $name => $foo) {
471: $attrName = MacroNode::PREFIX_TAG . "-$name";
472: if (isset($attrs[$attrName])) {
473: $left[] = array('openMacro', $name, $attrs[$attrName], MacroNode::PREFIX_TAG);
474: array_unshift($right, array('closeMacro', $name, '', MacroNode::PREFIX_TAG));
475: unset($attrs[$attrName]);
476: }
477: }
478:
479: foreach ($this->macros as $name => $foo) {
480: if (isset($attrs[$name])) {
481: if ($this->htmlNode->closing) {
482: $right[] = array('closeMacro', $name, '', MacroNode::PREFIX_NONE);
483: } else {
484: array_unshift($left, array('openMacro', $name, $attrs[$name], MacroNode::PREFIX_NONE));
485: }
486: unset($attrs[$name]);
487: }
488: }
489:
490: if ($attrs) {
491: throw new CompileException('Unknown macro-attribute ' . Parser::N_PREFIX
492: . implode(' and ' . Parser::N_PREFIX, array_keys($attrs)));
493: }
494:
495: if (!$this->htmlNode->closing) {
496: $this->htmlNode->attrCode = & $this->attrCodes[$uniq = ' n:' . Nette\Utils\Strings::random()];
497: $code = substr_replace($code, $uniq, strrpos($code, '/>') ?: strrpos($code, '>'), 0);
498: }
499:
500: foreach ($left as $item) {
501: $node = $this->{$item[0]}($item[1], $item[2], NULL, NULL, $item[3]);
502: if ($node->closing || $node->isEmpty) {
503: $this->htmlNode->attrCode .= $node->attrCode;
504: if ($node->isEmpty) {
505: unset($this->htmlNode->macroAttrs[$node->name]);
506: }
507: }
508: }
509:
510: $this->output .= $code;
511:
512: foreach ($right as $item) {
513: $node = $this->{$item[0]}($item[1], $item[2], NULL, NULL, $item[3]);
514: if ($node->closing) {
515: $this->htmlNode->attrCode .= $node->attrCode;
516: }
517: }
518:
519: if ($right && substr($this->output, -2) === '?>') {
520: $this->output .= "\n";
521: }
522: }
523:
524:
525: 526: 527: 528: 529: 530: 531:
532: public function expandMacro($name, $args, $modifiers = NULL, $nPrefix = NULL)
533: {
534: $inScript = in_array($this->context[0], array(self::CONTENT_JS, self::CONTENT_CSS));
535:
536: if (empty($this->macros[$name])) {
537: throw new CompileException("Unknown macro {{$name}}" . ($inScript ? ' (in JavaScript or CSS, try to put a space after bracket.)' : ''));
538: }
539:
540: if ($this->context[1] === self::CONTENT_URL) {
541: $modifiers = preg_replace('#\|nosafeurl\s?(?=\||\z)#i', '', $modifiers, -1, $found);
542: if (!$found && !preg_match('#\|datastream(?=\s|\||\z)#i', $modifiers)) {
543: $modifiers .= '|safeurl';
544: }
545: }
546:
547: $modifiers = preg_replace('#\|noescape\s?(?=\||\z)#i', '', $modifiers, -1, $found);
548: if (!$found && strpbrk($name, '=~%^&_')) {
549: $modifiers .= '|escape';
550: }
551:
552: if (!$found && $inScript && $name === '=' && preg_match('#["\'] *\z#', $this->tokens[$this->position - 1]->text)) {
553: throw new CompileException("Do not place {$this->tokens[$this->position]->text} inside quotes.");
554: }
555:
556: foreach (array_reverse($this->macros[$name]) as $macro) {
557: $node = new MacroNode($macro, $name, $args, $modifiers, $this->macroNode, $this->htmlNode, $nPrefix);
558: if ($macro->nodeOpened($node) !== FALSE) {
559: return $node;
560: }
561: }
562: throw new CompileException("Unhandled macro {{$name}}");
563: }
564:
565:
566: private static function printEndTag(MacroNode $node)
567: {
568: if ($node->prefix) {
569: return "</{$node->htmlNode->name}> for macro-attribute " . Parser::N_PREFIX
570: . implode(' and ' . Parser::N_PREFIX, array_keys($node->htmlNode->macroAttrs));
571: } else {
572: return "{/$node->name}";
573: }
574: }
575:
576: }
577: