paulgoughbooks_old
This repository has no backups
This repository's network speed is throttled to 100KB/sec
Upgrade your account to fix these warnings, or use backups.vc for automated backups
@ 2
paulgoughbooks_old / trunk / system / View / Parser.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 |
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014-2019 British Columbia Institute of Technology * Copyright (c) 2019-2020 CodeIgniter Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author CodeIgniter Dev Team * @copyright 2019-2020 CodeIgniter Foundation * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 4.0.0 * @filesource */ namespace CodeIgniter\View; use CodeIgniter\View\Exceptions\ViewException; use Psr\Log\LoggerInterface; /** * Class Parser * * ClassFormerlyKnownAsTemplateParser * * @package CodeIgniter\View */ class Parser extends View { /** * Left delimiter character for pseudo vars * * @var string */ public $leftDelimiter = '{'; /** * Right delimiter character for pseudo vars * * @var string */ public $rightDelimiter = '}'; /** * Stores extracted noparse blocks. * * @var array */ protected $noparseBlocks = []; /** * Stores any plugins registered at run-time. * * @var array */ protected $plugins = []; /** * Stores the context for each data element * when set by `setData` so the context is respected. * * @var array */ protected $dataContexts = []; //-------------------------------------------------------------------- /** * Constructor * * @param \Config\View $config * @param string $viewPath * @param mixed $loader * @param boolean $debug * @param LoggerInterface $logger */ public function __construct($config, string $viewPath = null, $loader = null, bool $debug = null, LoggerInterface $logger = null) { // Ensure user plugins override core plugins. $this->plugins = $config->plugins ?? []; parent::__construct($config, $viewPath, $loader, $debug, $logger); } //-------------------------------------------------------------------- /** * Parse a template * * Parses pseudo-variables contained in the specified template view, * replacing them with any data that has already been set. * * @param string $view * @param array $options * @param boolean $saveData * * @return string */ public function render(string $view, array $options = null, bool $saveData = null): string { $start = microtime(true); if (is_null($saveData)) { $saveData = $this->config->saveData; } $fileExt = pathinfo($view, PATHINFO_EXTENSION); $view = empty($fileExt) ? $view . '.php' : $view; // allow Views as .html, .tpl, etc (from CI3) // Was it cached? if (isset($options['cache'])) { $cacheName = $options['cache_name'] ?? str_replace('.php', '', $view); if ($output = cache($cacheName)) { $this->logPerformance($start, microtime(true), $view); return $output; } } $file = $this->viewPath . $view; if (! is_file($file)) { $file = $this->loader->locateFile($view, 'Views'); } // locateFile will return an empty string if the file cannot be found. if (empty($file)) { throw ViewException::forInvalidFile($file); } if (is_null($this->tempData)) { $this->tempData = $this->data; } $template = file_get_contents($file); $output = $this->parse($template, $this->tempData, $options); $this->logPerformance($start, microtime(true), $view); if ($saveData) { $this->data = $this->tempData; } // Should we cache? if (isset($options['cache'])) { cache()->save($cacheName, $output, (int) $options['cache']); } $this->tempData = null; return $output; } //-------------------------------------------------------------------- /** * Parse a String * * Parses pseudo-variables contained in the specified string, * replacing them with any data that has already been set. * * @param string $template * @param array $options * @param boolean $saveData * * @return string */ public function renderString(string $template, array $options = null, bool $saveData = null): string { $start = microtime(true); if (is_null($saveData)) { $saveData = $this->config->saveData; } if (is_null($this->tempData)) { $this->tempData = $this->data; } $output = $this->parse($template, $this->tempData, $options); $this->logPerformance($start, microtime(true), $this->excerpt($template)); if ($saveData) { $this->data = $this->tempData; } $this->tempData = null; return $output; } //-------------------------------------------------------------------- /** * Sets several pieces of view data at once. * In the Parser, we need to store the context here * so that the variable is correctly handled within the * parsing itself, and contexts (including raw) are respected. * * @param array $data * @param string $context The context to escape it for: html, css, js, url, raw * If 'raw', no escaping will happen * * @return RendererInterface */ public function setData(array $data = [], string $context = null): RendererInterface { if (! empty($context)) { foreach ($data as $key => &$value) { if (is_array($value)) { foreach ($value as &$obj) { $obj = $this->objectToArray($obj); } } else { $value = $this->objectToArray($value); } $this->dataContexts[$key] = $context; } } $this->tempData = $this->tempData ?? $this->data; $this->tempData = array_merge($this->tempData, $data); return $this; } //-------------------------------------------------------------------- /** * Parse a template * * Parses pseudo-variables contained in the specified template, * replacing them with the data in the second param * * @param string $template * @param array $data * @param array $options Future options * * @return string */ protected function parse(string $template, array $data = [], array $options = null): string { if ($template === '') { return ''; } // Remove any possible PHP tags since we don't support it // and parseConditionals needs it clean anyway... $template = str_replace(['<?', '?>'], ['<?', '?>'], $template); $template = $this->parseComments($template); $template = $this->extractNoparse($template); // Replace any conditional code here so we don't have to parse as much $template = $this->parseConditionals($template); // Handle any plugins before normal data, so that // it can potentially modify any template between its tags. $template = $this->parsePlugins($template); // loop over the data variables, replacing // the content as we go. foreach ($data as $key => $val) { $escape = true; if (is_array($val)) { $escape = false; $replace = $this->parsePair($key, $val, $template); } else { $replace = $this->parseSingle($key, (string) $val); } foreach ($replace as $pattern => $content) { $template = $this->replaceSingle($pattern, $content, $template, $escape); } } return $this->insertNoparse($template); } //-------------------------------------------------------------------- /** * Parse a single key/value, extracting it * * @param string $key * @param string $val * @return array */ protected function parseSingle(string $key, string $val): array { $pattern = '#' . $this->leftDelimiter . '!?\s*' . preg_quote($key) . '\s*\|*\s*([|\w<>=\(\),:.\-\s\+\\\\/]+)*\s*!?' . $this->rightDelimiter . '#ms'; return [$pattern => $val]; } //-------------------------------------------------------------------- /** * Parse a tag pair * * Parses tag pairs: {some_tag} string... {/some_tag} * * @param string $variable * @param array $data * @param string $template * @return array */ protected function parsePair(string $variable, array $data, string $template): array { // Holds the replacement patterns and contents // that will be used within a preg_replace in parse() $replace = []; // Find all matches of space-flexible versions of {tag}{/tag} so we // have something to loop over. preg_match_all( '#' . $this->leftDelimiter . '\s*' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '(.+?)' . $this->leftDelimiter . '\s*' . '/' . preg_quote($variable) . '\s*' . $this->rightDelimiter . '#s', $template, $matches, PREG_SET_ORDER ); /* * Each match looks like: * * $match[0] {tag}...{/tag} * $match[1] Contents inside the tag */ foreach ($matches as $match) { // Loop over each piece of $data, replacing // it's contents so that we know what to replace in parse() $str = ''; // holds the new contents for this tag pair. foreach ($data as $row) { // Objects that have a `toArray()` method should be // converted with that method (i.e. Entities) if (is_object($row) && method_exists($row, 'toArray')) { $row = $row->toArray(); } // Otherwise, cast as an array and it will grab public properties. else if (is_object($row)) { $row = (array)$row; } $temp = []; $pairs = []; $out = $match[1]; foreach ($row as $key => $val) { // For nested data, send us back through this method... if (is_array($val)) { $pair = $this->parsePair($key, $val, $match[1]); if (! empty($pair)) { $pairs[array_keys( $pair )[0]] = true; $temp = array_merge($temp, $pair); } continue; } else if (is_object($val)) { $val = 'Class: ' . get_class($val); } else if (is_resource($val)) { $val = 'Resource'; } $temp['#' . $this->leftDelimiter . '!?\s*' . preg_quote($key) . '\s*\|*\s*([|\w<>=\(\),:.\-\s\+\\\\/]+)*\s*!?' . $this->rightDelimiter . '#s'] = $val; } // Now replace our placeholders with the new content. foreach ($temp as $pattern => $content) { $out = $this->replaceSingle($pattern, $content, $out, ! isset( $pairs[$pattern] ) ); } $str .= $out; } //Escape | character from filters as it's handled as OR in regex $escaped_match = preg_replace('/(?<!\\\\)\\|/', '\\|', $match[0]); $replace['#' . $escaped_match . '#s'] = $str; } return $replace; } //-------------------------------------------------------------------- /** * Removes any comments from the file. Comments are wrapped in {# #} symbols: * * {# This is a comment #} * * @param string $template * * @return string */ protected function parseComments(string $template): string { return preg_replace('/\{#.*?#\}/s', '', $template); } //-------------------------------------------------------------------- /** * Extracts noparse blocks, inserting a hash in its place so that * those blocks of the page are not touched by parsing. * * @param string $template * * @return string */ protected function extractNoparse(string $template): string { $pattern = '/\{\s*noparse\s*\}(.*?)\{\s*\/noparse\s*\}/ms'; /* * $matches[][0] is the raw match * $matches[][1] is the contents */ if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { // Create a hash of the contents to insert in its place. $hash = md5($match[1]); $this->noparseBlocks[$hash] = $match[1]; $template = str_replace($match[0], "noparse_{$hash}", $template); } } return $template; } //-------------------------------------------------------------------- /** * Re-inserts the noparsed contents back into the template. * * @param string $template * * @return string */ public function insertNoparse(string $template): string { foreach ($this->noparseBlocks as $hash => $replace) { $template = str_replace("noparse_{$hash}", $replace, $template); unset($this->noparseBlocks[$hash]); } return $template; } //-------------------------------------------------------------------- /** * Parses any conditionals in the code, removing blocks that don't * pass so we don't try to parse it later. * * Valid conditionals: * - if * - elseif * - else * * @param string $template * * @return string */ protected function parseConditionals(string $template): string { $pattern = '/\{\s*(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*\}/ms'; /** * For each match: * [0] = raw match `{if var}` * [1] = conditional `if` * [2] = condition `do === true` * [3] = same as [2] */ preg_match_all($pattern, $template, $matches, PREG_SET_ORDER); foreach ($matches as $match) { // Build the string to replace the `if` statement with. $condition = $match[2]; $statement = $match[1] === 'elseif' ? '<?php elseif (' . $condition . '): ?>' : '<?php if (' . $condition . '): ?>'; $template = str_replace($match[0], $statement, $template); } $template = preg_replace('/\{\s*else\s*\}/ms', '<?php else: ?>', $template); $template = preg_replace('/\{\s*endif\s*\}/ms', '<?php endif; ?>', $template); // Parse the PHP itself, or insert an error so they can debug ob_start(); if (is_null($this->tempData)) { $this->tempData = $this->data; } extract($this->tempData); try { eval('?>' . $template . '<?php '); } catch (\ParseError $e) { ob_end_clean(); throw ViewException::forTagSyntaxError(str_replace(['?>', '<?php '], '', $template)); } return ob_get_clean(); } //-------------------------------------------------------------------- /** * Over-ride the substitution field delimiters. * * @param string $leftDelimiter * @param string $rightDelimiter * @return RendererInterface */ public function setDelimiters($leftDelimiter = '{', $rightDelimiter = '}'): RendererInterface { $this->leftDelimiter = $leftDelimiter; $this->rightDelimiter = $rightDelimiter; return $this; } //-------------------------------------------------------------------- /** * Handles replacing a pseudo-variable with the actual content. Will double-check * for escaping brackets. * * @param $pattern * @param $content * @param $template * @param boolean $escape * * @return string */ protected function replaceSingle($pattern, $content, $template, bool $escape = false): string { // Any dollar signs in the pattern will be mis-interpreted, so slash them $pattern = addcslashes($pattern, '$'); // Replace the content in the template $template = preg_replace_callback($pattern, function ($matches) use ($content, $escape) { // Check for {! !} syntax to not-escape this one. if (strpos($matches[0], '{!') === 0 && substr($matches[0], -2) === '!}') { $escape = false; } return $this->prepareReplacement($matches, $content, $escape); }, $template); return $template; } //-------------------------------------------------------------------- /** * Callback used during parse() to apply any filters to the value. * * @param array $matches * @param string $replace * @param boolean $escape * * @return string */ protected function prepareReplacement(array $matches, string $replace, bool $escape = true): string { $orig = array_shift($matches); // Our regex earlier will leave all chained values on a single line // so we need to break them apart so we can apply them all. $filters = isset($matches[0]) ? explode('|', $matches[0]) : []; if ($escape && ! isset($matches[0])) { if ($context = $this->shouldAddEscaping($orig)) { $filters[] = "esc({$context})"; } } return $this->applyFilters($replace, $filters); } //-------------------------------------------------------------------- /** * Checks the placeholder the view provided to see if we need to provide any autoescaping. * * @param string $key * * @return false|string */ public function shouldAddEscaping(string $key) { $escape = false; $key = trim(str_replace(['{', '}'], '', $key)); // If the key has a context stored (from setData) // we need to respect that. if (array_key_exists($key, $this->dataContexts)) { if ($this->dataContexts[$key] !== 'raw') { return $this->dataContexts[$key]; } } // No pipes, then we know we need to escape elseif (strpos($key, '|') === false) { $escape = 'html'; } // If there's a `noescape` then we're definitely false. elseif (strpos($key, 'noescape') !== false) { $escape = false; } // If no `esc` filter is found, then we'll need to add one. elseif (! preg_match('/\s+esc/', $key)) { $escape = 'html'; } return $escape; } //-------------------------------------------------------------------- /** * Given a set of filters, will apply each of the filters in turn * to $replace, and return the modified string. * * @param string $replace * @param array $filters * * @return string */ protected function applyFilters(string $replace, array $filters): string { // Determine the requested filters foreach ($filters as $filter) { // Grab any parameter we might need to send preg_match('/\([\w<>=\/\\\,:.\-\s\+]+\)/', $filter, $param); // Remove the () and spaces to we have just the parameter left $param = ! empty($param) ? trim($param[0], '() ') : null; // Params can be separated by commas to allow multiple parameters for the filter if (! empty($param)) { $param = explode(',', $param); // Clean it up foreach ($param as &$p) { $p = trim($p, ' "'); } } else { $param = []; } // Get our filter name $filter = ! empty($param) ? trim(strtolower(substr($filter, 0, strpos($filter, '(')))) : trim($filter); if (! array_key_exists($filter, $this->config->filters)) { continue; } // Filter it.... $replace = $this->config->filters[$filter]($replace, ...$param); } return $replace; } //-------------------------------------------------------------------- // Plugins //-------------------------------------------------------------------- /** * Scans the template for any parser plugins, and attempts to execute them. * Plugins are notated based on {+ +} opening and closing braces. * * When encountered, * * @param string $template * * @return string */ protected function parsePlugins(string $template) { foreach ($this->plugins as $plugin => $callable) { // Paired tags are enclosed in an array in the config array. $isPair = is_array($callable); $callable = $isPair ? array_shift($callable) : $callable; $pattern = $isPair ? '#{\+\s*' . $plugin . '([\w\d=-_:\+\s()/\"@.]*)?\s*\+}(.+?){\+\s*/' . $plugin . '\s*\+}#ims' : '#{\+\s*' . $plugin . '([\w\d=-_:\+\s()/\"@.]*)?\s*\+}#ims'; /** * Match tag pairs * * Each match is an array: * $matches[0] = entire matched string * $matches[1] = all parameters string in opening tag * $matches[2] = content between the tags to send to the plugin. */ preg_match_all($pattern, $template, $matches, PREG_SET_ORDER); if (empty($matches)) { continue; } foreach ($matches as $match) { $params = []; preg_match_all('/([\w-]+=\"[^"]+\")|([\w-]+=[^\"\s=]+)|(\"[^"]+\")|(\S+)/', trim($match[1]), $matchesParams); foreach ($matchesParams[0] as $item) { $keyVal = explode('=', $item); if (count($keyVal) === 2) { $params[$keyVal[0]] = str_replace('"', '', $keyVal[1]); } else { $params[] = str_replace('"', '', $item); } } $template = $isPair ? str_replace($match[0], $callable($match[2], $params), $template) : str_replace($match[0], $callable($params), $template); } } return $template; } /** * Makes a new plugin available during the parsing of the template. * * @param string $alias * @param callable $callback * * @param boolean $isPair * * @return $this */ public function addPlugin(string $alias, callable $callback, bool $isPair = false) { $this->plugins[$alias] = $isPair ? [$callback] : $callback; return $this; } //-------------------------------------------------------------------- /** * Removes a plugin from the available plugins. * * @param string $alias * * @return $this */ public function removePlugin(string $alias) { unset($this->plugins[$alias]); return $this; } /** * Converts an object to an array, respecting any * toArray() methods on an object. * * @param $value * * @return mixed */ protected function objectToArray($value) { // Objects that have a `toArray()` method should be // converted with that method (i.e. Entities) if (is_object($value) && method_exists($value, 'toArray')) { $value = $value->toArray(); } // Otherwise, cast as an array and it will grab public properties. else if (is_object($value)) { $value = (array)$value; } return $value; } //-------------------------------------------------------------------- } |
Commits for paulgoughbooks_old/trunk/system/View/Parser.php
Revision | Author | Commited | Message |
---|---|---|---|
2 | tporter | Tue 03 Nov, 2020 08:50:21 +0000 | Migration of Paul Goughs Books site to Codeignitor 4 |