Compare commits

..

5 Commits

Author SHA1 Message Date
Simon Wisselink 4c9b156d8b some link fixes 2021-12-03 11:56:44 +01:00
Simon Wisselink 313707df94 Added TOCs, rewrote most important links in documentation. Linked README to new Github Pages site 2021-12-03 11:47:39 +01:00
Simon Wisselink ea5f03e2e2 Removed BC docs, added TOC 2021-12-03 10:38:26 +01:00
Simon Wisselink d5d2e69d04 Set theme jekyll-theme-minimal 2021-12-03 10:16:00 +01:00
Simon Wisselink 845523e684 Add converted docs repo 2021-12-03 10:13:31 +01:00
279 changed files with 1520 additions and 2185 deletions
+2 -4
View File
@@ -7,10 +7,8 @@
# exclude from git export
/tests export-ignore
/utilities export-ignore
/docker-compose.yml export-ignore
/.github export-ignore
/run_tests_for_all_php_versions.sh export-ignore
/utilities/ export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/make-release.sh export-ignore
+7 -13
View File
@@ -1,10 +1,8 @@
# https://help.github.com/en/categories/automating-your-workflow-with-github-actions
on:
pull_request:
push:
branches:
- 'master'
- pull_request
- push
name: CI
@@ -30,8 +28,6 @@ jobs:
- "7.3"
- "7.4"
- "8.0"
- "8.1"
- "8.2"
compiler:
- default
@@ -40,12 +36,6 @@ jobs:
- os: ubuntu-latest
php-version: "8.0"
compiler: jit
- os: ubuntu-latest
php-version: "8.1"
compiler: jit
- os: ubuntu-latest
php-version: "8.2"
compiler: jit
steps:
- name: Checkout
@@ -75,5 +65,9 @@ jobs:
restore-keys: |
${{ runner.os }}-php-${{ matrix.php-version }}-
- name: Install dependencies
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest
- name: Run tests with phpunit
run: ./run-tests.sh
run: ./phpunit.sh
+1
View File
@@ -5,6 +5,7 @@
lexer/*.php
lexer/*.php.bak
lexer/*.out
utilies/*.php
# Dev
phpunit*
-83
View File
@@ -6,89 +6,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
- `$smarty->muteUndefinedOrNullWarnings()` now also mutes PHP7 notices for undefined array indexes [#736](https://github.com/smarty-php/smarty/issues/736)
## [4.3.0] - 2022-11-22
### Added
- PHP8.2 compatibility [#775](https://github.com/smarty-php/smarty/pull/775)
### Changed
- Include docs and demo in the releases [#799](https://github.com/smarty-php/smarty/issues/799)
- Using PHP functions as modifiers now triggers a deprecation notice because we will drop support for this in the next major release [#813](https://github.com/smarty-php/smarty/issues/813)
- Dropped remaining references to removed PHP-support in Smarty 4 from docs, lexer and security class. [#816](https://github.com/smarty-php/smarty/issues/816)
- Support umask when writing (template) files and set dir permissions to 777 [#548](https://github.com/smarty-php/smarty/issues/548) [#819](https://github.com/smarty-php/smarty/issues/819)
### Fixed
- Output buffer is now cleaned for internal PHP errors as well, not just for Exceptions [#514](https://github.com/smarty-php/smarty/issues/514)
- Fixed recursion and out of memory errors when caching in complicated template set-ups using inheritance and includes [#801](https://github.com/smarty-php/smarty/pull/801)
- Fixed PHP8.1 deprecation errors in strip_tags
- Fix Variable Usage in Exception message when unable to load subtemplate [#808](https://github.com/smarty-php/smarty/pull/808)
- Fixed PHP8.1 deprecation notices for strftime [#672](https://github.com/smarty-php/smarty/issues/672)
- Fixed PHP8.1 deprecation errors passing null to parameter in trim [#807](https://github.com/smarty-php/smarty/pull/807)
- Adapt Smarty upper/lower functions to be codesafe (e.g. for Turkish locale) [#586](https://github.com/smarty-php/smarty/pull/586)
- Bug fix for underscore and limited length in template name in custom resources [#581](https://github.com/smarty-php/smarty/pull/581)
## [4.2.1] - 2022-09-14
### Security
- Applied appropriate javascript and html escaping in mailto plugin to counter injection attacks [#454](https://github.com/smarty-php/smarty/issues/454)
### Fixed
- Fixed PHP8.1 deprecation notices in modifiers (upper, explode, number_format and replace) [#755](https://github.com/smarty-php/smarty/pull/755) and [#788](https://github.com/smarty-php/smarty/pull/788)
- Fixed PHP8.1 deprecation notices in capitalize modifier [#789](https://github.com/smarty-php/smarty/issues/789)
- Fixed use of `rand()` without a parameter in math function [#794](https://github.com/smarty-php/smarty/issues/794)
- Fixed unselected year/month/day not working in html_select_date [#395](https://github.com/smarty-php/smarty/issues/395)
## [4.2.0] - 2022-08-01
### Fixed
- Fixed problems with smarty_mb_str_replace [#549](https://github.com/smarty-php/smarty/issues/549)
- Fixed second parameter of unescape modifier not working [#777](https://github.com/smarty-php/smarty/issues/777)
### Changed
- Updated HTML of the debug template [#599](https://github.com/smarty-php/smarty/pull/599)
## [4.1.1] - 2022-05-17
### Security
- Prevent PHP injection through malicious block name or include file name. This addresses CVE-2022-29221
### Fixed
- Exclude docs and demo from export and composer [#751](https://github.com/smarty-php/smarty/pull/751)
- PHP 8.1 deprecation notices in demo/plugins/cacheresource.pdo.php [#706](https://github.com/smarty-php/smarty/issues/706)
- PHP 8.1 deprecation notices in truncate modifier [#699](https://github.com/smarty-php/smarty/issues/699)
- Math equation `max(x, y)` didn't work anymore [#721](https://github.com/smarty-php/smarty/issues/721)
- Fix PHP 8.1 deprecated warning when calling rtrim [#743](https://github.com/smarty-php/smarty/pull/743)
- PHP 8.1: fix deprecation in escape modifier [#727](https://github.com/smarty-php/smarty/pull/727)
## [4.1.0] - 2022-02-06
### Added
- PHP8.1 compatibility [#713](https://github.com/smarty-php/smarty/pull/713)
## [4.0.4] - 2022-01-18
### Fixed
- Fixed illegal characters bug in math function security check [#702](https://github.com/smarty-php/smarty/issues/702)
## [4.0.3] - 2022-01-10
### Security
- Prevent evasion of the `static_classes` security policy. This addresses CVE-2021-21408
## [4.0.2] - 2022-01-10
### Security
- Prevent arbitrary PHP code execution through maliciously crafted expression for the math function. This addresses CVE-2021-29454
## [4.0.1] - 2022-01-09
### Security
- Rewrote the mailto function to not use `eval` when encoding with javascript
## [4.0.0] - 2021-11-25
## [4.0.0-rc.0] - 2021-10-13
+10 -2
View File
@@ -7,7 +7,7 @@ Smarty is a template engine for PHP, facilitating the separation of presentation
Read the [documentation](https://smarty-php.github.io/smarty/) to find out how to use it.
## Requirements
Smarty can be run with PHP 7.1 to PHP 8.2.
Smarty can be run with PHP 7.1 to PHP 8.0.
## Installation
Smarty versions 3.1.11 or later can be installed with [Composer](https://getcomposer.org/).
@@ -17,4 +17,12 @@ To get the latest stable version of Smarty use:
composer require smarty/smarty
````
More in the [Getting Started](./docs/getting-started.md) section of the docs.
To get the latest, unreleased version, use:
```bash
composer require smarty/smarty:dev-master
````
To get the previous stable version of Smarty, Smarty 3, use:
```bash
composer require smarty/smarty:^3
````
+1 -1
View File
@@ -2,7 +2,7 @@
## Supported Versions
Smarty currently supports the latest minor version of Smarty 3 and Smarty 4.
Smarty currently supports the latest minor version of Smarty 3 and Smarty 4. (Smarty 4 has not been released yet.)
| Version | Supported |
| ------- | ------------------ |
+2 -2
View File
@@ -5,7 +5,7 @@
"keywords": [
"templating"
],
"homepage": "https://smarty-php.github.io/smarty/",
"homepage": "https://www.smarty.net",
"license": "LGPL-3.0",
"authors": [
{
@@ -27,7 +27,7 @@
],
"support": {
"issues": "https://github.com/smarty-php/smarty/issues",
"forum": "https://github.com/smarty-php/smarty/discussions"
"forum": "https://www.smarty.net/forums/"
},
"require": {
"php": "^7.1 || ^8.0"
+2 -2
View File
@@ -196,7 +196,7 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
* @return void
* @access protected
*/
protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime)
protected function fetch($id, $name, $cache_id = null, $compile_id = null, &$content, &$mtime)
{
$stmt = $this->getFetchStatement($this->fetchColumns, $id, $cache_id, $compile_id);
$stmt->execute();
@@ -244,7 +244,7 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
* @return boolean success
* @access protected
*/
protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
protected function save($id, $name, $cache_id = null, $compile_id = null, $exp_time, $content)
{
$stmt = $this->pdo->prepare($this->insertStatement);
$stmt->bindValue('id', $id);
-45
View File
@@ -1,45 +0,0 @@
version: "2"
services:
base:
build:
context: .
dockerfile: ./utilities/testrunners/php71/Dockerfile
volumes:
- .:/app
working_dir: /app
entrypoint: sh ./run-tests.sh
php71:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php71/Dockerfile
php72:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php72/Dockerfile
php73:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php73/Dockerfile
php74:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php74/Dockerfile
php80:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php80/Dockerfile
php81:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php81/Dockerfile
php82:
extends:
service: base
build:
dockerfile: ./utilities/testrunners/php82/Dockerfile
+5
View File
@@ -0,0 +1,5 @@
BUGS
====
Check the `BUGS` file that comes with the latest distribution of Smarty,
or check the website.
+15
View File
@@ -0,0 +1,15 @@
Resources {#inforesources}
=========
Smarty\'s homepage is located at [URL.SMARTY](&url.smarty;)
- You can join the mailing list by sending an e-mail to ``. An archive
of the mailing list can be viewed at [here](&url.ml.archive;)
- Forums are at [URL.FORUMS](&url.forums;)
- The wiki is located at [URL.WIKI](&url.wiki;)
- Join the chat at [irc.freenode.net\#smarty](&url.wiki;)
- FAQ\'s are [here](&url.faq_1;) and [here](&url.faq_2;)
+65 -2
View File
@@ -188,6 +188,67 @@ See also [`{html_select_date}`](#language.function.html.select.date),
[`date_format`](#language.modifier.date.format) and
[`$smarty.now`](#language.variables.smarty.now),
WAP/WML {#tips.wap}
=======
WAP/WML templates require a php [Content-Type
header](&url.php-manual;header) to be passed along with the template.
The easist way to do this would be to write a custom function that
prints the header. If you are using [caching](#caching), that won\'t
work so we\'ll do it using the [`{insert}`](#language.function.insert)
tag; remember `{insert}` tags are not cached! Be sure that there is
nothing output to the browser before the template, or else the header
may fail.
<?php
// be sure apache is configure for the .wml extensions!
// put this function somewhere in your application, or in Smarty.addons.php
function insert_header($params)
{
// this function expects $content argument
if (empty($params['content'])) {
return;
}
header($params['content']);
return;
}
?>
your Smarty template *must* begin with the insert tag :
{insert name=header content="Content-Type: text/vnd.wap.wml"}
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<!-- begin new wml deck -->
<wml>
<!-- begin first card -->
<card>
<do type="accept">
<go href="#two"/>
</do>
<p>
Welcome to WAP with Smarty!
Press OK to continue...
</p>
</card>
<!-- begin second card -->
<card id="two">
<p>
Pretty easy isn't it?
</p>
</card>
</wml>
Componentized Templates {#tips.componentized.templates}
=======================
@@ -198,7 +259,7 @@ Smarty object, [`assign()`](#api.assign) the variables and
[`display()`](#api.display) the template. So lets say for example we
have a stock ticker on our template. We would collect the stock data in
our application, then assign these variables in the template and display
it. Now wouldn't it be nice if you could add this stock ticker to any
it. Now wouldn\'t it be nice if you could add this stock ticker to any
application by merely including the template, and not worry about
fetching the data up front?
@@ -240,7 +301,9 @@ assigning it to a template variable.
See also: [`{include}`](#language.function.include).
See also [`{include_php}`](#language.function.include.php),
[`{include}`](#language.function.include) and
[`{php}`](#language.function.php).
Obfuscating E-mail Addresses {#tips.obfuscating.email}
============================
+1 -1
View File
@@ -109,7 +109,7 @@ the corresponding error is in the template.
- This means that your application registered a custom error handler
- This means that your application registered a custom error hander
(using [set\_error\_handler()](&url.php-manual;set_error_handler))
which is not respecting the given `$errno` as it should. If, for
whatever reason, this is the desired behaviour of your custom error
-13
View File
@@ -1,18 +1,6 @@
Basic Syntax
============
A simple Smarty template could look like this:
```html
<h1>{$title|escape}</h1>
<ul>
{foreach $cities as $city}
<li>{$city.name|escape} ({$city.population})</li>
{foreachelse}
<li>no cities found</li>
{/foreach}
</ul>
```
All Smarty template tags are enclosed within delimiters. By default
these are `{` and `}`, but they can be
[changed](../programmers/api-variables/variable-left-delimiter.md).
@@ -23,7 +11,6 @@ displayed as static content, or unchanged. When Smarty encounters
template tags, it attempts to interpret them, and displays the
appropriate output in their place.
The basis components of the Smarty syntax are:
- [Comments](./language-basic-syntax/language-syntax-comments.md)
- [Variables](./language-basic-syntax/language-syntax-variables.md)
- [Functions](./language-basic-syntax/language-syntax-functions.md)
@@ -3,7 +3,7 @@ Attributes {#language.syntax.attributes}
Most of the [functions](#language.syntax.functions) take attributes that
specify or modify their behavior. Attributes to Smarty functions are
much like HTML attributes. Static values don't have to be enclosed in
much like HTML attributes. Static values don\'t have to be enclosed in
quotes, but it is required for literal strings. Variables with or
without modifiers may also be used, and should not be in quotes. You can
even use PHP function results, plugin results and complex expressions.
@@ -16,10 +16,12 @@ Built-in Functions {#language.builtin.functions}
- [{function}](./language-builtin-functions/language-function-function.md)
- [{if},{elseif},{else}](./language-builtin-functions/language-function-if.md)
- [{include}](./language-builtin-functions/language-function-include.md)
- [{include_php}](./language-builtin-functions/language-function-include.php)
- [{insert}](./language-builtin-functions/language-function-insert.md)
- [{ldelim},{rdelim}](./language-builtin-functions/language-function-ldelim.md)
- [{literal}](./language-builtin-functions/language-function-literal.md)
- [{nocache}](./language-builtin-functions/language-function-nocache.md)
- [{php}](./language-builtin-functions/language-function-php.md)
- [{section},{sectionelse}](./language-builtin-functions/language-function-section.md)
- [{setfilter}](./language-builtin-functions/language-function-setfilter.md)
- [{strip}](./language-builtin-functions/language-function-strip.md)
@@ -135,6 +135,7 @@ The following functions can also *optionally* assign template variables.
[`{capture}`](#language.function.capture),
[`{include}`](#language.function.include),
[`{include_php}`](#language.function.include.php),
[`{insert}`](#language.function.insert),
[`{counter}`](#language.function.counter),
[`{cycle}`](#language.function.cycle),
@@ -3,14 +3,14 @@
`{block}` is used to define a named area of template source for template
inheritance. For details see section of [Template
Inheritance](#advanced.features.template.inheritance).
Interitance](#advanced.features.template.inheritance).
The `{block}` template source area of a child template will replace the
corresponding areas in the parent template(s).
correponding areas in the parent template(s).
Optionally `{block}` areas of child and parent templates can be merged
into each other. You can append or prepend the parent `{block}` content
by using the `append` or `prepend` option flag with the child's `{block}`
by using the `append` or `prepend` option flag with the childs `{block}`
definition. With the {\$smarty.block.parent} the `{block}` content of
the parent template can be inserted at any location of the child
`{block}` content. {\$smarty.block.child} inserts the `{block}` content
@@ -3,7 +3,7 @@
`{extends}` tags are used in child templates in template inheritance for
extending parent templates. For details see section of [Template
Inheritance](#advanced.features.template.inheritance).
Interitance](#advanced.features.template.inheritance).
- The `{extends}` tag must be on the first line of the template.
@@ -33,5 +33,5 @@ Inheritance](#advanced.features.template.inheritance).
See also [Template Inheritance](#advanced.features.template.inheritance)
See also [Template Interitance](#advanced.features.template.inheritance)
and [`{block}`](#language.function.block).
@@ -2,7 +2,7 @@
=====
The `{for}{forelse}` tag is used to create simple loops. The following
different formats are supported:
different formarts are supported:
- `{for $var=$start to $end}` simple loop with step size of 1.
@@ -0,0 +1,74 @@
{include\_php} {#language.function.include.php}
==============
> **Note**
>
> `{include_php}` is deprecated from Smarty, use registered plugins to
> properly insulate presentation from the application code. As of Smarty
> 3.1 the `{include_php}` tags are only available from [SmartyBC](#bc).
Attribute Name Type Required Default Description
---------------- --------- ---------- --------- ----------------------------------------------------------------------------------
file string Yes *n/a* The name of the php file to include as absolute path
once boolean No *TRUE* whether or not to include the php file more than once if included multiple times
assign string No *n/a* The name of the variable that the output of include\_php will be assigned to
**Option Flags:**
Name Description
--------- ----------------------------------------
nocache Disables caching of inluded PHP script
`{include_php}` tags are used to include a php script in your template.
The path of the attribute `file` can be either absolute, or relative to
[`$trusted_dir`](#variable.trusted.dir). If security is enabled, then
the script must be located in the `$trusted_dir` path of the securty
policy. See the [Security](#advanced.features.security) section for
details.
By default, php files are only included once even if called multiple
times in the template. You can specify that it should be included every
time with the `once` attribute. Setting once to FALSE will include the
php script each time it is included in the template.
You can optionally pass the `assign` attribute, which will specify a
template variable name that the output of `{include_php}` will be
assigned to instead of displayed.
The smarty object is available as `$_smarty_tpl->smarty` within the PHP
script that you include.
The `load_nav.php` file:
<?php
// load in variables from a mysql db and assign them to the template
require_once('database.class.php');
$db = new Db();
$db->query('select url, name from navigation order by name');
$this->assign('navigation', $db->getRows());
?>
where the template is:
{* absolute path, or relative to $trusted_dir *}
{include_php file='/path/to/load_nav.php'}
{include_php '/path/to/load_nav.php'} {* short-hand *}
{foreach item='nav' from=$navigation}
<a href="{$nav.url}">{$nav.name}</a><br />
{/foreach}
See also [`{include}`](#language.function.include),
[`$trusted_dir`](#variable.trusted.dir),
[`{php}`](#language.function.php),
[`{capture}`](#language.function.capture), [template
resources](#resources) and [componentized
templates](#tips.componentized.templates)
@@ -131,7 +131,7 @@ cache lifetime of 500 seconds.
In this example included template will be cached independent of the
global caching setting.
global cahing setting.
{include 'sub_template.tpl' caching}
@@ -188,5 +188,7 @@ current template.
See also [`{insert}`](#language.function.insert), [template resources](#resources) and
See also [`{include_php}`](#language.function.include.php),
[`{insert}`](#language.function.insert),
[`{php}`](#language.function.php), [template resources](#resources) and
[componentized templates](#tips.componentized.templates).
@@ -65,7 +65,7 @@ and display the returned results in place of the {insert} tag.
The path can be either absolute, or relative to
[`$trusted_dir`](#variable.trusted.dir). If security is enabled,
then the script must be located in the `$trusted_dir` path of the
security policy. See the [Security](#advanced.features.security)
securty policy. See the [Security](#advanced.features.security)
section for details.
The Smarty object is passed as the second argument. This way you can
@@ -0,0 +1,45 @@
{php} {#language.function.php}
=====
> **Note**
>
> `{php}` tags are deprecated from Smarty, and should not be used. Put
> your PHP logic in PHP scripts or plugin functions instead.
> **Note**
>
> As of Smarty 3.1 the `{php}` tags are only available from
> [SmartyBC](#bc).
The `{php}` tags allow PHP code to be embedded directly into the
template. They will not be escaped, regardless of the
[`$php_handling`](#variable.php.handling) setting.
{php}
// including a php script directly from the template.
include('/path/to/display_weather.php');
{/php}
{* this template includes a {php} block that assign's the variable $varX *}
{php}
global $foo, $bar;
if($foo == $bar){
echo 'This will be sent to browser';
}
// assign a variable to Smarty
$this->assign('varX','Toffee');
{/php}
{* output the variable *}
<strong>{$varX}</strong> is my fav ice cream :-)
See also [`$php_handling`](#variable.php.handling),
[`{include_php}`](#language.function.include.php),
[`{include}`](#language.function.include),
[`{insert}`](#language.function.insert) and [componentized
templates](#tips.componentized.templates).
@@ -251,8 +251,8 @@ The above example will output:
{section}\'s can be nested as deep as you like. With nested
{section}\'s, you can access complex data structures, such as
multi-dimensional arrays. This is an example `.php` script that
assigns the arrays.
multi-dimensional arrays. This is an example `.php` script thats
assign\'s the arrays.
<?php
@@ -10,7 +10,7 @@ The filter can be:
- A variable filter plugin specified by it\'s name.
- A modifier specified by it\'s name and optional additional
- A modidier specified by it\'s name and optional additional
parameter.
`{setfilter}...{/setfilter}` blocks can be nested. The filter definition
@@ -22,7 +22,7 @@ ftp and display the contents.
>
> If security is enabled and you are fetching a file from the local
> file system, `{fetch}` will only allow files from within the
> `$secure_dir` path of the security policy. See the
> `$secure_dir` path of the securty policy. See the
> [Security](#advanced.features.security) section for details.
- If the `assign` attribute is set, the output of the `{fetch}`
@@ -19,7 +19,7 @@ automatically calculated from the image file if they are not supplied.
from. If not given, the web server\'s document root
`$_ENV['DOCUMENT_ROOT']` is used as the base. If security is
enabled, then the image must be located in the `$secure_dir` path of
the security policy. See the [Security](#advanced.features.security)
the securty policy. See the [Security](#advanced.features.security)
section for details.
- `href` is the href value to link the image to. If link is supplied,
+1 -1
View File
@@ -115,7 +115,7 @@ These parameters follow the modifier name and are separated by a `:`
- Secondly - if security is enabled, all php-functions that are to
be used as modifiers have to be declared trusted in the
`$modifiers` property of the security policy. See the
`$modifiers` property of the securty policy. See the
[Security](../programmers/advanced-features/advanced-features-security.md) section for details.
See also [`registerPlugin()`](../programmers/api-functions/api-register-plugin.md), [combining
@@ -15,5 +15,5 @@ modifier](#language.modifier.to_charset).
> modifier should only be used in cases where the application cannot
> anticipate that a certain string is required in another encoding.
See also [Charset Encoding](#charset), [from\_charset
See also [Charset Enconding](#charset), [from\_charset
modifier](#language.modifier.from_charset).
@@ -15,5 +15,5 @@ modifier](#language.modifier.from_charset).
> modifier should only be used in cases where the application cannot
> anticipate that a certain string is required in another encoding.
See also [Charset Encoding](#charset), [from\_charset
See also [Charset Enconding](#charset), [from\_charset
modifier](#language.modifier.from_charset).
@@ -157,13 +157,13 @@ Returns the version of Smarty the template was compiled with.
----------------------
Returns block text from child template. See [Template
inheritance](#advanced.features.template.inheritance).
interitance](#advanced.features.template.inheritance).
{\$smarty.block.parent} {#language.variables.smarty.block.parent}
-----------------------
Returns block text from parent template. See [Template
inheritance](#advanced.features.template.inheritance)
interitance](#advanced.features.template.inheritance)
{\$smarty.ldelim}, {\$smarty.rdelim} {#language.variables.smarty.ldelim}
------------------------------------
-152
View File
@@ -1,152 +0,0 @@
Features
=======
Some of Smarty's features:
- It is extremely fast.
- It is efficient since the PHP parser does the dirty work.
- No template parsing overhead, only compiles once.
- It is smart about [recompiling](#variable.compile.check) only the
template files that have changed.
- You can easily create your own custom
[functions](#language.custom.functions) and [variable
modifiers](#language.modifiers), so the template language is
extremely extensible.
- Configurable template [{delimiter}](#variable.left.delimiter) tag
syntax, so you can use `{$foo}`, `{{$foo}}`, `<!--{$foo}-->`, etc.
- The [`{if}..{elseif}..{else}..{/if}`](#language.function.if)
constructs are passed to the PHP parser, so the `{if...}` expression
syntax can be as simple or as complex an evaluation as you like.
- Allows unlimited nesting of
[`sections`](#language.function.section), `if's` etc.
- Built-in [caching](#caching) support
- Arbitrary [template](#resources) sources
- [Template Inheritance](#advanced.features.template.inheritance) for
easy management of template content.
- [Plugin](#plugins) architecture
## Separation of presentation from application code
- This means templates can certainly contain logic under the condition
that it is for presentation only. Things such as
[including](./designers/language-builtin-functions/language-function-include.md) other templates,
[alternating](./designers/language-custom-functions/language-function-cycle.md) table row colors,
[upper-casing](./designers/language-modifiers/language-modifier-upper.md) a variable,
[looping](./designers/language-builtin-functions/language-function-foreach.md) over an array of data and
rendering it are examples of presentation logic.
- This does not mean however that Smarty forces a separation of
business and presentation logic. Smarty has no knowledge of which is
which, so placing business logic in the template is your own doing.
- Also, if you desire *no* logic in your templates you certainly can
do so by boiling the content down to text and variables only.
## How does it work?
Under the hood, Smarty "compiles" (basically copies and converts) the
templates into PHP scripts. This happens once when each template is
first invoked, and then the compiled versions are used from that point
forward. Smarty takes care of this for you, so the template designer
just edits the Smarty templates and never has to manage the compiled
versions. This approach keeps the templates easy to maintain, and yet
keeps execution times extremely fast since the compiled code is just
PHP. And of course, all PHP scripts take advantage of PHP op-code caches
such as APC.
## Template Inheritance
Template inheritance was introduced in Smarty 3. Before template
inheritance, we managed our templates in
pieces such as header and footer templates. This organization lends
itself to many problems that require some hoop-jumping, such as managing
content within the header/footer on a per-page basis. With template
inheritance, instead of including other templates we maintain our
templates as single pages. We can then manipulate blocks of content
within by inheriting them. This makes templates intuitive, efficient and
easy to manage. See
[Template Inheritance](./programmers/advanced-features/advanced-features-template-inheritance.md)
for more info.
## Why not use XML/XSLT syntax?
There are a couple of good reasons. First, Smarty can be used for more
than just XML/HTML based templates, such as generating emails,
javascript, CSV, and PDF documents. Second, XML/XSLT syntax is even more
verbose and fragile than PHP code! It is perfect for computers, but
horrible for humans. Smarty is about being easy to read, understand and
maintain.
## Template Security
Although Smarty insulates you from PHP, you still have the option to use
it in certain ways if you wish. Template security forces the restriction
of PHP (and select Smarty functions.) This is useful if you have third
parties editing templates, and you don't want to unleash the full power
of PHP or Smarty to them.
## Integration
Sometimes Smarty gets compared to Model-View-Controller (MVC)
frameworks. Smarty is not an MVC, it is just the presentation layer,
much like the View (V) part of an MVC. As a matter of fact, Smarty can
easily be integrated as the view layer of an MVC. Many of the more
popular ones have integration instructions for Smarty, or you may find
some help here in the forums and documentation.
## Other Template Engines
Smarty is not the only engine following the *"Separate Programming Code
from Presentation"* philosophy. For instance, Python has template
engines built around the same principles such as Django Templates and
CheetahTemplate. *Note: Languages such as Python do not mix with HTML
natively, which give them the advantage of proper programming code
separation from the outset. There are libraries available to mix Python
with HTML, but they are typically avoided.*
## What Smarty is Not
Smarty is not an application development framework. Smarty is not an
MVC. Smarty is not an alternative to Laravel, Symfony, CodeIgniter,
or any of the other application development frameworks for PHP.
Smarty is a template engine, and works as the (V)iew component of your
application. Smarty can easily be coupled to any of the engines listed
above as the view component. No different than any other software,
Smarty has a learning curve. Smarty does not guarantee good application
design or proper separation of presentation, this still needs to be
addressed by a competent developer and web designer.
## Is Smarty Right for Me?
Smarty is not meant to be a tool for every job. The important thing is
to identify if Smarty fits your needs. There are some important
questions to ask yourself:
### Template Syntax
Are you content with PHP tags mixed with HTML? Are your
web designers comfortable with PHP? Would your web designers prefer a
tag-based syntax designed for presentation? Some experience working with
both Smarty and PHP helps answer these questions.
### The Business Case
Is there a requirement to insulate the templates from
PHP? Do you have untrusted parties editing templates that you do not
wish to unleash the power of PHP to? Do you need to programmatically
control what is and is not available within the templates? Smarty
supplies these capabilities by design.
## Feature set
Does Smarty's features such as caching, template
inheritance and plugin architecture save development cycles writing code
that would be needed otherwise? Does the codebase or framework you plan
on using have the features you need for the presentation component?
## Sites using Smarty
Many well-known PHP projects make use of Smarty such as XOOPS CMS, CMS Made Simple, Tiki
CMS/Groupware and X-Cart to name a few.
## Summary
Whether you are using Smarty for a small website or massive enterprise
solution, it can accommodate your needs. There are numerous features
that make Smarty a great choice:
- separation of PHP from HTML/CSS just makes sense
- readability for organization and management
- security for 3rd party template access
- feature completeness, and easily extendable to your own needs
- massive user base, Smarty is here to stay
- LGPL license for commercial use
- 100% free to use, open source project
+353 -105
View File
@@ -1,56 +1,267 @@
What is Smarty?
==============
===============
## Requirements
Smarty can be run with PHP 7.1 to PHP 8.2.
Smarty is a template engine for PHP. More specifically, it facilitates a
manageable way to separate application logic and content from its
presentation. This is best described in a situation where the
application programmer and the template designer play different roles,
or in most cases are not the same person.
## Installation
Smarty versions 3.1.11 or later can be installed with [Composer](https://getcomposer.org/).
For example, let\'s say you are creating a web page that is displaying a
newspaper article.
To get the latest stable version of Smarty use:
```bash
composer require smarty/smarty
````
- The article `$headline`, `$tagline`, `$author` and `$body` are
content elements, they contain no information about how they will be
presented. They are [passed](#api.assign) into Smarty by the
application.
To get the latest, unreleased version, use:
```bash
composer require smarty/smarty:dev-master
````
- Then the template designer edits the templates and uses a
combination of HTML tags and [template tags](#language.basic.syntax)
to format the presentation of these
[variables](#language.syntax.variables) with elements such as
tables, div\'s, background colors, font sizes, style sheets, svg
etc.
To get the previous stable version of Smarty, Smarty 3, use:
```bash
composer require smarty/smarty:^3
````
- One day the programmer needs to change the way the article content
is retrieved, ie a change in application logic. This change does not
affect the template designer, the content will still arrive in the
template exactly the same.
Here's how you create an instance of Smarty in your PHP scripts:
```php
<?php
- Likewise, if the template designer wants to completely redesign the
templates, this would require no change to the application logic.
require 'vendor/autoload.php';
$smarty = new Smarty();
```
- Therefore, the programmer can make changes to the application logic
without the need to restructure templates, and the template designer
can make changes to templates without breaking application logic.
Now that the library files are in place, it's time to setup the Smarty
directories for your application.
One design goal of Smarty is the separation of business logic and
presentation logic.
Smarty requires four directories which are by default named
[`templates`](./programmers/api-variables/variable-template-dir.md),
[`configs`](./programmers/api-variables/variable-config-dir.md),
[`templates_c`](./programmers/api-variables/variable-compile-dir.md)
and
[`cache`](./programmers/api-variables/variable-cache-dir.md)
relative to the current working directory.
- This means templates can certainly contain logic under the condition
that it is for presentation only. Things such as
[including](#language.function.include) other templates,
[alternating](#language.function.cycle) table row colors,
[upper-casing](#language.modifier.upper) a variable,
[looping](#language.function.foreach) over an array of data and
[displaying](#api.display) it are examples of presentation logic.
The defaults can be changed as follows:
```php
$smarty = new Smarty();
$smarty->setTemplateDir('/some/template/dir');
$smarty->setConfigDir('/some/config/dir');
$smarty->setCompileDir('/some/compile/dir');
$smarty->setCacheDir('/some/cache/dir');
```
- This does not mean however that Smarty forces a separation of
business and presentation logic. Smarty has no knowledge of which is
which, so placing business logic in the template is your own doing.
The compile dir and cache dir need to be writable for the user running the PHP script.
- Also, if you desire *no* logic in your templates you certainly can
do so by boiling the content down to text and variables only.
**Some of Smarty\'s features:**
- It is extremely fast.
- It is efficient since the PHP parser does the dirty work.
- No template parsing overhead, only compiles once.
- It is smart about [recompiling](#variable.compile.check) only the
template files that have changed.
- You can easily create your own custom
[functions](#language.custom.functions) and [variable
modifiers](#language.modifiers), so the template language is
extremely extensible.
- Configurable template [{delimiter}](#variable.left.delimiter) tag
syntax, so you can use `{$foo}`, `{{$foo}}`, `<!--{$foo}-->`, etc.
- The [`{if}..{elseif}..{else}..{/if}`](#language.function.if)
constructs are passed to the PHP parser, so the `{if...}` expression
syntax can be as simple or as complex an evaluation as you like.
- Allows unlimited nesting of
[`sections`](#language.function.section), `if's` etc.
- Built-in [caching](#caching) support
- Arbitrary [template](#resources) sources
- [Template Inheritance](#advanced.features.template.inheritance) for
easy management of template content.
- [Plugin](#plugins) architecture
Installation
============
Requirements {#installation.requirements}
============
Smarty requires a web server running PHP 5.2 or greater.
Basic Installation {#installing.smarty.basic}
==================
Install the Smarty library files which are in the `/libs/` sub directory
of the distribution. These are `.php` files that you SHOULD NOT edit.
They are shared among all applications and only get changed when you
upgrade to a new version of Smarty.
In the examples below the Smarty tarball has been unpacked to:
- `/usr/local/lib/Smarty-v.e.r/` for \*nix machines
- and `c:\webroot\libs\Smarty-v.e.r\` for the windows environment.
<!-- -->
Smarty-v.e.r/
libs/
Smarty.class.php
debug.tpl
sysplugins/* (everything)
plugins/* (everything)
Smarty uses a PHP [constant](&url.php-manual;define) named
[`SMARTY_DIR`](#constant.smarty.dir) which is the **full system file
path** to the Smarty `libs/` directory. Basically, if your application
can find the `Smarty.class.php` file, you do not need to set the
[`SMARTY_DIR`](#constant.smarty.dir) as Smarty will figure it out on its
own. Therefore, if `Smarty.class.php` is not in your
[include\_path](&url.php-manual;ini.core.php#ini.include-path), or you
do not supply an absolute path to it in your application, then you must
define `SMARTY_DIR` manually. `SMARTY_DIR` **must include a trailing
slash/**.
::: {.informalexample}
Here\'s how you create an instance of Smarty in your PHP scripts:
<?php
// NOTE: Smarty has a capital 'S'
require_once('Smarty.class.php');
$smarty = new Smarty();
?>
:::
Try running the above script. If you get an error saying the
`Smarty.class.php` file could not be found, you need to do one of the
following:
<?php
// *nix style (note capital 'S')
define('SMARTY_DIR', '/usr/local/lib/Smarty-v.e.r/libs/');
// windows style
define('SMARTY_DIR', 'c:/webroot/libs/Smarty-v.e.r/libs/');
// hack version example that works on both *nix and windows
// Smarty is assumend to be in 'includes/' dir under current script
define('SMARTY_DIR',str_replace("\\","/",getcwd()).'/includes/Smarty-v.e.r/libs/');
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty = new Smarty();
?>
<?php
// *nix style (note capital 'S')
require_once('/usr/local/lib/Smarty-v.e.r/libs/Smarty.class.php');
// windows style
require_once('c:/webroot/libs/Smarty-v.e.r/libs/Smarty.class.php');
$smarty = new Smarty();
?>
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;
; *nix: "/path1:/path2"
include_path = ".:/usr/share/php:/usr/local/lib/Smarty-v.e.r/libs/"
; Windows: "\path1;\path2"
include_path = ".;c:\php\includes;c:\webroot\libs\Smarty-v.e.r\libs\"
<?php
// *nix
ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'/usr/local/lib/Smarty-v.e.r/libs/');
// windows
ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'c:/webroot/lib/Smarty-v.e.r/libs/');
?>
Now that the library files are in place, it\'s time to setup the Smarty
directories for your application:
- Smarty requires four directories which are by default named
`templates/`, `templates_c/`, `configs/` and `cache/`
- Each of these are definable by the Smarty class properties
[`$template_dir`](#variable.template.dir),
[`$compile_dir`](#variable.compile.dir),
[`$config_dir`](#variable.config.dir), and
[`$cache_dir`](#variable.cache.dir) respectively
- It is highly recommended that you setup a separate set of these
directories for each application that will use Smarty
- You can verify if your system has the correct access rights for
these directories with [`testInstall()`](#api.test.install).
For our installation example, we will be setting up the Smarty
environment for a guest book application. We picked an application only
for the purpose of a directory naming convention. You can use the same
environment for any application, just replace `guestbook/` with the name
of your application.
/usr/local/lib/Smarty-v.e.r/libs/
Smarty.class.php
debug.tpl
sysplugins/*
plugins/*
/web/www.example.com/
guestbook/
templates/
index.tpl
templates_c/
configs/
cache/
htdocs/
index.php
Be sure that you know the location of your web server\'s document root
as a file path. In the following examples, the document root is
`/web/www.example.com/guestbook/htdocs/`. The Smarty directories are
only accessed by the Smarty library and never accessed directly by the
web browser. Therefore to avoid any security concerns, it is recommended
(but not mandatory) to place these directories *outside* of the web
server\'s document root.
You will need as least one file under your document root, and that is
the script accessed by the web browser. We will name our script
`index.php`, and place it in a subdirectory under the document root
`/htdocs/`.
Smarty will need **write access** (windows users please ignore) to the
[`$compile_dir`](#variable.compile.dir) and
[`$cache_dir`](#variable.cache.dir) directories (`templates_c/` and
`cache/`), so be sure the web server user account can write to them.
> **Note**
>
@@ -59,62 +270,66 @@ The compile dir and cache dir need to be writable for the user running the PHP s
> can look in your `httpd.conf` file to see what user and group are
> being used.
```bash
chown nobody:nobody /web/www.example.com/guestbook/templates_c/
chmod 770 /web/www.example.com/guestbook/templates_c/
chown nobody:nobody /web/www.example.com/guestbook/cache/
chmod 770 /web/www.example.com/guestbook/cache/
```
chown nobody:nobody /web/www.example.com/guestbook/templates_c/
chmod 770 /web/www.example.com/guestbook/templates_c/
You can verify if your system has the correct access rights for
these directories with [`testInstall()`](./programmers/api-functions/api-test-install.md):
chown nobody:nobody /web/www.example.com/guestbook/cache/
chmod 770 /web/www.example.com/guestbook/cache/
```php
$smarty = new Smarty();
$smarty->setTemplateDir('/some/template/dir');
$smarty->setConfigDir('/some/config/dir');
$smarty->setCompileDir('/some/compile/dir');
$smarty->setCacheDir('/some/cache/dir');
$smarty->testInstall();
```
Now, let's create the `index.tpl` file that Smarty will display. This
needs to be located in the [`$template_dir`](./programmers/api-variables/variable-template-dir.md).
```html
{* Smarty *}
Hello {$name}, welcome to Smarty!
```
> **Note**
>
> `{* Smarty *}` is a template [comment](./designers/language-basic-syntax/language-syntax-comments.md). It
> `chmod 770` will be fairly tight security, it only allows user
> "nobody" and group "nobody" read/write access to the directories. If
> you would like to open up read access to anyone (mostly for your own
> convenience of viewing these files), you can use `775` instead.
We need to create the `index.tpl` file that Smarty will display. This
needs to be located in the [`$template_dir`](#variable.template.dir).
{* Smarty *}
Hello {$name}, welcome to Smarty!
> **Note**
>
> `{* Smarty *}` is a template [comment](#language.syntax.comments). It
> is not required, but it is good practice to start all your template
> files with this comment. It makes the file easy to recognize
> regardless of the file extension. For example, text editors could
> recognize the file and turn on special syntax highlighting.
Now lets edit our php file. We'll create an instance of Smarty,
[`assign()`](./programmers/api-functions/api-assign.md) a template variable and
[`display()`](./programmers/api-functions/api-display.md) the `index.tpl` file.
Now lets edit `index.php`. We\'ll create an instance of Smarty,
[`assign()`](#api.assign) a template variable and
[`display()`](#api.display) the `index.tpl` file.
```php
<?php
require 'vendor/autoload.php';
<?php
$smarty = new Smarty();
require_once(SMARTY_DIR . 'Smarty.class.php');
$smarty->setTemplateDir('/web/www.example.com/guestbook/templates/');
$smarty->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$smarty->setConfigDir('/web/www.example.com/guestbook/configs/');
$smarty->setCacheDir('/web/www.example.com/guestbook/cache/');
$smarty = new Smarty();
$smarty->assign('name', 'Ned');
$smarty->display('index.tpl');
$smarty->setTemplateDir('/web/www.example.com/guestbook/templates/');
$smarty->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$smarty->setConfigDir('/web/www.example.com/guestbook/configs/');
$smarty->setCacheDir('/web/www.example.com/guestbook/cache/');
```
$smarty->assign('name','Ned');
//** un-comment the following line to show the debug console
//$smarty->debugging = true;
$smarty->display('index.tpl');
?>
> **Note**
>
@@ -125,45 +340,78 @@ $smarty->display('index.tpl');
> absolute paths. This ensures that Smarty is getting files from the
> directories you intended.
Now, run your PHP file. You should see *\"Hello Ned, welcome to Smarty!\"*
Now navigate to the `index.php` file with the web browser. You should
see *\"Hello Ned, welcome to Smarty!\"*
You have completed the basic setup for Smarty!
## Extended Setup {#installing.smarty.extended}
Extended Setup {#installing.smarty.extended}
==============
This is a continuation of the [basic
installation](#installing.smarty.basic), please read that first!
A slightly more flexible way to setup Smarty is to extend the Smarty
class and initialize your Smarty
A slightly more flexible way to setup Smarty is to [extend the
class](&url.php-manual;ref.classobj) and initialize your Smarty
environment. So instead of repeatedly setting directory paths, assigning
the same vars, etc., we can do that in one place.
```php
<?php
Lets create a new directory `/php/includes/guestbook/` and make a new
file called `setup.php`. In our example environment, `/php/includes` is
in our `include_path`. Be sure you set this up too, or use absolute file
paths.
class Smarty_GuestBook extends Smarty {
public function __construct()
{
parent::__construct();
<?php
$this->setTemplateDir('/web/www.example.com/guestbook/templates/');
$this->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$this->setConfigDir('/web/www.example.com/guestbook/configs/');
$this->setCacheDir('/web/www.example.com/guestbook/cache/');
// load Smarty library
require('Smarty.class.php');
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->assign('app_name', 'Guest Book');
}
// The setup.php file is a good place to load
// required application library files, and you
// can do that right here. An example:
// require('guestbook/guestbook.lib.php');
}
```
class Smarty_GuestBook extends Smarty {
Now, we can use `Smarty_GuestBook` instead of `Smarty` in our scripts:
```php
$smarty = new Smarty_GuestBook();
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
```
function __construct()
{
// Class Constructor.
// These automatically get set with each new instance.
parent::__construct();
$this->setTemplateDir('/web/www.example.com/guestbook/templates/');
$this->setCompileDir('/web/www.example.com/guestbook/templates_c/');
$this->setConfigDir('/web/www.example.com/guestbook/configs/');
$this->setCacheDir('/web/www.example.com/guestbook/cache/');
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->assign('app_name', 'Guest Book');
}
}
?>
Now lets alter the `index.php` file to use `setup.php`:
<?php
require('guestbook/setup.php');
$smarty = new Smarty_GuestBook();
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
?>
Now you see it is quite simple to bring up an instance of Smarty, just
use `Smarty_GuestBook()` which automatically initializes everything for
our application.
+4 -27
View File
@@ -1,31 +1,12 @@
# Smarty 4 Documentation
Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic.
It allows you to write **templates**, using **variables**, **modifiers**, **functions** and **comments**, like this:
```html
<h1>{$title|escape}</h1>
<p>
The number of pixels is: {math equation="x * y" x=$height y=$width}.
</p>
```
When this template is rendered, with the value "Hello world" for the variable $title, 640 for $width,
and 480 for $height, the result is:
```html
<h1>Hello world</h1>
<p>
The number of pixels is: 307200.
</p>
```
## Introduction
- [Philosophy](./philosophy.md) - or "Why do I need a template engine?"
- [Features](./features.md) - or "Why do I want Smarty?"
- [Preface](./preface.md)
- [Getting Started](./getting-started.md)
## Smarty for template designers
## Smarty for template developers
- [Basic Syntax](./designers/language-basic-syntax.md)
- [Variables](./designers/language-variables.md)
- [Variable Modifiers](./designers/language-modifiers.md)
@@ -43,8 +24,4 @@ and 480 for $height, the result is:
- [Caching](./programmers/caching.md)
- [Resources](./programmers/resources.md)
- [Advanced Features](./programmers/advanced-features.md)
- [Extending Smarty With Plugins](./programmers/plugins.md)
## Other
- [Some random tips & tricks](./appendixes/tips.md)
- [Troubleshooting](./appendixes/troubleshooting.md)
- [Extending Smarty With Plugins](./programmers/plugins.md)
-108
View File
@@ -1,108 +0,0 @@
Philosophy
=======
## What is Smarty?
Smarty is a template engine for PHP. More specifically, it facilitates a
manageable way to separate application logic and content from its
presentation. This is best described in a situation where the
application programmer and the template designer play different roles,
or in most cases are not the same person.
For example, let\'s say you are creating a web page that is displaying a
newspaper article.
- The article `$headline`, `$tagline`, `$author` and `$body` are
content elements, they contain no information about how they will be
presented. They are [passed](#api.assign) into Smarty by the
application.
- Then the template designer edits the templates and uses a
combination of HTML tags and [template tags](#language.basic.syntax)
to format the presentation of these
[variables](#language.syntax.variables) with elements such as
tables, div\'s, background colors, font sizes, style sheets, svg
etc.
- One day the programmer needs to change the way the article content
is retrieved, ie a change in application logic. This change does not
affect the template designer, the content will still arrive in the
template exactly the same.
- Likewise, if the template designer wants to completely redesign the
templates, this would require no change to the application logic.
- Therefore, the programmer can make changes to the application logic
without the need to restructure templates, and the template designer
can make changes to templates without breaking application logic.
## Goals
The Smarty design was largely driven by these goals:
- clean separation of presentation from application code
- PHP backend, Smarty template frontend
- complement PHP, not replace it
- fast development/deployment for programmers and designers
- quick and easy to maintain
- syntax easy to understand, no PHP knowledge necessary
- flexibility for custom development
- security: insulation from PHP
- free, open source
## Two camps of thought
When it comes to templating in PHP, there are basically two camps of
thought. The first camp exclaims that \"PHP is a template engine\". This
approach simply mixes PHP code with HTML. Although this approach is
fastest from a pure script-execution point of view, many would argue
that the PHP syntax is messy and complicated when mixed with tagged
markup such as HTML.
The second camp exclaims that presentation should be void of all
programming code, and instead use simple tags to indicate where
application content is revealed. This approach is common with other
template engines (even in other programming languages), and is also the
approach that Smarty takes. The idea is to keep the templates focused
squarely on presentation, void of application code, and with as little
overhead as possible.
## Why is separating PHP from templates important?
Two major benefits:
- SYNTAX: Templates typically consist of semantic markup such as HTML.
PHP syntax works well for application code, but quickly degenerates
when mixed with HTML. Smarty\'s simple {tag} syntax is designed
specifically to express presentation. Smarty focuses your templates
on presentation and less on \"code\". This lends to quicker template
deployment and easier maintenance. Smarty syntax requires no working
knowledge of PHP, and is intuitive for programmers and
non-programmers alike.
- INSULATION: When PHP is mixed with templates, there are no
restrictions on what type of logic can be injected into a template.
Smarty insulates the templates from PHP, creating a controlled
separation of presentation from business logic. Smarty also has
security features that can further enforce restrictions on
templates.
## Web designers and PHP
A common question: "Web designers have to learn a syntax anyway, why
not PHP?" Of course web designers can learn PHP, and they may already
be familiar with it. The issue isn't their ability to learn PHP, it is
about the consequences of mixing PHP with HTML. If designers use PHP, it
is too easy to add code into templates that doesn't belong there (you
just handed them a swiss-army knife when they just needed a knife.) You
can teach them the rules of application design, but this is probably
something they don't really need to learn (now they are developers!)
The PHP manual is also an overwhelming pile of information to sift
through. It is like handing the owner of a car the factory assembly
manual when all they need is the owners manual. Smarty gives web
designers exactly the tools they need, and gives developers fine-grained
control over those tools. The simplicity of the tag-based syntax is also
a huge welcome for designers, it helps them streamline the organization
and management of templates.
+212
View File
@@ -0,0 +1,212 @@
Preface
=======
**The Philosophy**
The Smarty design was largely driven by these goals:
- clean separation of presentation from application code
- PHP backend, Smarty template frontend
- complement PHP, not replace it
- fast development/deployment for programmers and designers
- quick and easy to maintain
- syntax easy to understand, no PHP knowledge necessary
- flexibility for custom development
- security: insulation from PHP
- free, open source
**What is Smarty?**
Smarty is a template engine for PHP, facilitating the separation of
presentation (HTML/CSS) from application logic. This implies that *PHP
code is application logic*, and is separated from the presentation.
**Two camps of thought**
When it comes to templating in PHP, there are basically two camps of
thought. The first camp exclaims that \"PHP is a template engine\". This
approach simply mixes PHP code with HTML. Although this approach is
fastest from a pure script-execution point of view, many would argue
that the PHP syntax is messy and complicated when mixed with tagged
markup such as HTML.
The second camp exclaims that presentation should be void of all
programming code, and instead use simple tags to indicate where
application content is revealed. This approach is common with other
template engines (even in other programming languages), and is also the
approach that Smarty takes. The idea is to keep the templates focused
squarely on presentation, void of application code, and with as little
overhead as possible.
**Why is separating PHP from templates important?**
Two major benefits:
- SYNTAX: Templates typically consist of semantic markup such as HTML.
PHP syntax works well for application code, but quickly degenerates
when mixed with HTML. Smarty\'s simple {tag} syntax is designed
specifically to express presentation. Smarty focuses your templates
on presentation and less on \"code\". This lends to quicker template
deployment and easier maintenance. Smarty syntax requires no working
knowledge of PHP, and is intuitive for programmers and
non-programmers alike.
- INSULATION: When PHP is mixed with templates, there are no
restrictions on what type of logic can be injected into a template.
Smarty insulates the templates from PHP, creating a controlled
separation of presentation from business logic. Smarty also has
security features that can further enforce restrictions on
templates.
**Web designers and PHP**
A common question: \"Web designers have to learn a syntax anyways, why
not PHP?\" Of course web designers can learn PHP, and they may already
be familiar with it. The issue isn\'t their ability to learn PHP, it is
about the consequences of mixing PHP with HTML. If designers use PHP, it
is too easy to add code into templates that doesn\'t belong there (you
just handed them a swiss-army knife when they just needed a knife.) You
can teach them the rules of application design, but this is probably
something they don\'t really need to learn (now they are developers!)
The PHP manual is also an overwhelming pile of information to sift
through. It is like handing the owner of a car the factory assembly
manual when all they need is the owners manual. Smarty gives web
designers exactly the tools they need, and gives developers fine-grained
control over those tools. The simplicity of the tag-based syntax is also
a huge welcome for designers, it helps them streamline the organization
and management of templates.
**Implementation is Important**
Although Smarty gives you the tools to make a clean separation of
presentation from application code, it also gives you plenty of room to
bend those rules. A poor implementation (i.e. injecting PHP in
templates) will cause more problems than the presentation separation was
meant to resolve. The documentation does a good job of indicating what
things to watch out for. Also see the Best Practices section of the
Smarty website.
**How does it work?**
Under the hood, Smarty \"compiles\" (basically copies and converts) the
templates into PHP scripts. This happens once when each template is
first invoked, and then the compiled versions are used from that point
forward. Smarty takes care of this for you, so the template designer
just edits the Smarty templates and never has to manage the compiled
versions. This approach keeps the templates easy to maintain, and yet
keeps execution times extremely fast since the compiled code is just
PHP. And of course, all PHP scripts take advantage of PHP op-code caches
such as APC.
**Template Inheritance**
Template inheritance is new to Smarty 3, and it\'s one of many great new
features. Before template inheritance, we managed our templates in
pieces such as header and footer templates. This organization lends
itself to many problems that require some hoop-jumping, such as managing
content within the header/footer on a per-page basis. With template
inheritance, instead of including other templates we maintain our
templates as single pages. We can then manipulate blocks of content
within by inheriting them. This makes templates intuitive, efficient and
easy to manage. See the Template Inheritance section of th Smarty
website for more info.
**Why not use XML/XSLT syntax?**
There are a couple of good reasons. First, Smarty can be used for more
than just XML/HTML based templates, such as generating emails,
javascript, CSV, and PDF documents. Second, XML/XSLT syntax is even more
verbose and fragile than PHP code! It is perfect for computers, but
horrible for humans. Smarty is about being easy to read, understand and
maintain.
**Template Security**
Although Smarty insulates you from PHP, you still have the option to use
it in certain ways if you wish. Template security forces the restriction
of PHP (and select Smarty functions.) This is useful if you have third
parties editing templates, and you don\'t want to unleash the full power
of PHP or Smarty to them.
**Integration**
Sometimes Smarty gets compared to Model-View-Controller (MVC)
frameworks. Smarty is not an MVC, it is just the presentation layer,
much like the View (V) part of an MVC. As a matter of fact, Smarty can
easily be integrated as the view layer of an MVC. Many of the more
popular ones have integration instructions for Smarty, or you may find
some help here in the forums and documentation.
**Other Template Engines**
Smarty is not the only engine following the *\"Separate Programming Code
from Presentation\"* philosophy. For instance, Python has template
engines built around the same principles such as Django Templates and
CheetahTemplate. *Note: Languages such as Python do not mix with HTML
natively, which give them the advantage of proper programming code
separation from the outset. There are libraries available to mix Python
with HTML, but they are typically avoided.*
**What Smarty is Not**
Smarty is not an application development framework. Smarty is not an
MVC. Smarty is not an alternative to Zend Framework, CodeIgniter,
PHPCake, or any of the other application development frameworks for PHP.
Smarty is a template engine, and works as the (V)iew component of your
application. Smarty can easily be coupled to any of the engines listed
above as the view component. No different than any other software,
Smarty has a learning curve. Smarty does not guarantee good application
design or proper separation of presentation, this still needs to be
addressed by a competent developer and web designer.
**Is Smarty Right for Me?**
Smarty is not meant to be a tool for every job. The important thing is
to identify if Smarty fits your needs. There are some important
questions to ask yourself:
TEMPLATE SYNTAX. Are you content with PHP tags mixed with HTML? Are your
web designers comfortable with PHP? Would your web designers prefer a
tag-based syntax designed for presentation? Some experience working with
both Smarty and PHP helps answer these questions.
THE BUSINESS CASE: Is there a requirement to insulate the templates from
PHP? Do you have untrusted parties editing templates that you do not
wish to unleash the power of PHP to? Do you need to programmatically
control what is and is not available within the templates? Smarty
supplies these capabilities by design.
FEATURE SET: Does Smarty\'s features such as caching, template
inheritance and plugin architecture save development cycles writing code
that would be needed otherwise? Does the codebase or framework you plan
on using have the features you need for the presentation component?
Templating in PHP is a hot topic, and opinions widely vary. It is
important that you understand Smarty, understand your own requirements,
and make an informed decision for yourself. You are welcome to ask
specific questions in the forums or the IRC channel.
See also the section about \"Use Cases and Work Flow\" on the Smarty
website.
**Sites using Smarty**
There are tens of thousands of unique visitors on the Smarty website
daily, mostly developers reading documentation. Many well-known PHP
projects make use of Smarty such as XOOPS CMS, CMS Made Simple, Tiki
CMS/Groupware and X-Cart to name a few.
**Summary**
Whether you are using Smarty for a small website or massive enterprise
solution, it can accommodate your needs. There are numerous features
that make Smarty a great choice:
- separation of PHP from HTML/CSS just makes sense
- readability for organization and management
- security for 3rd party template access
- feature completeness, and easily extendable to your own needs
- massive user base, Smarty is here to stay
- LGPL license for commercial use
- 100% free to use, open source project
@@ -29,7 +29,7 @@ determined by your needs, but use the first method whenever possible to
keep template syntax to a minimum.
If security is enabled, no private methods or functions can be accessed
(beginning with \'\_\'). If a method and property of the same name exist,
(beginningwith \'\_\'). If a method and property of the same name exist,
the method will be used.
You can restrict the methods and properties that can be accessed by
@@ -2,20 +2,36 @@ Security {#advanced.features.security}
========
Security is good for situations when you have untrusted parties editing
the templates e.g. via ftp, and you want to reduce the risk of system
the templates eg via ftp, and you want to reduce the risk of system
security compromises through the template language.
The settings of the security policy are defined by properties of an
instance of the Smarty\_Security class. These are the possible settings:
- `$php_handling` determines how Smarty to handle PHP code embedded in
templates. Possible values are:
- Smarty::PHP\_PASSTHRU -\> echo PHP tags as they are
- Smarty::PHP\_QUOTE -\> escape tags as entities
- Smarty::PHP\_REMOVE -\> remove php tags
- Smarty::PHP\_ALLOW -\> execute php tags
The default value is Smarty::PHP\_PASSTHRU.
If security is enabled the [`$php_handling`](#variable.php.handling)
setting of the Smarty object is not checked for security.
- `$secure_dir` is an array of template directories that are
considered secure. [`$template_dir`](#variable.template.dir)
considered secure implicitly. The default is an empty array.
concidered secure implicitly. The default is an empty array.
- `$trusted_dir` is an array of all directories that are considered
trusted. Trusted directories are where you keep php scripts that are
executed directly from the templates with
[`{insert}`](#language.function.insert.php). The default is an
[`{include_php}`](#language.function.include.php). The default is an
empty array.
- `$trusted_uri` is an array of regular expressions matching URIs that
@@ -27,7 +43,7 @@ instance of the Smarty\_Security class. These are the possible settings:
like authentication-tokens).
The expression `'#https?://.*smarty.net$#i'` would allow accessing
the following URIs:
the follwing URIs:
- `http://smarty.net/foo`
@@ -94,8 +110,12 @@ instance of the Smarty\_Security class. These are the possible settings:
super globals can be accessed by the template. The default is
\"true\".
- `$allow_php_tag` is a boolean flag which controls if {php} and
{include\_php} tags can be used by the template. The default is
\"false\".
If security is enabled, no private methods, functions or properties of
static classes or assigned objects can be accessed (beginning with
static classes or assigned objects can be accessed (beginningwith
\'\_\') by the template.
To customize the security policy settings you can extend the
@@ -108,6 +128,8 @@ Smarty\_Security class or create an instance of it.
class My_Security_Policy extends Smarty_Security {
// disable all PHP functions
public $php_functions = null;
// remove PHP tags
public $php_handling = Smarty::PHP_REMOVE;
// allow everthing as modifier
public $php_modifiers = array();
}
@@ -123,6 +145,8 @@ Smarty\_Security class or create an instance of it.
$my_security_policy = new Smarty_Security($smarty);
// disable all PHP functions
$my_security_policy->php_functions = null;
// remove PHP tags
$my_security_policy->php_handling = Smarty::PHP_REMOVE;
// allow everthing as modifier
$my_security_policy->php_modifiers = array();
// enable security
@@ -140,5 +164,5 @@ Smarty\_Security class or create an instance of it.
> **Note**
>
> Most security policy settings are only checked when the template gets
> compiled. For that reason you should delete all cached and compiled
> compiled. For that reasion you should delete all cached and compiled
> template files when you change your security settings.
@@ -33,7 +33,7 @@ can override all or some of the parent named block areas.
you can define the whole template inheritance tree in the PHP script
when you are calling [`fetch()`](#api.fetch) or
[`display()`](#api.display) with the `extends:` template resource
type. The later provides even more flexibility.
type. The later provides even more flexibillity.
> **Note**
>
@@ -8,7 +8,7 @@ Modifications done to the Smarty object will be global for all
templates.
However the Smarty class variables and functions can be accessed or
called by individual template objects. Modification done to a template
called by induvidual template objects. Modification done to a template
object will apply only for that template and its included subtemplates.
@@ -26,7 +26,7 @@ the following parameters:
variables assigned to any of the objects in it\'s parent chain.
Data objects are used to create scopes for assigned variables. They can
be used to control which variables are seen by which templates.
be used to have controll which variables are seen by which templates.
<?php
@@ -9,7 +9,7 @@ string
disableSecurity
This disables security checking on templates.
This disables securty checking on templates.
See also [`enableSecurity()`](#api.enable.security), and
[Security](#advanced.features.security).
@@ -25,7 +25,7 @@ string
enableSecurity
This enables security checking on templates. It uses the following
This enables securty checking on templates. It uses the following
parameters:
- `securityclass` is an optional parameter. It\'s the name of the
@@ -16,6 +16,6 @@ given error was produced deliberately and must be ignored, or should be
passed on to the next error handler.
`Smarty::unmuteExpectedErrors()` removes the current error handler.
Please note, that if you\'ve registered any custom error handlers after
Please note, that if you\'ve registerd any custom error handlers after
the muteExpectedErrors() call, the unmute will not remove Smarty\'s
muting error handler, but the one registered last.
@@ -18,7 +18,7 @@ not find a definition for a tag otherwise. It uses the following
parameters:
If during compilation Smarty encounters tag which is not defined
internal, registered or located in the plugins folder it tries to
internal, registered or loacted in the plugins folder it tries to
resolve it by calling the registered default plugin handler. The handler
may be called several times for same undefined tag looping over valid
plugin types.
@@ -10,7 +10,7 @@ void
testInstall
This function verifies that all required working folders of the Smarty
installation can be accessed. It does output a corresponding protocol.
installation can be accessed. It does output a corresponding protocoll.
<?php
+1
View File
@@ -39,6 +39,7 @@ them directly, or use the corresponding setter/getter methods.
- [$left_delimiter](./api-variables/variable-left-delimiter.md)
- [$locking_timeout](./api-variables/variable-locking-timeout.md)
- [$merge_compiled_includes](./api-variables/variable-merge-compiled-includes.md)
- [$php_handling](./api-variables/variable-php-handling.md)
- [$plugins_dir](./api-variables/variable-plugins-dir.md)
- [$right_delimiter](./api-variables/variable-right-delimiter.md)
- [$smarty_debug_id](./api-variables/variable-smarty-debug-id.md)
@@ -1,7 +1,7 @@
\$compile\_id {#variable.compile.id}
=============
Persistent compile identifier. As an alternative to passing the same
Persistant compile identifier. As an alternative to passing the same
`$compile_id` to each and every function call, you can set this
`$compile_id` and it will be used implicitly thereafter.
@@ -10,7 +10,7 @@ post-filters](#plugins.prefilters.postfilters) you must use a unique
`$compile_id` to keep the compiled template files separated.
For example a [prefilter](#plugins.prefilters.postfilters) that
localizes your templates (that is: translates language dependent parts)
localizes your templates (that is: translates language dependend parts)
at compile time, then you could use the current language as
`$compile_id` and you will get a set of compiled templates for each
language you use.
@@ -3,7 +3,7 @@
Setting `$escape_html` to TRUE will escape all template variable output
by wrapping it in
`htmlspecialchars({$output}, ENT_QUOTES, $char_set);`,
`htmlspecialchars({$output}, ENT_QUOTES, SMARTY_RESOURCE_CHAR_SET);`,
which is the same as `{$variable|escape:"html"}`.
Template designers can choose to selectively disable this feature by
@@ -2,6 +2,6 @@
==================
This is maximum time in seconds a cache lock is valid to avoid dead
locks. The default value is 10 seconds.
locks. The deafult value is 10 seconds.
See also [`$cache_locking`](#variable.cache.locking)
@@ -0,0 +1,21 @@
\$php\_handling {#variable.php.handling}
===============
This tells Smarty how to handle PHP code embedded in the templates.
There are four possible settings, the default being
`Smarty::PHP_PASSTHRU`. Note that this does NOT affect php code within
[`{php}{/php}`](#language.function.php) tags in the template.
- `Smarty::PHP_PASSTHRU` - Smarty echos tags as-is.
- `Smarty::PHP_QUOTE` - Smarty quotes the tags as html entities.
- `Smarty::PHP_REMOVE` - Smarty removes the tags from the templates.
- `Smarty::PHP_ALLOW` - Smarty will execute the tags as PHP code.
> **Note**
>
> Embedding PHP code into templates is highly discouraged. Use [custom
> functions](#plugins.functions) or [modifiers](#plugins.modifiers)
> instead.
@@ -5,4 +5,4 @@
array of all directories that are considered trusted. Trusted
directories are where you keep php scripts that are executed directly
from the templates with
[`{insert}`](#language.function.insert.php).
[`{include_php}`](#language.function.include.php).
@@ -10,7 +10,7 @@ environments do not allow PHP processes to create directories, so this
must be disabled which is the default.
Sub directories are more efficient, so use them if you can.
Theoretically you get much better performance on a filesystem with 10
Theoretically you get much better perfomance on a filesystem with 10
directories each having 100 files, than with 1 directory having 1000
files. This was certainly the case with Solaris 7 (UFS)\... with newer
filesystems such as ext3 and especially reiserfs, the difference is
+2 -2
View File
@@ -25,10 +25,10 @@ like.
- You CANNOT remove a specified template name under multiple cache
groups such as `'/a/b/*/foo.tpl'`, the cache grouping works
left-to-right ONLY. You will need to group your templates under a
single cache group hierarchy to be able to clear them as a group.
single cache group heirarchy to be able to clear them as a group.
Cache grouping should not be confused with your template directory
hierarchy, the cache grouping has no knowledge of how your templates are
heirarchy, the cache grouping has no knowledge of how your templates are
structured. So for example, if you have a template structure like
`themes/blue/index.tpl` and you want to be able to clear all the cache
files for the "blue" theme, you will need to create a cache group
+6 -7
View File
@@ -5,17 +5,17 @@ Charset Encoding {#charset.encoding}
================
There are a variety of encodings for textual data, ISO-8859-1 (Latin1)
and UTF-8 being the most popular. Unless you change `Smarty::$_CHARSET`,
Smarty recognizes `UTF-8` as the internal charset if
[Multibyte String](https://www.php.net/mbstring) is available,
`ISO-8859-1` if not.
and UTF-8 being the most popular. Unless specified otherwise with the
`SMARTY_RESOURCE_CHAR_SET` constant, Smarty recognizes `UTF-8` as the
internal charset if [Multibyte String](https://www.php.net/mbstring) is
available, `ISO-8859-1` if not.
> **Note**
>
> `ISO-8859-1` has been PHP\'s default internal charset since the
> beginning. Unicode has been evolving since 1991. Since then it has
> become the one charset to conquer them all, as it is capable of
> encoding most of the known characters even across different character
> encoding most of the known characters even accross different character
> systems (latin, cyrillic, japanese, ...). `UTF-8` is unicode\'s most
> used encoding, as it allows referencing the thousands of character
> with the smallest size overhead possible.
@@ -36,9 +36,8 @@ Smarty recognizes `UTF-8` as the internal charset if
if (function_exists('mb_internal_charset')) {
mb_internal_charset('EUC-JP');
}
define('SMARTY_RESOURCE_CHAR_SET', 'EUC-JP');
require_once 'libs/Smarty.class.php';
Smarty::$_CHARSET = 'EUC-JP';
$smarty = new Smarty();
@@ -3,20 +3,20 @@ Extends Template Resources {#resources.extends}
The `extends:` resource is used to define child/parent relationships for
template inheritance from the PHP script. For details see section of
[Template Inheritance](#advanced.features.template.inheritance).
[Template Interitance](#advanced.features.template.inheritance).
As of Smarty 3.1 the `extends:` resource may use any available [template
resource](#resources), including `string:` and `eval:`. When [templates
from strings](#resources.string) are used, make sure they are properly
(url or base64) encoded. Is an `eval:` resource found within an
inheritance chain, its \"don\'t save a compile file\" property is
superseded by the `extends:` resource. The templates within an
superseeded by the `extends:` resource. The templates within an
inheritance chain are not compiled separately, though. Only a single
compiled template will be generated.
> **Note**
>
> Use this when inheritance is required programmatically. When inheriting
> Use this when inheritance is required programatically. When inheriting
> within PHP, it is not obvious from the child template what inheritance
> took place. If you have a choice, it is normally more flexible and
> intuitive to handle inheritance chains from within the templates.
+1 -1
View File
@@ -47,7 +47,7 @@ Templates from a specific \$template\_dir {#templates.from.specified.template.di
Smarty 3.1 introduced the bracket-syntax for specifying an element from
[`$template_dir`](#variable.template.dir). This allows websites
employing multiple sets of templates better control over which template
to access.
to acces.
The bracket-syntax can be used from anywhere you can specify the `file:`
resource type.
+2 -1
View File
@@ -23,4 +23,5 @@ to determine the appropriate value automatically. If defined, the path
See also [`$smarty.const`](../designers/language-variables/language-variables-smarty.md).
See also [`$smarty.const`](../designers/language-variables/language-variables-smarty.md) and
[`$php_handling constants`](./api-variables/variable-php-handling.md)
+1
View File
@@ -161,6 +161,7 @@ class Smarty_Internal_Templatelexer
'COMMENT' => 'comment',
'AS' => 'as',
'TO' => 'to',
'PHP' => '"<?php", "<%", "{php}" tag',
'LOGOP' => '"<", "==" ... logical operator',
'TLOGOP' => '"lt", "eq" ... logical operator; "is div by" ... if condition',
'SCOND' => '"is even" ... if condition',
-3
View File
@@ -747,9 +747,6 @@ value(res) ::= doublequoted_with_quotes(s). {
value(res) ::= varindexed(vi) DOUBLECOLON static_class_access(r). {
if ($this->security && $this->security->static_classes !== array()) {
$this->compiler->trigger_template_error('dynamic static class not allowed by security setting');
}
$prefixVar = $this->compiler->getNewPrefixVariable();
if (vi['var'] === '\'smarty\'') {
$this->compiler->appendPrefixCode("<?php {$prefixVar} = ". $this->compiler->compileTag('private_special_variable',array(),vi['smarty_internal_index']).';?>');
+2 -7
View File
@@ -5,11 +5,6 @@
* @package Smarty
*/
if (!defined('SMARTY_HELPER_FUNCTIONS_LOADED')) {
include __DIR__ . '/functions.php';
}
/**
* Smarty Autoloader
*
@@ -78,7 +73,7 @@ class Smarty_Autoloader
*/
public static function register($prepend = false)
{
self::$SMARTY_DIR = defined('SMARTY_DIR') ? SMARTY_DIR : __DIR__ . DIRECTORY_SEPARATOR;
self::$SMARTY_DIR = defined('SMARTY_DIR') ? SMARTY_DIR : dirname(__FILE__) . DIRECTORY_SEPARATOR;
self::$SMARTY_SYSPLUGINS_DIR = defined('SMARTY_SYSPLUGINS_DIR') ? SMARTY_SYSPLUGINS_DIR :
self::$SMARTY_DIR . 'sysplugins' . DIRECTORY_SEPARATOR;
spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
@@ -94,7 +89,7 @@ class Smarty_Autoloader
if ($class[ 0 ] !== 'S' || strpos($class, 'Smarty') !== 0) {
return;
}
$_class = smarty_strtolower_ascii($class);
$_class = strtolower($class);
if (isset(self::$rootClasses[ $_class ])) {
$file = self::$SMARTY_DIR . self::$rootClasses[ $_class ];
if (is_file($file)) {
+9 -17
View File
@@ -36,7 +36,7 @@ if (!defined('SMARTY_DIR')) {
/**
*
*/
define('SMARTY_DIR', __DIR__ . DIRECTORY_SEPARATOR);
define('SMARTY_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR);
}
/**
* set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins.
@@ -60,21 +60,12 @@ if (!defined('SMARTY_MBSTRING')) {
*/
define('SMARTY_MBSTRING', function_exists('mb_get_info'));
}
/**
* Load helper functions
*/
if (!defined('SMARTY_HELPER_FUNCTIONS_LOADED')) {
include __DIR__ . '/functions.php';
}
/**
* Load Smarty_Autoloader
*/
if (!class_exists('Smarty_Autoloader')) {
include __DIR__ . '/bootstrap.php';
include dirname(__FILE__) . '/bootstrap.php';
}
/**
* Load always needed external class files
*/
@@ -107,7 +98,7 @@ class Smarty extends Smarty_Internal_TemplateBase
/**
* smarty version
*/
const SMARTY_VERSION = '4.3.0';
const SMARTY_VERSION = '4.0.0';
/**
* define variable scopes
*/
@@ -876,7 +867,7 @@ class Smarty extends Smarty_Internal_TemplateBase
$this->plugins_dir = (array)$this->plugins_dir;
}
foreach ($this->plugins_dir as $k => $v) {
$this->plugins_dir[ $k ] = $this->_realpath(rtrim($v ?? '', '/\\') . DIRECTORY_SEPARATOR, true);
$this->plugins_dir[ $k ] = $this->_realpath(rtrim($v, '/\\') . DIRECTORY_SEPARATOR, true);
}
$this->_cache[ 'plugin_files' ] = array();
$this->_pluginsDirNormalized = true;
@@ -1354,7 +1345,7 @@ class Smarty extends Smarty_Internal_TemplateBase
*/
private function _normalizeDir($dirName, $dir)
{
$this->{$dirName} = $this->_realpath(rtrim($dir ?? '', "/\\") . DIRECTORY_SEPARATOR, true);
$this->{$dirName} = $this->_realpath(rtrim($dir, "/\\") . DIRECTORY_SEPARATOR, true);
}
/**
@@ -1376,7 +1367,7 @@ class Smarty extends Smarty_Internal_TemplateBase
}
foreach ($dir as $k => $v) {
if (!isset($processed[ $k ])) {
$dir[ $k ] = $v = $this->_realpath(rtrim($v ?? '', "/\\") . DIRECTORY_SEPARATOR, true);
$dir[ $k ] = $v = $this->_realpath(rtrim($v, "/\\") . DIRECTORY_SEPARATOR, true);
$processed[ $k ] = true;
}
}
@@ -1386,7 +1377,8 @@ class Smarty extends Smarty_Internal_TemplateBase
}
/**
* Mutes errors for "undefined index", "undefined array key" and "trying to read property of null".
* Activates PHP7 compatibility mode:
* - converts E_WARNINGS for "undefined array key" and "trying to read property of null" errors to E_NOTICE
*
* @void
*/
@@ -1395,7 +1387,7 @@ class Smarty extends Smarty_Internal_TemplateBase
}
/**
* Indicates if Smarty will mute errors for "undefined index", "undefined array key" and "trying to read property of null".
* Indicates if PHP7 compatibility mode is set.
* @bool
*/
public function isMutingUndefinedOrNullWarnings(): bool {
+1 -1
View File
@@ -11,6 +11,6 @@
* Load and register Smarty Autoloader
*/
if (!class_exists('Smarty_Autoloader')) {
include __DIR__ . '/Autoloader.php';
include dirname(__FILE__) . '/Autoloader.php';
}
Smarty_Autoloader::register(true);
+19 -34
View File
@@ -1,9 +1,9 @@
{capture name='_smarty_debug' assign=debug_output}
<!DOCTYPE html>
<html lang="en">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Smarty Debug Console</title>
<style>
<style type="text/css">
{literal}
body, h1, h2, h3, td, th, p {
font-family: sans-serif;
@@ -31,7 +31,6 @@
padding: 2px;
border-top: 1px solid black;
}
h3 {
text-align: left;
font-weight: bold;
@@ -68,11 +67,11 @@
color: green;
}
tr:nth-child(odd) {
.odd {
background-color: #eeeeee;
}
tr:nth-child(even) {
.even {
background-color: #fafafa;
}
@@ -85,16 +84,13 @@
color: black;
font-weight: bold;
}
#blue h3 {
color: blue;
}
#normal div {
color: black;
font-weight: normal;
}
#table_assigned_vars th {
color: blue;
font-weight: bold;
@@ -103,6 +99,7 @@
#table_config_vars th {
color: maroon;
}
{/literal}
</style>
</head>
@@ -115,11 +112,11 @@
<h2>included templates &amp; config files (load time in seconds)</h2>
<div>
{foreach $template_data as $template}
<span style="color: brown;">{$template.name}</span>
<br>&nbsp;&nbsp;<span class="exectime">
<font color=brown>{$template.name}</font>
<br />&nbsp;&nbsp;<span class="exectime">
(compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"})
</span>
<br>
<br />
{/foreach}
</div>
{/if}
@@ -128,22 +125,13 @@
<table id="table_assigned_vars">
{foreach $assigned_vars as $vars}
<tr>
<td>
<h3 style="color: blue;">${$vars@key}</h3>
{if isset($vars['nocache'])}<strong>Nocache</strong><br>{/if}
{if isset($vars['scope'])}<strong>Origin:</strong> {$vars['scope']|debug_print_var nofilter}{/if}
</td>
<td>
<h3>Value</h3>
{$vars['value']|debug_print_var:10:80 nofilter}
</td>
<td>
{if isset($vars['attributes'])}
<h3>Attributes</h3>
{$vars['attributes']|debug_print_var nofilter}
{/if}
<tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}">
<td><h3><font color=blue>${$vars@key}</font></h3>
{if isset($vars['nocache'])}<b>Nocache</b><br />{/if}
{if isset($vars['scope'])}<b>Origin:</b> {$vars['scope']|debug_print_var nofilter}{/if}
</td>
<td><h3>Value</h3>{$vars['value']|debug_print_var:10:80 nofilter}</td>
<td>{if isset($vars['attributes'])}<h3>Attributes</h3>{$vars['attributes']|debug_print_var nofilter} {/if}</td>
{/foreach}
</table>
@@ -151,14 +139,11 @@
<table id="table_config_vars">
{foreach $config_vars as $vars}
<tr>
<td>
<h3 style="color: blue;">#{$vars@key}#</h3>
{if isset($vars['scope'])}<strong>Origin:</strong> {$vars['scope']|debug_print_var nofilter}{/if}
</td>
<td>
{$vars['value']|debug_print_var:10:80 nofilter}
<tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}">
<td><h3><font color=blue>#{$vars@key}#</font></h3>
{if isset($vars['scope'])}<b>Origin:</b> {$vars['scope']|debug_print_var nofilter}{/if}
</td>
<td>{$vars['value']|debug_print_var:10:80 nofilter}</td>
</tr>
{/foreach}
-51
View File
@@ -1,51 +0,0 @@
<?php
/**
* This file is part of the Smarty package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Registers some helper/polyfill functions.
*/
const SMARTY_HELPER_FUNCTIONS_LOADED = true;
/**
* Converts the first characters in $string to uppercase (A-Z) if it is an ASCII lowercase character (a-z).
*
* May not be required when running PHP8.2+: https://wiki.php.net/rfc/strtolower-ascii
*
* @param $string
*
* @return string
*/
function smarty_ucfirst_ascii($string): string {
return smarty_strtoupper_ascii(substr($string, 0, 1)) . substr($string, 1);
}
/**
* Converts all uppercase ASCII characters (A-Z) in $string to lowercase (a-z).
*
* May not be required when running PHP8.2+: https://wiki.php.net/rfc/strtolower-ascii
*
* @param $string
*
* @return string
*/
function smarty_strtolower_ascii($string): string {
return strtr($string, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
}
/**
* Converts all lowercase ASCII characters (a-z) in $string to uppercase (A-Z).
*
* May not be required when running PHP8.2+: https://wiki.php.net/rfc/strtolower-ascii
*
* @param $string
*
* @return string
*/
function smarty_strtoupper_ascii($string): string {
return strtr($string, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
}
+33 -40
View File
@@ -101,7 +101,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$field_separator = "\n";
$option_separator = "\n";
$time = null;
// $all_empty = null;
// $day_empty = null;
// $month_empty = null;
@@ -114,7 +113,17 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
foreach ($params as $_key => $_value) {
switch ($_key) {
case 'time':
$$_key = $_value; // we'll handle conversion below
if (!is_array($_value) && $_value !== null) {
$template->_checkPlugins(
array(
array(
'function' => 'smarty_make_timestamp',
'file' => SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'
)
)
);
$time = smarty_make_timestamp($_value);
}
break;
case 'month_names':
if (is_array($_value) && count($_value) === 12) {
@@ -169,59 +178,43 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
}
// Note: date() is faster than strftime()
// Note: explode(date()) is faster than date() date() date()
if (isset($time) && is_array($time)) {
if (isset($time[$prefix . 'Year'])) {
if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) {
if (isset($params[ 'time' ][ $prefix . 'Year' ])) {
// $_REQUEST[$field_array] given
foreach ([
'Y' => 'Year',
'm' => 'Month',
'd' => 'Day'
] as $_elementKey => $_elementName) {
foreach (array(
'Y' => 'Year',
'm' => 'Month',
'd' => 'Day'
) as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName =
isset($time[$prefix . $_elementName]) ? $time[$prefix . $_elementName] :
isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] :
date($_elementKey);
}
} elseif (isset($time[$field_array][$prefix . 'Year'])) {
} elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Year' ])) {
// $_REQUEST given
foreach ([
'Y' => 'Year',
'm' => 'Month',
'd' => 'Day'
] as $_elementKey => $_elementName) {
foreach (array(
'Y' => 'Year',
'm' => 'Month',
'd' => 'Day'
) as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName = isset($time[$field_array][$prefix . $_elementName]) ?
$time[$field_array][$prefix . $_elementName] : date($_elementKey);
$$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ?
$params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey);
}
} else {
// no date found, use NOW
[$_year, $_month, $_day] = explode('-', date('Y-m-d'));
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} elseif (isset($time) && preg_match("/(\d*)-(\d*)-(\d*)/", $time, $matches)) {
$_year = $_month = $_day = null;
if ($matches[1] > '') $_year = (int) $matches[1];
if ($matches[2] > '') $_month = (int) $matches[2];
if ($matches[3] > '') $_day = (int) $matches[3];
} elseif ($time === null) {
if (array_key_exists('time', $params)) {
$_year = $_month = $_day = null;
$_year = $_month = $_day = $time = null;
} else {
[$_year, $_month, $_day] = explode('-', date('Y-m-d'));
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} else {
$template->_checkPlugins(
array(
array(
'function' => 'smarty_make_timestamp',
'file' => SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'
)
)
);
$time = smarty_make_timestamp($time);
[$_year, $_month, $_day] = explode('-', date('Y-m-d', $time));
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d', $time));
}
// make syntax "+N" or "-N" work with $start_year and $end_year
// Note preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match) is slower than trim+substr
foreach (array(
@@ -316,8 +309,8 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
for ($i = 1; $i <= 12; $i++) {
$_val = sprintf('%02d', $i);
$_text = isset($month_names) ? smarty_function_escape_special_chars($month_names[ $i ]) :
($month_format === '%m' ? $_val : @strftime($month_format, $_month_timestamps[ $i ]));
$_value = $month_value_format === '%m' ? $_val : @strftime($month_value_format, $_month_timestamps[ $i ]);
($month_format === '%m' ? $_val : strftime($month_format, $_month_timestamps[ $i ]));
$_value = $month_value_format === '%m' ? $_val : strftime($month_value_format, $_month_timestamps[ $i ]);
$_html_months .= '<option value="' . $_value . '"' . ($_val == $_month ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator;
}
+15 -20
View File
@@ -48,13 +48,8 @@
*/
function smarty_function_mailto($params)
{
static $_allowed_encoding = [
'javascript' => true,
'javascript_charcode' => true,
'hex' => true,
'none' => true
];
static $_allowed_encoding =
array('javascript' => true, 'javascript_charcode' => true, 'hex' => true, 'none' => true);
$extra = '';
if (empty($params[ 'address' ])) {
trigger_error("mailto: missing 'address' parameter", E_USER_WARNING);
@@ -62,19 +57,19 @@ function smarty_function_mailto($params)
} else {
$address = $params[ 'address' ];
}
$text = $address;
// netscape and mozilla do not decode %40 (@) in BCC field (bug?)
// so, don't encode it.
$mail_parms = [];
$search = array('%40', '%2C');
$replace = array('@', ',');
$mail_parms = array();
foreach ($params as $var => $value) {
switch ($var) {
case 'cc':
case 'bcc':
case 'followupto':
if (!empty($value)) {
$mail_parms[] = $var . '=' . str_replace(['%40', '%2C'], ['@', ','], rawurlencode($value));
$mail_parms[] = $var . '=' . str_replace($search, $replace, rawurlencode($value));
}
break;
case 'subject':
@@ -88,7 +83,6 @@ function smarty_function_mailto($params)
default:
}
}
if ($mail_parms) {
$address .= '?' . join('&', $mail_parms);
}
@@ -100,21 +94,22 @@ function smarty_function_mailto($params)
);
return;
}
$string = '<a href="mailto:' . htmlspecialchars($address, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, Smarty::$_CHARSET) .
'" ' . $extra . '>' . htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, Smarty::$_CHARSET) . '</a>';
// FIXME: (rodneyrehm) document.write() excues me what? 1998 has passed!
if ($encode === 'javascript') {
$string = 'document.write(\'<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>\');';
$js_encode = '';
for ($x = 0, $_length = strlen($string); $x < $_length; $x++) {
$js_encode .= '%' . bin2hex($string[ $x ]);
}
return '<script type="text/javascript">document.write(unescape(\'' . $js_encode . '\'))</script>';
return '<script type="text/javascript">eval(unescape(\'' . $js_encode . '\'))</script>';
} elseif ($encode === 'javascript_charcode') {
for ($x = 0, $_length = strlen($string); $x < $_length; $x++) {
$string = '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
for ($x = 0, $y = strlen($string); $x < $y; $x++) {
$ord[] = ord($string[ $x ]);
}
return '<script type="text/javascript">document.write(String.fromCharCode(' . implode(',', $ord) . '))</script>';
$_ret = "<script type=\"text/javascript\" language=\"javascript\">\n" . "{document.write(String.fromCharCode(" .
implode(',', $ord) . "))" . "}\n" . "</script>\n";
return $_ret;
} elseif ($encode === 'hex') {
preg_match('!^(.*)(\?.*)$!', $address, $match);
if (!empty($match[ 2 ])) {
@@ -137,6 +132,6 @@ function smarty_function_mailto($params)
return '<a href="' . $mailto . $address_encode . '" ' . $extra . '>' . $text_encode . '</a>';
} else {
// no encoding
return $string;
return '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
}
}
+1 -31
View File
@@ -28,12 +28,7 @@ function smarty_function_math($params, $template)
'int' => true,
'abs' => true,
'ceil' => true,
'acos' => true,
'acosh' => true,
'cos' => true,
'cosh' => true,
'deg2rad' => true,
'rad2deg' => true,
'exp' => true,
'floor' => true,
'log' => true,
@@ -44,51 +39,27 @@ function smarty_function_math($params, $template)
'pow' => true,
'rand' => true,
'round' => true,
'asin' => true,
'asinh' => true,
'sin' => true,
'sinh' => true,
'sqrt' => true,
'srand' => true,
'atan' => true,
'atanh' => true,
'tan' => true,
'tanh' => true
'tan' => true
);
// be sure equation parameter is present
if (empty($params[ 'equation' ])) {
trigger_error("math: missing equation parameter", E_USER_WARNING);
return;
}
$equation = $params[ 'equation' ];
// Remove whitespaces
$equation = preg_replace('/\s+/', '', $equation);
// Adapted from https://www.php.net/manual/en/function.eval.php#107377
$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
$functionsOrVars = '((?:0x[a-fA-F0-9]+)|([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*))';
$operators = '[,+\/*\^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functionsOrVars.'|('.$functionsOrVars.'\s*\((?1)*\)|\((?1)*\)))(?:'.$operators.'(?1))?)+$/';
if (!preg_match($regexp, $equation)) {
trigger_error("math: illegal characters", E_USER_WARNING);
return;
}
// make sure parenthesis are balanced
if (substr_count($equation, '(') !== substr_count($equation, ')')) {
trigger_error("math: unbalanced parenthesis", E_USER_WARNING);
return;
}
// disallow backticks
if (strpos($equation, '`') !== false) {
trigger_error("math: backtick character not allowed in equation", E_USER_WARNING);
return;
}
// also disallow dollar signs
if (strpos($equation, '$') !== false) {
trigger_error("math: dollar signs not allowed in equation", E_USER_WARNING);
@@ -125,7 +96,6 @@ function smarty_function_math($params, $template)
}
$smarty_math_result = null;
eval("\$smarty_math_result = " . $equation . ";");
if (empty($params[ 'format' ])) {
if (empty($params[ 'assign' ])) {
return $smarty_math_result;
-2
View File
@@ -22,8 +22,6 @@
*/
function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = false)
{
$string = (string) $string;
if (Smarty::$_MBSTRING) {
if ($lc_rest) {
// uppercase (including hyphenated words)
-36
View File
@@ -1,36 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty count modifier plugin
* Type: modifier
* Name: count
* Purpose: counts all elements in an array or in a Countable object
* Input:
* - Countable|array: array or object to count
* - mode: int defaults to 0 for normal count mode, if set to 1 counts recursive
*
* @param mixed $arrayOrObject input array/object
* @param int $mode count mode
*
* @return int
*/
function smarty_modifier_count($arrayOrObject, $mode = 0)
{
/*
* @see https://www.php.net/count
* > Prior to PHP 8.0.0, if the parameter was neither an array nor an object that implements the Countable interface,
* > 1 would be returned, unless value was null, in which case 0 would be returned.
*/
if ($arrayOrObject instanceof Countable || is_array($arrayOrObject)) {
return count($arrayOrObject, (int) $mode);
} elseif ($arrayOrObject === null) {
return 0;
}
return 1;
}
+1 -2
View File
@@ -78,8 +78,7 @@ function smarty_modifier_date_format($string, $format = null, $default_date = ''
}
$format = str_replace($_win_from, $_win_to, $format);
}
// @ to suppress deprecation errors when running in PHP8.1 or higher.
return @strftime($format, $timestamp);
return strftime($format, $timestamp);
} else {
return date($format, $timestamp);
}
+77 -7
View File
@@ -23,25 +23,95 @@
*/
function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $double_encode = true)
{
static $_double_encode = true;
static $is_loaded_1 = false;
static $is_loaded_2 = false;
if (!$char_set) {
$char_set = Smarty::$_CHARSET;
}
$string = (string)$string;
switch ($esc_type) {
case 'html':
return htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
if ($_double_encode) {
// php >=5.3.2 - go native
return htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.2.3 - only handle double encoding
return htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string = str_replace(
array(
'%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'
),
array(
'&',
';'
),
$string
);
return $string;
}
}
// no break
case 'htmlall':
if (Smarty::$_MBSTRING) {
$string = mb_convert_encoding($string, 'UTF-8', $char_set);
return htmlentities($string, ENT_QUOTES, 'UTF-8', $double_encode);
// mb_convert_encoding ignores htmlspecialchars()
if ($_double_encode) {
// php >=5.3.2 - go native
$string = htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.2.3 - only handle double encoding
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string =
str_replace(
array(
'%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'
),
array(
'&',
';'
),
$string
);
return $string;
}
}
// htmlentities() won't convert everything, so use mb_convert_encoding
return mb_convert_encoding($string, 'HTML-ENTITIES', $char_set);
}
// no MBString fallback
return htmlentities($string, ENT_QUOTES, $char_set, $double_encode);
if ($_double_encode) {
return htmlentities($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
return htmlentities($string, ENT_QUOTES, $char_set);
} else {
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlentities($string, ENT_QUOTES, $char_set);
$string = str_replace(
array(
'%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'
),
array(
'&',
';'
),
$string
);
return $string;
}
}
// no break
case 'url':
return rawurlencode($string);
-25
View File
@@ -1,25 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty explode modifier plugin
* Type: modifier
* Name: explode
* Purpose: split a string by a string
*
* @param string $separator
* @param string $string
* @param int|null $limit
*
* @return array
*/
function smarty_modifier_explode($separator, $string, ?int $limit = null)
{
// provide $string default to prevent deprecation errors in PHP >=8.1
return explode($separator, $string ?? '', $limit ?? PHP_INT_MAX);
}
-26
View File
@@ -1,26 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty number_format modifier plugin
* Type: modifier
* Name: number_format
* Purpose: Format a number with grouped thousands
*
* @param float|null $num
* @param int $decimals
* @param string|null $decimal_separator
* @param string|null $thousands_separator
*
* @return string
*/
function smarty_modifier_number_format(?float $num, int $decimals = 0, ?string $decimal_separator = ".", ?string $thousands_separator = ",")
{
// provide $num default to prevent deprecation errors in PHP >=8.1
return number_format($num ?? 0.0, $decimals, $decimal_separator, $thousands_separator);
}
+3 -3
View File
@@ -42,8 +42,8 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
if (!$middle) {
return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc;
}
return mb_substr($string, 0, intval($length / 2), Smarty::$_CHARSET) . $etc .
mb_substr($string, -intval($length / 2), $length, Smarty::$_CHARSET);
return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc .
mb_substr($string, -$length / 2, $length, Smarty::$_CHARSET);
}
return $string;
}
@@ -56,7 +56,7 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
if (!$middle) {
return substr($string, 0, $length) . $etc;
}
return substr($string, 0, intval($length / 2)) . $etc . substr($string, -intval($length / 2));
return substr($string, 0, $length / 2) . $etc . substr($string, -$length / 2);
}
return $string;
}
+37 -12
View File
@@ -18,10 +18,12 @@
* @param Smarty_Internal_TemplateCompilerBase $compiler
*
* @return string with compiled code
* @throws SmartyException
* @throws \SmartyException
*/
function smarty_modifiercompiler_escape($params, Smarty_Internal_TemplateCompilerBase $compiler)
{
static $_double_encode = true;
static $is_loaded = false;
$compiler->template->_checkPlugins(
array(
array(
@@ -39,30 +41,53 @@ function smarty_modifiercompiler_escape($params, Smarty_Internal_TemplateCompile
}
switch ($esc_type) {
case 'html':
return 'htmlspecialchars((string)' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
if ($_double_encode) {
return 'htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
} elseif ($double_encode) {
return 'htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
// no break
case 'htmlall':
if (Smarty::$_MBSTRING) {
return 'htmlentities(mb_convert_encoding((string)' . $params[ 0 ] . ', \'UTF-8\', ' .
var_export($char_set, true) . '), ENT_QUOTES, \'UTF-8\', ' .
var_export($double_encode, true) . ')';
if ($_double_encode) {
// php >=5.2.3 - go native
return 'mb_convert_encoding(htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' .
var_export($char_set, true) . ', ' . var_export($double_encode, true) .
'), "HTML-ENTITIES", ' . var_export($char_set, true) . ')';
} elseif ($double_encode) {
// php <5.2.3 - only handle double encoding
return 'mb_convert_encoding(htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' .
var_export($char_set, true) . '), "HTML-ENTITIES", ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
}
// no MBString fallback
return 'htmlentities((string)' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
if ($_double_encode) {
// php >=5.2.3 - go native
return 'htmlentities(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
} elseif ($double_encode) {
// php <5.2.3 - only handle double encoding
return 'htmlentities(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
// no break
case 'url':
return 'rawurlencode((string)' . $params[ 0 ] . ')';
return 'rawurlencode(' . $params[ 0 ] . ')';
case 'urlpathinfo':
return 'str_replace("%2F", "/", rawurlencode((string)' . $params[ 0 ] . '))';
return 'str_replace("%2F", "/", rawurlencode(' . $params[ 0 ] . '))';
case 'quotes':
// escape unescaped single quotes
return 'preg_replace("%(?<!\\\\\\\\)\'%", "\\\'", (string)' . $params[ 0 ] . ')';
return 'preg_replace("%(?<!\\\\\\\\)\'%", "\\\'",' . $params[ 0 ] . ')';
case 'javascript':
// escape quotes and backslashes, newlines, etc.
// see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
return 'strtr((string)' .
return 'strtr(' .
$params[ 0 ] .
', array("\\\\" => "\\\\\\\\", "\'" => "\\\\\'", "\"" => "\\\\\"", "\\r" => "\\\\r", "\\n" => "\\\n", "</" => "<\/", "<!--" => "<\!--", "<s" => "<\s", "<S" => "<\S" ))';
}
-23
View File
@@ -1,23 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty nl2br modifier plugin
* Type: modifier
* Name: nl2br
* Purpose: insert HTML line breaks before all newlines in a string
*
* @link https://www.smarty.net/docs/en/language.modifier.nl2br.tpl nl2br (Smarty online manual)
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_nl2br($params) {
return 'nl2br((string) ' . $params[0] . ', (bool) ' . ($params[1] ?? true) . ')';
}
-23
View File
@@ -1,23 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty round modifier plugin
* Type: modifier
* Name: round
* Purpose: Returns the rounded value of num to specified precision (number of digits after the decimal point)
*
* @link https://www.smarty.net/docs/en/language.modifier.round.tpl round (Smarty online manual)
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_round($params) {
return 'round((float) ' . $params[0] . ', (int) ' . ($params[1] ?? 0) . ', (int) ' . ($params[2] ?? PHP_ROUND_HALF_UP) . ')';
}
@@ -1,23 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty str_repeat modifier plugin
* Type: modifier
* Name: str_repeat
* Purpose: returns string repeated times times
*
* @link https://www.smarty.net/docs/en/language.modifier.str_repeat.tpl str_repeat (Smarty online manual)
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_str_repeat($params) {
return 'str_repeat((string) ' . $params[0] . ', (int) ' . $params[1] . ')';
}
+2 -2
View File
@@ -21,8 +21,8 @@
function smarty_modifiercompiler_strip_tags($params)
{
if (!isset($params[ 1 ]) || $params[ 1 ] === true || trim($params[ 1 ], '"') === 'true') {
return "preg_replace('!<[^>]*?>!', ' ', {$params[0]} ?: '')";
return "preg_replace('!<[^>]*?>!', ' ', {$params[0]})";
} else {
return 'strip_tags((string) ' . $params[ 0 ] . ')';
return 'strip_tags(' . $params[ 0 ] . ')';
}
}
-23
View File
@@ -1,23 +0,0 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty strlen modifier plugin
* Type: modifier
* Name: strlen
* Purpose: return the length of the given string
*
* @link https://www.smarty.net/docs/en/language.modifier.strlen.tpl strlen (Smarty online manual)
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_strlen($params) {
return 'strlen((string) ' . $params[0] . ')';
}
+9 -17
View File
@@ -14,34 +14,26 @@
* @author Rodney Rehm
*
* @param array $params parameters
* @param Smarty_Internal_TemplateCompilerBase $compiler
*
* @return string with compiled code
*/
function smarty_modifiercompiler_unescape($params, Smarty_Internal_TemplateCompilerBase $compiler)
function smarty_modifiercompiler_unescape($params)
{
$compiler->template->_checkPlugins(
array(
array(
'function' => 'smarty_literal_compiler_param',
'file' => SMARTY_PLUGINS_DIR . 'shared.literal_compiler_param.php'
)
)
);
$esc_type = smarty_literal_compiler_param($params, 1, 'html');
if (!isset($params[ 1 ])) {
$params[ 1 ] = 'html';
}
if (!isset($params[ 2 ])) {
$params[ 2 ] = '\'' . addslashes(Smarty::$_CHARSET) . '\'';
} else {
$params[ 2 ] = "'{$params[ 2 ]}'";
}
switch ($esc_type) {
switch (trim($params[ 1 ], '"\'')) {
case 'entity':
case 'htmlall':
if (Smarty::$_MBSTRING) {
return 'html_entity_decode(mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 2 ] . ', \'UTF-8\'), ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ' . $params[ 2 ] . ')';
return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 2 ] . ', \'HTML-ENTITIES\')';
}
return 'html_entity_decode(' . $params[ 0 ] . ', ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ' . $params[ 2 ] . ')';
return 'html_entity_decode(' . $params[ 0 ] . ', ENT_NOQUOTES, ' . $params[ 2 ] . ')';
case 'html':
return 'htmlspecialchars_decode(' . $params[ 0 ] . ', ENT_QUOTES)';
case 'url':
+2 -2
View File
@@ -21,8 +21,8 @@
function smarty_modifiercompiler_upper($params)
{
if (Smarty::$_MBSTRING) {
return 'mb_strtoupper(' . $params[ 0 ] . ' ?? \'\', \'' . addslashes(Smarty::$_CHARSET) . '\')';
return 'mb_strtoupper(' . $params[ 0 ] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
}
// no MBString fallback
return 'strtoupper(' . $params[ 0 ] . ' ?? \'\')';
return 'strtoupper(' . $params[ 0 ] . ')';
}
+1 -35
View File
@@ -44,43 +44,9 @@ if (!function_exists('smarty_mb_str_replace')) {
}
}
} else {
$mb_reg_charset = mb_regex_encoding();
// Check if mbstring regex is using UTF-8
$reg_is_unicode = !strcasecmp($mb_reg_charset, "UTF-8");
if(!$reg_is_unicode) {
// ...and set to UTF-8 if not
mb_regex_encoding("UTF-8");
}
// See if charset used by Smarty is matching one used by regex...
$current_charset = mb_regex_encoding();
$convert_result = (bool)strcasecmp(Smarty::$_CHARSET, $current_charset);
if($convert_result) {
// ...convert to it if not.
$subject = mb_convert_encoding($subject, $current_charset, Smarty::$_CHARSET);
$search = mb_convert_encoding($search, $current_charset, Smarty::$_CHARSET);
$replace = mb_convert_encoding($replace, $current_charset, Smarty::$_CHARSET);
}
$parts = mb_split(preg_quote($search), $subject ?? "") ?: array();
// If original regex encoding was not unicode...
if(!$reg_is_unicode) {
// ...restore original regex encoding to avoid breaking the system.
mb_regex_encoding($mb_reg_charset);
}
if($parts === false) {
// This exception is thrown if call to mb_split failed.
// Usually it happens, when $search or $replace are not valid for given mb_regex_encoding().
// There may be other cases for it to fail, please file an issue if you find a reproducible one.
throw new SmartyException("Source string is not a valid $current_charset sequence (probably)");
}
$parts = mb_split(preg_quote($search), $subject);
$count = count($parts) - 1;
$subject = implode($replace, $parts);
// Convert results back to charset used by Smarty, if needed.
if($convert_result) {
$subject = mb_convert_encoding($subject, Smarty::$_CHARSET, $current_charset);
}
}
return $subject;
}
+2 -2
View File
@@ -205,11 +205,11 @@ abstract class Smarty_CacheResource
}
// try sysplugins dir
if (isset(self::$sysplugins[ $type ])) {
$cache_resource_class = 'Smarty_Internal_CacheResource_' . smarty_ucfirst_ascii($type);
$cache_resource_class = 'Smarty_Internal_CacheResource_' . ucfirst($type);
return $smarty->_cache[ 'cacheresource_handlers' ][ $type ] = new $cache_resource_class();
}
// try plugins dir
$cache_resource_class = 'Smarty_CacheResource_' . smarty_ucfirst_ascii($type);
$cache_resource_class = 'Smarty_CacheResource_' . ucfirst($type);
if ($smarty->loadPlugin($cache_resource_class)) {
return $smarty->_cache[ 'cacheresource_handlers' ][ $type ] = new $cache_resource_class();
}
@@ -244,7 +244,7 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
*/
protected function sanitize($string)
{
$string = trim((string)$string, '|');
$string = trim($string, '|');
if (!$string) {
return '';
}
@@ -428,7 +428,7 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
$t[] = 'IVK#COMPILE' . $_compile;
}
$_name .= '#';
$cid = trim((string)$cache_id, '|');
$cid = trim($cache_id, '|');
if (!$cid) {
return $t;
}
@@ -196,8 +196,8 @@ class Smarty_Internal_CacheResource_File extends Smarty_CacheResource
*/
public function hasLock(Smarty $smarty, Smarty_Template_Cached $cached)
{
clearstatcache(true, $cached->lock_id ?? '');
if (null !== $cached->lock_id && is_file($cached->lock_id)) {
clearstatcache(true, $cached->lock_id);
if (is_file($cached->lock_id)) {
$t = filemtime($cached->lock_id);
return $t && (time() - $t < $smarty->locking_timeout);
} else {
@@ -125,7 +125,7 @@ class Smarty_Internal_Compile_Blockclose extends Smarty_Internal_Compile_Shared_
// setup buffer for template function code
$compiler->parser->current_buffer = new Smarty_Internal_ParseTree_Template();
$output = "<?php\n";
$output .= $compiler->cStyleComment(" {block {$_name}} ") . "\n";
$output .= "/* {block {$_name}} */\n";
$output .= "class {$_className} extends Smarty_Internal_Block\n";
$output .= "{\n";
foreach ($_block as $property => $value) {
@@ -155,7 +155,7 @@ class Smarty_Internal_Compile_Blockclose extends Smarty_Internal_Compile_Shared_
}
$output .= "}\n";
$output .= "}\n";
$output .= $compiler->cStyleComment(" {/block {$_name}} ") . "\n\n";
$output .= "/* {/block {$_name}} */\n\n";
$output .= "?>\n";
$compiler->parser->current_buffer->append_subtree(
$compiler->parser,
@@ -134,7 +134,7 @@ class Smarty_Internal_Compile_Functionclose extends Smarty_Internal_CompileBase
if ($compiler->template->compiled->has_nocache_code) {
$compiler->parent_compiler->tpl_function[ $_name ][ 'call_name_caching' ] = $_funcNameCaching;
$output = "<?php\n";
$output .= $compiler->cStyleComment(" {$_funcNameCaching} ") . "\n";
$output .= "/* {$_funcNameCaching} */\n";
$output .= "if (!function_exists('{$_funcNameCaching}')) {\n";
$output .= "function {$_funcNameCaching} (Smarty_Internal_Template \$_smarty_tpl,\$params) {\n";
$output .= "ob_start();\n";
@@ -157,9 +157,9 @@ class Smarty_Internal_Compile_Functionclose extends Smarty_Internal_CompileBase
$output = "<?php echo \"/*%%SmartyNocache:{$compiler->template->compiled->nocache_hash}%%*/<?php ";
$output .= "\\\$_smarty_tpl->smarty->ext->_tplFunction->restoreTemplateVariables(\\\$_smarty_tpl, '{$_name}');?>\n";
$output .= "/*/%%SmartyNocache:{$compiler->template->compiled->nocache_hash}%%*/\";\n?>";
$output .= "<?php echo str_replace('{$compiler->template->compiled->nocache_hash}', \$_smarty_tpl->compiled->nocache_hash ?? '', ob_get_clean());\n";
$output .= "<?php echo str_replace('{$compiler->template->compiled->nocache_hash}', \$_smarty_tpl->compiled->nocache_hash, ob_get_clean());\n";
$output .= "}\n}\n";
$output .= $compiler->cStyleComment("/ {$_funcName}_nocache ") . "\n\n";
$output .= "/*/ {$_funcName}_nocache */\n\n";
$output .= "?>\n";
$compiler->parser->current_buffer->append_subtree(
$compiler->parser,
@@ -179,7 +179,7 @@ class Smarty_Internal_Compile_Functionclose extends Smarty_Internal_CompileBase
}
$compiler->parent_compiler->tpl_function[ $_name ][ 'call_name' ] = $_funcName;
$output = "<?php\n";
$output .= $compiler->cStyleComment(" {$_funcName} ") . "\n";
$output .= "/* {$_funcName} */\n";
$output .= "if (!function_exists('{$_funcName}')) {\n";
$output .= "function {$_funcName}(Smarty_Internal_Template \$_smarty_tpl,\$params) {\n";
$output .= $_paramsCode;
@@ -196,7 +196,7 @@ class Smarty_Internal_Compile_Functionclose extends Smarty_Internal_CompileBase
);
$compiler->parser->current_buffer->append_subtree($compiler->parser, $_functionCode);
$output = "<?php\n}}\n";
$output .= $compiler->cStyleComment("/ {$_funcName} ") . "\n\n";
$output .= "/*/ {$_funcName} */\n\n";
$output .= "?>\n";
$compiler->parser->current_buffer->append_subtree(
$compiler->parser,
@@ -318,14 +318,14 @@ class Smarty_Internal_Compile_Include extends Smarty_Internal_CompileBase
}
// get compiled code
$compiled_code = "<?php\n\n";
$compiled_code .= $compiler->cStyleComment(" Start inline template \"{$sourceInfo}\" =============================") . "\n";
$compiled_code .= "/* Start inline template \"{$sourceInfo}\" =============================*/\n";
$compiled_code .= "function {$tpl->compiled->unifunc} (Smarty_Internal_Template \$_smarty_tpl) {\n";
$compiled_code .= "?>\n" . $tpl->compiler->compileTemplateSource($tpl, null, $compiler->parent_compiler);
$compiled_code .= "<?php\n";
$compiled_code .= "}\n?>\n";
$compiled_code .= $tpl->compiler->postFilter($tpl->compiler->blockOrFunctionCode);
$compiled_code .= "<?php\n\n";
$compiled_code .= $compiler->cStyleComment(" End inline template \"{$sourceInfo}\" =============================") . "\n";
$compiled_code .= "/* End inline template \"{$sourceInfo}\" =============================*/\n";
$compiled_code .= '?>';
unset($tpl->compiler);
if ($tpl->compiled->has_nocache_code) {
@@ -93,7 +93,7 @@ class Smarty_Internal_Compile_Insert extends Smarty_Internal_CompileBase
}
if (!empty($_dir)) {
foreach ((array)$_dir as $_script_dir) {
$_script_dir = rtrim($_script_dir ?? '', '/\\') . DIRECTORY_SEPARATOR;
$_script_dir = rtrim($_script_dir, '/\\') . DIRECTORY_SEPARATOR;
if (file_exists($_script_dir . $_script)) {
$_filepath = $_script_dir . $_script;
break;
@@ -143,7 +143,7 @@ class Smarty_Internal_Compile_Private_ForeachSection extends Smarty_Internal_Com
foreach ($this->resultOffsets as $key => $offset) {
foreach ($match[ $offset ] as $m) {
if (!empty($m)) {
$this->matchResults[ $key ][ smarty_strtolower_ascii($m) ] = true;
$this->matchResults[ $key ][ strtolower($m) ] = true;
}
}
}
@@ -213,12 +213,12 @@ class Smarty_Internal_Compile_Private_ForeachSection extends Smarty_Internal_Com
*/
public function compileSpecialVariable($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter)
{
$tag = smarty_strtolower_ascii(trim($parameter[ 0 ], '"\''));
$tag = strtolower(trim($parameter[ 0 ], '"\''));
$name = isset($parameter[ 1 ]) ? $compiler->getId($parameter[ 1 ]) : false;
if (!$name) {
$compiler->trigger_template_error("missing or illegal \$smarty.{$tag} name attribute", null, true);
}
$property = isset($parameter[ 2 ]) ? smarty_strtolower_ascii($compiler->getId($parameter[ 2 ])) : false;
$property = isset($parameter[ 2 ]) ? strtolower($compiler->getId($parameter[ 2 ])) : false;
if (!$property || !in_array($property, $this->nameProperties)) {
$compiler->trigger_template_error("missing or illegal \$smarty.{$tag} property attribute", null, true);
}
@@ -109,9 +109,6 @@ class Smarty_Internal_Compile_Private_Modifier extends Smarty_Internal_CompileBa
if (!is_object($compiler->smarty->security_policy)
|| $compiler->smarty->security_policy->isTrustedPhpModifier($modifier, $compiler)
) {
trigger_error('Using php-function "' . $modifier . '" as a modifier is deprecated and will be ' .
'removed in a future release. Use Smarty::registerPlugin to explicitly register ' .
'a custom modifier.', E_USER_DEPRECATED);
$output = "{$modifier}({$params})";
}
$compiler->known_modifier_type[ $modifier ] = $type;
@@ -93,7 +93,7 @@ class Smarty_Internal_Compile_Private_Print_Expression extends Smarty_Internal_C
}
// autoescape html
if ($compiler->template->smarty->escape_html) {
$output = "htmlspecialchars((string) {$output}, ENT_QUOTES, '" . addslashes(Smarty::$_CHARSET) . "')";
$output = "htmlspecialchars({$output}, ENT_QUOTES, '" . addslashes(Smarty::$_CHARSET) . "')";
}
// loop over registered filters
if (!empty($compiler->template->smarty->registered_filters[ Smarty::FILTER_VARIABLE ])) {
@@ -29,7 +29,7 @@ class Smarty_Internal_Compile_Private_Special_Variable extends Smarty_Internal_C
public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter)
{
$_index = preg_split("/\]\[/", substr($parameter, 1, strlen($parameter) - 2));
$variable = smarty_strtolower_ascii($compiler->getId($_index[ 0 ]));
$variable = strtolower($compiler->getId($_index[ 0 ]));
if ($variable === false) {
$compiler->trigger_template_error("special \$Smarty variable name index can not be variable", null, true);
}
@@ -40,7 +40,7 @@ class Smarty_Internal_Compile_Private_Special_Variable extends Smarty_Internal_C
case 'foreach':
case 'section':
if (!isset(Smarty_Internal_TemplateCompilerBase::$_tag_objects[ $variable ])) {
$class = 'Smarty_Internal_Compile_' . smarty_ucfirst_ascii($variable);
$class = 'Smarty_Internal_Compile_' . ucfirst($variable);
Smarty_Internal_TemplateCompilerBase::$_tag_objects[ $variable ] = new $class;
}
return Smarty_Internal_TemplateCompilerBase::$_tag_objects[ $variable ]->compileSpecialVariable(
@@ -76,7 +76,7 @@ class Smarty_Internal_Compile_Private_Special_Variable extends Smarty_Internal_C
$compiler->trigger_template_error("(secure mode) super globals not permitted");
break;
}
$compiled_ref = '$_' . smarty_strtoupper_ascii($variable);
$compiled_ref = '$_' . strtoupper($variable);
break;
case 'template':
return 'basename($_smarty_tpl->source->filepath)';
@@ -157,12 +157,10 @@ class Smarty_Internal_Config_File_Compiler
$this->smarty->_debug->end_compile($this->template);
}
// template header code
$template_header = sprintf(
"<?php /* Smarty version %s, created on %s\n compiled from '%s' */ ?>\n",
Smarty::SMARTY_VERSION,
date("Y-m-d H:i:s"),
str_replace('*/', '* /' , $this->template->source->filepath)
);
$template_header =
"<?php /* Smarty version " . Smarty::SMARTY_VERSION . ", created on " . strftime("%Y-%m-%d %H:%M:%S") .
"\n";
$template_header .= " compiled from '{$this->template->source->filepath}' */ ?>\n";
$code = '<?php $_smarty_tpl->smarty->ext->configLoad->_loadConfigVars($_smarty_tpl, ' .
var_export($this->config_data, true) . '); ?>';
return $template_header . $this->template->smarty->ext->_codeFrame->create($this->template, $code);
+2 -2
View File
@@ -210,7 +210,7 @@ class Smarty_Internal_Debug extends Smarty_Internal_Data
// copy the working dirs from application
$debObj->setCompileDir($smarty->getCompileDir());
// init properties by hand as user may have edited the original Smarty class
$debObj->setPluginsDir(is_dir(__DIR__ . '/../plugins') ? __DIR__ .
$debObj->setPluginsDir(is_dir(dirname(__FILE__) . '/../plugins') ? dirname(__FILE__) .
'/../plugins' : $smarty->getPluginsDir());
$debObj->force_compile = false;
$debObj->compile_check = Smarty::COMPILECHECK_ON;
@@ -221,7 +221,7 @@ class Smarty_Internal_Debug extends Smarty_Internal_Data
$debObj->debugging_ctrl = 'NONE';
$debObj->error_reporting = E_ALL & ~E_NOTICE;
$debObj->debug_tpl =
isset($smarty->debug_tpl) ? $smarty->debug_tpl : 'file:' . __DIR__ . '/../debug.tpl';
isset($smarty->debug_tpl) ? $smarty->debug_tpl : 'file:' . dirname(__FILE__) . '/../debug.tpl';
$debObj->registered_plugins = array();
$debObj->registered_resources = array();
$debObj->registered_filters = array();
@@ -71,7 +71,7 @@ class Smarty_Internal_ErrorHandler
}
if ($this->allowUndefinedArrayKeys && preg_match(
'/^(Undefined index|Undefined array key|Trying to access array offset on value of type null)/',
'/^(Undefined array key|Trying to access array offset on value of type null)/',
$errstr
)) {
return; // suppresses this error
@@ -36,7 +36,6 @@
* @property Smarty_Internal_Method_RegisterPlugin $registerPlugin
* @property mixed|\Smarty_Template_Cached configLoad
*/
#[\AllowDynamicProperties]
class Smarty_Internal_Extension_Handler
{
public $objType = null;
@@ -89,19 +88,20 @@ class Smarty_Internal_Extension_Handler
$objType = $data->_objType;
$propertyType = false;
if (!isset($this->resolvedProperties[ $match[ 0 ] ][ $objType ])) {
$property = $this->resolvedProperties['property'][$basename] ??
$this->resolvedProperties['property'][$basename] = smarty_strtolower_ascii(
join(
'_',
preg_split(
'/([A-Z][^A-Z]*)/',
$basename,
-1,
PREG_SPLIT_NO_EMPTY |
PREG_SPLIT_DELIM_CAPTURE
$property = isset($this->resolvedProperties[ 'property' ][ $basename ]) ?
$this->resolvedProperties[ 'property' ][ $basename ] :
$property = $this->resolvedProperties[ 'property' ][ $basename ] = strtolower(
join(
'_',
preg_split(
'/([A-Z][^A-Z]*)/',
$basename,
-1,
PREG_SPLIT_NO_EMPTY |
PREG_SPLIT_DELIM_CAPTURE
)
)
)
);
);
if ($property !== false) {
if (property_exists($data, $property)) {
$propertyType = $this->resolvedProperties[ $match[ 0 ] ][ $objType ] = 1;
@@ -145,7 +145,7 @@ class Smarty_Internal_Extension_Handler
public function upperCase($name)
{
$_name = explode('_', $name);
$_name = array_map('smarty_ucfirst_ascii', $_name);
$_name = array_map('ucfirst', $_name);
return implode('_', $_name);
}

Some files were not shown because too many files have changed in this diff Show More