Compare commits

..

2 Commits

Author SHA1 Message Date
Simon Wisselink 8b0be54986 Add CHANGELOG.md 2022-01-21 10:07:46 +01:00
Thomas A. Hirsch f89c6a2b3a php 8.1 compatibility (changes from https://github.com/smarty-php/smarty/pull/678) 2022-01-18 11:31:51 +01:00
737 changed files with 35958 additions and 23394 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
-60
View File
@@ -1,60 +0,0 @@
on:
push:
tags:
- '*'
name: CD
jobs:
release:
if: ${{ startsWith(github.ref_name, '5.') }}
runs-on: ubuntu-latest
env:
PHP_EXTENSIONS: dom, json, libxml, mbstring, pdo_sqlite, soap, xml, xmlwriter
steps:
- name: checkout code
uses: actions/checkout@v3
- name: Install PHP with extensions
uses: shivammathur/setup-php@v2
with:
php-version: 8.1
extensions: ${{ env.PHP_EXTENSIONS }}
- name: Install dependencies
uses: php-actions/composer@v6
- name: Run make
run: make
- name: create release assets
run: |
mkdir release
git archive release
cd release
make
cd ..
tar -cvzf release.tar.gz release
- name: create release
uses: actions/create-release@v1
id: create_release
with:
draft: false
prerelease: false
release_name: ${{ steps.version.outputs.version }}
tag_name: ${{ github.ref }}
env:
GITHUB_TOKEN: ${{ github.token }}
- name: upload artifacts
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ github.token }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./release.tar.gz
asset_name: release.tar.gz
asset_content_type: application/gzip
+13 -20
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
@@ -25,12 +23,12 @@ jobs:
- ubuntu-latest
php-version:
- "7.1"
- "7.2"
- "7.3"
- "7.4"
- "8.0"
- "8.1"
- "8.2"
compiler:
- default
@@ -39,16 +37,10 @@ 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
uses: actions/checkout@v3
uses: actions/checkout@v2
- name: Override PHP ini values for JIT compiler
if: matrix.compiler == 'jit'
@@ -62,20 +54,21 @@ jobs:
extensions: ${{ env.PHP_EXTENSIONS }}
ini-values: ${{ env.PHP_INI_VALUES }}
- name: Validate composer.json and composer.lock
run: composer validate
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
uses: actions/cache@v2
with:
path: vendor
key: smartyv5-${{ runner.os }}-php-${{ matrix.php-version }}-${{ hashFiles('**/composer.lock') }}
key: ${{ runner.os }}-php-${{ matrix.php-version }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
smartyv5-${{ runner.os }}-php-${{ matrix.php-version }}-
${{ runner.os }}-php-${{ matrix.php-version }}-
- name: Install dependencies
uses: php-actions/composer@v6
- name: Run make
run: make
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest
- name: Run tests with phpunit
run: php ./vendor/phpunit/phpunit/phpunit
run: ./phpunit.sh
+9 -6
View File
@@ -1,11 +1,14 @@
.idea/
# Smarty
lexer/*.php
lexer/*.php.bak
lexer/*.out
utilies/*.php
# Dev
phpunit*
.phpunit.result.cache
/vendor/*
/composer.lock
/src/Lexer/ConfigfileLexer.php
/src/Lexer/TemplateLexer.php
/src/Parser/ConfigfileParser.php
/src/Parser/TemplateParser.php
vendor/*
composer.lock
+3 -113
View File
@@ -7,117 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- Added support for PHP8.2
### Changed
- All Smarty code is now in the \Smarty namespace. For simple use-cases, you only need to add
`use \Smarty\Smarty;` to your script and everything will work. If you extend Smarty or use
Smarty plug-ins, please review your code to see if they assume specific class or method names.
E.g.: `Smarty_Internal_Template` is now `\Smarty\Template\`, `SmartyException` is now `\Smarty\Exception`.
- Template variable scope bubbling has been simplified and made more consistent.
The global scope now equals the Smarty scope in order to avoid global state side effects. Please read
the documentation for more details.
- Lexers and Parsers PHP files are no longer under version control, but generated from sources (.y and .plex)
- Smarty now always runs in multibyte mode, using `symfony/polyfill-mbstring` if required. Please use the
multibyte extension for optimal performance.
### Deprecated
- `$smarty->getPluginsDir()`
- `$smarty->loadFilter()`
- `$smarty->setPluginsDir()`
- `$smarty->assignGlobal()`
- Using `$smarty->registerFilter()` for registering variable filters will trigger a notice.
-
### Removed
- Dropped support for PHP7.1
- Removed `$smarty->left_delimiter` and `$smarty->right_delimiter`, use `$smarty->getLeftDelimiter()`/`$smarty->setLeftDelimiter()` and `$smarty->getRightDelimiter()`/`$smarty->setRightDelimiter()`
- Removed support for the `$cache_attrs` parameter for registered plugins
- Removed support for undocumented `{make_nocache}` tag
- Removed support for deprecated `{insert}` tag, the 'insert' plugin type and the associated $smarty->trusted_dir variable
- Removed the undocumented `{block_parent}` and `{parent}` alternatives to `{$smarty.block.parent}`
- Removed the undocumented `{block_child}` and `{child}` alternatives to `{$smarty.block.child}`
- Removed support for loading config files into a non-local scope using `{config_load}` from a template
- Removed `$smarty->autoload_filters` in favor of `$smarty->registerFilter()`
- Removed `$smarty->trusted_dir` and `$smarty->allow_php_templates` since support for executing php scripts from templates has been dropped
- Removed `$smarty->php_functions` and `$smarty->php_modifiers`. If you need a PHP-function in your templates,
register it as a modifier.
- Removed support for `$smarty->getTags()`
- Removed the abandoned `$smarty->direct_access_security` setting
- Dropped support for `$smarty->plugins_dir` and `$smarty->use_include_path`. If you must, use `$smarty->addPluginsDir()` instead,
but it's better to use Smarty::addExtension() to add an extension or Smarty::registerPlugin to
quickly register a plugin using a callback function.
- Removed constants such as SMARTY_DIR to prevent global side effects.
- Removed direct access to `$smarty->template_dir`. Use `$smarty->setTemplateDir()`.
- Removed direct access to `$smarty->cache_dir`. Use `$smarty->setCacheDir()`.
- Removed `$smarty->loadPlugin()`, use `$smarty->registerPlugin()` instead.
- Removed `$smarty->appendByRef()` and `$smarty->assignByRef()`.
### Fixed
- `$smarty->muteUndefinedOrNullWarnings()` now also mutes PHP7 notices for undefined array indexes [#736](https://github.com/smarty-php/smarty/issues/736)
- `$smarty->muteUndefinedOrNullWarnings()` now treats undefined vars and array access of a null or false variables
equivalent across all supported PHP versions
- `$smarty->muteUndefinedOrNullWarnings()` now allows dereferencing of non-objects across all supported PHP versions [#831](https://github.com/smarty-php/smarty/issues/831)
- PHP 8.1 deprecation warnings on null strings in modifiers [#834](https://github.com/smarty-php/smarty/pull/834)
## [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)
- PHP8.1 compatibility [#711](https://github.com/smarty-php/smarty/pull/711)
## [4.0.4] - 2022-01-18
@@ -1824,7 +1714,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
27.09.2011
- bugfix possible warning "attempt to modify property of non-object" in {section} (issue #34)
- added chaining to \Smarty\Data so $smarty->assign('a',1)->assign('b',2); is possible now
- added chaining to Smarty_Internal_Data so $smarty->assign('a',1)->assign('b',2); is possible now
- bugfix remove race condition when a custom resource did change timestamp during compilation
- bugfix variable property did not work on objects variable in template
- bugfix smarty_make_timestamp() failed to process DateTime objects properly
@@ -2159,7 +2049,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- optimize smarty_modified_escape for hex, hexentity, decentity.
28/12/2010
- changed $tpl_vars, $config_vars and $parent to belong to \Smarty\Data
- changed $tpl_vars, $config_vars and $parent to belong to Smarty_Internal_Data
- added Smarty::registerCacheResource() for dynamic cache resource object registration
27/12/2010
-19
View File
@@ -1,19 +0,0 @@
all: lexers parsers
lexers: src/Lexer/ConfigfileLexer.php src/Lexer/TemplateLexer.php
parsers: src/Parser/ConfigfileParser.php src/Parser/TemplateParser.php
src/Lexer/ConfigfileLexer.php: src/Lexer/ConfigfileLexer.plex
php ./utilities/make-lexer.php src/Lexer/ConfigfileLexer.plex src/Lexer/ConfigfileLexer.php
src/Lexer/TemplateLexer.php: src/Lexer/TemplateLexer.plex
php ./utilities/make-lexer.php src/Lexer/TemplateLexer.plex src/Lexer/TemplateLexer.php
src/Parser/ConfigfileParser.php: src/Parser/ConfigfileParser.y
php ./utilities/make-parser.php src/Parser/ConfigfileParser.y src/Parser/ConfigfileParser.php
src/Parser/TemplateParser.php: src/Parser/TemplateParser.y
php ./utilities/make-parser.php src/Parser/TemplateParser.y src/Parser/TemplateParser.php
clean:
rm -f src/Lexer/ConfigfileLexer.php src/Lexer/TemplateLexer.php src/Parser/ConfigfileParser.php src/Parser/TemplateParser.php
+1 -1
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 v5 can be run with PHP 7.2 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/).
+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 |
| ------- | ------------------ |
-50
View File
@@ -1,50 +0,0 @@
# @TODO
## Review direct variable property access
- review ->value{$index} in ForTag
- review ->(step|total|first|last|do_else|key|show|iteration|index)
- review ->tpl_vars, ->config_vars, ->value
## Review public static vars
- such as _CHARSET and _IS_WINDOWS
## Build
- add compiled lexers and parsers to Release assets automatically
## Benchmark
- benchmark to see that performance hasn't degraded
## Block / inheritance
- Consider phasing out $smarty.block.child as this reverses the inheritance hierarchy and might cause infinite loops
when combined with $smarty.block.parent
## Output buffering
- Fix ob_ output buffering commands being scattered around the codebase
## Event handlers
- startRenderCallbacks/endRenderCallbacks should be moved to a central eventdispatcher instead of being (un)registered on templates
## Plugin system
- fix template security checks in one place in compiler
## Beatify output
- compiled templates could be proper classes, possibly using [nette/php-generator](https://packagist.org/packages/nette/php-generator)
## Documentation
- beautify and review docs, possibly using [
Material for MkDocs ](https://squidfunk.github.io/mkdocs-material/publishing-your-site/)
## Resources
- Fix circular deps between resources and sources
```
$smarty = $this->_getSmartyObj();
[$name, $type] = \Smarty\Resource\BasePlugin::parseResourceName($config_file, $smarty->default_config_type);
$source = new Config($smarty, $config_file, $type, $name);
$source->handler->getContent($source);
```
## Unrelated / other
- review (and avoid) use of 'clone' keyword
- compiler->has_code seems silly. Why not have proper return values?
- what is 'user literal support', why are unit tests skipped?
+6 -17
View File
@@ -30,31 +30,20 @@
"forum": "https://github.com/smarty-php/smarty/discussions"
},
"require": {
"php": "^7.2 || ^8.0",
"symfony/polyfill-mbstring": "^1.27",
"nette/php-generator": "^3.6"
"php": "^7.1 || ^8.0"
},
"autoload": {
"psr-4" : {
"Smarty\\" : "src/"
},
"files": [
"src/functions.php"
"classmap": [
"libs/"
]
},
"extra": {
"branch-alias": {
"dev-master": "5.0.x-dev"
"dev-master": "4.0.x-dev"
}
},
"require-dev": {
"phpunit/phpunit": "^8.5 || ^7.5",
"smarty/smarty-lexer": "^4.0.1"
},
"repositories": [
{
"type": "vcs",
"url": "https://github.com/smarty-php/smarty-lexer"
}
]
"smarty/smarty-lexer": "^3.1"
}
}
+3 -3
View File
@@ -2,10 +2,10 @@
/**
* Example Application
*
* @package Example-application
*/
$smarty = new \Smarty\Smarty;
require '../libs/Smarty.class.php';
$smarty = new Smarty;
//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
@@ -6,11 +6,23 @@
* memcache as the storage resource for Smarty's output caching.
* *
*
* @package CacheResource-examples
* @author Uwe Tews
*/
class Smarty_CacheResource_Apc extends \Smarty\Cacheresource\KeyValueStore
class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore
{
/**
* Smarty_CacheResource_Apc constructor.
*
* @throws \Exception
*/
public function __construct()
{
// test if APC is present
if (!function_exists('apc_cache_info')) {
throw new Exception('APC Template Caching Error: APC is not installed');
}
}
/**
* Read values for a set of keys from cache
@@ -7,10 +7,10 @@
* Note that memcache has a limitation of 256 characters per cache-key.
* To avoid complications all cache-keys are translated to a sha1 hash.
*
* @package CacheResource-examples
* @author Rodney Rehm
*/
class Smarty_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
{
/**
* memcache instance
@@ -1,7 +1,5 @@
<?php
use Smarty\Exception;
/**
* MySQL CacheResource
* CacheResource Implementation based on the Custom API to use
@@ -21,73 +19,68 @@ use Smarty\Exception;
* INDEX(`modified`)
* ) ENGINE = InnoDB;</pre>
*
* @package CacheResource-examples
* @author Rodney Rehm
*/
class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
{
/**
* @var \PDO
*/
protected $db;
/**
* @return PDO
* @throws Exception
*/
protected function db(): PDO {
static $dbConn = null;
try {
return $dbConn ?? ($dbConn = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty"));
} catch (PDOException $e) {
throw new Exception('Mysql Resource failed: ' . $e->getMessage());
}
}
/**
* @var \PDOStatement
*/
protected $fetch;
/**
* @return false|PDOStatement
* @throws Exception
*/
protected function fetchQuery() {
static $query = null;
return $query ?? $query = $this->db()->prepare('SELECT modified, content FROM output_cache WHERE id = :id');
}
/**
* @var \PDOStatement
*/
protected $fetchTimestamp;
/**
* @return false|PDOStatement
* @throws Exception
*/
protected function fetchTimestampQuery() {
static $query = null;
return $query ?? $query = $this->db()->prepare('SELECT modified FROM output_cache WHERE id = :id');
}
/**
* @var \PDOStatement
*/
protected $save;
/**
* @return false|PDOStatement
* @throws Exception
*/
protected function saveQuery() {
static $query = null;
return $query ?? $query = $this->db()->prepare(
'REPLACE INTO output_cache (id, name, cache_id, compile_id, content)
/**
* Smarty_CacheResource_Mysql constructor.
*
* @throws \SmartyException
*/
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
} catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, content FROM output_cache WHERE id = :id');
$this->fetchTimestamp = $this->db->prepare('SELECT modified FROM output_cache WHERE id = :id');
$this->save = $this->db->prepare(
'REPLACE INTO output_cache (id, name, cache_id, compile_id, content)
VALUES (:id, :name, :cache_id, :compile_id, :content)'
);
}
);
}
/**
* fetch cached content and its modification time from data source
*
* @param string $id unique cache content identifier
* @param string $name template name
* @param string $cache_id cache id
* @param string $compile_id compile id
* @param string $content cached content
* @param integer $mtime cache modification timestamp (epoch)
*
* @return void
* @throws Exception
*/
/**
* fetch cached content and its modification time from data source
*
* @param string $id unique cache content identifier
* @param string $name template name
* @param string $cache_id cache id
* @param string $compile_id compile id
* @param string $content cached content
* @param integer $mtime cache modification timestamp (epoch)
*
* @return void
*/
protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime)
{
$this->fetchQuery()->execute(array('id' => $id));
$row = $this->fetchQuery()->fetch();
$this->fetchQuery()->closeCursor();
$this->fetch->execute(array('id' => $id));
$row = $this->fetch->fetch();
$this->fetch->closeCursor();
if ($row) {
$content = $row[ 'content' ];
$mtime = strtotime($row[ 'modified' ]);
@@ -112,9 +105,9 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
*/
protected function fetchTimestamp($id, $name, $cache_id, $compile_id)
{
$this->fetchTimestampQuery()->execute(array('id' => $id));
$mtime = strtotime($this->fetchTimestampQuery()->fetchColumn());
$this->fetchTimestampQuery()->closeCursor();
$this->fetchTimestamp->execute(array('id' => $id));
$mtime = strtotime($this->fetchTimestamp->fetchColumn());
$this->fetchTimestamp->closeCursor();
return $mtime;
}
@@ -132,14 +125,14 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
*/
protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
{
$this->saveQuery()->execute(
$this->save->execute(
array('id' => $id,
'name' => $name,
'cache_id' => $cache_id,
'compile_id' => $compile_id,
'content' => $content,)
);
return !!$this->saveQuery()->rowCount();
return !!$this->save->rowCount();
}
/**
@@ -157,18 +150,18 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
// delete the whole cache
if ($name === null && $cache_id === null && $compile_id === null && $exp_time === null) {
// returning the number of deleted caches would require a second query to count them
$query = $this->db()->query('TRUNCATE TABLE output_cache');
$query = $this->db->query('TRUNCATE TABLE output_cache');
return -1;
}
// build the filter
$where = array();
// equal test name
if ($name !== null) {
$where[] = 'name = ' . $this->db()->quote($name);
$where[] = 'name = ' . $this->db->quote($name);
}
// equal test compile_id
if ($compile_id !== null) {
$where[] = 'compile_id = ' . $this->db()->quote($compile_id);
$where[] = 'compile_id = ' . $this->db->quote($compile_id);
}
// range test expiration time
if ($exp_time !== null) {
@@ -178,13 +171,13 @@ class Smarty_CacheResource_Mysql extends \Smarty\Cacheresource\Custom
if ($cache_id !== null) {
$where[] =
'(cache_id = ' .
$this->db()->quote($cache_id) .
$this->db->quote($cache_id) .
' OR cache_id LIKE ' .
$this->db()->quote($cache_id . '|%') .
$this->db->quote($cache_id . '|%') .
')';
}
// run delete query
$query = $this->db()->query('DELETE FROM output_cache WHERE ' . join(' AND ', $where));
$query = $this->db->query('DELETE FROM output_cache WHERE ' . join(' AND ', $where));
return $query->rowCount();
}
}
@@ -1,7 +1,5 @@
<?php
use Smarty\Exception;
/**
* PDO Cache Handler
* Allows you to store Smarty Cache files into your db.
@@ -24,11 +22,12 @@ use Smarty\Exception;
* Example usage :
* $cnx = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
* $smarty->setCachingType('pdo');
* $smarty->loadPlugin('Smarty_CacheResource_Pdo');
* $smarty->registerCacheResource('pdo', new Smarty_CacheResource_Pdo($cnx, 'smarty_cache'));
*
* @author Beno!t POLASZEK - 2014
*/
class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
{
/**
* @var string[]
@@ -121,12 +120,12 @@ class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
* @param string $table : table (or view) name
* @param string $database : optional - if table is located in another db
*
* @throws \Smarty\Exception
* @throws \SmartyException
*/
public function __construct(PDO $pdo, $table, $database = null)
{
if (is_null($table)) {
throw new Exception("Table name for caching can't be null");
throw new SmartyException("Table name for caching can't be null");
}
$this->pdo = $pdo;
$this->table = $table;
@@ -197,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();
@@ -245,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);
@@ -323,7 +322,7 @@ class Smarty_CacheResource_Pdo extends \Smarty\Cacheresource\Custom
$where[] = 'compile_id = ' . $this->pdo->quote($compile_id);
}
// for clearing expired caches
if ($exp_time === \Smarty\Smarty::CLEAR_EXPIRED) {
if ($exp_time === Smarty::CLEAR_EXPIRED) {
$where[] = 'expire < CURRENT_TIMESTAMP';
} // range test expiration time
elseif ($exp_time !== null) {
@@ -1,12 +1,12 @@
<?php
require_once __DIR__ . '/cacheresource.pdo.php';
require_once 'cacheresource.pdo.php';
/**
* PDO Cache Handler with GZIP support
* Example usage :
* $cnx = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
* $smarty->setCachingType('pdo_gzip');
* $smarty->loadPlugin('Smarty_CacheResource_Pdo_Gzip');
* $smarty->registerCacheResource('pdo_gzip', new Smarty_CacheResource_Pdo_Gzip($cnx, 'smarty_cache'));
*
* @require Smarty_CacheResource_Pdo class
@@ -1,42 +1,38 @@
<?php
use Smarty\Exception;
use Smarty\Template;
use Smarty\Template\Source;
/**
* Extends All Resource
* Resource Implementation modifying the extends-Resource to walk
* through the template_dirs and inherit all templates of the same name
*
* @package Resource-examples
* @author Rodney Rehm
*/
class My_Resource_Extendsall extends \Smarty\Resource\ExtendsPlugin
class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends
{
/**
* populate Source Object with meta data from Resource
*
* @param Source $source source object
* @param Template $_template template object
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*
* @return void
*/
public function populate(Source $source, Template $_template = null)
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$uid = '';
$sources = array();
$timestamp = 0;
foreach ($source->getSmarty()->getTemplateDir() as $key => $directory) {
foreach ($source->smarty->getTemplateDir() as $key => $directory) {
try {
$s = Smarty\Resource\BasePlugin::source(null, $source->getSmarty(), 'file:' . '[' . $key . ']' . $source->name);
$s = Smarty_Resource::source(null, $source->smarty, 'file:' . '[' . $key . ']' . $source->name);
if (!$s->exists) {
continue;
}
$sources[ $s->uid ] = $s;
$uid .= $s->filepath;
$timestamp = $s->timestamp > $timestamp ? $s->timestamp : $timestamp;
} catch (Exception $e) {
} catch (SmartyException $e) {
}
}
if (!$sources) {
@@ -48,7 +44,7 @@ class My_Resource_Extendsall extends \Smarty\Resource\ExtendsPlugin
$s = current($sources);
$source->components = $sources;
$source->filepath = $s->filepath;
$source->uid = sha1($uid . $source->getSmarty()->_joined_template_dir);
$source->uid = sha1($uid . $source->smarty->_joined_template_dir);
$source->exists = true;
$source->timestamp = $timestamp;
}
+101
View File
@@ -0,0 +1,101 @@
<?php
/**
* MySQL Resource
* Resource Implementation based on the Custom API to use
* MySQL as the storage resource for Smarty's templates and configs.
* Table definition:
* <pre>CREATE TABLE IF NOT EXISTS `templates` (
* `name` varchar(100) NOT NULL,
* `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
* `source` text,
* PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
* Demo data:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello
* world"}{$x}');</pre>
*
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Mysql extends Smarty_Resource_Custom
{
/**
* PDO instance
*
* @var \PDO
*/
protected $db;
/**
* prepared fetch() statement
*
* @var \PDOStatement
*/
protected $fetch;
/**
* prepared fetchTimestamp() statement
*
* @var \PDOStatement
*/
protected $mtime;
/**
* Smarty_Resource_Mysql constructor.
*
* @throws \SmartyException
*/
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
} catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
$this->mtime = $this->db->prepare('SELECT modified FROM templates WHERE name = :name');
}
/**
* Fetch a template and its modification time from database
*
* @param string $name template name
* @param string $source template source
* @param integer $mtime template modification timestamp (epoch)
*
* @return void
*/
protected function fetch($name, &$source, &$mtime)
{
$this->fetch->execute(array('name' => $name));
$row = $this->fetch->fetch();
$this->fetch->closeCursor();
if ($row) {
$source = $row[ 'source' ];
$mtime = strtotime($row[ 'modified' ]);
} else {
$source = null;
$mtime = null;
}
}
/**
* Fetch a template's modification time from database
*
* @note implementing this method is optional. Only implement it if modification times can be accessed faster than
* loading the comple template source.
*
* @param string $name template name
*
* @return integer timestamp (epoch) the template was modified
*/
protected function fetchTimestamp($name)
{
$this->mtime->execute(array('name' => $name));
$mtime = $this->mtime->fetchColumn();
$this->mtime->closeCursor();
return strtotime($mtime);
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
/**
* MySQL Resource
* Resource Implementation based on the Custom API to use
* MySQL as the storage resource for Smarty's templates and configs.
* Note that this MySQL implementation fetches the source and timestamps in
* a single database query, instead of two separate like resource.mysql.php does.
* Table definition:
* <pre>CREATE TABLE IF NOT EXISTS `templates` (
* `name` varchar(100) NOT NULL,
* `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
* `source` text,
* PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
* Demo data:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello
* world"}{$x}');</pre>
*
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Mysqls extends Smarty_Resource_Custom
{
/**
* PDO instance
*
* @var \PDO
*/
protected $db;
/**
* prepared fetch() statement
*
* @var \PDOStatement
*/
protected $fetch;
/**
* Smarty_Resource_Mysqls constructor.
*
* @throws \SmartyException
*/
public function __construct()
{
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
} catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
}
/**
* Fetch a template and its modification time from database
*
* @param string $name template name
* @param string $source template source
* @param integer $mtime template modification timestamp (epoch)
*
* @return void
*/
protected function fetch($name, &$source, &$mtime)
{
$this->fetch->execute(array('name' => $name));
$row = $this->fetch->fetch();
$this->fetch->closeCursor();
if ($row) {
$source = $row[ 'source' ];
$mtime = strtotime($row[ 'modified' ]);
} else {
$source = null;
$mtime = null;
}
}
}
+2
View File
@@ -11,6 +11,8 @@
The current date and time is {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}
The value of global assigned variable $SCRIPT_NAME is {$SCRIPT_NAME}
Example of accessing server environment variable SERVER_NAME: {$smarty.server.SERVER_NAME}
The value of {ldelim}$Name{rdelim} is <b>{$Name}</b>
-39
View File
@@ -1,39 +0,0 @@
version: "2"
services:
base:
build:
context: .
dockerfile: ./utilities/testrunners/php72/Dockerfile
volumes:
- .:/app
working_dir: /app
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
+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
+2 -1
View File
@@ -11,7 +11,8 @@ of the console.
Set [`$debugging`](../programmers/api-variables/variable-debugging.md) to TRUE in Smarty, and if needed
set [`$debug_tpl`](../programmers/api-variables/variable-debug-template.md) to the template resource
path to `debug.tpl`. When you load the page, a Javascript console window will pop
path to `debug.tpl` (this is in [`SMARTY_DIR`](../programmers/smarty-constants.md) by
default). When you load the page, a Javascript console window will pop
up and give you the names of all the included templates and assigned
variables for the current page.
@@ -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.
@@ -10,6 +10,7 @@ within delimiters like so: `{funcname attr1="val1" attr2="val2"}`.
{config_load file="colors.conf"}
{include file="header.tpl"}
{insert file="banner_ads.tpl" title="My Site"}
{if $logged_in}
Welcome, <span style="color:{#fontColor#}">{$name}!</span>
@@ -16,6 +16,8 @@ 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)
@@ -17,7 +17,7 @@
var string Yes *n/a* The name of the variable being assigned
value string Yes *n/a* The value being assigned
index string No *n/a* The index for the new array element. If not specified the value is append to the end of the array.
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'smarty\'
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'global\'
**Option Flags:**
@@ -21,7 +21,7 @@ execution of a template**.
---------------- -------- ---------- --------- -----------------------------------------------------------------------
var string Yes *n/a* The name of the variable being assigned
value string Yes *n/a* The value being assigned
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'smarty\'
scope string No *n/a* The scope of the assigned variable: \'parent\',\'root\' or \'global\'
**Option Flags:**
@@ -135,6 +135,8 @@ 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),
[`{eval}`](#language.function.eval),
@@ -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
@@ -28,6 +28,13 @@ is the value passed in the `name` attribute. If you do not supply the
--------- -----------------------------------------
nocache Disables caching of this captured block
> **Note**
>
> Be careful when capturing [`{insert}`](#language.function.insert)
> output. If you have [`$caching`](#caching) enabled and you have
> [`{insert}`](#language.function.insert) commands that you expect to
> run within cached content, do not capture this content.
{* we don't want to print a div tag unless content is displayed *}
{capture name="banner"}
@@ -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.
@@ -8,6 +8,10 @@ template engine. Every `{if}` must be paired with a matching `{/if}`.
functions are recognized, such as *\|\|*, *or*, *&&*, *and*,
*is\_array()*, etc.
If securty is enabled, only PHP functions from `$php_functions` property
of the securty policy are allowed. See the
[Security](#advanced.features.security) section for details.
The following is a list of recognized qualifiers, which must be
separated from surrounding elements by spaces. Note that items listed in
\[brackets\] are optional. PHP equivalents are shown where applicable.
@@ -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 [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).
@@ -0,0 +1,86 @@
{insert} {#language.function.insert}
========
> **Note**
>
> `{insert}` 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 `{insert}` tags are only available from
> [SmartyBC](#bc).
`{insert}` tags work much like [`{include}`](#language.function.include)
tags, except that `{insert}` tags are NOT cached when template
[caching](#caching) is enabled. They will be executed on every
invocation of the template.
Attribute Name Type Required Default Description
---------------- -------------- ---------- --------- ----------------------------------------------------------------------------------
name string Yes *n/a* The name of the insert function (insert\_`name`) or insert plugin
assign string No *n/a* The name of the template variable the output will be assigned to
script string No *n/a* The name of the php script that is included before the insert function is called
\[var \...\] \[var type\] No *n/a* variable to pass to insert function
Let\'s say you have a template with a banner slot at the top of the
page. The banner can contain any mixture of HTML, images, flash, etc. so
we can\'t just use a static link here, and we don\'t want this contents
cached with the page. In comes the {insert} tag: the template knows
\#banner\_location\_id\# and \#site\_id\# values (gathered from a
[config file](#config.files)), and needs to call a function to get the
banner contents.
{* example of fetching a banner *}
{insert name="getBanner" lid=#banner_location_id# sid=#site_id#}
{insert "getBanner" lid=#banner_location_id# sid=#site_id#} {* short-hand *}
In this example, we are using the name "getBanner" and passing the
parameters \#banner\_location\_id\# and \#site\_id\#. Smarty will look
for a function named insert\_getBanner() in your PHP application,
passing the values of \#banner\_location\_id\# and \#site\_id\# as the
first argument in an associative array. All {insert} function names in
your application must be prepended with \"insert\_\" to remedy possible
function name-space conflicts. Your insert\_getBanner() function should
do something with the passed values and return the results. These
results are then displayed in the template in place of the {insert} tag.
In this example, Smarty would call this function:
insert\_getBanner(array(\"lid\" =\> \"12345\",\"sid\" =\> \"67890\"));
and display the returned results in place of the {insert} tag.
- If you supply the `assign` attribute, the output of the `{insert}`
tag will be assigned to this template variable instead of being
output to the template.
> **Note**
>
> Assigning the output to a template variable isn\'t too useful with
> [caching](#variable.caching) enabled.
- If you supply the `script` attribute, this php script will be
included (only once) before the `{insert}` function is executed.
This is the case where the insert function may not exist yet, and a
php script must be included first to make it work.
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
securty policy. See the [Security](#advanced.features.security)
section for details.
The Smarty object is passed as the second argument. This way you can
reference and modify information in the Smarty object from within the
`{insert}` function.
If no PHP script can be found Smarty is looking for a corresponding
insert plugin.
> **Note**
>
> It is possible to have portions of the template not cached. If you
> have [caching](#caching) turned on, `{insert}` tags will not be
> cached. They will run dynamically every time the page is created, even
> within cached pages. This works good for things like banners, polls,
> live weather, search results, user feedback areas, etc.
See also [`{include}`](#language.function.include)
@@ -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}
------------------------------------
+4 -6
View File
@@ -2,7 +2,7 @@ What is Smarty?
==============
## 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/).
@@ -143,9 +143,7 @@ the same vars, etc., we can do that in one place.
```php
<?php
use Smarty\Smarty;
class My_GuestBook extends Smarty {
class Smarty_GuestBook extends Smarty {
public function __construct()
{
@@ -163,9 +161,9 @@ class My_GuestBook extends Smarty {
}
```
Now, we can use `My_GuestBook` instead of `Smarty` in our scripts:
Now, we can use `Smarty_GuestBook` instead of `Smarty` in our scripts:
```php
$smarty = new My_GuestBook();
$smarty = new Smarty_GuestBook();
$smarty->assign('name','Ned');
$smarty->display('index.tpl');
```
+1
View File
@@ -37,6 +37,7 @@ and 480 for $height, the result is:
## Smarty for php developers
- [Charset Encoding](./programmers/charset.md)
- [Constants](./programmers/smarty-constants.md)
- [Smarty Class Variables](./programmers/api-variables.md)
- [Smarty Class Methods](./programmers/api-functions.md)
- [Caching](./programmers/caching.md)
@@ -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
@@ -10,14 +10,15 @@ output filters operate on the template output when it is executed.
Output filters can be either [registered](#api.register.filter) or
loaded from the [plugins directory](#variable.plugins.dir) by using the
[`loadFilter()`](#api.load.filter) method. Smarty will
[`loadFilter()`](#api.load.filter) method or by setting the
[`$autoload_filters`](#variable.autoload.filters) variable. Smarty will
pass the template output as the first argument, and expect the function
to return the result of the processing.
<?php
// put this in your application
function protect_email($tpl_output, \Smarty\Template\ $template)
function protect_email($tpl_output, Smarty_Internal_Template $template)
{
$tpl_output =
preg_replace('!(\S+)@([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,3}|[0-9]{1,3}))!',
@@ -37,5 +38,6 @@ to return the result of the processing.
See also [`registerFilter()`](#api.register.filter),
[`loadFilter()`](#api.load.filter),
[`$autoload_filters`](#variable.autoload.filters),
[postfilters](#advanced.features.postfilters) and
[`$plugins_dir`](#variable.plugins.dir).
@@ -5,14 +5,15 @@ Template postfilters are PHP functions that your templates are ran
through *after they are compiled*. Postfilters can be either
[registered](#api.register.filter) or loaded from the [plugins
directory](#variable.plugins.dir) by using the
[`loadFilter()`](#api.load.filter) function. Smarty will
[`loadFilter()`](#api.load.filter) function or by setting the
[`$autoload_filters`](#variable.autoload.filters) variable. Smarty will
pass the compiled template code as the first argument, and expect the
function to return the result of the processing.
<?php
// put this in your application
function add_header_comment($tpl_source, \Smarty\Template\ $template)
function add_header_comment($tpl_source, Smarty_Internal_Template $template)
{
return "<?php echo \"<!-- Created by Smarty! -->\n\"; ?>\n".$tpl_source;
}
@@ -8,7 +8,8 @@ putting in their templates, etc.
Prefilters can be either [registered](#api.register.filter) or loaded
from the [plugins directory](#variable.plugins.dir) by using
[`loadFilter()`](#api.load.filter) function.
[`loadFilter()`](#api.load.filter) function or by setting the
[`$autoload_filters`](#variable.autoload.filters) variable.
Smarty will pass the template source code as the first argument, and
expect the function to return the resulting template source code.
@@ -18,7 +19,7 @@ This will remove all the html comments in the template source.
<?php
// put this in your application
function remove_dw_comments($tpl_source, \Smarty\Template\ $template)
function remove_dw_comments($tpl_source, Smarty_Internal_Template $template)
{
return preg_replace("/<!--#.*-->/U",'',$tpl_source);
}
@@ -2,17 +2,39 @@ 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.
- `$trusted_uri` is an array of regular expressions matching URIs that
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
[`{include_php}`](#language.function.include.php). The default is an
empty array.
- `$trusted_uri` is an array of regular expressions matching URIs that
are considered trusted. This security directive used by
[`{fetch}`](#language.function.fetch) and
[`{html_image}`](#language.function.html.image). URIs passed to
@@ -21,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`
@@ -47,6 +69,19 @@ instance of the Smarty\_Security class. These are the possible settings:
static classes. To disable access to all static classes set
\$static\_classes = null.
- `$php_functions` is an array of PHP functions that are considered
trusted and can be used from within template. To disable access to
all PHP functions set \$php\_functions = null. An empty array (
\$php\_functions = array() ) will allow all PHP functions. The
default is array(\'isset\', \'empty\', \'count\', \'sizeof\',
\'in\_array\', \'is\_array\',\'time\',\'nl2br\').
- `$php_modifiers` is an array of PHP functions that are considered
trusted and can be used from within template as modifier. To disable
access to all PHP modifier set \$php\_modifier = null. An empty
array ( \$php\_modifier = array() ) will allow all PHP functions.
The default is array(\'escape\',\'count\').
- `$streams` is an array of streams that are considered trusted and
can be used from within template. To disable access to all streams
set \$streams = null. An empty array ( \$streams = array() ) will
@@ -75,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
@@ -84,9 +123,15 @@ Smarty\_Security class or create an instance of it.
<?php
require 'Smarty.class.php';
class My_Security_Policy extends \Smarty\Security {
public $allow_constants = false;
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();
}
$smarty = new Smarty();
// enable security
@@ -95,9 +140,15 @@ Smarty\_Security class or create an instance of it.
<?php
require 'Smarty.class.php';
$smarty = new Smarty();
$my_security_policy = new \Smarty\Security($smarty);
$my_security_policy->allow_constants = false;
$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
$smarty->enableSecurity($my_security_policy);
?>
@@ -113,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.
+2
View File
@@ -31,6 +31,7 @@ Smarty Class Methods {#api.functions}
- [getConfigVars()](./api-functions/api-get-config-vars.md) — returns the given loaded config variable value
- [getPluginsDir()](./api-functions/api-get-plugins-dir.md) — return the directory where plugins are stored
- [getRegisteredObject()](./api-functions/api-get-registered-object.md) — returns a reference to a registered object
- [getTags()](./api-functions/api-get-tags.md) — return tags used by template
- [getTemplateDir()](./api-functions/api-get-template-dir.md) — return the directory where templates are stored
- [getTemplateVars()](./api-functions/api-get-template-vars.md) — returns assigned variable value(s)
- [isCached()](./api-functions/api-is-cached.md) — returns true if there is a valid cache for this template
@@ -54,6 +55,7 @@ Smarty Class Methods {#api.functions}
- [unregisterPlugin()](./api-functions/api-unregister-plugin.md) — dynamically unregister plugins
- [unregisterObject()](./api-functions/api-unregister-object.md) — dynamically unregister an object
- [unregisterResource()](./api-functions/api-unregister-resource.md) — dynamically unregister a resource plugin
- [testInstall()](./api-functions/api-test-install.md) — checks Smarty installation
> **Note**
>
@@ -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).
@@ -31,9 +31,7 @@ PARAMETER.COMPILEID
<?php
use Smarty\Smarty;
include(SMARTY_DIR.'Smarty.class.php');
$smarty = new Smarty();
$smarty->setCaching(true);
@@ -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
@@ -0,0 +1,40 @@
getTags()
return tags used by template
Description
===========
string
getTags
object
template
This function returns an array of tagname/attribute pairs for all tags
used by the template. It uses the following parameters:
- `template` is the template object.
> **Note**
>
> This function is experimental.
<?php
include('Smarty.class.php');
$smarty = new Smarty;
// create template object
$tpl = $smarty->createTemplate('index.tpl');
// get tags
$tags = $smarty->getTags($tpl);
print_r($tags);
?>
@@ -22,8 +22,8 @@ string
compile\_id
- This only works if [`$caching`](#variable.caching) is set to one of
`\Smarty\Smarty::CACHING_LIFETIME_CURRENT` or
`\Smarty\Smarty::CACHING_LIFETIME_SAVED` to enable caching. See the [caching
`Smarty::CACHING_LIFETIME_CURRENT` or
`Smarty::CACHING_LIFETIME_SAVED` to enable caching. See the [caching
section](#caching) for more info.
- You can also pass a `$cache_id` as an optional second parameter in
@@ -18,7 +18,7 @@ string
name
The first argument specifies the type of the filter to load and can be
one of the following: `variable`, `pre`, `post` or `output`. The second argument
one of the following: `pre`, `post` or `output`. The second argument
specifies the `name` of the filter plugin.
@@ -37,5 +37,6 @@ specifies the `name` of the filter plugin.
See also [`registerFilter()`](#api.register.filter) and [advanced
See also [`registerFilter()`](#api.register.filter),
[`$autoload_filters`](#variable.autoload.filters) and [advanced
features](#advanced.features).
@@ -15,7 +15,7 @@ handler merely inspects `$errno` and `$errfile` to determine if the
given error was produced deliberately and must be ignored, or should be
passed on to the next error handler.
`\Smarty\Smarty::unmuteExpectedErrors()` removes the current error handler.
Please note, that if you\'ve registered any custom error handlers after
`Smarty::unmuteExpectedErrors()` removes the current error handler.
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.
@@ -31,7 +31,7 @@ how to create custom CacheResources.
<?php
$smarty->registerCacheResource('mysql', new My_CacheResource_Mysql());
$smarty->registerCacheResource('mysql', new Smarty_CacheResource_Mysql());
?>
@@ -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.
@@ -37,7 +37,7 @@ plugin types.
* @param string $name name of the undefined tag
* @param string $type tag type (e.g. Smarty::PLUGIN_FUNCTION, Smarty::PLUGIN_BLOCK,
Smarty::PLUGIN_COMPILER, Smarty::PLUGIN_MODIFIER, Smarty::PLUGIN_MODIFIERCOMPILER)
* @param \Smarty\Template\ $template template object
* @param Smarty_Internal_Template $template template object
* @param string &$callback returned function name
* @param string &$script optional returned script filepath if function is external
* @param bool &$cacheable true by default, set to false if plugin is not cachable (Smarty >= 3.1.8)
@@ -38,7 +38,8 @@ filters](#advanced.features.outputfilters) for more information on how
to set up an output filter function.
See also [`unregisterFilter()`](#api.unregister.filter),
[`loadFilter()`](#api.load.filter), [template pre
[`loadFilter()`](#api.load.filter),
[`$autoload_filters`](#variable.autoload.filters), [template pre
filters](#advanced.features.prefilters) [template post
filters](#advanced.features.postfilters) [template output
filters](#advanced.features.outputfilters) section.
@@ -32,9 +32,9 @@ cache\_attrs
This method registers functions or methods defined in your script as
plugin. It uses the following parameters:
- `cacheable` can be omitted in most cases. See
- `cacheable` and `cache_attrs` can be omitted in most cases. See
[controlling cacheability of plugins output](#caching.cacheable) on
how to use this properly.
how to use them properly.
<!-- -->
@@ -37,7 +37,7 @@ information on how to setup a function for fetching templates.
<?php
$smarty->registerResource('mysql', new My_Resource_Mysql());
$smarty->registerResource('mysql', new Smarty_Resource_Mysql());
?>
@@ -55,4 +55,5 @@ And the php script
See also [`display()`](#api.display), [`fetch()`](#api.fetch),
and [`{include}`](#language.function.include)
[`{include}`](#language.function.include) and
[`{insert}`](#language.function.insert)
@@ -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
+7
View File
@@ -4,7 +4,9 @@ Smarty Class Variables {#api.variables}
These are all of the available Smarty class variables. You can access
them directly, or use the corresponding setter/getter methods.
- [$allow_php_templates](./api-variables/variable-allow-php-templates.md)
- [$auto_literal](./api-variables/variable-auto-literal.md)
- [$autoload_filters](./api-variables/variable-autoload-filters.md)
- [$cache_dir](./api-variables/variable-cache-dir.md)
- [$cache_id](./api-variables/variable-cache-id.md)
- [$cache_lifetime](./api-variables/variable-cache-lifetime.md)
@@ -29,6 +31,7 @@ them directly, or use the corresponding setter/getter methods.
- [$default_resource_type](./api-variables/variable-default-resource-type.md)
- [$default_config_handler_func](./api-variables/variable-default-config-handler-func.md)
- [$default_template_handler_func](./api-variables/variable-default-template-handler-func.md)
- [$direct_access_security](./api-variables/variable-direct-access-security.md)
- [$error_reporting](./api-variables/variable-error-reporting.md)
- [$escape_html](./api-variables/variable-escape-html.md)
- [$force_cache](./api-variables/variable-force-cache.md)
@@ -36,9 +39,13 @@ 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)
- [$template_dir](./api-variables/variable-template-dir.md)
- [$trusted_dir](./api-variables/variable-trusted-dir.md)
- [$use_include_path](./api-variables/variable-use-include-path.md)
- [$use_sub_dirs](./api-variables/variable-use-sub-dirs.md)
> **Note**
@@ -0,0 +1,18 @@
\$allow\_php\_templates {#variable.allow.php.templates}
=======================
By default the PHP template file resource is disabled. Setting
`$allow_php_templates` to TRUE will enable PHP template files.
::: {.informalexample}
<?php
$smarty->allow_php_templates = true;
?>
:::
> **Note**
>
> The PHP template file resource is an undocumented deprecated feature.
@@ -0,0 +1,21 @@
\$autoload\_filters {#variable.autoload.filters}
===================
If there are some filters that you wish to load on every template
invocation, you can specify them using this variable and Smarty will
automatically load them for you. The variable is an associative array
where keys are filter types and values are arrays of the filter names.
For example:
::: {.informalexample}
<?php
$smarty->autoload_filters = array('pre' => array('trim', 'stamp'),
'output' => array('convert'));
?>
:::
See also [`registerFilter()`](#api.register.filter) and
[`loadFilter()`](#api.load.filter)
@@ -5,8 +5,8 @@ This is the length of time in seconds that a template cache is valid.
Once this time has expired, the cache will be regenerated.
- `$caching` must be turned on (either
\Smarty\Smarty::CACHING\_LIFETIME\_CURRENT or
\Smarty\Smarty::CACHING\_LIFETIME\_SAVED) for `$cache_lifetime` to have any
Smarty::CACHING\_LIFETIME\_CURRENT or
Smarty::CACHING\_LIFETIME\_SAVED) for `$cache_lifetime` to have any
purpose.
- A `$cache_lifetime` value of -1 will force the cache to never
@@ -14,11 +14,11 @@ Once this time has expired, the cache will be regenerated.
- A value of 0 will cause the cache to always regenerate (good for
testing only, to disable caching a more efficient method is to set
[`$caching`](#variable.caching) = \Smarty\Smarty::CACHING\_OFF).
[`$caching`](#variable.caching) = Smarty::CACHING\_OFF).
- If you want to give certain templates their own cache lifetime, you
could do this by setting [`$caching`](#variable.caching) =
\Smarty\Smarty::CACHING\_LIFETIME\_SAVED, then set `$cache_lifetime` to a
Smarty::CACHING\_LIFETIME\_SAVED, then set `$cache_lifetime` to a
unique value just before calling [`display()`](#api.display) or
[`fetch()`](#api.fetch).
@@ -4,7 +4,8 @@
If set to TRUE, Smarty will respect the If-Modified-Since header sent
from the client. If the cached file timestamp has not changed since the
last visit, then a `'304: Not Modified'` header will be sent instead of
the content.
the content. This works only on cached content without
[`{insert}`](#language.function.insert) tags.
See also [`$caching`](#variable.caching),
[`$cache_lifetime`](#variable.cache.lifetime), and the [caching
@@ -3,21 +3,21 @@
This tells Smarty whether or not to cache the output of the templates to
the [`$cache_dir`](#variable.cache.dir). By default this is set to the
constant \Smarty\Smarty::CACHING\_OFF. If your templates consistently generate
constant Smarty::CACHING\_OFF. If your templates consistently generate
the same content, it is advisable to turn on `$caching`, as this may
result in significant performance gains.
You can also have [multiple](#caching.multiple.caches) caches for the
same template.
- A constant value of \Smarty\Smarty::CACHING\_LIFETIME\_CURRENT or
\Smarty\Smarty ::CACHING\_LIFETIME\_SAVED enables caching.
- A constant value of Smarty::CACHING\_LIFETIME\_CURRENT or
Smarty::CACHING\_LIFETIME\_SAVED enables caching.
- A value of \Smarty\Smarty::CACHING\_LIFETIME\_CURRENT tells Smarty to use
- A value of Smarty::CACHING\_LIFETIME\_CURRENT tells Smarty to use
the current [`$cache_lifetime`](#variable.cache.lifetime) variable
to determine if the cache has expired.
- A value of \Smarty\Smarty::CACHING\_LIFETIME\_SAVED tells Smarty to use the
- A value of Smarty::CACHING\_LIFETIME\_SAVED tells Smarty to use the
[`$cache_lifetime`](#variable.cache.lifetime) value at the time the
cache was generated. This way you can set the
[`$cache_lifetime`](#variable.cache.lifetime) just before
@@ -18,7 +18,7 @@ enabled, then the cache files will get regenerated if an involved
template file or config file was updated.
As of Smarty 3.1 `$compile_check` can be set to the value
`\Smarty\Smarty::COMPILECHECK_CACHEMISS`. This enables Smarty to revalidate the
`Smarty::COMPILECHECK_CACHEMISS`. This enables Smarty to revalidate the
compiled template, once a cache file is regenerated. So if there was a
cached template, but it\'s expired, Smarty will run a single
compile\_check before regenerating the cache.
@@ -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.
@@ -2,7 +2,8 @@
============
This is the name of the template file used for the debugging console. By
default, it is named `debug.tpl` and is located in `src/debug.tpl`.
default, it is named `debug.tpl` and is located in the
[`SMARTY_DIR`](#constant.smarty.dir).
See also [`$debugging`](#variable.debugging) and the [debugging
console](#chapter.debugging.console) section.
@@ -8,7 +8,7 @@ resource.
>
> The default handler is currently only invoked for file resources. It
> is not triggered when the resource itself cannot be found, in which
> case a \Smarty\Exception is thrown.
> case a SmartyException is thrown.
<?php
@@ -8,7 +8,7 @@ resource.
>
> The default handler is currently only invoked for file resources. It
> is not triggered when the resource itself cannot be found, in which
> case a \Smarty\Exception is thrown.
> case a SmartyException is thrown.
<?php
@@ -0,0 +1,13 @@
\$direct\_access\_security {#variable.direct.access.security}
==========================
Direct access security inhibits direct browser access to compiled or
cached template files.
Direct access security is enabled by default. To disable it set
`$direct_access_security` to FALSE.
> **Note**
>
> This is a compile time option. If you change the setting you must make
> sure that the templates get recompiled.
@@ -7,7 +7,7 @@ When this value is set to a non-null-value it\'s value is used as php\'s
Smarty 3.1.2 introduced the
[`muteExpectedErrors()`](#api.mute.expected.errors) function. Calling
`\Smarty\Smarty::muteExpectedErrors();` after setting up custom error handling
`Smarty::muteExpectedErrors();` after setting up custom error handling
will ensure that warnings and notices (deliberately) produced by Smarty
will not be passed to other custom error handlers. If your error logs
are filling up with warnings regarding `filemtime()` or `unlink()`
@@ -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.
@@ -0,0 +1,28 @@
\$plugins\_dir {#variable.plugins.dir}
==============
This is the directory or directories where Smarty will look for the
plugins that it needs. Default is `plugins/` under the
[`SMARTY_DIR`](#constant.smarty.dir). If you supply a relative path,
Smarty will first look under the [`SMARTY_DIR`](#constant.smarty.dir),
then relative to the current working directory, then relative to the PHP
include\_path. If `$plugins_dir` is an array of directories, Smarty will
search for your plugin in each plugin directory **in the order they are
given**.
> **Note**
>
> For best performance, do not setup your `$plugins_dir` to have to use
> the PHP include path. Use an absolute pathname, or a path relative to
> `SMARTY_DIR` or the current working directory.
> **Note**
>
> As of Smarty 3.1 the attribute \$plugins\_dir is no longer accessible
> directly. Use [`getPluginsDir()`](#api.get.plugins.dir),
> [`setPluginsDir()`](#api.set.plugins.dir) and
> [`addPluginsDir()`](#api.add.plugins.dir) instead.
See also [`getPluginsDir()`](#api.get.plugins.dir),
[`setPluginsDir()`](#api.set.plugins.dir) and
[`addPluginsDir()`](#api.add.plugins.dir).
@@ -15,12 +15,22 @@ found.
> document root.
> **Note**
>
> If the directories known to `$template_dir` are relative to
> directories known to the
> [include\_path](&url.php-manual;ini.core.php#ini.include-path) you
> need to activate the [`$use_include_path`](#variable.use.include.path)
> option.
> **Note**
>
> As of Smarty 3.1 the attribute \$template\_dir is no longer accessible
> directly. Use [`getTemplateDir()`](#api.get.template.dir),
> [`setTemplateDir()`](#api.set.template.dir) and
> [`addTemplateDir()`](#api.add.template.dir) instead.
See also [`Template Resources`](#resources),
[`$use_include_path`](#variable.use.include.path),
[`getTemplateDir()`](#api.get.template.dir),
[`setTemplateDir()`](#api.set.template.dir) and
[`addTemplateDir()`](#api.add.template.dir).
@@ -0,0 +1,8 @@
\$trusted\_dir {#variable.trusted.dir}
==============
`$trusted_dir` is only for use when security is enabled. This 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
[`{include_php}`](#language.function.include.php).
@@ -0,0 +1,49 @@
\$use\_include\_path {#variable.use.include.path}
====================
This tells smarty to respect the
[include\_path](&url.php-manual;ini.core.php#ini.include-path) within
the [`File Template Resource`](#resources.file) handler and the plugin
loader to resolve the directories known to
[`$template_dir`](#variable.template.dir). The flag also makes the
plugin loader check the include\_path for
[`$plugins_dir`](#variable.plugins.dir).
> **Note**
>
> You should not design your applications to rely on the include\_path,
> as this may - depending on your implementation - slow down your system
> (and Smarty) considerably.
If use\_include\_path is enabled, file discovery for
[`$template_dir`](#variable.template.dir) and
[`$plugins_dir`](#variable.plugins.dir) work as follows.
- For each element `$directory` in array (\$template\_dir or
\$plugins\_dir) do
- Test if requested file is in `$directory` relative to the [current
working directory](&url.php-manual;function.getcwd.php). If file
found, return it.
- For each `$path` in include\_path do
- Test if requested file is in `$directory` relative to the `$path`
(possibly relative to the [current working
directory](&url.php-manual;function.getcwd.php)). If file found,
return it.
- Try default\_handler or fail.
This means that whenever a directory/file relative to the current
working directory is encountered, it is preferred over anything
potentially accessible through the include\_path.
> **Note**
>
> Smarty does not filter elements of the include\_path. That means a
> \".:\" within your include path will trigger the current working
> directory lookup twice.
See also [`Template Resources`](#resources) and
[`$template_dir`](#variable.template.dir)
@@ -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
+50 -2
View File
@@ -76,14 +76,62 @@ third parameter to [`registerPlugin()`](#api.register.plugin) is called
When registering a plugin with `$cacheable=false` the plugin is called
everytime the page is displayed, even if the page comes from the cache.
The plugin function behaves a little like an
[`{insert}`](#plugins.inserts) function.
> **Note**
>
> The `$cacheable` status will affect the compiled template code. If you
> The `$cacheable` status will effect the compiled template code. If you
> change the status you must manually delete existing compiled and
> cached template files to force a recompile.
Example `index.php`:
In contrast to [`{insert}`](#plugins.inserts) the attributes to the
plugins are not cached by default. They can be declared to be cached
with the fourth parameter `$cache_attrs`. `$cache_attrs` is an array of
attribute-names that should be cached, so the plugin-function get value
as it was the time the page was written to cache everytime it is fetched
from the cache.
<?php
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
function remaining_seconds($params, $smarty) {
$remain = $params['endtime'] - time();
if($remain >= 0){
return $remain . ' second(s)';
}else{
return 'done';
}
}
$smarty->registerPlugin('function','remaining', 'remaining_seconds', false, array('endtime'));
if (!$smarty->isCached('index.tpl')) {
// fetch $obj from db and assign...
$smarty->assignByRef('obj', $obj);
}
$smarty->display('index.tpl');
?>
where `index.tpl` is:
Time Remaining: {remaining endtime=$obj->endtime}
The number of seconds till the endtime of `$obj` is reached changes on
each display of the page, even if the page is cached. Since the endtime
attribute is cached the object only has to be pulled from the database
when page is written to the cache but not on subsequent requests of the
page.
index.php:
<?php
$smarty->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
+8 -8
View File
@@ -17,11 +17,11 @@ faster storage engine, centralize the cache to be accessible to multiple
servers.
Smarty allows CacheResource implementations to use one of the APIs
`\Smarty\Cacheresource\Custom` or `\Smarty\Cacheresource\KeyValueStore`.
`\Smarty\Cacheresource\Custom` is a simple API directing all read, write,
`Smarty_CacheResource_Custom` or `Smarty_CacheResource_KeyValueStore`.
`Smarty_CacheResource_Custom` is a simple API directing all read, write,
clear calls to your implementation. This API allows you to store
wherever and however you deem fit. The
`\Smarty\Cacheresource\KeyValueStore` API allows you to turn any \"dumb\"
`Smarty_CacheResource_KeyValueStore` API allows you to turn any \"dumb\"
KeyValue-Store (like APC, Memcache, ...) into a full-featured
CacheResource implementation. That is, everything around deep
cache-groups like \"a\|b\|c\" is being handled for you in way that
@@ -63,10 +63,10 @@ to invoke your custom CacheResource implementation.
* INDEX(`modified`)
* ) ENGINE = InnoDB;</pre>
*
* @package CacheResource-examples
* @author Rodney Rehm
*/
class My_CacheResource_Mysql extends \Smarty\Cacheresource\Custom {
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom {
// PDO instance
protected $db;
protected $fetch;
@@ -77,7 +77,7 @@ to invoke your custom CacheResource implementation.
try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
} catch (PDOException $e) {
throw new \Smarty\Exception('Mysql Resource failed: ' . $e->getMessage());
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, content FROM output_cache WHERE id = :id');
$this->fetchTimestamp = $this->db->prepare('SELECT modified FROM output_cache WHERE id = :id');
@@ -211,10 +211,10 @@ to invoke your custom CacheResource implementation.
* Note that memcache has a limitation of 256 characters per cache-key.
* To avoid complications all cache-keys are translated to a sha1 hash.
*
* @package CacheResource-examples
* @author Rodney Rehm
*/
class My_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore {
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
/**
* memcache instance
* @var Memcache
+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
+10 -7
View File
@@ -3,7 +3,7 @@ Setting Up Caching {#caching.setting.up}
The first thing to do is enable caching by setting
[`$caching`](#variable.caching) to one of
`\Smarty\Smarty::CACHING_LIFETIME_CURRENT` or `Smarty::CACHING_LIFETIME_SAVED`.
`Smarty::CACHING_LIFETIME_CURRENT` or `Smarty::CACHING_LIFETIME_SAVED`.
<?php
@@ -36,7 +36,7 @@ Each cached page has a limited lifetime determined by
seconds, or one hour. After that time expires, the cache is regenerated.
It is possible to give individual caches their own expiration time by
setting [`$caching`](#variable.caching) to
`\Smarty\Smarty::CACHING_LIFETIME_SAVED`. See
`Smarty::CACHING_LIFETIME_SAVED`. See
[`$cache_lifetime`](#variable.cache.lifetime) for more details.
@@ -92,7 +92,7 @@ however this also seriously degrades performance.
[`$force_compile`](#variable.force.compile) is meant to be used for
[debugging](#chapter.debugging.console) purposes. The appropriate way to
disable caching is to set [`$caching`](#variable.caching) to
\Smarty\Smarty::CACHING\_OFF.
Smarty::CACHING\_OFF.
The [`isCached()`](#api.is.cached) function can be used to test if a
template has a valid cache or not. If you have a cached template that
@@ -118,13 +118,16 @@ process.
You can keep parts of a page dynamic (disable caching) with the
[`{nocache}{/nocache}`](#language.function.nocache) block function, or by using the
[`{nocache}{/nocache}`](#language.function.nocache) block function, the
[`{insert}`](#language.function.insert) function, or by using the
`nocache` parameter for most template functions.
Let\'s say the whole page can be cached except for a banner that is
displayed down the side of the page. By using a [`{nocache}{/nocache}`](#language.function.nocache)
block for the banner, you can
keep this element dynamic within the cached content.
displayed down the side of the page. By using the
[`{insert}`](#language.function.insert) function for the banner, you can
keep this element dynamic within the cached content. See the
documentation on [`{insert}`](#language.function.insert) for more
details and examples.
You can clear all the cache files with the
[`clearAllCache()`](#api.clear.all.cache) function, or individual cache
+10 -6
View File
@@ -5,15 +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\Smarty::$_CHARSET`,
Smarty recognizes `UTF-8` as the internal charset.
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.
@@ -24,16 +26,18 @@ Smarty recognizes `UTF-8` as the internal charset.
> **Note**
>
> Smarty\'s internals and core plugins are truly UTF-8 compatible since
> Smarty 3.1.
> Smarty 3.1. To achieve unicode compatibility, the [Multibyte
> String](https://www.php.net/mbstring) PECL is required. Unless your PHP
> environment offers this package, Smarty will not be able to offer
> full-scale UTF-8 compatibility.
// use japanese character encoding
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();
+1
View File
@@ -13,6 +13,7 @@ Extending Smarty With Plugins {#plugins}
- [Prefilters/Postfilters](./plugins/plugins-prefilters-postfilters.md)
- [Output Filters](./plugins/plugins-outputfilters.md)
- [Resources](./plugins/plugins-resources.md)
- [Inserts](./plugins/plugins-inserts.md)
Version 2.0 introduced the plugin architecture that is used for almost
all the customizable functionality of Smarty. This includes:
@@ -60,6 +60,12 @@ cannot have both custom function `{func}` and block function
function implementation is called again with the new block contents
in the parameter `$content`.
If you have nested block functions, it\'s possible to find out what the
parent block function is by accessing `$smarty->_tag_stack` variable.
Just do a [`var_dump()`](&url.php-manual;var_dump) on it and the
structure should be apparent.
<?php
/*
* Smarty plugin
@@ -70,7 +76,7 @@ cannot have both custom function `{func}` and block function
* Purpose: translate a block of text
* -------------------------------------------------------------
*/
function smarty_block_translate($params, $content, \Smarty\Template $template, &$repeat)
function smarty_block_translate($params, $content, Smarty_Internal_Template $template, &$repeat)
{
// only output on the closing tag
if(!$repeat){
@@ -40,7 +40,7 @@ some other Smarty-provided functionality, it can use the supplied
* Purpose: outputs a random magic answer
* -------------------------------------------------------------
*/
function smarty_function_eightball($params, \Smarty\Template\ $template)
function smarty_function_eightball($params, Smarty_Internal_Template $template)
{
$answers = array('Yes',
'No',
@@ -71,7 +71,7 @@ which can be used in the template as:
* Purpose: assign a value to a template variable
* -------------------------------------------------------------
*/
function smarty_function_assign($params, \Smarty\Template\ $template)
function smarty_function_assign($params, Smarty_Internal_Template $template)
{
if (empty($params['var'])) {
trigger_error("assign: missing 'var' parameter");
@@ -0,0 +1,48 @@
Inserts {#plugins.inserts}
=======
Insert plugins are used to implement functions that are invoked by
[`{insert}`](#language.function.insert) tags in the template.
string
smarty\_insert\_
name
array
\$params
object
\$template
The first parameter to the function is an associative array of
attributes passed to the insert.
The insert function is supposed to return the result which will be
substituted in place of the `{insert}` tag in the template.
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: insert.time.php
* Type: time
* Name: time
* Purpose: Inserts current date/time according to format
* -------------------------------------------------------------
*/
function smarty_insert_time($params, Smarty_Internal_Template $template)
{
if (empty($params['format'])) {
trigger_error("insert time: missing 'format' parameter");
return;
}
return strftime($params['format']);
}
?>

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