Merge branch 'dev' of https://framagit.org/hubzilla/core into xdev_merge

This commit is contained in:
zotlabs 2018-10-30 18:11:49 -07:00
commit 70c55da1df
247 changed files with 6541 additions and 5710 deletions

View File

@ -1,3 +1,25 @@
Hubzilla 3.8.2 (2018-10-29)
- Merge unmerged changes from dev into master
- Fix issues with forum handling in mod network and ping
- Fix delivery chain linkage messed up if original post was edited
- Fix issues with the experimental queue worker
- Fix call to image source {1} from html template
- Group stream filters by threaded and unthreaded default view
- Show only unseen forum messages when clicking on forum notification
- Improve editor contact autocomplete performance
- Convert non UTF-8 content on link embeding
- Make textcomplete return up to 100 items
- Look for for matches in the entire string when suggesting emojis
- Add [summary] bbcode to autocomplete list
- Update blueimp_upload to version 9.23
- Update spanish strings
Addons
- Cart: don't allow items to be added unless user is logged into the Grid.
- Pubcrawl: simplify asencode_activity() addressing to reflect upcoming changes in mastodon 2.6
- Rendezvous: Update rendezvous_group.tpl to fix broken Bootstrap library reference
Hubzilla 3.8.1 (2018-10-21) Hubzilla 3.8.1 (2018-10-21)
- Fix issue with too long navbar banners - Fix issue with too long navbar banners
- Fix menu item edit link - Fix menu item edit link

View File

@ -60,7 +60,8 @@ class Master {
$k = explode('_',$worker['k']); $k = explode('_',$worker['k']);
q("delete from config where cat='queueworkers' and k='%s'", q("delete from config where cat='queueworkers' and k='%s'",
'workerstarted_'.$k[1]); 'workerstarted_'.$k[1]);
q("update config set k='workitem' where cat='queuework' and k='%s'", q("update config set k='%s' where cat='queuework' and k='%s'",
dbesc(uniqid('workitem:',true)),
'workitem_'.$k[1]); 'workitem_'.$k[1]);
unset($workers[$idx]); unset($workers[$idx]);
} }
@ -69,7 +70,7 @@ class Master {
return false; return false;
} }
} }
return uniqid(); return uniqid('',true);
} }

View File

@ -258,12 +258,18 @@ class Network extends \Zotlabs\Web\Controller {
} }
elseif($pf && $unseen && $nouveau) { elseif($pf && $unseen && $nouveau) {
$ttype = TERM_FORUM;
// This is for nouveau view public forum cid queries (if a forum notification is clicked) // This is for nouveau view public forum cid queries (if a forum notification is clicked)
$p = q("SELECT oid AS parent FROM term WHERE uid = " . intval(local_channel()) . " AND ttype = $ttype AND term = '" . dbesc($cid_r[0]['xchan_name']) . "'"); $p = q("SELECT oid AS parent FROM term WHERE uid = %d AND ttype = %d AND term = '%s'",
intval(local_channel()),
intval(TERM_FORUM),
dbesc($cid_r[0]['xchan_name'])
);
$p = ids_to_querystr($p, 'parent'); $p_str = ids_to_querystr($p, 'parent');
$sql_extra = " AND ( owner_xchan = '" . dbesc($cid_r[0]['abook_xchan']) . "' OR item.parent IN ( $p ) ) AND item_unseen = 1 "; if($p_str)
$p_sql = " OR item.parent IN ( $p_str ) ";
$sql_extra = " AND ( owner_xchan = '" . protect_sprintf(dbesc($cid_r[0]['abook_xchan'])) . "' OR owner_xchan = '" . protect_sprintf(dbesc($cid_r[0]['abook_xchan'])) . "' $p_sql ) AND item_unseen = 1 ";
} }
else { else {
// This is for threaded view cid queries (e.g. if a forum is selected from the forum filter) // This is for threaded view cid queries (e.g. if a forum is selected from the forum filter)
@ -273,6 +279,9 @@ class Network extends \Zotlabs\Web\Controller {
$p2 = q("SELECT oid AS parent FROM term WHERE uid = " . intval(local_channel()) . " AND ttype = $ttype AND term = '" . dbesc($cid_r[0]['xchan_name']) . "'"); $p2 = q("SELECT oid AS parent FROM term WHERE uid = " . intval(local_channel()) . " AND ttype = $ttype AND term = '" . dbesc($cid_r[0]['xchan_name']) . "'");
$p_str = ids_to_querystr(array_merge($p1,$p2),'parent'); $p_str = ids_to_querystr(array_merge($p1,$p2),'parent');
if(! $p_str)
killme();
$sql_extra = " AND item.parent IN ( $p_str ) "; $sql_extra = " AND item.parent IN ( $p_str ) ";
} }
} }

View File

@ -634,19 +634,25 @@ class Ping extends \Zotlabs\Web\Controller {
if($vnotify & VNOTIFY_FORUMS) { if($vnotify & VNOTIFY_FORUMS) {
$forums = get_forum_channels(local_channel()); $forums = get_forum_channels(local_channel());
if(! $forums) { if($forums) {
$result['forums'] = 0; $item_normal = item_normal();
}
else {
$perms_sql = item_permissions_sql(local_channel()) . item_normal();
$fcount = count($forums); $fcount = count($forums);
$forums['total'] = 0; $forums['total'] = 0;
for($x = 0; $x < $fcount; $x ++) { for($x = 0; $x < $fcount; $x ++) {
$r = q("select sum(item_unseen) as unseen from item $p = q("SELECT oid AS parent FROM term WHERE uid = %d AND ttype = %d AND term = '%s'",
where uid = %d and owner_xchan = '%s' and item_unseen = 1 $perms_sql ",
intval(local_channel()), intval(local_channel()),
intval(TERM_FORUM),
dbesc($forums[$x]['xchan_name'])
);
$p_str = ids_to_querystr($p, 'parent');
$p_sql = (($p_str) ? "OR parent IN ( $p_str )" : '');
$r = q("select count(id) as unseen from item
where uid = %d and ( owner_xchan = '%s' OR author_xchan = '%s' $p_sql ) and item_unseen = 1 $item_normal",
intval(local_channel()),
dbesc($forums[$x]['xchan_hash']),
dbesc($forums[$x]['xchan_hash']) dbesc($forums[$x]['xchan_hash'])
); );
if($r[0]['unseen']) { if($r[0]['unseen']) {

View File

@ -6,10 +6,6 @@ class Wiki_list {
function widget($arr) { function widget($arr) {
if(argc() < 3) {
return;
}
$channel = channelx_by_n(\App::$profile_uid); $channel = channelx_by_n(\App::$profile_uid);
$wikis = \Zotlabs\Lib\NativeWiki::listwikis($channel,get_observer_hash()); $wikis = \Zotlabs\Lib\NativeWiki::listwikis($channel,get_observer_hash());

215
composer.lock generated
View File

@ -157,16 +157,16 @@
}, },
{ {
"name": "league/html-to-markdown", "name": "league/html-to-markdown",
"version": "4.7.0", "version": "4.8.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/thephpleague/html-to-markdown.git", "url": "https://github.com/thephpleague/html-to-markdown.git",
"reference": "76c076483cef89860d32a3fd25312f5a42848a8c" "reference": "f9a879a068c68ff47b722de63f58bec79e448f9d"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/thephpleague/html-to-markdown/zipball/76c076483cef89860d32a3fd25312f5a42848a8c", "url": "https://api.github.com/repos/thephpleague/html-to-markdown/zipball/f9a879a068c68ff47b722de63f58bec79e448f9d",
"reference": "76c076483cef89860d32a3fd25312f5a42848a8c", "reference": "f9a879a068c68ff47b722de63f58bec79e448f9d",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -185,7 +185,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "4.8-dev" "dev-master": "4.9-dev"
} }
}, },
"autoload": { "autoload": {
@ -198,17 +198,17 @@
"MIT" "MIT"
], ],
"authors": [ "authors": [
{
"name": "Colin O'Dell",
"email": "colinodell@gmail.com",
"homepage": "http://www.colinodell.com",
"role": "Lead Developer"
},
{ {
"name": "Nick Cernis", "name": "Nick Cernis",
"email": "nick@cern.is", "email": "nick@cern.is",
"homepage": "http://modernnerd.net", "homepage": "http://modernnerd.net",
"role": "Original Author" "role": "Original Author"
},
{
"name": "Colin O'Dell",
"email": "colinodell@gmail.com",
"homepage": "https://www.colinodell.com",
"role": "Lead Developer"
} }
], ],
"description": "An HTML-to-markdown conversion helper for PHP", "description": "An HTML-to-markdown conversion helper for PHP",
@ -217,7 +217,7 @@
"html", "html",
"markdown" "markdown"
], ],
"time": "2018-05-19T23:47:12+00:00" "time": "2018-09-18T12:18:08+00:00"
}, },
{ {
"name": "lukasreschke/id3parser", "name": "lukasreschke/id3parser",
@ -520,16 +520,16 @@
}, },
{ {
"name": "sabre/dav", "name": "sabre/dav",
"version": "3.2.2", "version": "3.2.3",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sabre-io/dav.git", "url": "https://github.com/sabre-io/dav.git",
"reference": "e987775e619728f12205606c9cc3ee565ffb1516" "reference": "a9780ce4f35560ecbd0af524ad32d9d2c8954b80"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sabre-io/dav/zipball/e987775e619728f12205606c9cc3ee565ffb1516", "url": "https://api.github.com/repos/sabre-io/dav/zipball/a9780ce4f35560ecbd0af524ad32d9d2c8954b80",
"reference": "e987775e619728f12205606c9cc3ee565ffb1516", "reference": "a9780ce4f35560ecbd0af524ad32d9d2c8954b80",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -599,7 +599,7 @@
"framework", "framework",
"iCalendar" "iCalendar"
], ],
"time": "2017-02-15T03:06:08+00:00" "time": "2018-10-19T09:58:27+00:00"
}, },
{ {
"name": "sabre/event", "name": "sabre/event",
@ -1002,16 +1002,16 @@
}, },
{ {
"name": "smarty/smarty", "name": "smarty/smarty",
"version": "v3.1.32", "version": "v3.1.33",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/smarty-php/smarty.git", "url": "https://github.com/smarty-php/smarty.git",
"reference": "ac9d4b587e5bf53381e21881820a9830765cb459" "reference": "dd55b23121e55a3b4f1af90a707a6c4e5969530f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/smarty-php/smarty/zipball/ac9d4b587e5bf53381e21881820a9830765cb459", "url": "https://api.github.com/repos/smarty-php/smarty/zipball/dd55b23121e55a3b4f1af90a707a6c4e5969530f",
"reference": "ac9d4b587e5bf53381e21881820a9830765cb459", "reference": "dd55b23121e55a3b4f1af90a707a6c4e5969530f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -1051,7 +1051,7 @@
"keywords": [ "keywords": [
"templating" "templating"
], ],
"time": "2018-04-24T14:53:33+00:00" "time": "2018-09-12T20:54:16+00:00"
}, },
{ {
"name": "symfony/polyfill-ctype", "name": "symfony/polyfill-ctype",
@ -2160,16 +2160,16 @@
}, },
{ {
"name": "php-mock/php-mock-phpunit", "name": "php-mock/php-mock-phpunit",
"version": "2.1.1", "version": "2.1.2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/php-mock/php-mock-phpunit.git", "url": "https://github.com/php-mock/php-mock-phpunit.git",
"reference": "ff1cc1d4e7478ce74221e05742588619bee84f69" "reference": "57b92e621f14c2c07a4567cd29ed4e87de0d2912"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/php-mock/php-mock-phpunit/zipball/ff1cc1d4e7478ce74221e05742588619bee84f69", "url": "https://api.github.com/repos/php-mock/php-mock-phpunit/zipball/57b92e621f14c2c07a4567cd29ed4e87de0d2912",
"reference": "ff1cc1d4e7478ce74221e05742588619bee84f69", "reference": "57b92e621f14c2c07a4567cd29ed4e87de0d2912",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2210,7 +2210,7 @@
"test", "test",
"test double" "test double"
], ],
"time": "2018-04-06T13:54:43+00:00" "time": "2018-10-07T14:38:37+00:00"
}, },
{ {
"name": "phpdocumentor/reflection-common", "name": "phpdocumentor/reflection-common",
@ -2481,16 +2481,16 @@
}, },
{ {
"name": "phpunit/php-code-coverage", "name": "phpunit/php-code-coverage",
"version": "6.0.7", "version": "6.1.3",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "865662550c384bc1db7e51d29aeda1c2c161d69a" "reference": "4d3ae9b21a7d7e440bd0cf65565533117976859f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/865662550c384bc1db7e51d29aeda1c2c161d69a", "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/4d3ae9b21a7d7e440bd0cf65565533117976859f",
"reference": "865662550c384bc1db7e51d29aeda1c2c161d69a", "reference": "4d3ae9b21a7d7e440bd0cf65565533117976859f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2501,7 +2501,7 @@
"phpunit/php-text-template": "^1.2.1", "phpunit/php-text-template": "^1.2.1",
"phpunit/php-token-stream": "^3.0", "phpunit/php-token-stream": "^3.0",
"sebastian/code-unit-reverse-lookup": "^1.0.1", "sebastian/code-unit-reverse-lookup": "^1.0.1",
"sebastian/environment": "^3.1", "sebastian/environment": "^3.1 || ^4.0",
"sebastian/version": "^2.0.1", "sebastian/version": "^2.0.1",
"theseer/tokenizer": "^1.1" "theseer/tokenizer": "^1.1"
}, },
@ -2514,7 +2514,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "6.0-dev" "dev-master": "6.1-dev"
} }
}, },
"autoload": { "autoload": {
@ -2540,25 +2540,28 @@
"testing", "testing",
"xunit" "xunit"
], ],
"time": "2018-06-01T07:51:50+00:00" "time": "2018-10-23T05:59:32+00:00"
}, },
{ {
"name": "phpunit/php-file-iterator", "name": "phpunit/php-file-iterator",
"version": "2.0.1", "version": "2.0.2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/php-file-iterator.git", "url": "https://github.com/sebastianbergmann/php-file-iterator.git",
"reference": "cecbc684605bb0cc288828eb5d65d93d5c676d3c" "reference": "050bedf145a257b1ff02746c31894800e5122946"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/cecbc684605bb0cc288828eb5d65d93d5c676d3c", "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/050bedf145a257b1ff02746c31894800e5122946",
"reference": "cecbc684605bb0cc288828eb5d65d93d5c676d3c", "reference": "050bedf145a257b1ff02746c31894800e5122946",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": "^7.1" "php": "^7.1"
}, },
"require-dev": {
"phpunit/phpunit": "^7.1"
},
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
@ -2587,7 +2590,7 @@
"filesystem", "filesystem",
"iterator" "iterator"
], ],
"time": "2018-06-11T11:44:00+00:00" "time": "2018-09-13T20:33:42+00:00"
}, },
{ {
"name": "phpunit/php-text-template", "name": "phpunit/php-text-template",
@ -2681,16 +2684,16 @@
}, },
{ {
"name": "phpunit/php-token-stream", "name": "phpunit/php-token-stream",
"version": "3.0.0", "version": "3.0.1",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/php-token-stream.git", "url": "https://github.com/sebastianbergmann/php-token-stream.git",
"reference": "21ad88bbba7c3d93530d93994e0a33cd45f02ace" "reference": "c99e3be9d3e85f60646f152f9002d46ed7770d18"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/21ad88bbba7c3d93530d93994e0a33cd45f02ace", "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/c99e3be9d3e85f60646f152f9002d46ed7770d18",
"reference": "21ad88bbba7c3d93530d93994e0a33cd45f02ace", "reference": "c99e3be9d3e85f60646f152f9002d46ed7770d18",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2726,20 +2729,20 @@
"keywords": [ "keywords": [
"tokenizer" "tokenizer"
], ],
"time": "2018-02-01T13:16:43+00:00" "time": "2018-10-30T05:52:18+00:00"
}, },
{ {
"name": "phpunit/phpunit", "name": "phpunit/phpunit",
"version": "7.3.2", "version": "7.4.3",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git", "url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "34705f81bddc3f505b9599a2ef96e2b4315ba9b8" "reference": "c151651fb6ed264038d486ea262e243af72e5e64"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/34705f81bddc3f505b9599a2ef96e2b4315ba9b8", "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c151651fb6ed264038d486ea262e243af72e5e64",
"reference": "34705f81bddc3f505b9599a2ef96e2b4315ba9b8", "reference": "c151651fb6ed264038d486ea262e243af72e5e64",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -2760,11 +2763,11 @@
"phpunit/php-timer": "^2.0", "phpunit/php-timer": "^2.0",
"sebastian/comparator": "^3.0", "sebastian/comparator": "^3.0",
"sebastian/diff": "^3.0", "sebastian/diff": "^3.0",
"sebastian/environment": "^3.1", "sebastian/environment": "^3.1 || ^4.0",
"sebastian/exporter": "^3.1", "sebastian/exporter": "^3.1",
"sebastian/global-state": "^2.0", "sebastian/global-state": "^2.0",
"sebastian/object-enumerator": "^3.0.3", "sebastian/object-enumerator": "^3.0.3",
"sebastian/resource-operations": "^1.0", "sebastian/resource-operations": "^2.0",
"sebastian/version": "^2.0.1" "sebastian/version": "^2.0.1"
}, },
"conflict": { "conflict": {
@ -2784,7 +2787,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "7.3-dev" "dev-master": "7.4-dev"
} }
}, },
"autoload": { "autoload": {
@ -2810,7 +2813,7 @@
"testing", "testing",
"xunit" "xunit"
], ],
"time": "2018-08-22T06:39:21+00:00" "time": "2018-10-23T05:57:41+00:00"
}, },
{ {
"name": "psr/container", "name": "psr/container",
@ -3391,25 +3394,25 @@
}, },
{ {
"name": "sebastian/resource-operations", "name": "sebastian/resource-operations",
"version": "1.0.0", "version": "2.0.1",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/resource-operations.git", "url": "https://github.com/sebastianbergmann/resource-operations.git",
"reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52" "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/4d7a795d35b889bf80a0cc04e08d77cedfa917a9",
"reference": "ce990bb21759f94aeafd30209e8cfcdfa8bc3f52", "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=5.6.0" "php": "^7.1"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "1.0.x-dev" "dev-master": "2.0-dev"
} }
}, },
"autoload": { "autoload": {
@ -3429,7 +3432,7 @@
], ],
"description": "Provides a list of PHP built-in functions that operate on resources", "description": "Provides a list of PHP built-in functions that operate on resources",
"homepage": "https://www.github.com/sebastianbergmann/resource-operations", "homepage": "https://www.github.com/sebastianbergmann/resource-operations",
"time": "2015-07-28T20:34:47+00:00" "time": "2018-10-04T04:07:39+00:00"
}, },
{ {
"name": "sebastian/version", "name": "sebastian/version",
@ -3476,7 +3479,7 @@
}, },
{ {
"name": "symfony/browser-kit", "name": "symfony/browser-kit",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/browser-kit.git", "url": "https://github.com/symfony/browser-kit.git",
@ -3533,16 +3536,16 @@
}, },
{ {
"name": "symfony/class-loader", "name": "symfony/class-loader",
"version": "v3.4.15", "version": "v3.4.17",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/class-loader.git", "url": "https://github.com/symfony/class-loader.git",
"reference": "31db283fc86d3143e7ff87e922177b457d909c30" "reference": "f31333bdff54c7595f834d510a6d2325573ddb36"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/class-loader/zipball/31db283fc86d3143e7ff87e922177b457d909c30", "url": "https://api.github.com/repos/symfony/class-loader/zipball/f31333bdff54c7595f834d510a6d2325573ddb36",
"reference": "31db283fc86d3143e7ff87e922177b457d909c30", "reference": "f31333bdff54c7595f834d510a6d2325573ddb36",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3585,20 +3588,20 @@
], ],
"description": "Symfony ClassLoader Component", "description": "Symfony ClassLoader Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-07-26T11:19:56+00:00" "time": "2018-10-02T12:28:39+00:00"
}, },
{ {
"name": "symfony/config", "name": "symfony/config",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/config.git", "url": "https://github.com/symfony/config.git",
"reference": "76015a3cc372b14d00040ff58e18e29f69eba717" "reference": "b3d4d7b567d7a49e6dfafb6d4760abc921177c96"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/config/zipball/76015a3cc372b14d00040ff58e18e29f69eba717", "url": "https://api.github.com/repos/symfony/config/zipball/b3d4d7b567d7a49e6dfafb6d4760abc921177c96",
"reference": "76015a3cc372b14d00040ff58e18e29f69eba717", "reference": "b3d4d7b567d7a49e6dfafb6d4760abc921177c96",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3648,20 +3651,20 @@
], ],
"description": "Symfony Config Component", "description": "Symfony Config Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-08-08T06:37:38+00:00" "time": "2018-09-08T13:24:10+00:00"
}, },
{ {
"name": "symfony/console", "name": "symfony/console",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/console.git", "url": "https://github.com/symfony/console.git",
"reference": "ca80b8ced97cf07390078b29773dc384c39eee1f" "reference": "dc7122fe5f6113cfaba3b3de575d31112c9aa60b"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/ca80b8ced97cf07390078b29773dc384c39eee1f", "url": "https://api.github.com/repos/symfony/console/zipball/dc7122fe5f6113cfaba3b3de575d31112c9aa60b",
"reference": "ca80b8ced97cf07390078b29773dc384c39eee1f", "reference": "dc7122fe5f6113cfaba3b3de575d31112c9aa60b",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3716,20 +3719,20 @@
], ],
"description": "Symfony Console Component", "description": "Symfony Console Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-07-26T11:24:31+00:00" "time": "2018-10-03T08:15:46+00:00"
}, },
{ {
"name": "symfony/css-selector", "name": "symfony/css-selector",
"version": "v3.4.15", "version": "v3.4.17",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/css-selector.git", "url": "https://github.com/symfony/css-selector.git",
"reference": "edda5a6155000ff8c3a3f85ee5c421af93cca416" "reference": "3503415d4aafabc31cd08c3a4ebac7f43fde8feb"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/css-selector/zipball/edda5a6155000ff8c3a3f85ee5c421af93cca416", "url": "https://api.github.com/repos/symfony/css-selector/zipball/3503415d4aafabc31cd08c3a4ebac7f43fde8feb",
"reference": "edda5a6155000ff8c3a3f85ee5c421af93cca416", "reference": "3503415d4aafabc31cd08c3a4ebac7f43fde8feb",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3769,20 +3772,20 @@
], ],
"description": "Symfony CssSelector Component", "description": "Symfony CssSelector Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-07-26T09:06:28+00:00" "time": "2018-10-02T16:33:53+00:00"
}, },
{ {
"name": "symfony/dependency-injection", "name": "symfony/dependency-injection",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/dependency-injection.git", "url": "https://github.com/symfony/dependency-injection.git",
"reference": "bae4983003c9d451e278504d7d9b9d7fc1846873" "reference": "f6b9d893ad28aefd8942dc0469c8397e2216fe30"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/dependency-injection/zipball/bae4983003c9d451e278504d7d9b9d7fc1846873", "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/f6b9d893ad28aefd8942dc0469c8397e2216fe30",
"reference": "bae4983003c9d451e278504d7d9b9d7fc1846873", "reference": "f6b9d893ad28aefd8942dc0469c8397e2216fe30",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3840,20 +3843,20 @@
], ],
"description": "Symfony DependencyInjection Component", "description": "Symfony DependencyInjection Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-08-08T11:48:58+00:00" "time": "2018-10-02T12:40:59+00:00"
}, },
{ {
"name": "symfony/dom-crawler", "name": "symfony/dom-crawler",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/dom-crawler.git", "url": "https://github.com/symfony/dom-crawler.git",
"reference": "1c4519d257e652404c3aa550207ccd8ada66b38e" "reference": "80e60271bb288de2a2259662cff125cff4f93f95"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/dom-crawler/zipball/1c4519d257e652404c3aa550207ccd8ada66b38e", "url": "https://api.github.com/repos/symfony/dom-crawler/zipball/80e60271bb288de2a2259662cff125cff4f93f95",
"reference": "1c4519d257e652404c3aa550207ccd8ada66b38e", "reference": "80e60271bb288de2a2259662cff125cff4f93f95",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -3897,11 +3900,11 @@
], ],
"description": "Symfony DomCrawler Component", "description": "Symfony DomCrawler Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-07-26T11:00:49+00:00" "time": "2018-10-02T12:40:59+00:00"
}, },
{ {
"name": "symfony/event-dispatcher", "name": "symfony/event-dispatcher",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/event-dispatcher.git", "url": "https://github.com/symfony/event-dispatcher.git",
@ -3964,16 +3967,16 @@
}, },
{ {
"name": "symfony/filesystem", "name": "symfony/filesystem",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/filesystem.git", "url": "https://github.com/symfony/filesystem.git",
"reference": "c0f5f62db218fa72195b8b8700e4b9b9cf52eb5e" "reference": "596d12b40624055c300c8b619755b748ca5cf0b5"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/filesystem/zipball/c0f5f62db218fa72195b8b8700e4b9b9cf52eb5e", "url": "https://api.github.com/repos/symfony/filesystem/zipball/596d12b40624055c300c8b619755b748ca5cf0b5",
"reference": "c0f5f62db218fa72195b8b8700e4b9b9cf52eb5e", "reference": "596d12b40624055c300c8b619755b748ca5cf0b5",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -4010,7 +4013,7 @@
], ],
"description": "Symfony Filesystem Component", "description": "Symfony Filesystem Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-08-18T16:52:46+00:00" "time": "2018-10-02T12:40:59+00:00"
}, },
{ {
"name": "symfony/polyfill-mbstring", "name": "symfony/polyfill-mbstring",
@ -4073,16 +4076,16 @@
}, },
{ {
"name": "symfony/translation", "name": "symfony/translation",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/translation.git", "url": "https://github.com/symfony/translation.git",
"reference": "fa2182669f7983b7aa5f1a770d053f79f0ef144f" "reference": "9f0b61e339160a466ebcde167a6c5521c810e304"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/translation/zipball/fa2182669f7983b7aa5f1a770d053f79f0ef144f", "url": "https://api.github.com/repos/symfony/translation/zipball/9f0b61e339160a466ebcde167a6c5521c810e304",
"reference": "fa2182669f7983b7aa5f1a770d053f79f0ef144f", "reference": "9f0b61e339160a466ebcde167a6c5521c810e304",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -4138,20 +4141,20 @@
], ],
"description": "Symfony Translation Component", "description": "Symfony Translation Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-08-07T12:45:11+00:00" "time": "2018-10-02T16:36:10+00:00"
}, },
{ {
"name": "symfony/yaml", "name": "symfony/yaml",
"version": "v4.1.4", "version": "v4.1.6",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/yaml.git", "url": "https://github.com/symfony/yaml.git",
"reference": "b832cc289608b6d305f62149df91529a2ab3c314" "reference": "367e689b2fdc19965be435337b50bc8adf2746c9"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/yaml/zipball/b832cc289608b6d305f62149df91529a2ab3c314", "url": "https://api.github.com/repos/symfony/yaml/zipball/367e689b2fdc19965be435337b50bc8adf2746c9",
"reference": "b832cc289608b6d305f62149df91529a2ab3c314", "reference": "367e689b2fdc19965be435337b50bc8adf2746c9",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -4197,7 +4200,7 @@
], ],
"description": "Symfony Yaml Component", "description": "Symfony Yaml Component",
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-08-18T16:52:46+00:00" "time": "2018-10-02T16:36:10+00:00"
}, },
{ {
"name": "theseer/tokenizer", "name": "theseer/tokenizer",

View File

@ -248,20 +248,12 @@ function bb_to_markdown($Text, $options = []) {
// Convert it to HTML - don't try oembed // Convert it to HTML - don't try oembed
$Text = bbcode($Text, [ 'tryoembed' => false ]); $Text = bbcode($Text, [ 'tryoembed' => false ]);
// Markdownify does not preserve previously escaped html entities such as <> and &.
//$Text = str_replace(array('&lt;','&gt;','&amp;'),array('&_lt_;','&_gt_;','&_amp_;'),$Text);
// Now convert HTML to Markdown // Now convert HTML to Markdown
$Text = html2markdown($Text); $Text = html2markdown($Text);
//html2markdown adds backslashes infront of hashes after a new line. remove them //html2markdown adds backslashes infront of hashes after a new line. remove them
$Text = str_replace("\n\#", "\n#", $Text); $Text = str_replace("\n\#", "\n#", $Text);
// It also adds backslashes to our attempt at getting around the html entity preservation for some weird reason.
//$Text = str_replace(array('&\\_lt\\_;','&\\_gt\\_;','&\\_amp\\_;'),array('&lt;','&gt;','&amp;'),$Text);
// If the text going into bbcode() has a plain URL in it, i.e. // If the text going into bbcode() has a plain URL in it, i.e.
// with no [url] tags around it, it will come out of parseString() // with no [url] tags around it, it will come out of parseString()
// looking like: <http://url.com>, which gets removed by strip_tags(). // looking like: <http://url.com>, which gets removed by strip_tags().
@ -291,12 +283,24 @@ function bb_to_markdown($Text, $options = []) {
* If the HTML text can not get parsed it will return an empty string. * If the HTML text can not get parsed it will return an empty string.
* *
* @param string $html The HTML code to convert * @param string $html The HTML code to convert
* @param array $options an array of options to pass to the environment
* @return string Markdown representation of the given HTML text, empty on error * @return string Markdown representation of the given HTML text, empty on error
*/ */
function html2markdown($html, $options = []) { function html2markdown($html, $options = []) {
$markdown = ''; $markdown = '';
$internal_errors = libxml_use_internal_errors(true); if(! $options) {
$options = [
'header_style' => 'setext', // Set to 'atx' to output H1 and H2 headers as # Header1 and ## Header2
'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML
'strip_tags' => false, // Set to true to strip tags that don't have markdown equivalents. N.B. Strips tags, not their content. Useful to clean MS Word HTML output.
'bold_style' => '**', // DEPRECATED: Set to '__' if you prefer the underlined style
'italic_style' => '*', // DEPRECATED: Set to '_' if you prefer the underlined style
'remove_nodes' => '', // space-separated list of dom nodes that should be removed. example: 'meta style script'
'hard_break' => false, // Set to true to turn <br> into `\n` instead of ` \n`
'list_item_style' => '-', // Set the default character for each <li> in a <ul>. Can be '-', '*', or '+'
];
}
$environment = Environment::createDefaultEnvironment($options); $environment = Environment::createDefaultEnvironment($options);
$environment->addConverter(new TableConverter()); $environment->addConverter(new TableConverter());
@ -308,8 +312,6 @@ function html2markdown($html,$options = []) {
logger("Invalid HTML. HTMLToMarkdown library threw an exception."); logger("Invalid HTML. HTMLToMarkdown library threw an exception.");
} }
libxml_use_internal_errors($internal_errors);
return $markdown; return $markdown;
} }

View File

@ -52,12 +52,12 @@ class MarkdownTest extends UnitTestCase {
' &nbsp;', ' &nbsp;',
'' ''
], ],
/* it is not clear why this test fails
'strong, b, em, i, bib' => [ 'strong, b, em, i, bib' => [
'<strong>strong</strong> <b>bold</b> <em>em</em> <i>italic</i> <b>bo<i>italic</i>ld</b>', '<strong>strong</strong> <b>bold</b> <em>em</em> <i>italic</i> <b>bo<i>italic</i>ld</b>',
'**strong** **bold** _em_ _italic_ **bo_italic_ld**' '**strong** **bold** *em* *italic* **bo*italic*ld**'
], ],
*/
'empty tags' => [ 'empty tags' => [
'text1 <b></b> text2 <i></i>', 'text1 <b></b> text2 <i></i>',
'text1 text2' 'text1 text2'
@ -70,10 +70,6 @@ class MarkdownTest extends UnitTestCase {
'&amp; lt &lt; gt &gt;', '&amp; lt &lt; gt &gt;',
'& lt < gt >' '& lt < gt >'
], ],
'our escaped HTML entities' => [
'&_lt_; &_gt_; &_amp_;',
'&\_lt\_; &\_gt\_; &\_amp\_;'
],
'linebreak' => [ 'linebreak' => [
"line1<br>line2\nline3", "line1<br>line2\nline3",
"line1 \nline2 line3" "line1 \nline2 line3"
@ -84,15 +80,15 @@ class MarkdownTest extends UnitTestCase {
], ],
'unordered list' => [ 'unordered list' => [
'<ul><li>Item 1</li><li>Item 2</li><li>Item <b>3</b></li></ul>', '<ul><li>Item 1</li><li>Item 2</li><li>Item <b>3</b></li></ul>',
"- Item 1\n- Item 2\n- Item 3" "- Item 1\n- Item 2\n- Item **3**"
], ],
'ordered list' => [ 'ordered list' => [
'<ol><li>Item 1</li><li>Item 2</li><li>Item <b>3</b></li></ol>', '<ol><li>Item 1</li><li>Item 2</li><li>Item <b>3</b></li></ol>',
"1. Item 1\n2. Item 2\n3. Item 3" "1. Item 1\n2. Item 2\n3. Item **3**"
], ],
'nested lists' => [ 'nested lists' => [
'<ul><li>Item 1<ol><li>Item 1a</li><li>Item <b>1b</b></ol></li><li>Item 2</li></ul>', '<ul><li>Item 1<ol><li>Item 1a</li><li>Item <b>1b</b></ol></li><li>Item 2</li></ul>',
"- Item 1\n 1. Item 1a\n 2. Item 1b\n- Item 2" "- Item 1\n 1. Item 1a\n 2. Item **1b**\n- Item 2"
], ],
'img' => [ 'img' => [
'<img src="/path/to/img.png" alt="alt text" title="title text">', '<img src="/path/to/img.png" alt="alt text" title="title text">',
@ -118,12 +114,10 @@ class MarkdownTest extends UnitTestCase {
'<code>&lt;p&gt;HTML text&lt;/p&gt;</code>', '<code>&lt;p&gt;HTML text&lt;/p&gt;</code>',
'`<p>HTML text</p>`' '`<p>HTML text</p>`'
], ],
/* it is not clear why this test fails
'pre' => [ 'pre' => [
'<pre> line with spaces </pre>', '<pre> one line with spaces </pre>',
'` line with spaces `' "```\n one line with spaces \n```"
], ],
*/
'div p' => [ 'div p' => [
'<div>div</div><div><p>p</p></div>', '<div>div</div><div><p>p</p></div>',
"<div>div</div><div>p\n\n</div>" "<div>div</div><div>p\n\n</div>"

View File

@ -300,6 +300,7 @@ return array(
'League\\HTMLToMarkdown\\ElementInterface' => $vendorDir . '/league/html-to-markdown/src/ElementInterface.php', 'League\\HTMLToMarkdown\\ElementInterface' => $vendorDir . '/league/html-to-markdown/src/ElementInterface.php',
'League\\HTMLToMarkdown\\Environment' => $vendorDir . '/league/html-to-markdown/src/Environment.php', 'League\\HTMLToMarkdown\\Environment' => $vendorDir . '/league/html-to-markdown/src/Environment.php',
'League\\HTMLToMarkdown\\HtmlConverter' => $vendorDir . '/league/html-to-markdown/src/HtmlConverter.php', 'League\\HTMLToMarkdown\\HtmlConverter' => $vendorDir . '/league/html-to-markdown/src/HtmlConverter.php',
'League\\HTMLToMarkdown\\HtmlConverterInterface' => $vendorDir . '/league/html-to-markdown/src/HtmlConverterInterface.php',
'Michelf\\Markdown' => $vendorDir . '/michelf/php-markdown/Michelf/Markdown.php', 'Michelf\\Markdown' => $vendorDir . '/michelf/php-markdown/Michelf/Markdown.php',
'Michelf\\MarkdownExtra' => $vendorDir . '/michelf/php-markdown/Michelf/MarkdownExtra.php', 'Michelf\\MarkdownExtra' => $vendorDir . '/michelf/php-markdown/Michelf/MarkdownExtra.php',
'Michelf\\MarkdownInterface' => $vendorDir . '/michelf/php-markdown/Michelf/MarkdownInterface.php', 'Michelf\\MarkdownInterface' => $vendorDir . '/michelf/php-markdown/Michelf/MarkdownInterface.php',

View File

@ -468,6 +468,7 @@ class ComposerStaticInit7b34d7e50a62201ec5d5e526a5b8b35d
'League\\HTMLToMarkdown\\ElementInterface' => __DIR__ . '/..' . '/league/html-to-markdown/src/ElementInterface.php', 'League\\HTMLToMarkdown\\ElementInterface' => __DIR__ . '/..' . '/league/html-to-markdown/src/ElementInterface.php',
'League\\HTMLToMarkdown\\Environment' => __DIR__ . '/..' . '/league/html-to-markdown/src/Environment.php', 'League\\HTMLToMarkdown\\Environment' => __DIR__ . '/..' . '/league/html-to-markdown/src/Environment.php',
'League\\HTMLToMarkdown\\HtmlConverter' => __DIR__ . '/..' . '/league/html-to-markdown/src/HtmlConverter.php', 'League\\HTMLToMarkdown\\HtmlConverter' => __DIR__ . '/..' . '/league/html-to-markdown/src/HtmlConverter.php',
'League\\HTMLToMarkdown\\HtmlConverterInterface' => __DIR__ . '/..' . '/league/html-to-markdown/src/HtmlConverterInterface.php',
'Michelf\\Markdown' => __DIR__ . '/..' . '/michelf/php-markdown/Michelf/Markdown.php', 'Michelf\\Markdown' => __DIR__ . '/..' . '/michelf/php-markdown/Michelf/Markdown.php',
'Michelf\\MarkdownExtra' => __DIR__ . '/..' . '/michelf/php-markdown/Michelf/MarkdownExtra.php', 'Michelf\\MarkdownExtra' => __DIR__ . '/..' . '/michelf/php-markdown/Michelf/MarkdownExtra.php',
'Michelf\\MarkdownInterface' => __DIR__ . '/..' . '/michelf/php-markdown/Michelf/MarkdownInterface.php', 'Michelf\\MarkdownInterface' => __DIR__ . '/..' . '/michelf/php-markdown/Michelf/MarkdownInterface.php',

View File

@ -156,17 +156,17 @@
}, },
{ {
"name": "league/html-to-markdown", "name": "league/html-to-markdown",
"version": "4.7.0", "version": "4.8.0",
"version_normalized": "4.7.0.0", "version_normalized": "4.8.0.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/thephpleague/html-to-markdown.git", "url": "https://github.com/thephpleague/html-to-markdown.git",
"reference": "76c076483cef89860d32a3fd25312f5a42848a8c" "reference": "f9a879a068c68ff47b722de63f58bec79e448f9d"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/thephpleague/html-to-markdown/zipball/76c076483cef89860d32a3fd25312f5a42848a8c", "url": "https://api.github.com/repos/thephpleague/html-to-markdown/zipball/f9a879a068c68ff47b722de63f58bec79e448f9d",
"reference": "76c076483cef89860d32a3fd25312f5a42848a8c", "reference": "f9a879a068c68ff47b722de63f58bec79e448f9d",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -179,14 +179,14 @@
"phpunit/phpunit": "4.*", "phpunit/phpunit": "4.*",
"scrutinizer/ocular": "~1.1" "scrutinizer/ocular": "~1.1"
}, },
"time": "2018-05-19T23:47:12+00:00", "time": "2018-09-18T12:18:08+00:00",
"bin": [ "bin": [
"bin/html-to-markdown" "bin/html-to-markdown"
], ],
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "4.8-dev" "dev-master": "4.9-dev"
} }
}, },
"installation-source": "dist", "installation-source": "dist",
@ -200,17 +200,17 @@
"MIT" "MIT"
], ],
"authors": [ "authors": [
{
"name": "Colin O'Dell",
"email": "colinodell@gmail.com",
"homepage": "http://www.colinodell.com",
"role": "Lead Developer"
},
{ {
"name": "Nick Cernis", "name": "Nick Cernis",
"email": "nick@cern.is", "email": "nick@cern.is",
"homepage": "http://modernnerd.net", "homepage": "http://modernnerd.net",
"role": "Original Author" "role": "Original Author"
},
{
"name": "Colin O'Dell",
"email": "colinodell@gmail.com",
"homepage": "https://www.colinodell.com",
"role": "Lead Developer"
} }
], ],
"description": "An HTML-to-markdown conversion helper for PHP", "description": "An HTML-to-markdown conversion helper for PHP",
@ -533,17 +533,17 @@
}, },
{ {
"name": "sabre/dav", "name": "sabre/dav",
"version": "3.2.2", "version": "3.2.3",
"version_normalized": "3.2.2.0", "version_normalized": "3.2.3.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sabre-io/dav.git", "url": "https://github.com/sabre-io/dav.git",
"reference": "e987775e619728f12205606c9cc3ee565ffb1516" "reference": "a9780ce4f35560ecbd0af524ad32d9d2c8954b80"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sabre-io/dav/zipball/e987775e619728f12205606c9cc3ee565ffb1516", "url": "https://api.github.com/repos/sabre-io/dav/zipball/a9780ce4f35560ecbd0af524ad32d9d2c8954b80",
"reference": "e987775e619728f12205606c9cc3ee565ffb1516", "reference": "a9780ce4f35560ecbd0af524ad32d9d2c8954b80",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -574,7 +574,7 @@
"ext-curl": "*", "ext-curl": "*",
"ext-pdo": "*" "ext-pdo": "*"
}, },
"time": "2017-02-15T03:06:08+00:00", "time": "2018-10-19T09:58:27+00:00",
"bin": [ "bin": [
"bin/sabredav", "bin/sabredav",
"bin/naturalselection" "bin/naturalselection"
@ -1029,23 +1029,23 @@
}, },
{ {
"name": "smarty/smarty", "name": "smarty/smarty",
"version": "v3.1.32", "version": "v3.1.33",
"version_normalized": "3.1.32.0", "version_normalized": "3.1.33.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/smarty-php/smarty.git", "url": "https://github.com/smarty-php/smarty.git",
"reference": "ac9d4b587e5bf53381e21881820a9830765cb459" "reference": "dd55b23121e55a3b4f1af90a707a6c4e5969530f"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/smarty-php/smarty/zipball/ac9d4b587e5bf53381e21881820a9830765cb459", "url": "https://api.github.com/repos/smarty-php/smarty/zipball/dd55b23121e55a3b4f1af90a707a6c4e5969530f",
"reference": "ac9d4b587e5bf53381e21881820a9830765cb459", "reference": "dd55b23121e55a3b4f1af90a707a6c4e5969530f",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=5.2" "php": ">=5.2"
}, },
"time": "2018-04-24T14:53:33+00:00", "time": "2018-09-12T20:54:16+00:00",
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {

View File

@ -4,6 +4,24 @@ Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) princip
## [Unreleased][unreleased] ## [Unreleased][unreleased]
## [4.8.0] - 2018-09-18
### Added
- Added support for email auto-linking
- Added a new interface (`HtmlConverterInterface`) for the main `HtmlConverter` class
- Added additional test cases (#14)
### Changed
- The `italic_style` option now defaults to `'*'` so that in-word emphasis is handled properly (#75)
### Fixed
- Fixed several issues of `<code>` and `<pre>` tags not converting to blocks or inlines properly (#26, #70, #102, #140, #161, #162)
- Fixed in-word emphasis using underscores as delimiter (#75)
- Fixed character escaping inside of `<div>` elements
- Fixed header edge cases
### Deprecated
- The `bold_style` and `italic_style` options have been deprecated (#75)
## [4.7.0] - 2018-05-19 ## [4.7.0] - 2018-05-19
### Added ### Added
- Added `setOptions()` function for chainable calling (#149) - Added `setOptions()` function for chainable calling (#149)
@ -217,7 +235,8 @@ not ideally set, so this releases fixes that. Moving forwards this should reduce
### Added ### Added
- Initial release - Initial release
[unreleased]: https://github.com/thephpleague/html-to-markdown/compare/4.7.0...master [unreleased]: https://github.com/thephpleague/html-to-markdown/compare/4.8.0...master
[4.8.0]: https://github.com/thephpleague/html-to-markdown/compare/4.7.0...4.8.0
[4.7.0]: https://github.com/thephpleague/html-to-markdown/compare/4.6.2...4.7.0 [4.7.0]: https://github.com/thephpleague/html-to-markdown/compare/4.6.2...4.7.0
[4.6.2]: https://github.com/thephpleague/html-to-markdown/compare/4.6.1...4.6.2 [4.6.2]: https://github.com/thephpleague/html-to-markdown/compare/4.6.1...4.6.2
[4.6.1]: https://github.com/thephpleague/html-to-markdown/compare/4.6.0...4.6.1 [4.6.1]: https://github.com/thephpleague/html-to-markdown/compare/4.6.0...4.6.1

View File

@ -9,7 +9,7 @@
{ {
"name": "Colin O'Dell", "name": "Colin O'Dell",
"email": "colinodell@gmail.com", "email": "colinodell@gmail.com",
"homepage": "http://www.colinodell.com", "homepage": "https://www.colinodell.com",
"role": "Lead Developer" "role": "Lead Developer"
}, },
{ {
@ -42,7 +42,7 @@
"bin": ["bin/html-to-markdown"], "bin": ["bin/html-to-markdown"],
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "4.8-dev" "dev-master": "4.9-dev"
} }
} }
} }

View File

@ -12,6 +12,8 @@ class Configuration
public function __construct(array $config = array()) public function __construct(array $config = array())
{ {
$this->config = $config; $this->config = $config;
$this->checkForDeprecatedOptions($config);
} }
/** /**
@ -19,6 +21,7 @@ class Configuration
*/ */
public function merge(array $config = array()) public function merge(array $config = array())
{ {
$this->checkForDeprecatedOptions($config);
$this->config = array_replace_recursive($this->config, $config); $this->config = array_replace_recursive($this->config, $config);
} }
@ -27,6 +30,7 @@ class Configuration
*/ */
public function replace(array $config = array()) public function replace(array $config = array())
{ {
$this->checkForDeprecatedOptions($config);
$this->config = $config; $this->config = $config;
} }
@ -36,6 +40,7 @@ class Configuration
*/ */
public function setOption($key, $value) public function setOption($key, $value)
{ {
$this->checkForDeprecatedOptions(array($key => $value));
$this->config[$key] = $value; $this->config[$key] = $value;
} }
@ -57,4 +62,15 @@ class Configuration
return $this->config[$key]; return $this->config[$key];
} }
private function checkForDeprecatedOptions(array $config)
{
foreach ($config as $key => $value) {
if ($key === 'bold_style' && $value !== '**') {
@trigger_error('Customizing the bold_style option is deprecated and may be removed in the next major version', E_USER_DEPRECATED);
} elseif ($key === 'italic_style' && $value !== '*') {
@trigger_error('Customizing the italic_style option is deprecated and may be removed in the next major version', E_USER_DEPRECATED);
}
}
}
} }

View File

@ -13,7 +13,7 @@ class CodeConverter implements ConverterInterface
*/ */
public function convert(ElementInterface $element) public function convert(ElementInterface $element)
{ {
$language = null; $language = '';
// Checking for language class on the code block // Checking for language class on the code block
$classes = $element->getAttribute('class'); $classes = $element->getAttribute('class');
@ -24,8 +24,7 @@ class CodeConverter implements ConverterInterface
foreach ($classes as $class) { foreach ($classes as $class) {
if (strpos($class, 'language-') !== false) { if (strpos($class, 'language-') !== false) {
// Found one, save it as the selected language and stop looping over the classes. // Found one, save it as the selected language and stop looping over the classes.
// The space after the language avoids gluing the actual code with the language tag $language = str_replace('language-', '', $class);
$language = str_replace('language-', '', $class) . ' ';
break; break;
} }
} }
@ -39,14 +38,13 @@ class CodeConverter implements ConverterInterface
$code = preg_replace('/<code\b[^>]*>/', '', $code); $code = preg_replace('/<code\b[^>]*>/', '', $code);
$code = str_replace('</code>', '', $code); $code = str_replace('</code>', '', $code);
// Checking if the code has multiple lines // Checking if it's a code block or span
$lines = preg_split('/\r\n|\r|\n/', $code); if ($this->shouldBeBlock($element, $code)) {
if (count($lines) > 1) { // Code block detected, newlines will be added in parent
// Multiple lines detected, adding three backticks and newlines $markdown .= '```' . $language . "\n" . $code . "\n" . '```';
$markdown .= '```' . $language . "\n" . $code . "\n" . '```' . "\n\n";
} else { } else {
// One line of code, wrapping it on one backtick. // One line of code, wrapping it on one backtick, removing new lines
$markdown .= '`' . $language . $code . '`'; $markdown .= '`' . preg_replace('/\r\n|\r|\n/', '', $code) . '`';
} }
return $markdown; return $markdown;
@ -59,4 +57,23 @@ class CodeConverter implements ConverterInterface
{ {
return array('code'); return array('code');
} }
/**
* @param ElementInterface $element
* @param string $code
*
* @return bool
*/
private function shouldBeBlock(ElementInterface $element, $code)
{
if ($element->getParent()->getTagName() == 'pre') {
return true;
}
if (preg_match('/[^\s]` `/', $code)) {
return true;
}
return false;
}
} }

View File

@ -34,6 +34,10 @@ class HeaderConverter implements ConverterInterface, ConfigurationAwareInterface
$level = (int) substr($element->getTagName(), 1, 1); $level = (int) substr($element->getTagName(), 1, 1);
$style = $this->config->getOption('header_style', self::STYLE_SETEXT); $style = $this->config->getOption('header_style', self::STYLE_SETEXT);
if (strlen($element->getValue()) === 0) {
return '';
}
if (($level === 1 || $level === 2) && !$element->isDescendantOf('blockquote') && $style === self::STYLE_SETEXT) { if (($level === 1 || $level === 2) && !$element->isDescendantOf('blockquote') && $style === self::STYLE_SETEXT) {
return $this->createSetextHeader($level, $element->getValue()); return $this->createSetextHeader($level, $element->getValue());
} }

View File

@ -21,6 +21,8 @@ class LinkConverter implements ConverterInterface
$markdown = '[' . $text . '](' . $href . ' "' . $title . '")'; $markdown = '[' . $text . '](' . $href . ' "' . $title . '")';
} elseif ($href === $text && $this->isValidAutolink($href)) { } elseif ($href === $text && $this->isValidAutolink($href)) {
$markdown = '<' . $href . '>'; $markdown = '<' . $href . '>';
} elseif ($href === 'mailto:' . $text && $this->isValidEmail($text)) {
$markdown = '<' . $text . '>';
} else { } else {
$markdown = '[' . $text . '](' . $href . ')'; $markdown = '[' . $text . '](' . $href . ')';
} }
@ -49,4 +51,15 @@ class LinkConverter implements ConverterInterface
{ {
return preg_match('/^[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*/i', $href) === 1; return preg_match('/^[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*/i', $href) === 1;
} }
/**
* @param string $email
*
* @return bool
*/
private function isValidEmail($email)
{
// Email validation is messy business, but this should cover most cases
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
} }

View File

@ -13,8 +13,6 @@ class PreformattedConverter implements ConverterInterface
*/ */
public function convert(ElementInterface $element) public function convert(ElementInterface $element)
{ {
$markdown = '';
$pre_content = html_entity_decode($element->getChildrenAsString()); $pre_content = html_entity_decode($element->getChildrenAsString());
$pre_content = str_replace(array('<pre>', '</pre>'), '', $pre_content); $pre_content = str_replace(array('<pre>', '</pre>'), '', $pre_content);
@ -28,28 +26,22 @@ class PreformattedConverter implements ConverterInterface
$firstBacktick = strpos(trim($pre_content), '`'); $firstBacktick = strpos(trim($pre_content), '`');
$lastBacktick = strrpos(trim($pre_content), '`'); $lastBacktick = strrpos(trim($pre_content), '`');
if ($firstBacktick === 0 && $lastBacktick === strlen(trim($pre_content)) - 1) { if ($firstBacktick === 0 && $lastBacktick === strlen(trim($pre_content)) - 1) {
return $pre_content; return $pre_content . "\n\n";
} }
// If the execution reaches this point it means it's just a pre tag, with no code tag nested // If the execution reaches this point it means it's just a pre tag, with no code tag nested
// Empty lines are a special case // Empty lines are a special case
if ($pre_content === '') { if ($pre_content === '') {
return "```\n```\n"; return "```\n```\n\n";
} }
// Normalizing new lines // Normalizing new lines
$pre_content = preg_replace('/\r\n|\r|\n/', PHP_EOL, $pre_content); $pre_content = preg_replace('/\r\n|\r|\n/', "\n", $pre_content);
// Is it a single line?
if (strpos($pre_content, PHP_EOL) === false) {
// One line of code, wrapping it on one backtick.
return '`' . $pre_content . '`';
}
// Ensure there's a newline at the end // Ensure there's a newline at the end
if (strrpos($pre_content, PHP_EOL) !== strlen($pre_content) - 1) { if (strrpos($pre_content, "\n") !== strlen($pre_content) - strlen("\n")) {
$pre_content .= PHP_EOL; $pre_content .= "\n";
} }
// Use three backticks // Use three backticks

View File

@ -22,7 +22,9 @@ class TextConverter implements ConverterInterface
$markdown = preg_replace('~\s+~u', ' ', $markdown); $markdown = preg_replace('~\s+~u', ' ', $markdown);
// Escape the following characters: '*', '_', '[', ']' and '\' // Escape the following characters: '*', '_', '[', ']' and '\'
if ($element->getParent() && $element->getParent()->getTagName() !== 'div') {
$markdown = preg_replace('~([*_\\[\\]\\\\])~u', '\\\\$1', $markdown); $markdown = preg_replace('~([*_\\[\\]\\\\])~u', '\\\\$1', $markdown);
}
$markdown = preg_replace('~^#~u', '\\\\#', $markdown); $markdown = preg_replace('~^#~u', '\\\\#', $markdown);

View File

@ -14,7 +14,7 @@ namespace League\HTMLToMarkdown;
* *
* @license http://www.opensource.org/licenses/mit-license.php MIT * @license http://www.opensource.org/licenses/mit-license.php MIT
*/ */
class HtmlConverter class HtmlConverter implements HtmlConverterInterface
{ {
/** /**
* @var Environment * @var Environment
@ -35,8 +35,8 @@ class HtmlConverter
'header_style' => 'setext', // Set to 'atx' to output H1 and H2 headers as # Header1 and ## Header2 'header_style' => 'setext', // Set to 'atx' to output H1 and H2 headers as # Header1 and ## Header2
'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML 'suppress_errors' => true, // Set to false to show warnings when loading malformed HTML
'strip_tags' => false, // Set to true to strip tags that don't have markdown equivalents. N.B. Strips tags, not their content. Useful to clean MS Word HTML output. 'strip_tags' => false, // Set to true to strip tags that don't have markdown equivalents. N.B. Strips tags, not their content. Useful to clean MS Word HTML output.
'bold_style' => '**', // Set to '__' if you prefer the underlined style 'bold_style' => '**', // DEPRECATED: Set to '__' if you prefer the underlined style
'italic_style' => '_', // Set to '*' if you prefer the asterisk style 'italic_style' => '*', // DEPRECATED: Set to '_' if you prefer the underlined style
'remove_nodes' => '', // space-separated list of dom nodes that should be removed. example: 'meta style script' 'remove_nodes' => '', // space-separated list of dom nodes that should be removed. example: 'meta style script'
'hard_break' => false, // Set to true to turn <br> into `\n` instead of ` \n` 'hard_break' => false, // Set to true to turn <br> into `\n` instead of ` \n`
'list_item_style' => '-', // Set the default character for each <li> in a <ul>. Can be '-', '*', or '+' 'list_item_style' => '-', // Set the default character for each <li> in a <ul>. Can be '-', '*', or '+'

View File

@ -0,0 +1,26 @@
<?php
namespace League\HTMLToMarkdown;
/**
* Interface for an HTML-to-Markdown converter.
*
* @author Colin O'Dell <colinodell@gmail.com>
*
* @link https://github.com/thephpleague/html-to-markdown/ Latest version on GitHub.
*
* @license http://www.opensource.org/licenses/mit-license.php MIT
*/
interface HtmlConverterInterface
{
/**
* Convert the given $html to Markdown
*
* @param string $html
*
* @throws \InvalidArgumentException
*
* @return string The Markdown version of the html
*/
public function convert($html);
}

View File

@ -1,6 +1,12 @@
ChangeLog ChangeLog
========= =========
3.2.3 (2018-10-19)
------------------
* #982: Make sure that files that are siblings of directories, are reported
as files (@nickvergessen)
3.2.2 (2017-02-14) 3.2.2 (2017-02-14)
------------------ ------------------

0
vendor/sabre/dav/bin/build.php vendored Executable file → Normal file
View File

0
vendor/sabre/dav/bin/googlecode_upload.py vendored Executable file → Normal file
View File

0
vendor/sabre/dav/bin/migrateto20.php vendored Executable file → Normal file
View File

0
vendor/sabre/dav/bin/migrateto21.php vendored Executable file → Normal file
View File

0
vendor/sabre/dav/bin/migrateto30.php vendored Executable file → Normal file
View File

0
vendor/sabre/dav/bin/migrateto32.php vendored Executable file → Normal file
View File

0
vendor/sabre/dav/bin/sabredav.php vendored Executable file → Normal file
View File

View File

@ -52,12 +52,15 @@ class AddressData implements XmlDeserializable {
]; ];
$elems = (array)$reader->parseInnerTree(); $elems = (array)$reader->parseInnerTree();
$elems = array_filter($elems, function($element) {
return $element['name'] === '{urn:ietf:params:xml:ns:carddav}prop' &&
isset($element['attributes']['name']);
});
$result['addressDataProperties'] = array_map(function($element) { $result['addressDataProperties'] = array_map(function($element) {
return $element['attributes']['name']; return $element['attributes']['name'];
}, $elems); }, $elems);
return $result; return $result;
} }
} }

View File

@ -893,15 +893,16 @@ class Server extends EventEmitter implements LoggerAwareInterface {
$newDepth--; $newDepth--;
} }
$propertyNames = $propFind->getRequestedProperties();
$propFindType = !empty($propertyNames) ? PropFind::NORMAL : PropFind::ALLPROPS;
foreach ($this->tree->getChildren($path) as $childNode) { foreach ($this->tree->getChildren($path) as $childNode) {
$subPropFind = clone $propFind;
$subPropFind->setDepth($newDepth);
if ($path !== '') { if ($path !== '') {
$subPath = $path . '/' . $childNode->getName(); $subPath = $path . '/' . $childNode->getName();
} else { } else {
$subPath = $childNode->getName(); $subPath = $childNode->getName();
} }
$subPropFind->setPath($subPath); $subPropFind = new PropFind($subPath, $propertyNames, $newDepth, $propFindType);
yield [ yield [
$subPropFind, $subPropFind,

View File

@ -298,7 +298,9 @@ class Tree {
*/ */
protected function copyNode(INode $source, ICollection $destinationParent, $destinationName = null) { protected function copyNode(INode $source, ICollection $destinationParent, $destinationName = null) {
if (!$destinationName) $destinationName = $source->getName(); if ((string)$destinationName === '') {
$destinationName = $source->getName();
}
if ($source instanceof IFile) { if ($source instanceof IFile) {

View File

@ -60,7 +60,7 @@ class AbstractBasicTest extends \PHPUnit_Framework_TestCase {
$backend->setRealm('writing unittests on a saturday night'); $backend->setRealm('writing unittests on a saturday night');
$backend->challenge($request, $response); $backend->challenge($request, $response);
$this->assertEquals( $this->assertContains(
'Basic realm="writing unittests on a saturday night"', 'Basic realm="writing unittests on a saturday night"',
$response->getHeader('WWW-Authenticate') $response->getHeader('WWW-Authenticate')
); );

View File

@ -24,6 +24,22 @@ class TreeTest extends \PHPUnit_Framework_TestCase {
} }
function testCopyFile() {
$tree = new TreeMock();
$tree->copy('hi/file', 'hi/newfile');
$this->assertArrayHasKey('newfile', $tree->getNodeForPath('hi')->newFiles);
}
function testCopyFile0() {
$tree = new TreeMock();
$tree->copy('hi/file', 'hi/0');
$this->assertArrayHasKey('0', $tree->getNodeForPath('hi')->newFiles);
}
function testMove() { function testMove() {
$tree = new TreeMock(); $tree = new TreeMock();

View File

@ -2,7 +2,14 @@
This file contains a brief description of new features which have been added to Smarty 3.1 This file contains a brief description of new features which have been added to Smarty 3.1
Smarty 3.1.32 New tags for inheritance parent and child Smarty 3.1.33-dev
Variable capture name in Smarty special variable
================================================
{$smarty.capture.$foo} can now be used to access the content of a named
capture block
Smarty 3.1.32
New tags for inheritance parent and child
========================================= =========================================
{parent} == {$smarty.block.parent} {parent} == {$smarty.block.parent}
{child} == {$smarty.block.child} {child} == {$smarty.block.child}

View File

@ -1,4 +1,46 @@
===== 3.1.32 ===== (24.04.2018) ===== 3.1.33 release ===== 12.09.2018
===== 3.1.33-dev-12 =====
03.09.2018
- bugfix {foreach} using new style property access like {$item@property} on
Smarty 2 style named foreach loop could produce errors https://github.com/smarty-php/smarty/issues/484
31.08.2018
- bugfix some custom left and right delimiters like '{^' '^}' did not work
https://github.com/smarty-php/smarty/issues/450 https://github.com/smarty-php/smarty/pull/482
- reformating for PSR-2 coding standards https://github.com/smarty-php/smarty/pull/483
- bugfix on Windows absolute filepathes did fail if the drive letter was followed by a linux DIRECTORY_SEPARATOR
like C:/ at Smarty > 3.1.33-dev-5 https://github.com/smarty-php/smarty/issues/451
- PSR-2 code style fixes for config and template file Lexer/Parser generated with
the Smarty Lexer/Parser generator from https://github.com/smarty-php/smarty-lexer
https://github.com/smarty-php/smarty/pull/483
26.08.2018
- bugfix/enhancement {capture} allow variable as capture block name in Smarty special variable
like $smarty.capture.$foo https://github.com/smarty-php/smarty/issues/478 https://github.com/smarty-php/smarty/pull/481
===== 3.1.33-dev-6 =====
19.08.2018
- fix PSR-2 coding standards and PHPDoc blocks https://github.com/smarty-php/smarty/pull/452
https://github.com/smarty-php/smarty/pull/475
https://github.com/smarty-php/smarty/pull/473
- bugfix PHP5.2 compatibility https://github.com/smarty-php/smarty/pull/472
===== 3.1.33-dev-4 =====
17.05.2018
- bugfix strip-block produces different output in Smarty v3.1.32 https://github.com/smarty-php/smarty/issues/436
- bugfix Smarty::compileAllTemplates ignores `$extension` parameter https://github.com/smarty-php/smarty/issues/437
https://github.com/smarty-php/smarty/pull/438
- improvement do not compute total property in {foreach} if not needed https://github.com/smarty-php/smarty/issues/443
- bugfix plugins may not be loaded when setMergeCompiledIncludes is true https://github.com/smarty-php/smarty/issues/435
26.04.2018
- bugfix regarding Security Vulnerability did not solve the problem under Linux.
Security issue CVE-2018-16831
===== 3.1.32 ===== (24.04.2018)
24.04.2018 24.04.2018
- bugfix possible Security Vulnerability in Smarty_Security class. - bugfix possible Security Vulnerability in Smarty_Security class.

View File

@ -2,7 +2,9 @@
"name": "smarty/smarty", "name": "smarty/smarty",
"type": "library", "type": "library",
"description": "Smarty - the compiling PHP template engine", "description": "Smarty - the compiling PHP template engine",
"keywords": ["templating"], "keywords": [
"templating"
],
"homepage": "http://www.smarty.net", "homepage": "http://www.smarty.net",
"license": "LGPL-3.0", "license": "LGPL-3.0",
"authors": [ "authors": [
@ -28,12 +30,13 @@
"php": ">=5.2" "php": ">=5.2"
}, },
"autoload": { "autoload": {
"files": ["libs/bootstrap.php"] "files": [
"libs/bootstrap.php"
]
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "3.1.x-dev" "dev-master": "3.1.x-dev"
} }
} }
} }

View File

@ -4,27 +4,32 @@
* *
* @package Example-application * @package Example-application
*/ */
require '../libs/Smarty.class.php'; require '../libs/Smarty.class.php';
$smarty = new Smarty; $smarty = new Smarty;
//$smarty->force_compile = true; //$smarty->force_compile = true;
$smarty->debugging = true; $smarty->debugging = true;
$smarty->caching = true; $smarty->caching = true;
$smarty->cache_lifetime = 120; $smarty->cache_lifetime = 120;
$smarty->assign("Name", "Fred Irving Johnathan Bradley Peppergill", true); $smarty->assign("Name", "Fred Irving Johnathan Bradley Peppergill", true);
$smarty->assign("FirstName", array("John", "Mary", "James", "Henry")); $smarty->assign("FirstName", array("John", "Mary", "James", "Henry"));
$smarty->assign("LastName", array("Doe", "Smith", "Johnson", "Case")); $smarty->assign("LastName", array("Doe", "Smith", "Johnson", "Case"));
$smarty->assign("Class", array(array("A", "B", "C", "D"), array("E", "F", "G", "H"), array("I", "J", "K", "L"), $smarty->assign(
array("M", "N", "O", "P"))); "Class",
array(
$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"), array("A", "B", "C", "D"),
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234"))); array("E", "F", "G", "H"),
array("I", "J", "K", "L"),
array("M", "N", "O", "P")
)
);
$smarty->assign(
"contacts",
array(
array("phone" => "1", "fax" => "2", "cell" => "3"),
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")
)
);
$smarty->assign("option_values", array("NY", "NE", "KS", "IA", "OK", "TX")); $smarty->assign("option_values", array("NY", "NE", "KS", "IA", "OK", "TX"));
$smarty->assign("option_output", array("New York", "Nebraska", "Kansas", "Iowa", "Oklahoma", "Texas")); $smarty->assign("option_output", array("New York", "Nebraska", "Kansas", "Iowa", "Oklahoma", "Texas"));
$smarty->assign("option_selected", "NE"); $smarty->assign("option_selected", "NE");
$smarty->display('index.tpl'); $smarty->display('index.tpl');

View File

@ -11,6 +11,11 @@
*/ */
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() public function __construct()
{ {
// test if APC is present // test if APC is present
@ -34,7 +39,6 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore
foreach ($res as $k => $v) { foreach ($res as $k => $v) {
$_res[ $k ] = $v; $_res[ $k ] = $v;
} }
return $_res; return $_res;
} }
@ -51,7 +55,6 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore
foreach ($keys as $k => $v) { foreach ($keys as $k => $v) {
apc_store($k, $v, $expire); apc_store($k, $v, $expire);
} }
return true; return true;
} }
@ -67,7 +70,6 @@ class Smarty_CacheResource_Apc extends Smarty_CacheResource_KeyValueStore
foreach ($keys as $k) { foreach ($keys as $k) {
apc_delete($k); apc_delete($k);
} }
return true; return true;
} }

View File

@ -19,6 +19,9 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
*/ */
protected $memcache = null; protected $memcache = null;
/**
* Smarty_CacheResource_Memcache constructor.
*/
public function __construct() public function __construct()
{ {
if (class_exists('Memcached')) { if (class_exists('Memcached')) {
@ -50,7 +53,6 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
foreach ($res as $k => $v) { foreach ($res as $k => $v) {
$_res[ $lookup[ $k ] ] = $v; $_res[ $lookup[ $k ] ] = $v;
} }
return $_res; return $_res;
} }
@ -68,7 +70,6 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
$k = sha1($k); $k = sha1($k);
$this->memcache->set($k, $v, 0, $expire); $this->memcache->set($k, $v, 0, $expire);
} }
return true; return true;
} }
@ -85,7 +86,6 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
$k = sha1($k); $k = sha1($k);
$this->memcache->delete($k); $this->memcache->delete($k);
} }
return true; return true;
} }
@ -96,6 +96,6 @@ class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
*/ */
protected function purge() protected function purge()
{ {
$this->memcache->flush(); return $this->memcache->flush();
} }
} }

View File

@ -24,27 +24,44 @@
*/ */
class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
{ {
// PDO instance /**
* @var \PDO
*/
protected $db; protected $db;
/**
* @var \PDOStatement
*/
protected $fetch; protected $fetch;
/**
* @var \PDOStatement
*/
protected $fetchTimestamp; protected $fetchTimestamp;
/**
* @var \PDOStatement
*/
protected $save; protected $save;
/**
* Smarty_CacheResource_Mysql constructor.
*
* @throws \SmartyException
*/
public function __construct() public function __construct()
{ {
try { try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty"); $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
} } catch (PDOException $e) {
catch (PDOException $e) {
throw new SmartyException('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->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->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) $this->save = $this->db->prepare(
VALUES (:id, :name, :cache_id, :compile_id, :content)'); 'REPLACE INTO output_cache (id, name, cache_id, compile_id, content)
VALUES (:id, :name, :cache_id, :compile_id, :content)'
);
} }
/** /**
@ -76,7 +93,8 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
/** /**
* Fetch cached content's modification timestamp from data source * Fetch cached content's modification timestamp from data source
* *
* @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the complete cached content. * @note implementing this method is optional. Only implement it if modification times can be accessed faster than
* loading the complete cached content.
* *
* @param string $id unique cache content identifier * @param string $id unique cache content identifier
* @param string $name template name * @param string $name template name
@ -90,7 +108,6 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
$this->fetchTimestamp->execute(array('id' => $id)); $this->fetchTimestamp->execute(array('id' => $id));
$mtime = strtotime($this->fetchTimestamp->fetchColumn()); $mtime = strtotime($this->fetchTimestamp->fetchColumn());
$this->fetchTimestamp->closeCursor(); $this->fetchTimestamp->closeCursor();
return $mtime; return $mtime;
} }
@ -108,9 +125,13 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
*/ */
protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content) protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
{ {
$this->save->execute(array('id' => $id, 'name' => $name, 'cache_id' => $cache_id, 'compile_id' => $compile_id, $this->save->execute(
'content' => $content,)); array('id' => $id,
'name' => $name,
'cache_id' => $cache_id,
'compile_id' => $compile_id,
'content' => $content,)
);
return !!$this->save->rowCount(); return !!$this->save->rowCount();
} }
@ -130,7 +151,6 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
if ($name === null && $cache_id === null && $compile_id === null && $exp_time === null) { 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 // 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; return -1;
} }
// build the filter // build the filter
@ -149,12 +169,15 @@ class Smarty_CacheResource_Mysql extends Smarty_CacheResource_Custom
} }
// equal test cache_id and match sub-groups // equal test cache_id and match sub-groups
if ($cache_id !== null) { if ($cache_id !== null) {
$where[] = '(cache_id = ' . $this->db->quote($cache_id) . ' OR cache_id LIKE ' . $where[] =
$this->db->quote($cache_id . '|%') . ')'; '(cache_id = ' .
$this->db->quote($cache_id) .
' OR cache_id LIKE ' .
$this->db->quote($cache_id . '|%') .
')';
} }
// run delete query // 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(); return $query->rowCount();
} }
} }

View File

@ -29,28 +29,27 @@
*/ */
class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
{ {
/**
protected $fetchStatements = Array('default' => 'SELECT %2$s * @var string[]
*/
protected $fetchStatements = array('default' => 'SELECT %2$s
FROM %1$s FROM %1$s
WHERE 1 WHERE 1
AND id = :id AND id = :id
AND cache_id IS NULL AND cache_id IS NULL
AND compile_id IS NULL', AND compile_id IS NULL',
'withCacheId' => 'SELECT %2$s 'withCacheId' => 'SELECT %2$s
FROM %1$s FROM %1$s
WHERE 1 WHERE 1
AND id = :id AND id = :id
AND cache_id = :cache_id AND cache_id = :cache_id
AND compile_id IS NULL', AND compile_id IS NULL',
'withCompileId' => 'SELECT %2$s 'withCompileId' => 'SELECT %2$s
FROM %1$s FROM %1$s
WHERE 1 WHERE 1
AND id = :id AND id = :id
AND compile_id = :compile_id AND compile_id = :compile_id
AND cache_id IS NULL', AND cache_id IS NULL',
'withCacheIdAndCompileId' => 'SELECT %2$s 'withCacheIdAndCompileId' => 'SELECT %2$s
FROM %1$s FROM %1$s
WHERE 1 WHERE 1
@ -58,6 +57,9 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
AND cache_id = :cache_id AND cache_id = :cache_id
AND compile_id = :compile_id'); AND compile_id = :compile_id');
/**
* @var string
*/
protected $insertStatement = 'INSERT INTO %s protected $insertStatement = 'INSERT INTO %s
SET id = :id, SET id = :id,
@ -76,89 +78,108 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
expire = DATE_ADD(CURRENT_TIMESTAMP, INTERVAL :expire SECOND), expire = DATE_ADD(CURRENT_TIMESTAMP, INTERVAL :expire SECOND),
content = :content'; content = :content';
/**
* @var string
*/
protected $deleteStatement = 'DELETE FROM %1$s WHERE %2$s'; protected $deleteStatement = 'DELETE FROM %1$s WHERE %2$s';
/**
* @var string
*/
protected $truncateStatement = 'TRUNCATE TABLE %s'; protected $truncateStatement = 'TRUNCATE TABLE %s';
/**
* @var string
*/
protected $fetchColumns = 'modified, content'; protected $fetchColumns = 'modified, content';
/**
* @var string
*/
protected $fetchTimestampColumns = 'modified'; protected $fetchTimestampColumns = 'modified';
protected $pdo, $table, $database; /**
* @var \PDO
*/
protected $pdo;
/* /**
* @var
*/
protected $table;
/**
* @var null
*/
protected $database;
/**
* Constructor * Constructor
* *
* @param PDO $pdo PDO : active connection * @param PDO $pdo PDO : active connection
* @param string $table : table (or view) name * @param string $table : table (or view) name
* @param string $database : optional - if table is located in another db * @param string $database : optional - if table is located in another db
*
* @throws \SmartyException
*/ */
public function __construct(PDO $pdo, $table, $database = null) public function __construct(PDO $pdo, $table, $database = null)
{ {
if (is_null($table)) { if (is_null($table)) {
throw new SmartyException("Table name for caching can't be null"); throw new SmartyException("Table name for caching can't be null");
} }
$this->pdo = $pdo; $this->pdo = $pdo;
$this->table = $table; $this->table = $table;
$this->database = $database; $this->database = $database;
$this->fillStatementsWithTableName(); $this->fillStatementsWithTableName();
} }
/* /**
* Fills the table name into the statements. * Fills the table name into the statements.
* *
* @return Current Instance * @return $this Current Instance
* @access protected * @access protected
*/ */
protected function fillStatementsWithTableName() protected function fillStatementsWithTableName()
{ {
foreach ($this->fetchStatements as &$statement) {
foreach ($this->fetchStatements AS &$statement) {
$statement = sprintf($statement, $this->getTableName(), '%s'); $statement = sprintf($statement, $this->getTableName(), '%s');
} }
$this->insertStatement = sprintf($this->insertStatement, $this->getTableName()); $this->insertStatement = sprintf($this->insertStatement, $this->getTableName());
$this->deleteStatement = sprintf($this->deleteStatement, $this->getTableName(), '%s'); $this->deleteStatement = sprintf($this->deleteStatement, $this->getTableName(), '%s');
$this->truncateStatement = sprintf($this->truncateStatement, $this->getTableName()); $this->truncateStatement = sprintf($this->truncateStatement, $this->getTableName());
return $this; return $this;
} }
/* /**
* Gets the fetch statement, depending on what you specify * Gets the fetch statement, depending on what you specify
* *
* @param string $columns : the column(s) name(s) you want to retrieve from the database * @param string $columns : the column(s) name(s) you want to retrieve from the database
* @param string $id unique cache content identifier * @param string $id unique cache content identifier
* @param string|null $cache_id cache id * @param string|null $cache_id cache id
* @param string|null $compile_id compile id * @param string|null $compile_id compile id
*
* @access protected * @access protected
* @return \PDOStatement
*/ */
protected function getFetchStatement($columns, $id, $cache_id = null, $compile_id = null) protected function getFetchStatement($columns, $id, $cache_id = null, $compile_id = null)
{ {
$args = array();
if (!is_null($cache_id) && !is_null($compile_id)) { if (!is_null($cache_id) && !is_null($compile_id)) {
$query = $this->fetchStatements[ 'withCacheIdAndCompileId' ] AND $query = $this->fetchStatements[ 'withCacheIdAndCompileId' ] and
$args = Array('id' => $id, 'cache_id' => $cache_id, 'compile_id' => $compile_id); $args = array('id' => $id, 'cache_id' => $cache_id, 'compile_id' => $compile_id);
} elseif (is_null($cache_id) && !is_null($compile_id)) { } elseif (is_null($cache_id) && !is_null($compile_id)) {
$query = $this->fetchStatements[ 'withCompileId' ] AND $query = $this->fetchStatements[ 'withCompileId' ] and
$args = Array('id' => $id, 'compile_id' => $compile_id); $args = array('id' => $id, 'compile_id' => $compile_id);
} elseif (!is_null($cache_id) && is_null($compile_id)) { } elseif (!is_null($cache_id) && is_null($compile_id)) {
$query = $this->fetchStatements[ 'withCacheId' ] AND $args = Array('id' => $id, 'cache_id' => $cache_id); $query = $this->fetchStatements[ 'withCacheId' ] and $args = array('id' => $id, 'cache_id' => $cache_id);
} else { } else {
$query = $this->fetchStatements[ 'default' ] AND $args = Array('id' => $id); $query = $this->fetchStatements[ 'default' ] and $args = array('id' => $id);
} }
$query = sprintf($query, $columns); $query = sprintf($query, $columns);
$stmt = $this->pdo->prepare($query); $stmt = $this->pdo->prepare($query);
foreach ($args as $key => $value) {
foreach ($args AS $key => $value) {
$stmt->bindValue($key, $value); $stmt->bindValue($key, $value);
} }
return $stmt; return $stmt;
} }
@ -177,12 +198,10 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
*/ */
protected function fetch($id, $name, $cache_id = null, $compile_id = null, &$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 = $this->getFetchStatement($this->fetchColumns, $id, $cache_id, $compile_id);
$stmt->execute(); $stmt->execute();
$row = $stmt->fetch(); $row = $stmt->fetch();
$stmt->closeCursor(); $stmt->closeCursor();
if ($row) { if ($row) {
$content = $this->outputContent($row[ 'content' ]); $content = $this->outputContent($row[ 'content' ]);
$mtime = strtotime($row[ 'modified' ]); $mtime = strtotime($row[ 'modified' ]);
@ -212,7 +231,6 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
// $stmt -> closeCursor(); // $stmt -> closeCursor();
// return $mtime; // return $mtime;
// } // }
/** /**
* Save content to cache * Save content to cache
* *
@ -228,9 +246,7 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
*/ */
protected function save($id, $name, $cache_id = null, $compile_id = null, $exp_time, $content) protected function save($id, $name, $cache_id = null, $compile_id = null, $exp_time, $content)
{ {
$stmt = $this->pdo->prepare($this->insertStatement); $stmt = $this->pdo->prepare($this->insertStatement);
$stmt->bindValue('id', $id); $stmt->bindValue('id', $id);
$stmt->bindValue('name', $name); $stmt->bindValue('name', $name);
$stmt->bindValue('cache_id', $cache_id, (is_null($cache_id)) ? PDO::PARAM_NULL : PDO::PARAM_STR); $stmt->bindValue('cache_id', $cache_id, (is_null($cache_id)) ? PDO::PARAM_NULL : PDO::PARAM_STR);
@ -238,14 +254,14 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
$stmt->bindValue('expire', (int)$exp_time, PDO::PARAM_INT); $stmt->bindValue('expire', (int)$exp_time, PDO::PARAM_INT);
$stmt->bindValue('content', $this->inputContent($content)); $stmt->bindValue('content', $this->inputContent($content));
$stmt->execute(); $stmt->execute();
return !!$stmt->rowCount(); return !!$stmt->rowCount();
} }
/* /**
* Encodes the content before saving to database * Encodes the content before saving to database
* *
* @param string $content * @param string $content
*
* @return string $content * @return string $content
* @access protected * @access protected
*/ */
@ -254,10 +270,11 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
return $content; return $content;
} }
/* /**
* Decodes the content before saving to database * Decodes the content before saving to database
* *
* @param string $content * @param string $content
*
* @return string $content * @return string $content
* @access protected * @access protected
*/ */
@ -279,7 +296,6 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
*/ */
protected function delete($name = null, $cache_id = null, $compile_id = null, $exp_time = null) protected function delete($name = null, $cache_id = null, $compile_id = null, $exp_time = null)
{ {
// delete the whole cache // delete the whole cache
if ($name === null && $cache_id === null && $compile_id === null && $exp_time === null) { 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 // returning the number of deleted caches would require a second query to count them
@ -294,8 +310,12 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
} }
// equal test cache_id and match sub-groups // equal test cache_id and match sub-groups
if ($cache_id !== null) { if ($cache_id !== null) {
$where[] = '(cache_id = ' . $this->pdo->quote($cache_id) . ' OR cache_id LIKE ' . $where[] =
$this->pdo->quote($cache_id . '|%') . ')'; '(cache_id = ' .
$this->pdo->quote($cache_id) .
' OR cache_id LIKE ' .
$this->pdo->quote($cache_id . '|%') .
')';
} }
// equal test compile_id // equal test compile_id
if ($compile_id !== null) { if ($compile_id !== null) {
@ -324,4 +344,3 @@ class Smarty_CacheResource_Pdo extends Smarty_CacheResource_Custom
return (is_null($this->database)) ? "`{$this->table}`" : "`{$this->database}`.`{$this->table}`"; return (is_null($this->database)) ? "`{$this->table}`" : "`{$this->database}`.`{$this->table}`";
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
require_once 'cacheresource.pdo.php';
/** /**
* PDO Cache Handler with GZIP support * PDO Cache Handler with GZIP support
@ -11,15 +12,13 @@
* @require Smarty_CacheResource_Pdo class * @require Smarty_CacheResource_Pdo class
* @author Beno!t POLASZEK - 2014 * @author Beno!t POLASZEK - 2014
*/ */
require_once 'cacheresource.pdo.php';
class Smarty_CacheResource_Pdo_Gzip extends Smarty_CacheResource_Pdo class Smarty_CacheResource_Pdo_Gzip extends Smarty_CacheResource_Pdo
{ {
/**
/*
* Encodes the content before saving to database * Encodes the content before saving to database
* *
* @param string $content * @param string $content
*
* @return string $content * @return string $content
* @access protected * @access protected
*/ */
@ -28,10 +27,11 @@ class Smarty_CacheResource_Pdo_Gzip extends Smarty_CacheResource_Pdo
return gzdeflate($content); return gzdeflate($content);
} }
/* /**
* Decodes the content before saving to database * Decodes the content before saving to database
* *
* @param string $content * @param string $content
*
* @return string $content * @return string $content
* @access protected * @access protected
*/ */
@ -40,4 +40,3 @@ class Smarty_CacheResource_Pdo_Gzip extends Smarty_CacheResource_Pdo
return gzinflate($content); return gzinflate($content);
} }
} }

View File

@ -32,15 +32,13 @@ class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends
$sources[ $s->uid ] = $s; $sources[ $s->uid ] = $s;
$uid .= $s->filepath; $uid .= $s->filepath;
$timestamp = $s->timestamp > $timestamp ? $s->timestamp : $timestamp; $timestamp = $s->timestamp > $timestamp ? $s->timestamp : $timestamp;
} } catch (SmartyException $e) {
catch (SmartyException $e) {
} }
} }
if (!$sources) { if (!$sources) {
$source->exists = false; $source->exists = false;
return; return;
} }
$sources = array_reverse($sources, true); $sources = array_reverse($sources, true);
reset($sources); reset($sources);
$s = current($sources); $s = current($sources);
@ -51,15 +49,14 @@ class Smarty_Resource_Extendsall extends Smarty_Internal_Resource_Extends
$source->timestamp = $timestamp; $source->timestamp = $timestamp;
} }
/* /**
* Disable timestamp checks for extendsall resource. * Disable timestamp checks for extendsall resource.
* The individual source components will be checked. * The individual source components will be checked.
* *
* @return bool * @return bool false
*/ */
public function checkTimestamps() public function checkTimestamps()
{ {
return false; return false;
} }
} }

View File

@ -12,28 +12,46 @@
* PRIMARY KEY (`name`) * PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre> * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
* Demo data: * Demo data:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre> * <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello
* world"}{$x}');</pre>
*
* *
* @package Resource-examples * @package Resource-examples
* @author Rodney Rehm * @author Rodney Rehm
*/ */
class Smarty_Resource_Mysql extends Smarty_Resource_Custom class Smarty_Resource_Mysql extends Smarty_Resource_Custom
{ {
// PDO instance /**
* PDO instance
*
* @var \PDO
*/
protected $db; protected $db;
// prepared fetch() statement /**
* prepared fetch() statement
*
* @var \PDOStatement
*/
protected $fetch; protected $fetch;
// prepared fetchTimestamp() statement /**
* prepared fetchTimestamp() statement
*
* @var \PDOStatement
*/
protected $mtime; protected $mtime;
/**
* Smarty_Resource_Mysql constructor.
*
* @throws \SmartyException
*/
public function __construct() public function __construct()
{ {
try { try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty"); $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
} } catch (PDOException $e) {
catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage()); throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
} }
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name'); $this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
@ -66,7 +84,8 @@ class Smarty_Resource_Mysql extends Smarty_Resource_Custom
/** /**
* Fetch a template's modification time from database * 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. * @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 * @param string $name template name
* *
@ -77,7 +96,6 @@ class Smarty_Resource_Mysql extends Smarty_Resource_Custom
$this->mtime->execute(array('name' => $name)); $this->mtime->execute(array('name' => $name));
$mtime = $this->mtime->fetchColumn(); $mtime = $this->mtime->fetchColumn();
$this->mtime->closeCursor(); $this->mtime->closeCursor();
return strtotime($mtime); return strtotime($mtime);
} }
} }

View File

@ -14,25 +14,39 @@
* PRIMARY KEY (`name`) * PRIMARY KEY (`name`)
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre> * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
* Demo data: * Demo data:
* <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre> * <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello
* world"}{$x}');</pre>
*
* *
* @package Resource-examples * @package Resource-examples
* @author Rodney Rehm * @author Rodney Rehm
*/ */
class Smarty_Resource_Mysqls extends Smarty_Resource_Custom class Smarty_Resource_Mysqls extends Smarty_Resource_Custom
{ {
// PDO instance /**
* PDO instance
*
* @var \PDO
*/
protected $db; protected $db;
// prepared fetch() statement /**
* prepared fetch() statement
*
* @var \PDOStatement
*/
protected $fetch; protected $fetch;
/**
* Smarty_Resource_Mysqls constructor.
*
* @throws \SmartyException
*/
public function __construct() public function __construct()
{ {
try { try {
$this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty"); $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty");
} } catch (PDOException $e) {
catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage()); throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
} }
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name'); $this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');

View File

@ -54,8 +54,8 @@ class Smarty_Autoloader
if (!defined('SMARTY_SPL_AUTOLOAD')) { if (!defined('SMARTY_SPL_AUTOLOAD')) {
define('SMARTY_SPL_AUTOLOAD', 0); define('SMARTY_SPL_AUTOLOAD', 0);
} }
if (SMARTY_SPL_AUTOLOAD && if (SMARTY_SPL_AUTOLOAD
set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false && set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false
) { ) {
$registeredAutoLoadFunctions = spl_autoload_functions(); $registeredAutoLoadFunctions = spl_autoload_functions();
if (!isset($registeredAutoLoadFunctions[ 'spl_autoload' ])) { if (!isset($registeredAutoLoadFunctions[ 'spl_autoload' ])) {

View File

@ -27,7 +27,7 @@
* @author Uwe Tews <uwe dot tews at gmail dot com> * @author Uwe Tews <uwe dot tews at gmail dot com>
* @author Rodney Rehm * @author Rodney Rehm
* @package Smarty * @package Smarty
* @version 3.1.32 * @version 3.1.33
*/ */
/** /**
* set SMARTY_DIR to absolute path to Smarty library files. * set SMARTY_DIR to absolute path to Smarty library files.
@ -112,7 +112,7 @@ class Smarty extends Smarty_Internal_TemplateBase
/** /**
* smarty version * smarty version
*/ */
const SMARTY_VERSION = '3.1.32'; const SMARTY_VERSION = '3.1.33';
/** /**
* define variable scopes * define variable scopes
*/ */
@ -166,133 +166,157 @@ class Smarty extends Smarty_Internal_TemplateBase
const PLUGIN_COMPILER = 'compiler'; const PLUGIN_COMPILER = 'compiler';
const PLUGIN_MODIFIER = 'modifier'; const PLUGIN_MODIFIER = 'modifier';
const PLUGIN_MODIFIERCOMPILER = 'modifiercompiler'; const PLUGIN_MODIFIERCOMPILER = 'modifiercompiler';
/** /**
* assigned global tpl vars * assigned global tpl vars
*/ */
public static $global_tpl_vars = array(); public static $global_tpl_vars = array();
/** /**
* Flag denoting if Multibyte String functions are available * Flag denoting if Multibyte String functions are available
*/ */
public static $_MBSTRING = SMARTY_MBSTRING; public static $_MBSTRING = SMARTY_MBSTRING;
/** /**
* The character set to adhere to (e.g. "UTF-8") * The character set to adhere to (e.g. "UTF-8")
*/ */
public static $_CHARSET = SMARTY_RESOURCE_CHAR_SET; public static $_CHARSET = SMARTY_RESOURCE_CHAR_SET;
/** /**
* The date format to be used internally * The date format to be used internally
* (accepts date() and strftime()) * (accepts date() and strftime())
*/ */
public static $_DATE_FORMAT = SMARTY_RESOURCE_DATE_FORMAT; public static $_DATE_FORMAT = SMARTY_RESOURCE_DATE_FORMAT;
/** /**
* Flag denoting if PCRE should run in UTF-8 mode * Flag denoting if PCRE should run in UTF-8 mode
*/ */
public static $_UTF8_MODIFIER = 'u'; public static $_UTF8_MODIFIER = 'u';
/** /**
* Flag denoting if operating system is windows * Flag denoting if operating system is windows
*/ */
public static $_IS_WINDOWS = false; public static $_IS_WINDOWS = false;
/** /**
* auto literal on delimiters with whitespace * auto literal on delimiters with whitespace
* *
* @var boolean * @var boolean
*/ */
public $auto_literal = true; public $auto_literal = true;
/** /**
* display error on not assigned variables * display error on not assigned variables
* *
* @var boolean * @var boolean
*/ */
public $error_unassigned = false; public $error_unassigned = false;
/** /**
* look up relative file path in include_path * look up relative file path in include_path
* *
* @var boolean * @var boolean
*/ */
public $use_include_path = false; public $use_include_path = false;
/** /**
* flag if template_dir is normalized * flag if template_dir is normalized
* *
* @var bool * @var bool
*/ */
public $_templateDirNormalized = false; public $_templateDirNormalized = false;
/** /**
* joined template directory string used in cache keys * joined template directory string used in cache keys
* *
* @var string * @var string
*/ */
public $_joined_template_dir = null; public $_joined_template_dir = null;
/** /**
* flag if config_dir is normalized * flag if config_dir is normalized
* *
* @var bool * @var bool
*/ */
public $_configDirNormalized = false; public $_configDirNormalized = false;
/** /**
* joined config directory string used in cache keys * joined config directory string used in cache keys
* *
* @var string * @var string
*/ */
public $_joined_config_dir = null; public $_joined_config_dir = null;
/** /**
* default template handler * default template handler
* *
* @var callable * @var callable
*/ */
public $default_template_handler_func = null; public $default_template_handler_func = null;
/** /**
* default config handler * default config handler
* *
* @var callable * @var callable
*/ */
public $default_config_handler_func = null; public $default_config_handler_func = null;
/** /**
* default plugin handler * default plugin handler
* *
* @var callable * @var callable
*/ */
public $default_plugin_handler_func = null; public $default_plugin_handler_func = null;
/** /**
* flag if template_dir is normalized * flag if template_dir is normalized
* *
* @var bool * @var bool
*/ */
public $_compileDirNormalized = false; public $_compileDirNormalized = false;
/** /**
* flag if plugins_dir is normalized * flag if plugins_dir is normalized
* *
* @var bool * @var bool
*/ */
public $_pluginsDirNormalized = false; public $_pluginsDirNormalized = false;
/** /**
* flag if template_dir is normalized * flag if template_dir is normalized
* *
* @var bool * @var bool
*/ */
public $_cacheDirNormalized = false; public $_cacheDirNormalized = false;
/** /**
* force template compiling? * force template compiling?
* *
* @var boolean * @var boolean
*/ */
public $force_compile = false; public $force_compile = false;
/** /**
* use sub dirs for compiled/cached files? * use sub dirs for compiled/cached files?
* *
* @var boolean * @var boolean
*/ */
public $use_sub_dirs = false; public $use_sub_dirs = false;
/** /**
* allow ambiguous resources (that are made unique by the resource handler) * allow ambiguous resources (that are made unique by the resource handler)
* *
* @var boolean * @var boolean
*/ */
public $allow_ambiguous_resources = false; public $allow_ambiguous_resources = false;
/** /**
* merge compiled includes * merge compiled includes
* *
* @var boolean * @var boolean
*/ */
public $merge_compiled_includes = false; public $merge_compiled_includes = false;
/* /*
* flag for behaviour when extends: resource and {extends} tag are used simultaneous * flag for behaviour when extends: resource and {extends} tag are used simultaneous
* if false disable execution of {extends} in templates called by extends resource. * if false disable execution of {extends} in templates called by extends resource.
@ -301,30 +325,35 @@ class Smarty extends Smarty_Internal_TemplateBase
* @var boolean * @var boolean
*/ */
public $extends_recursion = true; public $extends_recursion = true;
/** /**
* force cache file creation * force cache file creation
* *
* @var boolean * @var boolean
*/ */
public $force_cache = false; public $force_cache = false;
/** /**
* template left-delimiter * template left-delimiter
* *
* @var string * @var string
*/ */
public $left_delimiter = "{"; public $left_delimiter = "{";
/** /**
* template right-delimiter * template right-delimiter
* *
* @var string * @var string
*/ */
public $right_delimiter = "}"; public $right_delimiter = "}";
/** /**
* array of strings which shall be treated as literal by compiler * array of strings which shall be treated as literal by compiler
* *
* @var array string * @var array string
*/ */
public $literals = array(); public $literals = array();
/** /**
* class name * class name
* This should be instance of Smarty_Security. * This should be instance of Smarty_Security.
@ -333,24 +362,28 @@ class Smarty extends Smarty_Internal_TemplateBase
* @see Smarty_Security * @see Smarty_Security
*/ */
public $security_class = 'Smarty_Security'; public $security_class = 'Smarty_Security';
/** /**
* implementation of security class * implementation of security class
* *
* @var Smarty_Security * @var Smarty_Security
*/ */
public $security_policy = null; public $security_policy = null;
/** /**
* controls handling of PHP-blocks * controls handling of PHP-blocks
* *
* @var integer * @var integer
*/ */
public $php_handling = self::PHP_PASSTHRU; public $php_handling = self::PHP_PASSTHRU;
/** /**
* controls if the php template file resource is allowed * controls if the php template file resource is allowed
* *
* @var bool * @var bool
*/ */
public $allow_php_templates = false; public $allow_php_templates = false;
/** /**
* debug mode * debug mode
* Setting this to true enables the debug-console. * Setting this to true enables the debug-console.
@ -358,6 +391,7 @@ class Smarty extends Smarty_Internal_TemplateBase
* @var boolean * @var boolean
*/ */
public $debugging = false; public $debugging = false;
/** /**
* This determines if debugging is enable-able from the browser. * This determines if debugging is enable-able from the browser.
* <ul> * <ul>
@ -368,6 +402,7 @@ class Smarty extends Smarty_Internal_TemplateBase
* @var string * @var string
*/ */
public $debugging_ctrl = 'NONE'; public $debugging_ctrl = 'NONE';
/** /**
* Name of debugging URL-param. * Name of debugging URL-param.
* Only used when $debugging_ctrl is set to 'URL'. * Only used when $debugging_ctrl is set to 'URL'.
@ -376,54 +411,63 @@ class Smarty extends Smarty_Internal_TemplateBase
* @var string * @var string
*/ */
public $smarty_debug_id = 'SMARTY_DEBUG'; public $smarty_debug_id = 'SMARTY_DEBUG';
/** /**
* Path of debug template. * Path of debug template.
* *
* @var string * @var string
*/ */
public $debug_tpl = null; public $debug_tpl = null;
/** /**
* When set, smarty uses this value as error_reporting-level. * When set, smarty uses this value as error_reporting-level.
* *
* @var int * @var int
*/ */
public $error_reporting = null; public $error_reporting = null;
/** /**
* Controls whether variables with the same name overwrite each other. * Controls whether variables with the same name overwrite each other.
* *
* @var boolean * @var boolean
*/ */
public $config_overwrite = true; public $config_overwrite = true;
/** /**
* Controls whether config values of on/true/yes and off/false/no get converted to boolean. * Controls whether config values of on/true/yes and off/false/no get converted to boolean.
* *
* @var boolean * @var boolean
*/ */
public $config_booleanize = true; public $config_booleanize = true;
/** /**
* Controls whether hidden config sections/vars are read from the file. * Controls whether hidden config sections/vars are read from the file.
* *
* @var boolean * @var boolean
*/ */
public $config_read_hidden = false; public $config_read_hidden = false;
/** /**
* locking concurrent compiles * locking concurrent compiles
* *
* @var boolean * @var boolean
*/ */
public $compile_locking = true; public $compile_locking = true;
/** /**
* Controls whether cache resources should use locking mechanism * Controls whether cache resources should use locking mechanism
* *
* @var boolean * @var boolean
*/ */
public $cache_locking = false; public $cache_locking = false;
/** /**
* seconds to wait for acquiring a lock before ignoring the write lock * seconds to wait for acquiring a lock before ignoring the write lock
* *
* @var float * @var float
*/ */
public $locking_timeout = 10; public $locking_timeout = 10;
/** /**
* resource type used if none given * resource type used if none given
* Must be an valid key of $registered_resources. * Must be an valid key of $registered_resources.
@ -431,6 +475,7 @@ class Smarty extends Smarty_Internal_TemplateBase
* @var string * @var string
*/ */
public $default_resource_type = 'file'; public $default_resource_type = 'file';
/** /**
* caching type * caching type
* Must be an element of $cache_resource_types. * Must be an element of $cache_resource_types.
@ -438,160 +483,189 @@ class Smarty extends Smarty_Internal_TemplateBase
* @var string * @var string
*/ */
public $caching_type = 'file'; public $caching_type = 'file';
/** /**
* config type * config type
* *
* @var string * @var string
*/ */
public $default_config_type = 'file'; public $default_config_type = 'file';
/** /**
* check If-Modified-Since headers * check If-Modified-Since headers
* *
* @var boolean * @var boolean
*/ */
public $cache_modified_check = false; public $cache_modified_check = false;
/** /**
* registered plugins * registered plugins
* *
* @var array * @var array
*/ */
public $registered_plugins = array(); public $registered_plugins = array();
/** /**
* registered objects * registered objects
* *
* @var array * @var array
*/ */
public $registered_objects = array(); public $registered_objects = array();
/** /**
* registered classes * registered classes
* *
* @var array * @var array
*/ */
public $registered_classes = array(); public $registered_classes = array();
/** /**
* registered filters * registered filters
* *
* @var array * @var array
*/ */
public $registered_filters = array(); public $registered_filters = array();
/** /**
* registered resources * registered resources
* *
* @var array * @var array
*/ */
public $registered_resources = array(); public $registered_resources = array();
/** /**
* registered cache resources * registered cache resources
* *
* @var array * @var array
*/ */
public $registered_cache_resources = array(); public $registered_cache_resources = array();
/** /**
* autoload filter * autoload filter
* *
* @var array * @var array
*/ */
public $autoload_filters = array(); public $autoload_filters = array();
/** /**
* default modifier * default modifier
* *
* @var array * @var array
*/ */
public $default_modifiers = array(); public $default_modifiers = array();
/** /**
* autoescape variable output * autoescape variable output
* *
* @var boolean * @var boolean
*/ */
public $escape_html = false; public $escape_html = false;
/** /**
* start time for execution time calculation * start time for execution time calculation
* *
* @var int * @var int
*/ */
public $start_time = 0; public $start_time = 0;
/** /**
* required by the compiler for BC * required by the compiler for BC
* *
* @var string * @var string
*/ */
public $_current_file = null; public $_current_file = null;
/** /**
* internal flag to enable parser debugging * internal flag to enable parser debugging
* *
* @var bool * @var bool
*/ */
public $_parserdebug = false; public $_parserdebug = false;
/** /**
* This object type (Smarty = 1, template = 2, data = 4) * This object type (Smarty = 1, template = 2, data = 4)
* *
* @var int * @var int
*/ */
public $_objType = 1; public $_objType = 1;
/** /**
* Debug object * Debug object
* *
* @var Smarty_Internal_Debug * @var Smarty_Internal_Debug
*/ */
public $_debug = null; public $_debug = null;
/** /**
* template directory * template directory
* *
* @var array * @var array
*/ */
protected $template_dir = array('./templates/'); protected $template_dir = array('./templates/');
/** /**
* flags for normalized template directory entries * flags for normalized template directory entries
* *
* @var array * @var array
*/ */
protected $_processedTemplateDir = array(); protected $_processedTemplateDir = array();
/** /**
* config directory * config directory
* *
* @var array * @var array
*/ */
protected $config_dir = array('./configs/'); protected $config_dir = array('./configs/');
/** /**
* flags for normalized template directory entries * flags for normalized template directory entries
* *
* @var array * @var array
*/ */
protected $_processedConfigDir = array(); protected $_processedConfigDir = array();
/** /**
* compile directory * compile directory
* *
* @var string * @var string
*/ */
protected $compile_dir = './templates_c/'; protected $compile_dir = './templates_c/';
/** /**
* plugins directory * plugins directory
* *
* @var array * @var array
*/ */
protected $plugins_dir = array(); protected $plugins_dir = array();
/** /**
* cache directory * cache directory
* *
* @var string * @var string
*/ */
protected $cache_dir = './cache/'; protected $cache_dir = './cache/';
/** /**
* removed properties * removed properties
* *
* @var string[] * @var string[]
*/ */
protected $obsoleteProperties = array('resource_caching', 'template_resource_caching', 'direct_access_security', protected $obsoleteProperties = array(
'resource_caching', 'template_resource_caching', 'direct_access_security',
'_dir_perms', '_file_perms', 'plugin_search_order', '_dir_perms', '_file_perms', 'plugin_search_order',
'inheritance_merge_compiled_includes', 'resource_cache_mode',); 'inheritance_merge_compiled_includes', 'resource_cache_mode',
);
/** /**
* List of private properties which will call getter/setter on a direct access * List of private properties which will call getter/setter on a direct access
* *
* @var string[] * @var string[]
*/ */
protected $accessMap = array('template_dir' => 'TemplateDir', 'config_dir' => 'ConfigDir', protected $accessMap = array(
'template_dir' => 'TemplateDir', 'config_dir' => 'ConfigDir',
'plugins_dir' => 'PluginsDir', 'compile_dir' => 'CompileDir', 'plugins_dir' => 'PluginsDir', 'compile_dir' => 'CompileDir',
'cache_dir' => 'CacheDir',); 'cache_dir' => 'CacheDir',
);
/** /**
* Initialize new Smarty object * Initialize new Smarty object
@ -657,7 +731,7 @@ class Smarty extends Smarty_Internal_TemplateBase
* @param string|Smarty_Security $security_class if a string is used, it must be class-name * @param string|Smarty_Security $security_class if a string is used, it must be class-name
* *
* @return Smarty current Smarty instance for chaining * @return Smarty current Smarty instance for chaining
* @throws SmartyException when an invalid class name is provided * @throws \SmartyException
*/ */
public function enableSecurity($security_class = null) public function enableSecurity($security_class = null)
{ {
@ -835,7 +909,7 @@ class Smarty extends Smarty_Internal_TemplateBase
$this->plugins_dir = (array)$this->plugins_dir; $this->plugins_dir = (array)$this->plugins_dir;
} }
foreach ($this->plugins_dir as $k => $v) { foreach ($this->plugins_dir as $k => $v) {
$this->plugins_dir[ $k ] = $this->_realpath(rtrim($v, "/\\") . DIRECTORY_SEPARATOR, true); $this->plugins_dir[ $k ] = $this->_realpath(rtrim($v, '/\\') . DIRECTORY_SEPARATOR, true);
} }
$this->_cache[ 'plugin_files' ] = array(); $this->_cache[ 'plugin_files' ] = array();
$this->_pluginsDirNormalized = true; $this->_pluginsDirNormalized = true;
@ -984,8 +1058,8 @@ class Smarty extends Smarty_Internal_TemplateBase
* @param string $plugin_name class plugin name to load * @param string $plugin_name class plugin name to load
* @param bool $check check if already loaded * @param bool $check check if already loaded
* *
* @throws SmartyException
* @return string |boolean filepath of loaded file or false * @return string |boolean filepath of loaded file or false
* @throws \SmartyException
*/ */
public function loadPlugin($plugin_name, $check = true) public function loadPlugin($plugin_name, $check = true)
{ {
@ -1004,12 +1078,13 @@ class Smarty extends Smarty_Internal_TemplateBase
* @return string * @return string
* @throws \SmartyException * @throws \SmartyException
*/ */
public function _getTemplateId($template_name, public function _getTemplateId(
$template_name,
$cache_id = null, $cache_id = null,
$compile_id = null, $compile_id = null,
$caching = null, $caching = null,
Smarty_Internal_Template $template = null) Smarty_Internal_Template $template = null
{ ) {
$template_name = (strpos($template_name, ':') === false) ? "{$this->default_resource_type}:{$template_name}" : $template_name = (strpos($template_name, ':') === false) ? "{$this->default_resource_type}:{$template_name}" :
$template_name; $template_name;
$cache_id = $cache_id === null ? $this->cache_id : $cache_id; $cache_id = $cache_id === null ? $this->cache_id : $cache_id;
@ -1036,30 +1111,19 @@ class Smarty extends Smarty_Internal_TemplateBase
* @param string $path file path * @param string $path file path
* @param bool $realpath if true - convert to absolute * @param bool $realpath if true - convert to absolute
* false - convert to relative * false - convert to relative
* null - keep as it is but remove /./ /../ * null - keep as it is but
* remove /./ /../
* *
* @return string * @return string
*/ */
public function _realpath($path, $realpath = null) public function _realpath($path, $realpath = null)
{ {
static $nds = null;
static $sepDotsep = null;
static $sepDot = null;
static $sepSep =null;
if (!isset($nds)) {
$nds = array('/' => '\\', '\\' => '/'); $nds = array('/' => '\\', '\\' => '/');
$sepDotsep = DIRECTORY_SEPARATOR . '.' . DIRECTORY_SEPARATOR; preg_match(
$sepDot = DIRECTORY_SEPARATOR . '.'; '%^(?<root>(?:[[:alpha:]]:[\\\\/]|/|[\\\\]{2}[[:alpha:]]+|[[:print:]]{2,}:[/]{2}|[\\\\])?)(?<path>(.*))$%u',
$sepSep = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR;
}
// normalize DIRECTORY_SEPARATOR
$path = str_replace(array($nds[DIRECTORY_SEPARATOR], $sepDotsep), DIRECTORY_SEPARATOR, $path);
if (strpos($path,$sepDot) === false && (($realpath === false && $path[0] === '.') || $realpath === null) && $path[0] !== '\\') {
return $path;
}
preg_match('%^(?<root>(?:[[:alpha:]]:[\\\\]|/|[\\\\]{2}[[:alpha:]]+|[[:print:]]{2,}:[/]{2}|[\\\\])?)(?<path>(.*))$%u',
$path, $path,
$parts); $parts
);
$path = $parts[ 'path' ]; $path = $parts[ 'path' ];
if ($parts[ 'root' ] === '\\') { if ($parts[ 'root' ] === '\\') {
$parts[ 'root' ] = substr(getcwd(), 0, 2) . $parts[ 'root' ]; $parts[ 'root' ] = substr(getcwd(), 0, 2) . $parts[ 'root' ];
@ -1068,24 +1132,18 @@ class Smarty extends Smarty_Internal_TemplateBase
$path = getcwd() . DIRECTORY_SEPARATOR . $path; $path = getcwd() . DIRECTORY_SEPARATOR . $path;
} }
} }
// remove noop 'DIRECTORY_SEPARATOR DIRECTORY_SEPARATOR' and 'DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR' patterns // normalize DIRECTORY_SEPARATOR
$path = str_replace(array($sepDotsep,$sepSep), DIRECTORY_SEPARATOR, $path); $path = str_replace($nds[ DIRECTORY_SEPARATOR ], DIRECTORY_SEPARATOR, $path);
// resolve '..DIRECTORY_SEPARATOR' pattern, smallest first $parts[ 'root' ] = str_replace($nds[ DIRECTORY_SEPARATOR ], DIRECTORY_SEPARATOR, $parts[ 'root' ]);
if (strpos($path, '..' . DIRECTORY_SEPARATOR) !== false && do {
preg_match_all('#[\\\\/]([.][.][\\\\/])+#u', $path, $match) $path = preg_replace(
) { array('#[\\\\/]{2}#', '#[\\\\/][.][\\\\/]#', '#[\\\\/]([^\\\\/.]+)[\\\\/][.][.][\\\\/]#'),
$counts = array();
foreach ($match[ 0 ] as $m) {
$counts[] = (int)((strlen($m) - 1) / 3);
}
sort($counts);
foreach ($counts as $count) {
$path = preg_replace('#([\\\\/]+[^\\\\/]+){' . $count .
'}[\\\\/]+([.][.][\\\\/]+){' . $count . '}#u',
DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR,
$path); $path,
} -1,
} $count
);
} while ($count > 0);
return $realpath !== false ? $parts[ 'root' ] . $path : str_ireplace(getcwd(), '.', $parts[ 'root' ] . $path); return $realpath !== false ? $parts[ 'root' ] . $path : str_ireplace(getcwd(), '.', $parts[ 'root' ] . $path);
} }
@ -1282,7 +1340,6 @@ class Smarty extends Smarty_Internal_TemplateBase
* @param string $name property name * @param string $name property name
* *
* @return mixed * @return mixed
* @throws \SmartyException
*/ */
public function __get($name) public function __get($name)
{ {
@ -1307,7 +1364,6 @@ class Smarty extends Smarty_Internal_TemplateBase
* @param string $name property name * @param string $name property name
* @param mixed $value parameter passed to setter * @param mixed $value parameter passed to setter
* *
* @throws \SmartyException
*/ */
public function __set($name, $value) public function __set($name, $value)
{ {
@ -1316,14 +1372,12 @@ class Smarty extends Smarty_Internal_TemplateBase
$this->{$method}($value); $this->{$method}($value);
} elseif (in_array($name, $this->obsoleteProperties)) { } elseif (in_array($name, $this->obsoleteProperties)) {
return; return;
} else { } elseif (is_object($value) && method_exists($value, $name)) {
if (is_object($value) && method_exists($value, $name)) {
$this->$name = $value; $this->$name = $value;
} else { } else {
trigger_error('Undefined property: ' . get_class($this) . '::$' . $name, E_USER_NOTICE); trigger_error('Undefined property: ' . get_class($this) . '::$' . $name, E_USER_NOTICE);
} }
} }
}
/** /**
* Normalize and set directory string * Normalize and set directory string
@ -1345,7 +1399,6 @@ class Smarty extends Smarty_Internal_TemplateBase
* Normalize template_dir or config_dir * Normalize template_dir or config_dir
* *
* @param bool $isConfig true for config_dir * @param bool $isConfig true for config_dir
*
*/ */
private function _normalizeTemplateConfig($isConfig) private function _normalizeTemplateConfig($isConfig)
{ {

View File

@ -28,7 +28,7 @@
/** /**
* @ignore * @ignore
*/ */
require_once(dirname(__FILE__) . '/Smarty.class.php'); require_once dirname(__FILE__) . '/Smarty.class.php';
/** /**
* Smarty Backward Compatibility Wrapper Class * Smarty Backward Compatibility Wrapper Class
@ -53,7 +53,6 @@ class SmartyBC extends Smarty
/** /**
* Initialize new SmartyBC object * Initialize new SmartyBC object
*
*/ */
public function __construct() public function __construct()
{ {
@ -130,9 +129,13 @@ class SmartyBC extends Smarty
* @throws SmartyException * @throws SmartyException
* @internal param array $block_functs list of methods that are block format * @internal param array $block_functs list of methods that are block format
*/ */
public function register_object($object, $object_impl, $allowed = array(), $smarty_args = true, public function register_object(
$block_methods = array()) $object,
{ $object_impl,
$allowed = array(),
$smarty_args = true,
$block_methods = array()
) {
settype($allowed, 'array'); settype($allowed, 'array');
settype($smarty_args, 'boolean'); settype($smarty_args, 'boolean');
$this->registerObject($object, $object_impl, $allowed, $smarty_args, $block_methods); $this->registerObject($object, $object_impl, $allowed, $smarty_args, $block_methods);

View File

@ -1,5 +1,5 @@
<?php <?php
/* /**
* This file is part of the Smarty package. * This file is part of the Smarty package.
* *
* (c) Sebastian Bergmann <sebastian@phpunit.de> * (c) Sebastian Bergmann <sebastian@phpunit.de>
@ -7,11 +7,10 @@
* For the full copyright and license information, please view the LICENSE * For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
/**
/*
* Load and register Smarty Autoloader * Load and register Smarty Autoloader
*/ */
if (!class_exists('Smarty_Autoloader')) { if (!class_exists('Smarty_Autoloader')) {
require dirname(__FILE__) . '/Autoloader.php'; include dirname(__FILE__) . '/Autoloader.php';
} }
Smarty_Autoloader::register(true); Smarty_Autoloader::register(true);

View File

@ -113,10 +113,10 @@
<div> <div>
{foreach $template_data as $template} {foreach $template_data as $template}
<font color=brown>{$template.name}</font> <font color=brown>{$template.name}</font>
<br>&nbsp;&nbsp;<span class="exectime"> <br />&nbsp;&nbsp;<span class="exectime">
(compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"}) (compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"})
</span> </span>
<br> <br />
{/foreach} {/foreach}
</div> </div>
{/if} {/if}
@ -127,7 +127,7 @@
{foreach $assigned_vars as $vars} {foreach $assigned_vars as $vars}
<tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}"> <tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}">
<td><h3><font color=blue>${$vars@key}</font></h3> <td><h3><font color=blue>${$vars@key}</font></h3>
{if isset($vars['nocache'])}<b>Nocache</b></br>{/if} {if isset($vars['nocache'])}<b>Nocache</b><br />{/if}
{if isset($vars['scope'])}<b>Origin:</b> {$vars['scope']|debug_print_var nofilter}{/if} {if isset($vars['scope'])}<b>Origin:</b> {$vars['scope']|debug_print_var nofilter}{/if}
</td> </td>
<td><h3>Value</h3>{$vars['value']|debug_print_var:10:80 nofilter}</td> <td><h3>Value</h3>{$vars['value']|debug_print_var:10:80 nofilter}</td>

View File

@ -20,7 +20,6 @@
* - indent_char - string (" ") * - indent_char - string (" ")
* - wrap_boundary - boolean (true) * - wrap_boundary - boolean (true)
* *
*
* @link http://www.smarty.net/manual/en/language.function.textformat.php {textformat} * @link http://www.smarty.net/manual/en/language.function.textformat.php {textformat}
* (Smarty online manual) * (Smarty online manual)
* *
@ -39,10 +38,15 @@ function smarty_block_textformat($params, $content, Smarty_Internal_Template $te
return; return;
} }
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
$template->_checkPlugins(array(array('function' => 'smarty_modifier_mb_wordwrap', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'modifier.mb_wordwrap.php'))); array(
array(
'function' => 'smarty_modifier_mb_wordwrap',
'file' => SMARTY_PLUGINS_DIR . 'modifier.mb_wordwrap.php'
)
)
);
} }
$style = null; $style = null;
$indent = 0; $indent = 0;
$indent_first = 0; $indent_first = 0;
@ -51,7 +55,6 @@ function smarty_block_textformat($params, $content, Smarty_Internal_Template $te
$wrap_char = "\n"; $wrap_char = "\n";
$wrap_cut = false; $wrap_cut = false;
$assign = null; $assign = null;
foreach ($params as $_key => $_val) { foreach ($params as $_key => $_val) {
switch ($_key) { switch ($_key) {
case 'style': case 'style':
@ -60,38 +63,40 @@ function smarty_block_textformat($params, $content, Smarty_Internal_Template $te
case 'assign': case 'assign':
$$_key = (string)$_val; $$_key = (string)$_val;
break; break;
case 'indent': case 'indent':
case 'indent_first': case 'indent_first':
case 'wrap': case 'wrap':
$$_key = (int)$_val; $$_key = (int)$_val;
break; break;
case 'wrap_cut': case 'wrap_cut':
$$_key = (bool)$_val; $$_key = (bool)$_val;
break; break;
default: default:
trigger_error("textformat: unknown attribute '{$_key}'"); trigger_error("textformat: unknown attribute '{$_key}'");
} }
} }
if ($style === 'email') { if ($style === 'email') {
$wrap = 72; $wrap = 72;
} }
// split into paragraphs // split into paragraphs
$_paragraphs = preg_split('![\r\n]{2}!', $content); $_paragraphs = preg_split('![\r\n]{2}!', $content);
foreach ($_paragraphs as &$_paragraph) { foreach ($_paragraphs as &$_paragraph) {
if (!$_paragraph) { if (!$_paragraph) {
continue; continue;
} }
// convert mult. spaces & special chars to single space // convert mult. spaces & special chars to single space
$_paragraph = $_paragraph =
preg_replace(array('!\s+!' . Smarty::$_UTF8_MODIFIER, preg_replace(
'!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER), array(
array(' ', '!\s+!' . Smarty::$_UTF8_MODIFIER,
''), $_paragraph); '!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER
),
array(
' ',
''
),
$_paragraph
);
// indent first line // indent first line
if ($indent_first > 0) { if ($indent_first > 0) {
$_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph; $_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph;
@ -108,7 +113,6 @@ function smarty_block_textformat($params, $content, Smarty_Internal_Template $te
} }
} }
$_output = implode($wrap_char . $wrap_char, $_paragraphs); $_output = implode($wrap_char . $wrap_char, $_paragraphs);
if ($assign) { if ($assign) {
$template->assign($assign, $_output); $template->assign($assign, $_output);
} else { } else {

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFunction * @subpackage PluginsFunction
*/ */
/** /**
* Smarty {counter} function plugin * Smarty {counter} function plugin
* Type: function * Type: function
@ -24,50 +23,40 @@
function smarty_function_counter($params, $template) function smarty_function_counter($params, $template)
{ {
static $counters = array(); static $counters = array();
$name = (isset($params[ 'name' ])) ? $params[ 'name' ] : 'default'; $name = (isset($params[ 'name' ])) ? $params[ 'name' ] : 'default';
if (!isset($counters[ $name ])) { if (!isset($counters[ $name ])) {
$counters[ $name ] = array('start' => 1, 'skip' => 1, 'direction' => 'up', 'count' => 1); $counters[ $name ] = array('start' => 1, 'skip' => 1, 'direction' => 'up', 'count' => 1);
} }
$counter =& $counters[ $name ]; $counter =& $counters[ $name ];
if (isset($params[ 'start' ])) { if (isset($params[ 'start' ])) {
$counter[ 'start' ] = $counter[ 'count' ] = (int)$params[ 'start' ]; $counter[ 'start' ] = $counter[ 'count' ] = (int)$params[ 'start' ];
} }
if (!empty($params[ 'assign' ])) { if (!empty($params[ 'assign' ])) {
$counter[ 'assign' ] = $params[ 'assign' ]; $counter[ 'assign' ] = $params[ 'assign' ];
} }
if (isset($counter[ 'assign' ])) { if (isset($counter[ 'assign' ])) {
$template->assign($counter[ 'assign' ], $counter[ 'count' ]); $template->assign($counter[ 'assign' ], $counter[ 'count' ]);
} }
if (isset($params[ 'print' ])) { if (isset($params[ 'print' ])) {
$print = (bool)$params[ 'print' ]; $print = (bool)$params[ 'print' ];
} else { } else {
$print = empty($counter[ 'assign' ]); $print = empty($counter[ 'assign' ]);
} }
if ($print) { if ($print) {
$retval = $counter[ 'count' ]; $retval = $counter[ 'count' ];
} else { } else {
$retval = null; $retval = null;
} }
if (isset($params[ 'skip' ])) { if (isset($params[ 'skip' ])) {
$counter[ 'skip' ] = $params[ 'skip' ]; $counter[ 'skip' ] = $params[ 'skip' ];
} }
if (isset($params[ 'direction' ])) { if (isset($params[ 'direction' ])) {
$counter[ 'direction' ] = $params[ 'direction' ]; $counter[ 'direction' ] = $params[ 'direction' ];
} }
if ($counter[ 'direction' ] === 'down') { if ($counter[ 'direction' ] === 'down') {
$counter[ 'count' ] -= $counter[ 'skip' ]; $counter[ 'count' ] -= $counter[ 'skip' ];
} else { } else {
$counter[ 'count' ] += $counter[ 'skip' ]; $counter[ 'count' ] += $counter[ 'skip' ];
} }
return $retval; return $retval;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFunction * @subpackage PluginsFunction
*/ */
/** /**
* Smarty {cycle} function plugin * Smarty {cycle} function plugin
* Type: function * Type: function
@ -29,7 +28,6 @@
* {cycle name=row values="one,two,three" reset=true} * {cycle name=row values="one,two,three" reset=true}
* {cycle name=row} * {cycle name=row}
* *
*
* @link http://www.smarty.net/manual/en/language.function.cycle.php {cycle} * @link http://www.smarty.net/manual/en/language.function.cycle.php {cycle}
* (Smarty online manual) * (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com> * @author Monte Ohrt <monte at ohrt dot com>
@ -43,20 +41,16 @@
* *
* @return string|null * @return string|null
*/ */
function smarty_function_cycle($params, $template) function smarty_function_cycle($params, $template)
{ {
static $cycle_vars; static $cycle_vars;
$name = (empty($params[ 'name' ])) ? 'default' : $params[ 'name' ]; $name = (empty($params[ 'name' ])) ? 'default' : $params[ 'name' ];
$print = (isset($params[ 'print' ])) ? (bool)$params[ 'print' ] : true; $print = (isset($params[ 'print' ])) ? (bool)$params[ 'print' ] : true;
$advance = (isset($params[ 'advance' ])) ? (bool)$params[ 'advance' ] : true; $advance = (isset($params[ 'advance' ])) ? (bool)$params[ 'advance' ] : true;
$reset = (isset($params[ 'reset' ])) ? (bool)$params[ 'reset' ] : false; $reset = (isset($params[ 'reset' ])) ? (bool)$params[ 'reset' ] : false;
if (!isset($params[ 'values' ])) { if (!isset($params[ 'values' ])) {
if (!isset($cycle_vars[ $name ][ 'values' ])) { if (!isset($cycle_vars[ $name ][ 'values' ])) {
trigger_error('cycle: missing \'values\' parameter'); trigger_error('cycle: missing \'values\' parameter');
return; return;
} }
} else { } else {
@ -65,34 +59,28 @@ function smarty_function_cycle($params, $template)
} }
$cycle_vars[ $name ][ 'values' ] = $params[ 'values' ]; $cycle_vars[ $name ][ 'values' ] = $params[ 'values' ];
} }
if (isset($params[ 'delimiter' ])) { if (isset($params[ 'delimiter' ])) {
$cycle_vars[ $name ][ 'delimiter' ] = $params[ 'delimiter' ]; $cycle_vars[ $name ][ 'delimiter' ] = $params[ 'delimiter' ];
} elseif (!isset($cycle_vars[ $name ][ 'delimiter' ])) { } elseif (!isset($cycle_vars[ $name ][ 'delimiter' ])) {
$cycle_vars[ $name ][ 'delimiter' ] = ','; $cycle_vars[ $name ][ 'delimiter' ] = ',';
} }
if (is_array($cycle_vars[ $name ][ 'values' ])) { if (is_array($cycle_vars[ $name ][ 'values' ])) {
$cycle_array = $cycle_vars[ $name ][ 'values' ]; $cycle_array = $cycle_vars[ $name ][ 'values' ];
} else { } else {
$cycle_array = explode($cycle_vars[ $name ][ 'delimiter' ], $cycle_vars[ $name ][ 'values' ]); $cycle_array = explode($cycle_vars[ $name ][ 'delimiter' ], $cycle_vars[ $name ][ 'values' ]);
} }
if (!isset($cycle_vars[ $name ][ 'index' ]) || $reset) { if (!isset($cycle_vars[ $name ][ 'index' ]) || $reset) {
$cycle_vars[ $name ][ 'index' ] = 0; $cycle_vars[ $name ][ 'index' ] = 0;
} }
if (isset($params[ 'assign' ])) { if (isset($params[ 'assign' ])) {
$print = false; $print = false;
$template->assign($params[ 'assign' ], $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]); $template->assign($params[ 'assign' ], $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]);
} }
if ($print) { if ($print) {
$retval = $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]; $retval = $cycle_array[ $cycle_vars[ $name ][ 'index' ] ];
} else { } else {
$retval = null; $retval = null;
} }
if ($advance) { if ($advance) {
if ($cycle_vars[ $name ][ 'index' ] >= count($cycle_array) - 1) { if ($cycle_vars[ $name ][ 'index' ] >= count($cycle_array) - 1) {
$cycle_vars[ $name ][ 'index' ] = 0; $cycle_vars[ $name ][ 'index' ] = 0;
@ -100,6 +88,5 @@ function smarty_function_cycle($params, $template)
$cycle_vars[ $name ][ 'index' ]++; $cycle_vars[ $name ][ 'index' ]++;
} }
} }
return $retval; return $retval;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFunction * @subpackage PluginsFunction
*/ */
/** /**
* Smarty {fetch} plugin * Smarty {fetch} plugin
* Type: function * Type: function
@ -26,20 +25,16 @@ function smarty_function_fetch($params, $template)
{ {
if (empty($params[ 'file' ])) { if (empty($params[ 'file' ])) {
trigger_error('[plugin] fetch parameter \'file\' cannot be empty', E_USER_NOTICE); trigger_error('[plugin] fetch parameter \'file\' cannot be empty', E_USER_NOTICE);
return; return;
} }
// strip file protocol // strip file protocol
if (stripos($params[ 'file' ], 'file://') === 0) { if (stripos($params[ 'file' ], 'file://') === 0) {
$params[ 'file' ] = substr($params[ 'file' ], 7); $params[ 'file' ] = substr($params[ 'file' ], 7);
} }
$protocol = strpos($params[ 'file' ], '://'); $protocol = strpos($params[ 'file' ], '://');
if ($protocol !== false) { if ($protocol !== false) {
$protocol = strtolower(substr($params[ 'file' ], 0, $protocol)); $protocol = strtolower(substr($params[ 'file' ], 0, $protocol));
} }
if (isset($template->smarty->security_policy)) { if (isset($template->smarty->security_policy)) {
if ($protocol) { if ($protocol) {
// remote resource (or php stream, …) // remote resource (or php stream, …)
@ -53,7 +48,6 @@ function smarty_function_fetch($params, $template)
} }
} }
} }
$content = ''; $content = '';
if ($protocol === 'http') { if ($protocol === 'http') {
// http fetch // http fetch
@ -104,7 +98,6 @@ function smarty_function_fetch($params, $template)
if (!empty($param_value)) { if (!empty($param_value)) {
if (!preg_match('![\w\d-]+: .+!', $param_value)) { if (!preg_match('![\w\d-]+: .+!', $param_value)) {
trigger_error("[plugin] invalid header format '{$param_value}'", E_USER_NOTICE); trigger_error("[plugin] invalid header format '{$param_value}'", E_USER_NOTICE);
return; return;
} else { } else {
$extra_headers[] = $param_value; $extra_headers[] = $param_value;
@ -121,7 +114,6 @@ function smarty_function_fetch($params, $template)
$proxy_port = (int)$param_value; $proxy_port = (int)$param_value;
} else { } else {
trigger_error("[plugin] invalid value for attribute '{$param_key }'", E_USER_NOTICE); trigger_error("[plugin] invalid value for attribute '{$param_key }'", E_USER_NOTICE);
return; return;
} }
break; break;
@ -140,13 +132,11 @@ function smarty_function_fetch($params, $template)
$timeout = (int)$param_value; $timeout = (int)$param_value;
} else { } else {
trigger_error("[plugin] invalid value for attribute '{$param_key}'", E_USER_NOTICE); trigger_error("[plugin] invalid value for attribute '{$param_key}'", E_USER_NOTICE);
return; return;
} }
break; break;
default: default:
trigger_error("[plugin] unrecognized attribute '{$param_key}'", E_USER_NOTICE); trigger_error("[plugin] unrecognized attribute '{$param_key}'", E_USER_NOTICE);
return; return;
} }
} }
@ -156,10 +146,8 @@ function smarty_function_fetch($params, $template)
} else { } else {
$fp = fsockopen($server_name, $port, $errno, $errstr, $timeout); $fp = fsockopen($server_name, $port, $errno, $errstr, $timeout);
} }
if (!$fp) { if (!$fp) {
trigger_error("[plugin] unable to fetch: $errstr ($errno)", E_USER_NOTICE); trigger_error("[plugin] unable to fetch: $errstr ($errno)", E_USER_NOTICE);
return; return;
} else { } else {
if ($_is_proxy) { if ($_is_proxy) {
@ -187,23 +175,19 @@ function smarty_function_fetch($params, $template)
if (!empty($user) && !empty($pass)) { if (!empty($user) && !empty($pass)) {
fputs($fp, 'Authorization: BASIC ' . base64_encode("$user:$pass") . "\r\n"); fputs($fp, 'Authorization: BASIC ' . base64_encode("$user:$pass") . "\r\n");
} }
fputs($fp, "\r\n"); fputs($fp, "\r\n");
while (!feof($fp)) { while (!feof($fp)) {
$content .= fgets($fp, 4096); $content .= fgets($fp, 4096);
} }
fclose($fp); fclose($fp);
$csplit = preg_split("!\r\n\r\n!", $content, 2); $csplit = preg_split("!\r\n\r\n!", $content, 2);
$content = $csplit[ 1 ]; $content = $csplit[ 1 ];
if (!empty($params[ 'assign_headers' ])) { if (!empty($params[ 'assign_headers' ])) {
$template->assign($params[ 'assign_headers' ], preg_split("!\r\n!", $csplit[ 0 ])); $template->assign($params[ 'assign_headers' ], preg_split("!\r\n!", $csplit[ 0 ]));
} }
} }
} else { } else {
trigger_error("[plugin fetch] unable to parse URL, check syntax", E_USER_NOTICE); trigger_error("[plugin fetch] unable to parse URL, check syntax", E_USER_NOTICE);
return; return;
} }
} else { } else {
@ -212,7 +196,6 @@ function smarty_function_fetch($params, $template)
throw new SmartyException("{fetch} cannot read resource '" . $params[ 'file' ] . "'"); throw new SmartyException("{fetch} cannot read resource '" . $params[ 'file' ] . "'");
} }
} }
if (!empty($params[ 'assign' ])) { if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $content); $template->assign($params[ 'assign' ], $content);
} else { } else {

View File

@ -29,7 +29,6 @@
* - assign (optional) - assign the output as an array to this variable * - assign (optional) - assign the output as an array to this variable
* - escape (optional) - escape the content (not value), defaults to true * - escape (optional) - escape the content (not value), defaults to true
* *
*
* @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes} * @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes}
* (Smarty online manual) * (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com> * @author Christopher Kvarme <christopher.kvarme@flashjab.com>
@ -45,9 +44,14 @@
*/ */
function smarty_function_html_checkboxes($params, Smarty_Internal_Template $template) function smarty_function_html_checkboxes($params, Smarty_Internal_Template $template)
{ {
$template->_checkPlugins(array(array('function' => 'smarty_function_escape_special_chars', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'))); array(
array(
'function' => 'smarty_function_escape_special_chars',
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'
)
)
);
$name = 'checkbox'; $name = 'checkbox';
$values = null; $values = null;
$options = null; $options = null;
@ -57,31 +61,25 @@ function smarty_function_html_checkboxes($params, Smarty_Internal_Template $temp
$labels = true; $labels = true;
$label_ids = false; $label_ids = false;
$output = null; $output = null;
$extra = ''; $extra = '';
foreach ($params as $_key => $_val) { foreach ($params as $_key => $_val) {
switch ($_key) { switch ($_key) {
case 'name': case 'name':
case 'separator': case 'separator':
$$_key = (string)$_val; $$_key = (string)$_val;
break; break;
case 'escape': case 'escape':
case 'labels': case 'labels':
case 'label_ids': case 'label_ids':
$$_key = (bool)$_val; $$_key = (bool)$_val;
break; break;
case 'options': case 'options':
$$_key = (array)$_val; $$_key = (array)$_val;
break; break;
case 'values': case 'values':
case 'output': case 'output':
$$_key = array_values((array)$_val); $$_key = array_values((array)$_val);
break; break;
case 'checked': case 'checked':
case 'selected': case 'selected':
if (is_array($_val)) { if (is_array($_val)) {
@ -91,8 +89,11 @@ function smarty_function_html_checkboxes($params, Smarty_Internal_Template $temp
if (method_exists($_sel, '__toString')) { if (method_exists($_sel, '__toString')) {
$_sel = smarty_function_escape_special_chars((string)$_sel->__toString()); $_sel = smarty_function_escape_special_chars((string)$_sel->__toString());
} else { } else {
trigger_error('html_checkboxes: selected attribute contains an object of class \'' . trigger_error(
get_class($_sel) . '\' without __toString() method', E_USER_NOTICE); 'html_checkboxes: selected attribute contains an object of class \'' .
get_class($_sel) . '\' without __toString() method',
E_USER_NOTICE
);
continue; continue;
} }
} else { } else {
@ -104,42 +105,43 @@ function smarty_function_html_checkboxes($params, Smarty_Internal_Template $temp
if (method_exists($_val, '__toString')) { if (method_exists($_val, '__toString')) {
$selected = smarty_function_escape_special_chars((string)$_val->__toString()); $selected = smarty_function_escape_special_chars((string)$_val->__toString());
} else { } else {
trigger_error('html_checkboxes: selected attribute is an object of class \'' . get_class($_val) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_checkboxes: selected attribute is an object of class \'' . get_class($_val) .
'\' without __toString() method',
E_USER_NOTICE
);
} }
} else { } else {
$selected = smarty_function_escape_special_chars((string)$_val); $selected = smarty_function_escape_special_chars((string)$_val);
} }
break; break;
case 'checkboxes': case 'checkboxes':
trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', trigger_error(
E_USER_WARNING); 'html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead',
E_USER_WARNING
);
$options = (array)$_val; $options = (array)$_val;
break; break;
case 'assign': case 'assign':
break; break;
case 'strict': case 'strict':
break; break;
case 'disabled': case 'disabled':
case 'readonly': case 'readonly':
if (!empty($params[ 'strict' ])) { if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) { if (!is_scalar($_val)) {
trigger_error("html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute", trigger_error(
E_USER_NOTICE); "html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute",
E_USER_NOTICE
);
} }
if ($_val === true || $_val === $_key) { if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"'; $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
} }
break; break;
} }
// omit break; to fall through! // omit break; to fall through!
// no break
default: default:
if (!is_array($_val)) { if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
@ -149,34 +151,49 @@ function smarty_function_html_checkboxes($params, Smarty_Internal_Template $temp
break; break;
} }
} }
if (!isset($options) && !isset($values)) { if (!isset($options) && !isset($values)) {
return ''; return '';
} /* raise error here? */ } /* raise error here? */
$_html_result = array(); $_html_result = array();
if (isset($options)) { if (isset($options)) {
foreach ($options as $_key => $_val) { foreach ($options as $_key => $_val) {
$_html_result[] = $_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, smarty_function_html_checkboxes_output(
$label_ids, $escape); $name,
$_key,
$_val,
$selected,
$extra,
$separator,
$labels,
$label_ids,
$escape
);
} }
} else { } else {
foreach ($values as $_i => $_key) { foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : ''; $_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result[] = $_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, smarty_function_html_checkboxes_output(
$label_ids, $escape); $name,
$_key,
$_val,
$selected,
$extra,
$separator,
$labels,
$label_ids,
$escape
);
} }
} }
if (!empty($params[ 'assign' ])) { if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $_html_result); $template->assign($params[ 'assign' ], $_html_result);
} else { } else {
return implode("\n", $_html_result); return implode("\n", $_html_result);
} }
} }
/** /**
* @param $name * @param $name
* @param $value * @param $value
@ -190,59 +207,69 @@ function smarty_function_html_checkboxes($params, Smarty_Internal_Template $temp
* *
* @return string * @return string
*/ */
function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, function smarty_function_html_checkboxes_output(
$label_ids, $escape = true) $name,
{ $value,
$output,
$selected,
$extra,
$separator,
$labels,
$label_ids,
$escape = true
) {
$_output = ''; $_output = '';
if (is_object($value)) { if (is_object($value)) {
if (method_exists($value, '__toString')) { if (method_exists($value, '__toString')) {
$value = (string)$value->__toString(); $value = (string)$value->__toString();
} else { } else {
trigger_error('html_options: value is an object of class \'' . get_class($value) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_options: value is an object of class \'' . get_class($value) .
'\' without __toString() method',
E_USER_NOTICE
);
return ''; return '';
} }
} else { } else {
$value = (string)$value; $value = (string)$value;
} }
if (is_object($output)) { if (is_object($output)) {
if (method_exists($output, '__toString')) { if (method_exists($output, '__toString')) {
$output = (string)$output->__toString(); $output = (string)$output->__toString();
} else { } else {
trigger_error('html_options: output is an object of class \'' . get_class($output) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_options: output is an object of class \'' . get_class($output) .
'\' without __toString() method',
E_USER_NOTICE
);
return ''; return '';
} }
} else { } else {
$output = (string)$output; $output = (string)$output;
} }
if ($labels) { if ($labels) {
if ($label_ids) { if ($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $_id = smarty_function_escape_special_chars(
$name . '_' . $value)); preg_replace(
'![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER,
'_',
$name . '_' . $value
)
);
$_output .= '<label for="' . $_id . '">'; $_output .= '<label for="' . $_id . '">';
} else { } else {
$_output .= '<label>'; $_output .= '<label>';
} }
} }
$name = smarty_function_escape_special_chars($name); $name = smarty_function_escape_special_chars($name);
$value = smarty_function_escape_special_chars($value); $value = smarty_function_escape_special_chars($value);
if ($escape) { if ($escape) {
$output = smarty_function_escape_special_chars($output); $output = smarty_function_escape_special_chars($output);
} }
$_output .= '<input type="checkbox" name="' . $name . '[]" value="' . $value . '"'; $_output .= '<input type="checkbox" name="' . $name . '[]" value="' . $value . '"';
if ($labels && $label_ids) { if ($labels && $label_ids) {
$_output .= ' id="' . $_id . '"'; $_output .= ' id="' . $_id . '"';
} }
if (is_array($selected)) { if (is_array($selected)) {
if (isset($selected[ $value ])) { if (isset($selected[ $value ])) {
$_output .= ' checked="checked"'; $_output .= ' checked="checked"';
@ -250,13 +277,10 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
} elseif ($value === $selected) { } elseif ($value === $selected) {
$_output .= ' checked="checked"'; $_output .= ' checked="checked"';
} }
$_output .= $extra . ' />' . $output; $_output .= $extra . ' />' . $output;
if ($labels) { if ($labels) {
$_output .= '</label>'; $_output .= '</label>';
} }
$_output .= $separator; $_output .= $separator;
return $_output; return $_output;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFunction * @subpackage PluginsFunction
*/ */
/** /**
* Smarty {html_image} function plugin * Smarty {html_image} function plugin
* Type: function * Type: function
@ -22,7 +21,6 @@
* - basedir - (optional) - base directory for absolute paths, default is environment variable DOCUMENT_ROOT * - basedir - (optional) - base directory for absolute paths, default is environment variable DOCUMENT_ROOT
* - path_prefix - prefix for path output (optional, default empty) * - path_prefix - prefix for path output (optional, default empty)
* *
*
* @link http://www.smarty.net/manual/en/language.function.html.image.php {html_image} * @link http://www.smarty.net/manual/en/language.function.html.image.php {html_image}
* (Smarty online manual) * (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com> * @author Monte Ohrt <monte at ohrt dot com>
@ -38,9 +36,14 @@
*/ */
function smarty_function_html_image($params, Smarty_Internal_Template $template) function smarty_function_html_image($params, Smarty_Internal_Template $template)
{ {
$template->_checkPlugins(array(array('function' => 'smarty_function_escape_special_chars', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'))); array(
array(
'function' => 'smarty_function_escape_special_chars',
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'
)
)
);
$alt = ''; $alt = '';
$file = ''; $file = '';
$height = ''; $height = '';
@ -60,53 +63,50 @@ function smarty_function_html_image($params, Smarty_Internal_Template $template)
case 'basedir': case 'basedir':
$$_key = $_val; $$_key = $_val;
break; break;
case 'alt': case 'alt':
if (!is_array($_val)) { if (!is_array($_val)) {
$$_key = smarty_function_escape_special_chars($_val); $$_key = smarty_function_escape_special_chars($_val);
} else { } else {
throw new SmartyException ("html_image: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE); throw new SmartyException(
"html_image: extra attribute '{$_key}' cannot be an array",
E_USER_NOTICE
);
} }
break; break;
case 'link': case 'link':
case 'href': case 'href':
$prefix = '<a href="' . $_val . '">'; $prefix = '<a href="' . $_val . '">';
$suffix = '</a>'; $suffix = '</a>';
break; break;
default: default:
if (!is_array($_val)) { if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else { } else {
throw new SmartyException ("html_image: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE); throw new SmartyException(
"html_image: extra attribute '{$_key}' cannot be an array",
E_USER_NOTICE
);
} }
break; break;
} }
} }
if (empty($file)) { if (empty($file)) {
trigger_error('html_image: missing \'file\' parameter', E_USER_NOTICE); trigger_error('html_image: missing \'file\' parameter', E_USER_NOTICE);
return; return;
} }
if ($file[ 0 ] === '/') { if ($file[ 0 ] === '/') {
$_image_path = $basedir . $file; $_image_path = $basedir . $file;
} else { } else {
$_image_path = $file; $_image_path = $file;
} }
// strip file protocol // strip file protocol
if (stripos($params[ 'file' ], 'file://') === 0) { if (stripos($params[ 'file' ], 'file://') === 0) {
$params[ 'file' ] = substr($params[ 'file' ], 7); $params[ 'file' ] = substr($params[ 'file' ], 7);
} }
$protocol = strpos($params[ 'file' ], '://'); $protocol = strpos($params[ 'file' ], '://');
if ($protocol !== false) { if ($protocol !== false) {
$protocol = strtolower(substr($params[ 'file' ], 0, $protocol)); $protocol = strtolower(substr($params[ 'file' ], 0, $protocol));
} }
if (isset($template->smarty->security_policy)) { if (isset($template->smarty->security_policy)) {
if ($protocol) { if ($protocol) {
// remote resource (or php stream, …) // remote resource (or php stream, …)
@ -120,25 +120,20 @@ function smarty_function_html_image($params, Smarty_Internal_Template $template)
} }
} }
} }
if (!isset($params[ 'width' ]) || !isset($params[ 'height' ])) { if (!isset($params[ 'width' ]) || !isset($params[ 'height' ])) {
// FIXME: (rodneyrehm) getimagesize() loads the complete file off a remote resource, use custom [jpg,png,gif]header reader! // FIXME: (rodneyrehm) getimagesize() loads the complete file off a remote resource, use custom [jpg,png,gif]header reader!
if (!$_image_data = @getimagesize($_image_path)) { if (!$_image_data = @getimagesize($_image_path)) {
if (!file_exists($_image_path)) { if (!file_exists($_image_path)) {
trigger_error("html_image: unable to find '{$_image_path}'", E_USER_NOTICE); trigger_error("html_image: unable to find '{$_image_path}'", E_USER_NOTICE);
return; return;
} elseif (!is_readable($_image_path)) { } elseif (!is_readable($_image_path)) {
trigger_error("html_image: unable to read '{$_image_path}'", E_USER_NOTICE); trigger_error("html_image: unable to read '{$_image_path}'", E_USER_NOTICE);
return; return;
} else { } else {
trigger_error("html_image: '{$_image_path}' is not a valid image file", E_USER_NOTICE); trigger_error("html_image: '{$_image_path}' is not a valid image file", E_USER_NOTICE);
return; return;
} }
} }
if (!isset($params[ 'width' ])) { if (!isset($params[ 'width' ])) {
$width = $_image_data[ 0 ]; $width = $_image_data[ 0 ];
} }
@ -146,7 +141,6 @@ function smarty_function_html_image($params, Smarty_Internal_Template $template)
$height = $_image_data[ 1 ]; $height = $_image_data[ 1 ];
} }
} }
if (isset($params[ 'dpi' ])) { if (isset($params[ 'dpi' ])) {
if (strstr($_SERVER[ 'HTTP_USER_AGENT' ], 'Mac')) { if (strstr($_SERVER[ 'HTTP_USER_AGENT' ], 'Mac')) {
// FIXME: (rodneyrehm) wrong dpi assumption // FIXME: (rodneyrehm) wrong dpi assumption
@ -159,7 +153,6 @@ function smarty_function_html_image($params, Smarty_Internal_Template $template)
$width = round($width * $_resize); $width = round($width * $_resize);
$height = round($height * $_resize); $height = round($height * $_resize);
} }
return $prefix . '<img src="' . $path_prefix . $file . '" alt="' . $alt . '" width="' . $width . '" height="' . return $prefix . '<img src="' . $path_prefix . $file . '" alt="' . $alt . '" width="' . $width . '" height="' .
$height . '"' . $extra . ' />' . $suffix; $height . '"' . $extra . ' />' . $suffix;
} }

View File

@ -21,7 +21,6 @@
* - id (optional) - string default not set * - id (optional) - string default not set
* - class (optional) - string default not set * - class (optional) - string default not set
* *
*
* @link http://www.smarty.net/manual/en/language.function.html.options.php {html_image} * @link http://www.smarty.net/manual/en/language.function.html.options.php {html_image}
* (Smarty online manual) * (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com> * @author Monte Ohrt <monte at ohrt dot com>
@ -37,9 +36,14 @@
*/ */
function smarty_function_html_options($params, Smarty_Internal_Template $template) function smarty_function_html_options($params, Smarty_Internal_Template $template)
{ {
$template->_checkPlugins(array(array('function' => 'smarty_function_escape_special_chars', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'))); array(
array(
'function' => 'smarty_function_escape_special_chars',
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'
)
)
);
$name = null; $name = null;
$values = null; $values = null;
$options = null; $options = null;
@ -47,9 +51,7 @@ function smarty_function_html_options($params, Smarty_Internal_Template $templat
$output = null; $output = null;
$id = null; $id = null;
$class = null; $class = null;
$extra = ''; $extra = '';
foreach ($params as $_key => $_val) { foreach ($params as $_key => $_val) {
switch ($_key) { switch ($_key) {
case 'name': case 'name':
@ -57,16 +59,13 @@ function smarty_function_html_options($params, Smarty_Internal_Template $templat
case 'id': case 'id':
$$_key = (string)$_val; $$_key = (string)$_val;
break; break;
case 'options': case 'options':
$options = (array)$_val; $options = (array)$_val;
break; break;
case 'values': case 'values':
case 'output': case 'output':
$$_key = array_values((array)$_val); $$_key = array_values((array)$_val);
break; break;
case 'selected': case 'selected':
if (is_array($_val)) { if (is_array($_val)) {
$selected = array(); $selected = array();
@ -75,8 +74,11 @@ function smarty_function_html_options($params, Smarty_Internal_Template $templat
if (method_exists($_sel, '__toString')) { if (method_exists($_sel, '__toString')) {
$_sel = smarty_function_escape_special_chars((string)$_sel->__toString()); $_sel = smarty_function_escape_special_chars((string)$_sel->__toString());
} else { } else {
trigger_error('html_options: selected attribute contains an object of class \'' . trigger_error(
get_class($_sel) . '\' without __toString() method', E_USER_NOTICE); 'html_options: selected attribute contains an object of class \'' .
get_class($_sel) . '\' without __toString() method',
E_USER_NOTICE
);
continue; continue;
} }
} else { } else {
@ -88,33 +90,34 @@ function smarty_function_html_options($params, Smarty_Internal_Template $templat
if (method_exists($_val, '__toString')) { if (method_exists($_val, '__toString')) {
$selected = smarty_function_escape_special_chars((string)$_val->__toString()); $selected = smarty_function_escape_special_chars((string)$_val->__toString());
} else { } else {
trigger_error('html_options: selected attribute is an object of class \'' . get_class($_val) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_options: selected attribute is an object of class \'' . get_class($_val) .
'\' without __toString() method',
E_USER_NOTICE
);
} }
} else { } else {
$selected = smarty_function_escape_special_chars((string)$_val); $selected = smarty_function_escape_special_chars((string)$_val);
} }
break; break;
case 'strict': case 'strict':
break; break;
case 'disabled': case 'disabled':
case 'readonly': case 'readonly':
if (!empty($params[ 'strict' ])) { if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) { if (!is_scalar($_val)) {
trigger_error("html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute", trigger_error(
E_USER_NOTICE); "html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute",
E_USER_NOTICE
);
} }
if ($_val === true || $_val === $_key) { if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"'; $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
} }
break; break;
} }
// omit break; to fall through! // omit break; to fall through!
// no break
default: default:
if (!is_array($_val)) { if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
@ -124,16 +127,12 @@ function smarty_function_html_options($params, Smarty_Internal_Template $templat
break; break;
} }
} }
if (!isset($options) && !isset($values)) { if (!isset($options) && !isset($values)) {
/* raise error here? */ /* raise error here? */
return ''; return '';
} }
$_html_result = ''; $_html_result = '';
$_idx = 0; $_idx = 0;
if (isset($options)) { if (isset($options)) {
foreach ($options as $_key => $_val) { foreach ($options as $_key => $_val) {
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx); $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx);
@ -144,7 +143,6 @@ function smarty_function_html_options($params, Smarty_Internal_Template $templat
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx); $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx);
} }
} }
if (!empty($name)) { if (!empty($name)) {
$_html_class = !empty($class) ? ' class="' . $class . '"' : ''; $_html_class = !empty($class) ? ' class="' . $class . '"' : '';
$_html_id = !empty($id) ? ' id="' . $id . '"' : ''; $_html_id = !empty($id) ? ' id="' . $id . '"' : '';
@ -152,9 +150,9 @@ function smarty_function_html_options($params, Smarty_Internal_Template $templat
'<select name="' . $name . '"' . $_html_class . $_html_id . $extra . '>' . "\n" . $_html_result . '<select name="' . $name . '"' . $_html_class . $_html_id . $extra . '>' . "\n" . $_html_result .
'</select>' . "\n"; '</select>' . "\n";
} }
return $_html_result; return $_html_result;
} }
/** /**
* @param $key * @param $key
* @param $value * @param $value
@ -183,9 +181,11 @@ function smarty_function_html_options_optoutput($key, $value, $selected, $id, $c
if (method_exists($value, '__toString')) { if (method_exists($value, '__toString')) {
$value = smarty_function_escape_special_chars((string)$value->__toString()); $value = smarty_function_escape_special_chars((string)$value->__toString());
} else { } else {
trigger_error('html_options: value is an object of class \'' . get_class($value) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_options: value is an object of class \'' . get_class($value) .
'\' without __toString() method',
E_USER_NOTICE
);
return ''; return '';
} }
} else { } else {
@ -196,13 +196,19 @@ function smarty_function_html_options_optoutput($key, $value, $selected, $id, $c
} else { } else {
$_idx = 0; $_idx = 0;
$_html_result = $_html_result =
smarty_function_html_options_optgroup($key, $value, $selected, !empty($id) ? ($id . '-' . $idx) : null, smarty_function_html_options_optgroup(
$class, $_idx); $key,
$value,
$selected,
!empty($id) ? ($id . '-' . $idx) : null,
$class,
$_idx
);
$idx++; $idx++;
} }
return $_html_result; return $_html_result;
} }
/** /**
* @param $key * @param $key
* @param $values * @param $values
@ -220,6 +226,5 @@ function smarty_function_html_options_optgroup($key, $values, $selected, $id, $c
$optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, $idx); $optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, $idx);
} }
$optgroup_html .= "</optgroup>\n"; $optgroup_html .= "</optgroup>\n";
return $optgroup_html; return $optgroup_html;
} }

View File

@ -29,7 +29,6 @@
* {html_radios values=$ids name='box' separator='<br>' output=$names} * {html_radios values=$ids name='box' separator='<br>' output=$names}
* {html_radios values=$ids checked=$checked separator='<br>' output=$names} * {html_radios values=$ids checked=$checked separator='<br>' output=$names}
* *
*
* @link http://smarty.php.net/manual/en/language.function.html.radios.php {html_radios} * @link http://smarty.php.net/manual/en/language.function.html.radios.php {html_radios}
* (Smarty online manual) * (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com> * @author Christopher Kvarme <christopher.kvarme@flashjab.com>
@ -45,9 +44,14 @@
*/ */
function smarty_function_html_radios($params, Smarty_Internal_Template $template) function smarty_function_html_radios($params, Smarty_Internal_Template $template)
{ {
$template->_checkPlugins(array(array('function' => 'smarty_function_escape_special_chars', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'))); array(
array(
'function' => 'smarty_function_escape_special_chars',
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'
)
)
);
$name = 'radio'; $name = 'radio';
$values = null; $values = null;
$options = null; $options = null;
@ -58,14 +62,12 @@ function smarty_function_html_radios($params, Smarty_Internal_Template $template
$label_ids = false; $label_ids = false;
$output = null; $output = null;
$extra = ''; $extra = '';
foreach ($params as $_key => $_val) { foreach ($params as $_key => $_val) {
switch ($_key) { switch ($_key) {
case 'name': case 'name':
case 'separator': case 'separator':
$$_key = (string)$_val; $$_key = (string)$_val;
break; break;
case 'checked': case 'checked':
case 'selected': case 'selected':
if (is_array($_val)) { if (is_array($_val)) {
@ -74,57 +76,55 @@ function smarty_function_html_radios($params, Smarty_Internal_Template $template
if (method_exists($_val, '__toString')) { if (method_exists($_val, '__toString')) {
$selected = smarty_function_escape_special_chars((string)$_val->__toString()); $selected = smarty_function_escape_special_chars((string)$_val->__toString());
} else { } else {
trigger_error('html_radios: selected attribute is an object of class \'' . get_class($_val) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_radios: selected attribute is an object of class \'' . get_class($_val) .
'\' without __toString() method',
E_USER_NOTICE
);
} }
} else { } else {
$selected = (string)$_val; $selected = (string)$_val;
} }
break; break;
case 'escape': case 'escape':
case 'labels': case 'labels':
case 'label_ids': case 'label_ids':
$$_key = (bool)$_val; $$_key = (bool)$_val;
break; break;
case 'options': case 'options':
$$_key = (array)$_val; $$_key = (array)$_val;
break; break;
case 'values': case 'values':
case 'output': case 'output':
$$_key = array_values((array)$_val); $$_key = array_values((array)$_val);
break; break;
case 'radios': case 'radios':
trigger_error('html_radios: the use of the "radios" attribute is deprecated, use "options" instead', trigger_error(
E_USER_WARNING); 'html_radios: the use of the "radios" attribute is deprecated, use "options" instead',
E_USER_WARNING
);
$options = (array)$_val; $options = (array)$_val;
break; break;
case 'assign': case 'assign':
break; break;
case 'strict': case 'strict':
break; break;
case 'disabled': case 'disabled':
case 'readonly': case 'readonly':
if (!empty($params[ 'strict' ])) { if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) { if (!is_scalar($_val)) {
trigger_error("html_options: {$_key} attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", trigger_error(
E_USER_NOTICE); "html_options: {$_key} attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute",
E_USER_NOTICE
);
} }
if ($_val === true || $_val === $_key) { if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"'; $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
} }
break; break;
} }
// omit break; to fall through! // omit break; to fall through!
// no break
default: default:
if (!is_array($_val)) { if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
@ -134,36 +134,50 @@ function smarty_function_html_radios($params, Smarty_Internal_Template $template
break; break;
} }
} }
if (!isset($options) && !isset($values)) { if (!isset($options) && !isset($values)) {
/* raise error here? */ /* raise error here? */
return ''; return '';
} }
$_html_result = array(); $_html_result = array();
if (isset($options)) { if (isset($options)) {
foreach ($options as $_key => $_val) { foreach ($options as $_key => $_val) {
$_html_result[] = $_html_result[] =
smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, smarty_function_html_radios_output(
$label_ids, $escape); $name,
$_key,
$_val,
$selected,
$extra,
$separator,
$labels,
$label_ids,
$escape
);
} }
} else { } else {
foreach ($values as $_i => $_key) { foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : ''; $_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result[] = $_html_result[] =
smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, smarty_function_html_radios_output(
$label_ids, $escape); $name,
$_key,
$_val,
$selected,
$extra,
$separator,
$labels,
$label_ids,
$escape
);
} }
} }
if (!empty($params[ 'assign' ])) { if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $_html_result); $template->assign($params[ 'assign' ], $_html_result);
} else { } else {
return implode("\n", $_html_result); return implode("\n", $_html_result);
} }
} }
/** /**
* @param $name * @param $name
* @param $value * @param $value
@ -177,69 +191,76 @@ function smarty_function_html_radios($params, Smarty_Internal_Template $template
* *
* @return string * @return string
*/ */
function smarty_function_html_radios_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, function smarty_function_html_radios_output(
$escape) $name,
{ $value,
$output,
$selected,
$extra,
$separator,
$labels,
$label_ids,
$escape
) {
$_output = ''; $_output = '';
if (is_object($value)) { if (is_object($value)) {
if (method_exists($value, '__toString')) { if (method_exists($value, '__toString')) {
$value = (string)$value->__toString(); $value = (string)$value->__toString();
} else { } else {
trigger_error('html_options: value is an object of class \'' . get_class($value) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_options: value is an object of class \'' . get_class($value) .
'\' without __toString() method',
E_USER_NOTICE
);
return ''; return '';
} }
} else { } else {
$value = (string)$value; $value = (string)$value;
} }
if (is_object($output)) { if (is_object($output)) {
if (method_exists($output, '__toString')) { if (method_exists($output, '__toString')) {
$output = (string)$output->__toString(); $output = (string)$output->__toString();
} else { } else {
trigger_error('html_options: output is an object of class \'' . get_class($output) . trigger_error(
'\' without __toString() method', E_USER_NOTICE); 'html_options: output is an object of class \'' . get_class($output) .
'\' without __toString() method',
E_USER_NOTICE
);
return ''; return '';
} }
} else { } else {
$output = (string)$output; $output = (string)$output;
} }
if ($labels) { if ($labels) {
if ($label_ids) { if ($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $_id = smarty_function_escape_special_chars(
$name . '_' . $value)); preg_replace(
'![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER,
'_',
$name . '_' . $value
)
);
$_output .= '<label for="' . $_id . '">'; $_output .= '<label for="' . $_id . '">';
} else { } else {
$_output .= '<label>'; $_output .= '<label>';
} }
} }
$name = smarty_function_escape_special_chars($name); $name = smarty_function_escape_special_chars($name);
$value = smarty_function_escape_special_chars($value); $value = smarty_function_escape_special_chars($value);
if ($escape) { if ($escape) {
$output = smarty_function_escape_special_chars($output); $output = smarty_function_escape_special_chars($output);
} }
$_output .= '<input type="radio" name="' . $name . '" value="' . $value . '"'; $_output .= '<input type="radio" name="' . $name . '" value="' . $value . '"';
if ($labels && $label_ids) { if ($labels && $label_ids) {
$_output .= ' id="' . $_id . '"'; $_output .= ' id="' . $_id . '"';
} }
if ($value === $selected) { if ($value === $selected) {
$_output .= ' checked="checked"'; $_output .= ' checked="checked"';
} }
$_output .= $extra . ' />' . $output; $_output .= $extra . ' />' . $output;
if ($labels) { if ($labels) {
$_output .= '</label>'; $_output .= '</label>';
} }
$_output .= $separator; $_output .= $separator;
return $_output; return $_output;
} }

View File

@ -28,7 +28,6 @@
* - 2.0 complete rewrite for performance, * - 2.0 complete rewrite for performance,
* added attributes month_names, *_id * added attributes month_names, *_id
* *
*
* @link http://www.smarty.net/manual/en/language.function.html.select.date.php {html_select_date} * @link http://www.smarty.net/manual/en/language.function.html.select.date.php {html_select_date}
* (Smarty online manual) * (Smarty online manual)
* @version 2.0 * @version 2.0
@ -45,8 +44,14 @@
*/ */
function smarty_function_html_select_date($params, Smarty_Internal_Template $template) function smarty_function_html_select_date($params, Smarty_Internal_Template $template)
{ {
$template->_checkPlugins(array(array('function' => 'smarty_function_escape_special_chars', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'))); array(
array(
'function' => 'smarty_function_escape_special_chars',
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'
)
)
);
// generate timestamps used for month names only // generate timestamps used for month names only
static $_month_timestamps = null; static $_month_timestamps = null;
static $_current_year = null; static $_current_year = null;
@ -57,7 +62,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$_month_timestamps[ $i ] = mktime(0, 0, 0, $i, 1, 2000); $_month_timestamps[ $i ] = mktime(0, 0, 0, $i, 1, 2000);
} }
} }
/* Default values. */ /* Default values. */
$prefix = 'Date_'; $prefix = 'Date_';
$start_year = null; $start_year = null;
@ -106,17 +110,21 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$day_id = null; $day_id = null;
$month_id = null; $month_id = null;
$year_id = null; $year_id = null;
foreach ($params as $_key => $_value) { foreach ($params as $_key => $_value) {
switch ($_key) { switch ($_key) {
case 'time': case 'time':
if (!is_array($_value) && $_value !== null) { if (!is_array($_value) && $_value !== null) {
$template->_checkPlugins(array(array('function' => 'smarty_make_timestamp', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'))); array(
array(
'function' => 'smarty_make_timestamp',
'file' => SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'
)
)
);
$time = smarty_make_timestamp($_value); $time = smarty_make_timestamp($_value);
} }
break; break;
case 'month_names': case 'month_names':
if (is_array($_value) && count($_value) === 12) { if (is_array($_value) && count($_value) === 12) {
$$_key = $_value; $$_key = $_value;
@ -124,7 +132,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
trigger_error('html_select_date: month_names must be an array of 12 strings', E_USER_NOTICE); trigger_error('html_select_date: month_names must be an array of 12 strings', E_USER_NOTICE);
} }
break; break;
case 'prefix': case 'prefix':
case 'field_array': case 'field_array':
case 'start_year': case 'start_year':
@ -153,7 +160,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
case 'year_id': case 'year_id':
$$_key = (string)$_value; $$_key = (string)$_value;
break; break;
case 'display_days': case 'display_days':
case 'display_months': case 'display_months':
case 'display_years': case 'display_years':
@ -161,7 +167,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
case 'reverse_years': case 'reverse_years':
$$_key = (bool)$_value; $$_key = (bool)$_value;
break; break;
default: default:
if (!is_array($_value)) { if (!is_array($_value)) {
$extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"'; $extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"';
@ -171,15 +176,16 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
break; break;
} }
} }
// Note: date() is faster than strftime() // Note: date() is faster than strftime()
// Note: explode(date()) is faster than date() date() date() // Note: explode(date()) is faster than date() date() date()
if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) { if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) {
if (isset($params[ 'time' ][ $prefix . 'Year' ])) { if (isset($params[ 'time' ][ $prefix . 'Year' ])) {
// $_REQUEST[$field_array] given // $_REQUEST[$field_array] given
foreach (array('Y' => 'Year', foreach (array(
'Y' => 'Year',
'm' => 'Month', 'm' => 'Month',
'd' => 'Day') as $_elementKey => $_elementName) { 'd' => 'Day'
) as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName); $_variableName = '_' . strtolower($_elementName);
$$_variableName = $$_variableName =
isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] : isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] :
@ -187,9 +193,11 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
} }
} elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Year' ])) { } elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Year' ])) {
// $_REQUEST given // $_REQUEST given
foreach (array('Y' => 'Year', foreach (array(
'Y' => 'Year',
'm' => 'Month', 'm' => 'Month',
'd' => 'Day') as $_elementKey => $_elementName) { 'd' => 'Day'
) as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName); $_variableName = '_' . strtolower($_elementName);
$$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ? $$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ?
$params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey); $params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey);
@ -207,11 +215,12 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
} else { } else {
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d', $time)); list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d', $time));
} }
// make syntax "+N" or "-N" work with $start_year and $end_year // make syntax "+N" or "-N" work with $start_year and $end_year
// Note preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match) is slower than trim+substr // Note preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match) is slower than trim+substr
foreach (array('start', foreach (array(
'end') as $key) { 'start',
'end'
) as $key) {
$key .= '_year'; $key .= '_year';
$t = $$key; $t = $$key;
if ($t === null) { if ($t === null) {
@ -224,14 +233,12 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$$key = (int)$$key; $$key = (int)$$key;
} }
} }
// flip for ascending or descending // flip for ascending or descending
if (($start_year > $end_year && !$reverse_years) || ($start_year < $end_year && $reverse_years)) { if (($start_year > $end_year && !$reverse_years) || ($start_year < $end_year && $reverse_years)) {
$t = $end_year; $t = $end_year;
$end_year = $start_year; $end_year = $start_year;
$start_year = $t; $start_year = $t;
} }
// generate year <select> or <input> // generate year <select> or <input>
if ($display_years) { if ($display_years) {
$_extra = ''; $_extra = '';
@ -242,7 +249,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
if ($year_extra) { if ($year_extra) {
$_extra .= ' ' . $year_extra; $_extra .= ' ' . $year_extra;
} }
if ($year_as_text) { if ($year_as_text) {
$_html_years = $_html_years =
'<input type="text" name="' . $_name . '" value="' . $_year . '" size="4" maxlength="4"' . $_extra . '<input type="text" name="' . $_name . '" value="' . $_year . '" size="4" maxlength="4"' . $_extra .
@ -250,31 +256,29 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
} else { } else {
$_html_years = '<select name="' . $_name . '"'; $_html_years = '<select name="' . $_name . '"';
if ($year_id !== null || $all_id !== null) { if ($year_id !== null || $all_id !== null) {
$_html_years .= ' id="' . smarty_function_escape_special_chars($year_id !== null ? $_html_years .= ' id="' . smarty_function_escape_special_chars(
$year_id !== null ?
($year_id ? $year_id : $_name) : ($year_id ? $year_id : $_name) :
($all_id ? ($all_id . $_name) : ($all_id ? ($all_id . $_name) :
$_name)) . '"'; $_name)
) . '"';
} }
if ($year_size) { if ($year_size) {
$_html_years .= ' size="' . $year_size . '"'; $_html_years .= ' size="' . $year_size . '"';
} }
$_html_years .= $_extra . $extra_attrs . '>' . $option_separator; $_html_years .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($year_empty) || isset($all_empty)) { if (isset($year_empty) || isset($all_empty)) {
$_html_years .= '<option value="">' . (isset($year_empty) ? $year_empty : $all_empty) . '</option>' . $_html_years .= '<option value="">' . (isset($year_empty) ? $year_empty : $all_empty) . '</option>' .
$option_separator; $option_separator;
} }
$op = $start_year > $end_year ? -1 : 1; $op = $start_year > $end_year ? -1 : 1;
for ($i = $start_year; $op > 0 ? $i <= $end_year : $i >= $end_year; $i += $op) { for ($i = $start_year; $op > 0 ? $i <= $end_year : $i >= $end_year; $i += $op) {
$_html_years .= '<option value="' . $i . '"' . ($_year == $i ? ' selected="selected"' : '') . '>' . $i . $_html_years .= '<option value="' . $i . '"' . ($_year == $i ? ' selected="selected"' : '') . '>' . $i .
'</option>' . $option_separator; '</option>' . $option_separator;
} }
$_html_years .= '</select>'; $_html_years .= '</select>';
} }
} }
// generate month <select> or <input> // generate month <select> or <input>
if ($display_months) { if ($display_months) {
$_extra = ''; $_extra = '';
@ -285,24 +289,23 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
if ($month_extra) { if ($month_extra) {
$_extra .= ' ' . $month_extra; $_extra .= ' ' . $month_extra;
} }
$_html_months = '<select name="' . $_name . '"'; $_html_months = '<select name="' . $_name . '"';
if ($month_id !== null || $all_id !== null) { if ($month_id !== null || $all_id !== null) {
$_html_months .= ' id="' . smarty_function_escape_special_chars($month_id !== null ? $_html_months .= ' id="' . smarty_function_escape_special_chars(
$month_id !== null ?
($month_id ? $month_id : $_name) : ($month_id ? $month_id : $_name) :
($all_id ? ($all_id . $_name) : ($all_id ? ($all_id . $_name) :
$_name)) . '"'; $_name)
) . '"';
} }
if ($month_size) { if ($month_size) {
$_html_months .= ' size="' . $month_size . '"'; $_html_months .= ' size="' . $month_size . '"';
} }
$_html_months .= $_extra . $extra_attrs . '>' . $option_separator; $_html_months .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($month_empty) || isset($all_empty)) { if (isset($month_empty) || isset($all_empty)) {
$_html_months .= '<option value="">' . (isset($month_empty) ? $month_empty : $all_empty) . '</option>' . $_html_months .= '<option value="">' . (isset($month_empty) ? $month_empty : $all_empty) . '</option>' .
$option_separator; $option_separator;
} }
for ($i = 1; $i <= 12; $i++) { for ($i = 1; $i <= 12; $i++) {
$_val = sprintf('%02d', $i); $_val = sprintf('%02d', $i);
$_text = isset($month_names) ? smarty_function_escape_special_chars($month_names[ $i ]) : $_text = isset($month_names) ? smarty_function_escape_special_chars($month_names[ $i ]) :
@ -311,10 +314,8 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$_html_months .= '<option value="' . $_value . '"' . ($_val == $_month ? ' selected="selected"' : '') . $_html_months .= '<option value="' . $_value . '"' . ($_val == $_month ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator; '>' . $_text . '</option>' . $option_separator;
} }
$_html_months .= '</select>'; $_html_months .= '</select>';
} }
// generate day <select> or <input> // generate day <select> or <input>
if ($display_days) { if ($display_days) {
$_extra = ''; $_extra = '';
@ -325,23 +326,22 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
if ($day_extra) { if ($day_extra) {
$_extra .= ' ' . $day_extra; $_extra .= ' ' . $day_extra;
} }
$_html_days = '<select name="' . $_name . '"'; $_html_days = '<select name="' . $_name . '"';
if ($day_id !== null || $all_id !== null) { if ($day_id !== null || $all_id !== null) {
$_html_days .= ' id="' . $_html_days .= ' id="' .
smarty_function_escape_special_chars($day_id !== null ? ($day_id ? $day_id : $_name) : smarty_function_escape_special_chars(
($all_id ? ($all_id . $_name) : $_name)) . '"'; $day_id !== null ? ($day_id ? $day_id : $_name) :
($all_id ? ($all_id . $_name) : $_name)
) . '"';
} }
if ($day_size) { if ($day_size) {
$_html_days .= ' size="' . $day_size . '"'; $_html_days .= ' size="' . $day_size . '"';
} }
$_html_days .= $_extra . $extra_attrs . '>' . $option_separator; $_html_days .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($day_empty) || isset($all_empty)) { if (isset($day_empty) || isset($all_empty)) {
$_html_days .= '<option value="">' . (isset($day_empty) ? $day_empty : $all_empty) . '</option>' . $_html_days .= '<option value="">' . (isset($day_empty) ? $day_empty : $all_empty) . '</option>' .
$option_separator; $option_separator;
} }
for ($i = 1; $i <= 31; $i++) { for ($i = 1; $i <= 31; $i++) {
$_val = sprintf('%02d', $i); $_val = sprintf('%02d', $i);
$_text = $day_format === '%02d' ? $_val : sprintf($day_format, $i); $_text = $day_format === '%02d' ? $_val : sprintf($day_format, $i);
@ -349,10 +349,8 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$_html_days .= '<option value="' . $_value . '"' . ($_val == $_day ? ' selected="selected"' : '') . '>' . $_html_days .= '<option value="' . $_value . '"' . ($_val == $_day ? ' selected="selected"' : '') . '>' .
$_text . '</option>' . $option_separator; $_text . '</option>' . $option_separator;
} }
$_html_days .= '</select>'; $_html_days .= '</select>';
} }
// order the fields for output // order the fields for output
$_html = ''; $_html = '';
for ($i = 0; $i <= 2; $i++) { for ($i = 0; $i <= 2; $i++) {
@ -366,7 +364,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$_html .= $_html_years; $_html .= $_html_years;
} }
break; break;
case 'm': case 'm':
case 'M': case 'M':
if (isset($_html_months)) { if (isset($_html_months)) {
@ -376,7 +373,6 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
$_html .= $_html_months; $_html .= $_html_months;
} }
break; break;
case 'd': case 'd':
case 'D': case 'D':
if (isset($_html_days)) { if (isset($_html_days)) {
@ -388,6 +384,5 @@ function smarty_function_html_select_date($params, Smarty_Internal_Template $tem
break; break;
} }
} }
return $_html; return $_html;
} }

View File

@ -26,88 +26,86 @@
*/ */
function smarty_function_html_select_time($params, Smarty_Internal_Template $template) function smarty_function_html_select_time($params, Smarty_Internal_Template $template)
{ {
$template->_checkPlugins(array(array('function' => 'smarty_function_escape_special_chars', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'))); array(
array(
'function' => 'smarty_function_escape_special_chars',
'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'
)
)
);
$prefix = 'Time_'; $prefix = 'Time_';
$field_array = null; $field_array = null;
$field_separator = "\n"; $field_separator = "\n";
$option_separator = "\n"; $option_separator = "\n";
$time = null; $time = null;
$display_hours = true; $display_hours = true;
$display_minutes = true; $display_minutes = true;
$display_seconds = true; $display_seconds = true;
$display_meridian = true; $display_meridian = true;
$hour_format = '%02d'; $hour_format = '%02d';
$hour_value_format = '%02d'; $hour_value_format = '%02d';
$minute_format = '%02d'; $minute_format = '%02d';
$minute_value_format = '%02d'; $minute_value_format = '%02d';
$second_format = '%02d'; $second_format = '%02d';
$second_value_format = '%02d'; $second_value_format = '%02d';
$hour_size = null; $hour_size = null;
$minute_size = null; $minute_size = null;
$second_size = null; $second_size = null;
$meridian_size = null; $meridian_size = null;
$all_empty = null; $all_empty = null;
$hour_empty = null; $hour_empty = null;
$minute_empty = null; $minute_empty = null;
$second_empty = null; $second_empty = null;
$meridian_empty = null; $meridian_empty = null;
$all_id = null; $all_id = null;
$hour_id = null; $hour_id = null;
$minute_id = null; $minute_id = null;
$second_id = null; $second_id = null;
$meridian_id = null; $meridian_id = null;
$use_24_hours = true; $use_24_hours = true;
$minute_interval = 1; $minute_interval = 1;
$second_interval = 1; $second_interval = 1;
$extra_attrs = ''; $extra_attrs = '';
$all_extra = null; $all_extra = null;
$hour_extra = null; $hour_extra = null;
$minute_extra = null; $minute_extra = null;
$second_extra = null; $second_extra = null;
$meridian_extra = null; $meridian_extra = null;
foreach ($params as $_key => $_value) { foreach ($params as $_key => $_value) {
switch ($_key) { switch ($_key) {
case 'time': case 'time':
if (!is_array($_value) && $_value !== null) { if (!is_array($_value) && $_value !== null) {
$template->_checkPlugins(array(array('function' => 'smarty_make_timestamp', $template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'))); array(
array(
'function' => 'smarty_make_timestamp',
'file' => SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'
)
)
);
$time = smarty_make_timestamp($_value); $time = smarty_make_timestamp($_value);
} }
break; break;
case 'prefix': case 'prefix':
case 'field_array': case 'field_array':
case 'field_separator': case 'field_separator':
case 'option_separator': case 'option_separator':
case 'all_extra': case 'all_extra':
case 'hour_extra': case 'hour_extra':
case 'minute_extra': case 'minute_extra':
case 'second_extra': case 'second_extra':
case 'meridian_extra': case 'meridian_extra':
case 'all_empty': case 'all_empty':
case 'hour_empty': case 'hour_empty':
case 'minute_empty': case 'minute_empty':
case 'second_empty': case 'second_empty':
case 'meridian_empty': case 'meridian_empty':
case 'all_id': case 'all_id':
case 'hour_id': case 'hour_id':
case 'minute_id': case 'minute_id':
case 'second_id': case 'second_id':
case 'meridian_id': case 'meridian_id':
case 'hour_format': case 'hour_format':
case 'hour_value_format': case 'hour_value_format':
case 'minute_format': case 'minute_format':
@ -116,7 +114,6 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
case 'second_value_format': case 'second_value_format':
$$_key = (string)$_value; $$_key = (string)$_value;
break; break;
case 'display_hours': case 'display_hours':
case 'display_minutes': case 'display_minutes':
case 'display_seconds': case 'display_seconds':
@ -124,17 +121,14 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
case 'use_24_hours': case 'use_24_hours':
$$_key = (bool)$_value; $$_key = (bool)$_value;
break; break;
case 'minute_interval': case 'minute_interval':
case 'second_interval': case 'second_interval':
case 'hour_size': case 'hour_size':
case 'minute_size': case 'minute_size':
case 'second_size': case 'second_size':
case 'meridian_size': case 'meridian_size':
$$_key = (int)$_value; $$_key = (int)$_value;
break; break;
default: default:
if (!is_array($_value)) { if (!is_array($_value)) {
$extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"'; $extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"';
@ -144,13 +138,14 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
break; break;
} }
} }
if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) { if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) {
if (isset($params[ 'time' ][ $prefix . 'Hour' ])) { if (isset($params[ 'time' ][ $prefix . 'Hour' ])) {
// $_REQUEST[$field_array] given // $_REQUEST[$field_array] given
foreach (array('H' => 'Hour', foreach (array(
'H' => 'Hour',
'i' => 'Minute', 'i' => 'Minute',
's' => 'Second') as $_elementKey => $_elementName) { 's' => 'Second'
) as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName); $_variableName = '_' . strtolower($_elementName);
$$_variableName = $$_variableName =
isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] : isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] :
@ -163,9 +158,11 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time)); list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
} elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Hour' ])) { } elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Hour' ])) {
// $_REQUEST given // $_REQUEST given
foreach (array('H' => 'Hour', foreach (array(
'H' => 'Hour',
'i' => 'Minute', 'i' => 'Minute',
's' => 'Second') as $_elementKey => $_elementName) { 's' => 'Second'
) as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName); $_variableName = '_' . strtolower($_elementName);
$$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ? $$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ?
$params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey); $params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey);
@ -187,7 +184,6 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
} else { } else {
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time)); list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
} }
// generate hour <select> // generate hour <select>
if ($display_hours) { if ($display_hours) {
$_html_hours = ''; $_html_hours = '';
@ -199,42 +195,37 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
if ($hour_extra) { if ($hour_extra) {
$_extra .= ' ' . $hour_extra; $_extra .= ' ' . $hour_extra;
} }
$_html_hours = '<select name="' . $_name . '"'; $_html_hours = '<select name="' . $_name . '"';
if ($hour_id !== null || $all_id !== null) { if ($hour_id !== null || $all_id !== null) {
$_html_hours .= ' id="' . $_html_hours .= ' id="' .
smarty_function_escape_special_chars($hour_id !== null ? ($hour_id ? $hour_id : $_name) : smarty_function_escape_special_chars(
($all_id ? ($all_id . $_name) : $_name)) . '"'; $hour_id !== null ? ($hour_id ? $hour_id : $_name) :
($all_id ? ($all_id . $_name) : $_name)
) . '"';
} }
if ($hour_size) { if ($hour_size) {
$_html_hours .= ' size="' . $hour_size . '"'; $_html_hours .= ' size="' . $hour_size . '"';
} }
$_html_hours .= $_extra . $extra_attrs . '>' . $option_separator; $_html_hours .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($hour_empty) || isset($all_empty)) { if (isset($hour_empty) || isset($all_empty)) {
$_html_hours .= '<option value="">' . (isset($hour_empty) ? $hour_empty : $all_empty) . '</option>' . $_html_hours .= '<option value="">' . (isset($hour_empty) ? $hour_empty : $all_empty) . '</option>' .
$option_separator; $option_separator;
} }
$start = $use_24_hours ? 0 : 1; $start = $use_24_hours ? 0 : 1;
$end = $use_24_hours ? 23 : 12; $end = $use_24_hours ? 23 : 12;
for ($i = $start; $i <= $end; $i++) { for ($i = $start; $i <= $end; $i++) {
$_val = sprintf('%02d', $i); $_val = sprintf('%02d', $i);
$_text = $hour_format === '%02d' ? $_val : sprintf($hour_format, $i); $_text = $hour_format === '%02d' ? $_val : sprintf($hour_format, $i);
$_value = $hour_value_format === '%02d' ? $_val : sprintf($hour_value_format, $i); $_value = $hour_value_format === '%02d' ? $_val : sprintf($hour_value_format, $i);
if (!$use_24_hours) { if (!$use_24_hours) {
$_hour12 = $_hour == 0 ? 12 : ($_hour <= 12 ? $_hour : $_hour - 12); $_hour12 = $_hour == 0 ? 12 : ($_hour <= 12 ? $_hour : $_hour - 12);
} }
$selected = $_hour !== null ? ($use_24_hours ? $_hour == $_val : $_hour12 == $_val) : null; $selected = $_hour !== null ? ($use_24_hours ? $_hour == $_val : $_hour12 == $_val) : null;
$_html_hours .= '<option value="' . $_value . '"' . ($selected ? ' selected="selected"' : '') . '>' . $_html_hours .= '<option value="' . $_value . '"' . ($selected ? ' selected="selected"' : '') . '>' .
$_text . '</option>' . $option_separator; $_text . '</option>' . $option_separator;
} }
$_html_hours .= '</select>'; $_html_hours .= '</select>';
} }
// generate minute <select> // generate minute <select>
if ($display_minutes) { if ($display_minutes) {
$_html_minutes = ''; $_html_minutes = '';
@ -246,24 +237,23 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
if ($minute_extra) { if ($minute_extra) {
$_extra .= ' ' . $minute_extra; $_extra .= ' ' . $minute_extra;
} }
$_html_minutes = '<select name="' . $_name . '"'; $_html_minutes = '<select name="' . $_name . '"';
if ($minute_id !== null || $all_id !== null) { if ($minute_id !== null || $all_id !== null) {
$_html_minutes .= ' id="' . smarty_function_escape_special_chars($minute_id !== null ? $_html_minutes .= ' id="' . smarty_function_escape_special_chars(
$minute_id !== null ?
($minute_id ? $minute_id : $_name) : ($minute_id ? $minute_id : $_name) :
($all_id ? ($all_id . $_name) : ($all_id ? ($all_id . $_name) :
$_name)) . '"'; $_name)
) . '"';
} }
if ($minute_size) { if ($minute_size) {
$_html_minutes .= ' size="' . $minute_size . '"'; $_html_minutes .= ' size="' . $minute_size . '"';
} }
$_html_minutes .= $_extra . $extra_attrs . '>' . $option_separator; $_html_minutes .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($minute_empty) || isset($all_empty)) { if (isset($minute_empty) || isset($all_empty)) {
$_html_minutes .= '<option value="">' . (isset($minute_empty) ? $minute_empty : $all_empty) . '</option>' . $_html_minutes .= '<option value="">' . (isset($minute_empty) ? $minute_empty : $all_empty) . '</option>' .
$option_separator; $option_separator;
} }
$selected = $_minute !== null ? ($_minute - $_minute % $minute_interval) : null; $selected = $_minute !== null ? ($_minute - $_minute % $minute_interval) : null;
for ($i = 0; $i <= 59; $i += $minute_interval) { for ($i = 0; $i <= 59; $i += $minute_interval) {
$_val = sprintf('%02d', $i); $_val = sprintf('%02d', $i);
@ -272,10 +262,8 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
$_html_minutes .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') . $_html_minutes .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator; '>' . $_text . '</option>' . $option_separator;
} }
$_html_minutes .= '</select>'; $_html_minutes .= '</select>';
} }
// generate second <select> // generate second <select>
if ($display_seconds) { if ($display_seconds) {
$_html_seconds = ''; $_html_seconds = '';
@ -287,24 +275,23 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
if ($second_extra) { if ($second_extra) {
$_extra .= ' ' . $second_extra; $_extra .= ' ' . $second_extra;
} }
$_html_seconds = '<select name="' . $_name . '"'; $_html_seconds = '<select name="' . $_name . '"';
if ($second_id !== null || $all_id !== null) { if ($second_id !== null || $all_id !== null) {
$_html_seconds .= ' id="' . smarty_function_escape_special_chars($second_id !== null ? $_html_seconds .= ' id="' . smarty_function_escape_special_chars(
$second_id !== null ?
($second_id ? $second_id : $_name) : ($second_id ? $second_id : $_name) :
($all_id ? ($all_id . $_name) : ($all_id ? ($all_id . $_name) :
$_name)) . '"'; $_name)
) . '"';
} }
if ($second_size) { if ($second_size) {
$_html_seconds .= ' size="' . $second_size . '"'; $_html_seconds .= ' size="' . $second_size . '"';
} }
$_html_seconds .= $_extra . $extra_attrs . '>' . $option_separator; $_html_seconds .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($second_empty) || isset($all_empty)) { if (isset($second_empty) || isset($all_empty)) {
$_html_seconds .= '<option value="">' . (isset($second_empty) ? $second_empty : $all_empty) . '</option>' . $_html_seconds .= '<option value="">' . (isset($second_empty) ? $second_empty : $all_empty) . '</option>' .
$option_separator; $option_separator;
} }
$selected = $_second !== null ? ($_second - $_second % $second_interval) : null; $selected = $_second !== null ? ($_second - $_second % $second_interval) : null;
for ($i = 0; $i <= 59; $i += $second_interval) { for ($i = 0; $i <= 59; $i += $second_interval) {
$_val = sprintf('%02d', $i); $_val = sprintf('%02d', $i);
@ -313,10 +300,8 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
$_html_seconds .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') . $_html_seconds .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator; '>' . $_text . '</option>' . $option_separator;
} }
$_html_seconds .= '</select>'; $_html_seconds .= '</select>';
} }
// generate meridian <select> // generate meridian <select>
if ($display_meridian && !$use_24_hours) { if ($display_meridian && !$use_24_hours) {
$_html_meridian = ''; $_html_meridian = '';
@ -328,36 +313,36 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
if ($meridian_extra) { if ($meridian_extra) {
$_extra .= ' ' . $meridian_extra; $_extra .= ' ' . $meridian_extra;
} }
$_html_meridian = '<select name="' . $_name . '"'; $_html_meridian = '<select name="' . $_name . '"';
if ($meridian_id !== null || $all_id !== null) { if ($meridian_id !== null || $all_id !== null) {
$_html_meridian .= ' id="' . smarty_function_escape_special_chars($meridian_id !== null ? $_html_meridian .= ' id="' . smarty_function_escape_special_chars(
$meridian_id !== null ?
($meridian_id ? $meridian_id : ($meridian_id ? $meridian_id :
$_name) : $_name) :
($all_id ? ($all_id . $_name) : ($all_id ? ($all_id . $_name) :
$_name)) . '"'; $_name)
) . '"';
} }
if ($meridian_size) { if ($meridian_size) {
$_html_meridian .= ' size="' . $meridian_size . '"'; $_html_meridian .= ' size="' . $meridian_size . '"';
} }
$_html_meridian .= $_extra . $extra_attrs . '>' . $option_separator; $_html_meridian .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($meridian_empty) || isset($all_empty)) { if (isset($meridian_empty) || isset($all_empty)) {
$_html_meridian .= '<option value="">' . (isset($meridian_empty) ? $meridian_empty : $all_empty) . $_html_meridian .= '<option value="">' . (isset($meridian_empty) ? $meridian_empty : $all_empty) .
'</option>' . $option_separator; '</option>' . $option_separator;
} }
$_html_meridian .= '<option value="am"' . ($_hour > 0 && $_hour < 12 ? ' selected="selected"' : '') . $_html_meridian .= '<option value="am"' . ($_hour > 0 && $_hour < 12 ? ' selected="selected"' : '') .
'>AM</option>' . $option_separator . '<option value="pm"' . '>AM</option>' . $option_separator . '<option value="pm"' .
($_hour < 12 ? '' : ' selected="selected"') . '>PM</option>' . $option_separator . ($_hour < 12 ? '' : ' selected="selected"') . '>PM</option>' . $option_separator .
'</select>'; '</select>';
} }
$_html = ''; $_html = '';
foreach (array('_html_hours', foreach (array(
'_html_hours',
'_html_minutes', '_html_minutes',
'_html_seconds', '_html_seconds',
'_html_meridian') as $k) { '_html_meridian'
) as $k) {
if (isset($$k)) { if (isset($$k)) {
if ($_html) { if ($_html) {
$_html .= $field_separator; $_html .= $field_separator;
@ -365,6 +350,5 @@ function smarty_function_html_select_time($params, Smarty_Internal_Template $tem
$_html .= $$k; $_html .= $$k;
} }
} }
return $_html; return $_html;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFunction * @subpackage PluginsFunction
*/ */
/** /**
* Smarty {html_table} function plugin * Smarty {html_table} function plugin
* Type: function * Type: function
@ -35,7 +34,6 @@
* {table loop=$data cols=4 tr_attr='"bgcolor=red"'} * {table loop=$data cols=4 tr_attr='"bgcolor=red"'}
* {table loop=$data cols="first,second,third" tr_attr=$colors} * {table loop=$data cols="first,second,third" tr_attr=$colors}
* *
*
* @author Monte Ohrt <monte at ohrt dot com> * @author Monte Ohrt <monte at ohrt dot com>
* @author credit to Messju Mohr <messju at lammfellpuschen dot de> * @author credit to Messju Mohr <messju at lammfellpuschen dot de>
* @author credit to boots <boots dot smarty at yahoo dot com> * @author credit to boots <boots dot smarty at yahoo dot com>
@ -61,19 +59,15 @@ function smarty_function_html_table($params)
$inner = 'cols'; $inner = 'cols';
$caption = ''; $caption = '';
$loop = null; $loop = null;
if (!isset($params[ 'loop' ])) { if (!isset($params[ 'loop' ])) {
trigger_error("html_table: missing 'loop' parameter", E_USER_WARNING); trigger_error("html_table: missing 'loop' parameter", E_USER_WARNING);
return; return;
} }
foreach ($params as $_key => $_value) { foreach ($params as $_key => $_value) {
switch ($_key) { switch ($_key) {
case 'loop': case 'loop':
$$_key = (array)$_value; $$_key = (array)$_value;
break; break;
case 'cols': case 'cols':
if (is_array($_value) && !empty($_value)) { if (is_array($_value) && !empty($_value)) {
$cols = $_value; $cols = $_value;
@ -87,11 +81,9 @@ function smarty_function_html_table($params)
$cols_count = $cols; $cols_count = $cols;
} }
break; break;
case 'rows': case 'rows':
$$_key = (int)$_value; $$_key = (int)$_value;
break; break;
case 'table_attr': case 'table_attr':
case 'trailpad': case 'trailpad':
case 'hdir': case 'hdir':
@ -100,7 +92,6 @@ function smarty_function_html_table($params)
case 'caption': case 'caption':
$$_key = (string)$_value; $$_key = (string)$_value;
break; break;
case 'tr_attr': case 'tr_attr':
case 'td_attr': case 'td_attr':
case 'th_attr': case 'th_attr':
@ -108,7 +99,6 @@ function smarty_function_html_table($params)
break; break;
} }
} }
$loop_count = count($loop); $loop_count = count($loop);
if (empty($params[ 'rows' ])) { if (empty($params[ 'rows' ])) {
/* no rows specified */ /* no rows specified */
@ -119,17 +109,13 @@ function smarty_function_html_table($params)
$cols_count = ceil($loop_count / $rows); $cols_count = ceil($loop_count / $rows);
} }
} }
$output = "<table $table_attr>\n"; $output = "<table $table_attr>\n";
if (!empty($caption)) { if (!empty($caption)) {
$output .= '<caption>' . $caption . "</caption>\n"; $output .= '<caption>' . $caption . "</caption>\n";
} }
if (is_array($cols)) { if (is_array($cols)) {
$cols = ($hdir === 'right') ? $cols : array_reverse($cols); $cols = ($hdir === 'right') ? $cols : array_reverse($cols);
$output .= "<thead><tr>\n"; $output .= "<thead><tr>\n";
for ($r = 0; $r < $cols_count; $r++) { for ($r = 0; $r < $cols_count; $r++) {
$output .= '<th' . smarty_function_html_table_cycle('th', $th_attr, $r) . '>'; $output .= '<th' . smarty_function_html_table_cycle('th', $th_attr, $r) . '>';
$output .= $cols[ $r ]; $output .= $cols[ $r ];
@ -137,19 +123,16 @@ function smarty_function_html_table($params)
} }
$output .= "</tr></thead>\n"; $output .= "</tr></thead>\n";
} }
$output .= "<tbody>\n"; $output .= "<tbody>\n";
for ($r = 0; $r < $rows; $r++) { for ($r = 0; $r < $rows; $r++) {
$output .= "<tr" . smarty_function_html_table_cycle('tr', $tr_attr, $r) . ">\n"; $output .= "<tr" . smarty_function_html_table_cycle('tr', $tr_attr, $r) . ">\n";
$rx = ($vdir === 'down') ? $r * $cols_count : ($rows - 1 - $r) * $cols_count; $rx = ($vdir === 'down') ? $r * $cols_count : ($rows - 1 - $r) * $cols_count;
for ($c = 0; $c < $cols_count; $c++) { for ($c = 0; $c < $cols_count; $c++) {
$x = ($hdir === 'right') ? $rx + $c : $rx + $cols_count - 1 - $c; $x = ($hdir === 'right') ? $rx + $c : $rx + $cols_count - 1 - $c;
if ($inner !== 'cols') { if ($inner !== 'cols') {
/* shuffle x to loop over rows*/ /* shuffle x to loop over rows*/
$x = floor($x / $cols_count) + ($x % $cols_count) * $rows; $x = floor($x / $cols_count) + ($x % $cols_count) * $rows;
} }
if ($x < $loop_count) { if ($x < $loop_count) {
$output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">" . $loop[ $x ] . "</td>\n"; $output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">" . $loop[ $x ] . "</td>\n";
} else { } else {
@ -160,9 +143,9 @@ function smarty_function_html_table($params)
} }
$output .= "</tbody>\n"; $output .= "</tbody>\n";
$output .= "</table>\n"; $output .= "</table>\n";
return $output; return $output;
} }
/** /**
* @param $name * @param $name
* @param $var * @param $var
@ -177,6 +160,5 @@ function smarty_function_html_table_cycle($name, $var, $no)
} else { } else {
$ret = $var[ $no % count($var) ]; $ret = $var[ $no % count($var) ];
} }
return ($ret) ? ' ' . $ret : ''; return ($ret) ? ' ' . $ret : '';
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFunction * @subpackage PluginsFunction
*/ */
/** /**
* Smarty {mailto} function plugin * Smarty {mailto} function plugin
* Type: function * Type: function
@ -37,7 +36,6 @@
* {mailto address="me@domain.com" cc="you@domain.com,they@domain.com"} * {mailto address="me@domain.com" cc="you@domain.com,they@domain.com"}
* {mailto address="me@domain.com" extra='class="mailto"'} * {mailto address="me@domain.com" extra='class="mailto"'}
* *
*
* @link http://www.smarty.net/manual/en/language.function.mailto.php {mailto} * @link http://www.smarty.net/manual/en/language.function.mailto.php {mailto}
* (Smarty online manual) * (Smarty online manual)
* @version 1.2 * @version 1.2
@ -53,15 +51,12 @@ function smarty_function_mailto($params)
static $_allowed_encoding = static $_allowed_encoding =
array('javascript' => true, 'javascript_charcode' => true, 'hex' => true, 'none' => true); array('javascript' => true, 'javascript_charcode' => true, 'hex' => true, 'none' => true);
$extra = ''; $extra = '';
if (empty($params[ 'address' ])) { if (empty($params[ 'address' ])) {
trigger_error("mailto: missing 'address' parameter", E_USER_WARNING); trigger_error("mailto: missing 'address' parameter", E_USER_WARNING);
return; return;
} else { } else {
$address = $params[ 'address' ]; $address = $params[ 'address' ];
} }
$text = $address; $text = $address;
// netscape and mozilla do not decode %40 (@) in BCC field (bug?) // netscape and mozilla do not decode %40 (@) in BCC field (bug?)
// so, don't encode it. // so, don't encode it.
@ -77,57 +72,48 @@ function smarty_function_mailto($params)
$mail_parms[] = $var . '=' . str_replace($search, $replace, rawurlencode($value)); $mail_parms[] = $var . '=' . str_replace($search, $replace, rawurlencode($value));
} }
break; break;
case 'subject': case 'subject':
case 'newsgroups': case 'newsgroups':
$mail_parms[] = $var . '=' . rawurlencode($value); $mail_parms[] = $var . '=' . rawurlencode($value);
break; break;
case 'extra': case 'extra':
case 'text': case 'text':
$$var = $value; $$var = $value;
// no break
default: default:
} }
} }
if ($mail_parms) { if ($mail_parms) {
$address .= '?' . join('&', $mail_parms); $address .= '?' . join('&', $mail_parms);
} }
$encode = (empty($params[ 'encode' ])) ? 'none' : $params[ 'encode' ]; $encode = (empty($params[ 'encode' ])) ? 'none' : $params[ 'encode' ];
if (!isset($_allowed_encoding[ $encode ])) { if (!isset($_allowed_encoding[ $encode ])) {
trigger_error("mailto: 'encode' parameter must be none, javascript, javascript_charcode or hex", trigger_error(
E_USER_WARNING); "mailto: 'encode' parameter must be none, javascript, javascript_charcode or hex",
E_USER_WARNING
);
return; return;
} }
// FIXME: (rodneyrehm) document.write() excues me what? 1998 has passed! // FIXME: (rodneyrehm) document.write() excues me what? 1998 has passed!
if ($encode === 'javascript') { if ($encode === 'javascript') {
$string = 'document.write(\'<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>\');'; $string = 'document.write(\'<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>\');';
$js_encode = ''; $js_encode = '';
for ($x = 0, $_length = strlen($string); $x < $_length; $x++) { for ($x = 0, $_length = strlen($string); $x < $_length; $x++) {
$js_encode .= '%' . bin2hex($string[ $x ]); $js_encode .= '%' . bin2hex($string[ $x ]);
} }
return '<script type="text/javascript">eval(unescape(\'' . $js_encode . '\'))</script>'; return '<script type="text/javascript">eval(unescape(\'' . $js_encode . '\'))</script>';
} elseif ($encode === 'javascript_charcode') { } elseif ($encode === 'javascript_charcode') {
$string = '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>'; $string = '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
for ($x = 0, $y = strlen($string); $x < $y; $x++) { for ($x = 0, $y = strlen($string); $x < $y; $x++) {
$ord[] = ord($string[ $x ]); $ord[] = ord($string[ $x ]);
} }
$_ret = "<script type=\"text/javascript\" language=\"javascript\">\n" . "{document.write(String.fromCharCode(" . $_ret = "<script type=\"text/javascript\" language=\"javascript\">\n" . "{document.write(String.fromCharCode(" .
implode(',', $ord) . "))" . "}\n" . "</script>\n"; implode(',', $ord) . "))" . "}\n" . "</script>\n";
return $_ret; return $_ret;
} elseif ($encode === 'hex') { } elseif ($encode === 'hex') {
preg_match('!^(.*)(\?.*)$!', $address, $match); preg_match('!^(.*)(\?.*)$!', $address, $match);
if (!empty($match[ 2 ])) { if (!empty($match[ 2 ])) {
trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript.", E_USER_WARNING); trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript.", E_USER_WARNING);
return; return;
} }
$address_encode = ''; $address_encode = '';
@ -142,9 +128,7 @@ function smarty_function_mailto($params)
for ($x = 0, $_length = strlen($text); $x < $_length; $x++) { for ($x = 0, $_length = strlen($text); $x < $_length; $x++) {
$text_encode .= '&#x' . bin2hex($text[ $x ]) . ';'; $text_encode .= '&#x' . bin2hex($text[ $x ]) . ';';
} }
$mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;"; $mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;";
return '<a href="' . $mailto . $address_encode . '" ' . $extra . '>' . $text_encode . '</a>'; return '<a href="' . $mailto . $address_encode . '" ' . $extra . '>' . $text_encode . '</a>';
} else { } else {
// no encoding // no encoding

View File

@ -6,7 +6,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFunction * @subpackage PluginsFunction
*/ */
/** /**
* Smarty {math} function plugin * Smarty {math} function plugin
* Type: function * Type: function
@ -25,66 +24,71 @@
function smarty_function_math($params, $template) function smarty_function_math($params, $template)
{ {
static $_allowed_funcs = static $_allowed_funcs =
array('int' => true, 'abs' => true, 'ceil' => true, 'cos' => true, 'exp' => true, 'floor' => true, array(
'log' => true, 'log10' => true, 'max' => true, 'min' => true, 'pi' => true, 'pow' => true, 'rand' => true, 'int' => true,
'round' => true, 'sin' => true, 'sqrt' => true, 'srand' => true, 'tan' => true); 'abs' => true,
'ceil' => true,
'cos' => true,
'exp' => true,
'floor' => true,
'log' => true,
'log10' => true,
'max' => true,
'min' => true,
'pi' => true,
'pow' => true,
'rand' => true,
'round' => true,
'sin' => true,
'sqrt' => true,
'srand' => true,
'tan' => true
);
// be sure equation parameter is present // be sure equation parameter is present
if (empty($params[ 'equation' ])) { if (empty($params[ 'equation' ])) {
trigger_error("math: missing equation parameter", E_USER_WARNING); trigger_error("math: missing equation parameter", E_USER_WARNING);
return; return;
} }
$equation = $params[ 'equation' ]; $equation = $params[ 'equation' ];
// make sure parenthesis are balanced // make sure parenthesis are balanced
if (substr_count($equation, '(') !== substr_count($equation, ')')) { if (substr_count($equation, '(') !== substr_count($equation, ')')) {
trigger_error("math: unbalanced parenthesis", E_USER_WARNING); trigger_error("math: unbalanced parenthesis", E_USER_WARNING);
return; return;
} }
// disallow backticks // disallow backticks
if (strpos($equation, '`') !== false) { if (strpos($equation, '`') !== false) {
trigger_error("math: backtick character not allowed in equation", E_USER_WARNING); trigger_error("math: backtick character not allowed in equation", E_USER_WARNING);
return; return;
} }
// also disallow dollar signs // also disallow dollar signs
if (strpos($equation, '$') !== false) { if (strpos($equation, '$') !== false) {
trigger_error("math: dollar signs not allowed in equation", E_USER_WARNING); trigger_error("math: dollar signs not allowed in equation", E_USER_WARNING);
return; return;
} }
foreach ($params as $key => $val) { foreach ($params as $key => $val) {
if ($key !== 'equation' && $key !== 'format' && $key !== 'assign') { if ($key !== 'equation' && $key !== 'format' && $key !== 'assign') {
// make sure value is not empty // make sure value is not empty
if (strlen($val) === 0) { if (strlen($val) === 0) {
trigger_error("math: parameter '{$key}' is empty", E_USER_WARNING); trigger_error("math: parameter '{$key}' is empty", E_USER_WARNING);
return; return;
} }
if (!is_numeric($val)) { if (!is_numeric($val)) {
trigger_error("math: parameter '{$key}' is not numeric", E_USER_WARNING); trigger_error("math: parameter '{$key}' is not numeric", E_USER_WARNING);
return; return;
} }
} }
} }
// match all vars in equation, make sure all are passed // match all vars in equation, make sure all are passed
preg_match_all('!(?:0x[a-fA-F0-9]+)|([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)!', $equation, $match); preg_match_all('!(?:0x[a-fA-F0-9]+)|([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)!', $equation, $match);
foreach ($match[ 1 ] as $curr_var) { foreach ($match[ 1 ] as $curr_var) {
if ($curr_var && !isset($params[ $curr_var ]) && !isset($_allowed_funcs[ $curr_var ])) { if ($curr_var && !isset($params[ $curr_var ]) && !isset($_allowed_funcs[ $curr_var ])) {
trigger_error("math: function call '{$curr_var}' not allowed, or missing parameter '{$curr_var}'", E_USER_WARNING); trigger_error(
"math: function call '{$curr_var}' not allowed, or missing parameter '{$curr_var}'",
E_USER_WARNING
);
return; return;
} }
} }
foreach ($params as $key => $val) { foreach ($params as $key => $val) {
if ($key !== 'equation' && $key !== 'format' && $key !== 'assign') { if ($key !== 'equation' && $key !== 'format' && $key !== 'assign') {
$equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation); $equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
@ -92,7 +96,6 @@ function smarty_function_math($params, $template)
} }
$smarty_math_result = null; $smarty_math_result = null;
eval("\$smarty_math_result = " . $equation . ";"); eval("\$smarty_math_result = " . $equation . ";");
if (empty($params[ 'format' ])) { if (empty($params[ 'format' ])) {
if (empty($params[ 'assign' ])) { if (empty($params[ 'assign' ])) {
return $smarty_math_result; return $smarty_math_result;

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifier * @subpackage PluginsModifier
*/ */
/** /**
* Smarty capitalize modifier plugin * Smarty capitalize modifier plugin
* Type: modifier * Type: modifier
@ -29,50 +28,75 @@ function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = fals
$upper_string = mb_convert_case($string, MB_CASE_TITLE, Smarty::$_CHARSET); $upper_string = mb_convert_case($string, MB_CASE_TITLE, Smarty::$_CHARSET);
} else { } else {
// uppercase word breaks // uppercase word breaks
$upper_string = preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER, $upper_string = preg_replace_callback(
'smarty_mod_cap_mbconvert_cb', $string); "!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER,
'smarty_mod_cap_mbconvert_cb',
$string
);
} }
// check uc_digits case // check uc_digits case
if (!$uc_digits) { if (!$uc_digits) {
if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches, if (preg_match_all(
PREG_OFFSET_CAPTURE)) { "!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER,
$string,
$matches,
PREG_OFFSET_CAPTURE
)
) {
foreach ($matches[ 1 ] as $match) { foreach ($matches[ 1 ] as $match) {
$upper_string = $upper_string =
substr_replace($upper_string, mb_strtolower($match[ 0 ], Smarty::$_CHARSET), $match[ 1 ], substr_replace(
strlen($match[ 0 ])); $upper_string,
mb_strtolower($match[ 0 ], Smarty::$_CHARSET),
$match[ 1 ],
strlen($match[ 0 ])
);
} }
} }
} }
$upper_string = $upper_string =
preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_mbconvert2_cb', preg_replace_callback(
$upper_string); "!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER,
'smarty_mod_cap_mbconvert2_cb',
$upper_string
);
return $upper_string; return $upper_string;
} }
// lowercase first // lowercase first
if ($lc_rest) { if ($lc_rest) {
$string = strtolower($string); $string = strtolower($string);
} }
// uppercase (including hyphenated words) // uppercase (including hyphenated words)
$upper_string = $upper_string =
preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst_cb', preg_replace_callback(
$string); "!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER,
'smarty_mod_cap_ucfirst_cb',
$string
);
// check uc_digits case // check uc_digits case
if (!$uc_digits) { if (!$uc_digits) {
if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches, if (preg_match_all(
PREG_OFFSET_CAPTURE)) { "!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER,
$string,
$matches,
PREG_OFFSET_CAPTURE
)
) {
foreach ($matches[ 1 ] as $match) { foreach ($matches[ 1 ] as $match) {
$upper_string = $upper_string =
substr_replace($upper_string, strtolower($match[ 0 ]), $match[ 1 ], strlen($match[ 0 ])); substr_replace($upper_string, strtolower($match[ 0 ]), $match[ 1 ], strlen($match[ 0 ]));
} }
} }
} }
$upper_string = preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst2_cb', $upper_string = preg_replace_callback(
$upper_string); "!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER,
'smarty_mod_cap_ucfirst2_cb',
$upper_string
);
return $upper_string; return $upper_string;
} }
/* /**
* *
* Bug: create_function() use exhausts memory when used in long loops * Bug: create_function() use exhausts memory when used in long loops
* Fix: use declared functions for callbacks instead of using create_function() * Fix: use declared functions for callbacks instead of using create_function()
@ -89,6 +113,7 @@ function smarty_mod_cap_mbconvert_cb($matches)
{ {
return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 2 ]), MB_CASE_UPPER, Smarty::$_CHARSET); return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 2 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
} }
/** /**
* @param $matches * @param $matches
* *
@ -98,6 +123,7 @@ function smarty_mod_cap_mbconvert2_cb($matches)
{ {
return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 3 ]), MB_CASE_UPPER, Smarty::$_CHARSET); return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 3 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
} }
/** /**
* @param $matches * @param $matches
* *
@ -107,6 +133,7 @@ function smarty_mod_cap_ucfirst_cb($matches)
{ {
return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 2 ])); return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 2 ]));
} }
/** /**
* @param $matches * @param $matches
* *

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifier * @subpackage PluginsModifier
*/ */
/** /**
* Smarty date_format modifier plugin * Smarty date_format modifier plugin
* Type: modifier * Type: modifier
@ -38,7 +37,7 @@ function smarty_modifier_date_format($string, $format = null, $default_date = ''
static $is_loaded = false; static $is_loaded = false;
if (!$is_loaded) { if (!$is_loaded) {
if (!is_callable('smarty_make_timestamp')) { if (!is_callable('smarty_make_timestamp')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php'); include_once SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php';
} }
$is_loaded = true; $is_loaded = true;
} }
@ -51,20 +50,24 @@ function smarty_modifier_date_format($string, $format = null, $default_date = ''
} }
if ($formatter === 'strftime' || ($formatter === 'auto' && strpos($format, '%') !== false)) { if ($formatter === 'strftime' || ($formatter === 'auto' && strpos($format, '%') !== false)) {
if (Smarty::$_IS_WINDOWS) { if (Smarty::$_IS_WINDOWS) {
$_win_from = array('%D', $_win_from = array(
'%D',
'%h', '%h',
'%n', '%n',
'%r', '%r',
'%R', '%R',
'%t', '%t',
'%T'); '%T'
$_win_to = array('%m/%d/%y', );
$_win_to = array(
'%m/%d/%y',
'%b', '%b',
"\n", "\n",
'%I:%M:%S %p', '%I:%M:%S %p',
'%H:%M', '%H:%M',
"\t", "\t",
'%H:%M:%S'); '%H:%M:%S'
);
if (strpos($format, '%e') !== false) { if (strpos($format, '%e') !== false) {
$_win_from[] = '%e'; $_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $timestamp)); $_win_to[] = sprintf('%\' 2d', date('j', $timestamp));
@ -75,7 +78,6 @@ function smarty_modifier_date_format($string, $format = null, $default_date = ''
} }
$format = str_replace($_win_from, $_win_to, $format); $format = str_replace($_win_from, $_win_to, $format);
} }
return strftime($format, $timestamp); return strftime($format, $timestamp);
} else { } else {
return date($format, $timestamp); return date($format, $timestamp);

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage Debug * @subpackage Debug
*/ */
/** /**
* Smarty debug_print_var modifier plugin * Smarty debug_print_var modifier plugin
* Type: modifier * Type: modifier
@ -38,7 +37,6 @@ function smarty_modifier_debug_print_var($var, $max = 10, $length = 40, $depth =
$depth--; $depth--;
} }
break; break;
case 'object': case 'object':
$object_vars = get_object_vars($var); $object_vars = get_object_vars($var);
$results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>'; $results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>';
@ -56,7 +54,6 @@ function smarty_modifier_debug_print_var($var, $max = 10, $length = 40, $depth =
$depth--; $depth--;
} }
break; break;
case 'boolean': case 'boolean':
case 'NULL': case 'NULL':
case 'resource': case 'resource':
@ -71,12 +68,10 @@ function smarty_modifier_debug_print_var($var, $max = 10, $length = 40, $depth =
} }
$results = '<i>' . $results . '</i>'; $results = '<i>' . $results . '</i>';
break; break;
case 'integer': case 'integer':
case 'float': case 'float':
$results = htmlspecialchars((string)$var); $results = htmlspecialchars((string)$var);
break; break;
case 'string': case 'string':
$results = strtr($var, $_replace); $results = strtr($var, $_replace);
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
@ -88,10 +83,8 @@ function smarty_modifier_debug_print_var($var, $max = 10, $length = 40, $depth =
$results = substr($var, 0, $length - 3) . '...'; $results = substr($var, 0, $length - 3) . '...';
} }
} }
$results = htmlspecialchars('"' . $results . '"', ENT_QUOTES, Smarty::$_CHARSET); $results = htmlspecialchars('"' . $results . '"', ENT_QUOTES, Smarty::$_CHARSET);
break; break;
case 'unknown type': case 'unknown type':
default: default:
$results = strtr((string)$var, $_replace); $results = strtr((string)$var, $_replace);
@ -104,9 +97,7 @@ function smarty_modifier_debug_print_var($var, $max = 10, $length = 40, $depth =
$results = substr($results, 0, $length - 3) . '...'; $results = substr($results, 0, $length - 3) . '...';
} }
} }
$results = htmlspecialchars($results, ENT_QUOTES, Smarty::$_CHARSET); $results = htmlspecialchars($results, ENT_QUOTES, Smarty::$_CHARSET);
} }
return $results; return $results;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifier * @subpackage PluginsModifier
*/ */
/** /**
* Smarty escape modifier plugin * Smarty escape modifier plugin
* Type: modifier * Type: modifier
@ -30,11 +29,9 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
if ($_double_encode === null) { if ($_double_encode === null) {
$_double_encode = version_compare(PHP_VERSION, '5.2.3', '>='); $_double_encode = version_compare(PHP_VERSION, '5.2.3', '>=');
} }
if (!$char_set) { if (!$char_set) {
$char_set = Smarty::$_CHARSET; $char_set = Smarty::$_CHARSET;
} }
switch ($esc_type) { switch ($esc_type) {
case 'html': case 'html':
if ($_double_encode) { if ($_double_encode) {
@ -48,14 +45,21 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
// php <5.2.3 - prevent double encoding // php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string); $string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set); $string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%', $string = str_replace(
'%%%SMARTY_END%%%'), array('&', array(
';'), $string); '%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'
),
array(
'&',
';'
),
$string
);
return $string; return $string;
} }
} }
// no break
case 'htmlall': case 'htmlall':
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
// mb_convert_encoding ignores htmlspecialchars() // mb_convert_encoding ignores htmlspecialchars()
@ -71,18 +75,23 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string); $string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set); $string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string = $string =
str_replace(array('%%%SMARTY_START%%%', str_replace(
'%%%SMARTY_END%%%'), array('&', array(
';'), $string); '%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'
),
array(
'&',
';'
),
$string
);
return $string; return $string;
} }
} }
// htmlentities() won't convert everything, so use mb_convert_encoding // htmlentities() won't convert everything, so use mb_convert_encoding
return mb_convert_encoding($string, 'HTML-ENTITIES', $char_set); return mb_convert_encoding($string, 'HTML-ENTITIES', $char_set);
} }
// no MBString fallback // no MBString fallback
if ($_double_encode) { if ($_double_encode) {
return htmlentities($string, ENT_QUOTES, $char_set, $double_encode); return htmlentities($string, ENT_QUOTES, $char_set, $double_encode);
@ -92,24 +101,28 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
} else { } else {
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string); $string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlentities($string, ENT_QUOTES, $char_set); $string = htmlentities($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%', $string = str_replace(
'%%%SMARTY_END%%%'), array('&', array(
';'), $string); '%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'
),
array(
'&',
';'
),
$string
);
return $string; return $string;
} }
} }
// no break
case 'url': case 'url':
return rawurlencode($string); return rawurlencode($string);
case 'urlpathinfo': case 'urlpathinfo':
return str_replace('%2F', '/', rawurlencode($string)); return str_replace('%2F', '/', rawurlencode($string));
case 'quotes': case 'quotes':
// escape unescaped single quotes // escape unescaped single quotes
return preg_replace("%(?<!\\\\)'%", "\\'", $string); return preg_replace("%(?<!\\\\)'%", "\\'", $string);
case 'hex': case 'hex':
// escape every byte into hex // escape every byte into hex
// Note that the UTF-8 encoded character ä will be represented as %c3%a4 // Note that the UTF-8 encoded character ä will be represented as %c3%a4
@ -118,15 +131,13 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
for ($x = 0; $x < $_length; $x++) { for ($x = 0; $x < $_length; $x++) {
$return .= '%' . bin2hex($string[ $x ]); $return .= '%' . bin2hex($string[ $x ]);
} }
return $return; return $return;
case 'hexentity': case 'hexentity':
$return = ''; $return = '';
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
if (!$is_loaded_1) { if (!$is_loaded_1) {
if (!is_callable('smarty_mb_to_unicode')) { if (!is_callable('smarty_mb_to_unicode')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php'); include_once SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php';
} }
$is_loaded_1 = true; $is_loaded_1 = true;
} }
@ -134,7 +145,6 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) { foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#x' . strtoupper(dechex($unicode)) . ';'; $return .= '&#x' . strtoupper(dechex($unicode)) . ';';
} }
return $return; return $return;
} }
// no MBString fallback // no MBString fallback
@ -142,15 +152,13 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
for ($x = 0; $x < $_length; $x++) { for ($x = 0; $x < $_length; $x++) {
$return .= '&#x' . bin2hex($string[ $x ]) . ';'; $return .= '&#x' . bin2hex($string[ $x ]) . ';';
} }
return $return; return $return;
case 'decentity': case 'decentity':
$return = ''; $return = '';
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
if (!$is_loaded_1) { if (!$is_loaded_1) {
if (!is_callable('smarty_mb_to_unicode')) { if (!is_callable('smarty_mb_to_unicode')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php'); include_once SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php';
} }
$is_loaded_1 = true; $is_loaded_1 = true;
} }
@ -158,7 +166,6 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) { foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#' . $unicode . ';'; $return .= '&#' . $unicode . ';';
} }
return $return; return $return;
} }
// no MBString fallback // no MBString fallback
@ -166,42 +173,59 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
for ($x = 0; $x < $_length; $x++) { for ($x = 0; $x < $_length; $x++) {
$return .= '&#' . ord($string[ $x ]) . ';'; $return .= '&#' . ord($string[ $x ]) . ';';
} }
return $return; return $return;
case 'javascript': case 'javascript':
// escape quotes and backslashes, newlines, etc. // escape quotes and backslashes, newlines, etc.
return strtr($string, array('\\' => '\\\\', return strtr(
$string,
array(
'\\' => '\\\\',
"'" => "\\'", "'" => "\\'",
'"' => '\\"', '"' => '\\"',
"\r" => '\\r', "\r" => '\\r',
"\n" => '\\n', "\n" => '\\n',
'</' => '<\/')); '</' => '<\/'
)
);
case 'mail': case 'mail':
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
if (!$is_loaded_2) { if (!$is_loaded_2) {
if (!is_callable('smarty_mb_str_replace')) { if (!is_callable('smarty_mb_str_replace')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php'); include_once SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php';
} }
$is_loaded_2 = true; $is_loaded_2 = true;
} }
return smarty_mb_str_replace(array('@', return smarty_mb_str_replace(
'.'), array(' [AT] ', array(
' [DOT] '), $string); '@',
'.'
),
array(
' [AT] ',
' [DOT] '
),
$string
);
} }
// no MBString fallback // no MBString fallback
return str_replace(array('@', return str_replace(
'.'), array(' [AT] ', array(
' [DOT] '), $string); '@',
'.'
),
array(
' [AT] ',
' [DOT] '
),
$string
);
case 'nonstd': case 'nonstd':
// escape non-standard chars, such as ms document quotes // escape non-standard chars, such as ms document quotes
$return = ''; $return = '';
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
if (!$is_loaded_1) { if (!$is_loaded_1) {
if (!is_callable('smarty_mb_to_unicode')) { if (!is_callable('smarty_mb_to_unicode')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php'); include_once SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php';
} }
$is_loaded_1 = true; $is_loaded_1 = true;
} }
@ -212,10 +236,8 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
$return .= chr($unicode); $return .= chr($unicode);
} }
} }
return $return; return $return;
} }
$_length = strlen($string); $_length = strlen($string);
for ($_i = 0; $_i < $_length; $_i++) { for ($_i = 0; $_i < $_length; $_i++) {
$_ord = ord(substr($string, $_i, 1)); $_ord = ord(substr($string, $_i, 1));
@ -226,9 +248,7 @@ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $
$return .= substr($string, $_i, 1); $return .= substr($string, $_i, 1);
} }
} }
return $return; return $return;
default: default:
return $string; return $string;
} }

View File

@ -11,7 +11,6 @@
* Name: mb_wordwrap * Name: mb_wordwrap
* Purpose: Wrap a string to a given number of characters * Purpose: Wrap a string to a given number of characters
* *
* @link http://php.net/manual/en/function.wordwrap.php for similarity * @link http://php.net/manual/en/function.wordwrap.php for similarity
* *
* @param string $str the string to wrap * @param string $str the string to wrap
@ -30,30 +29,28 @@ function smarty_modifier_mb_wordwrap($str, $width = 75, $break = "\n", $cut = fa
$t = ''; $t = '';
$_previous = false; $_previous = false;
$_space = false; $_space = false;
foreach ($tokens as $_token) { foreach ($tokens as $_token) {
$token_length = mb_strlen($_token, Smarty::$_CHARSET); $token_length = mb_strlen($_token, Smarty::$_CHARSET);
$_tokens = array($_token); $_tokens = array($_token);
if ($token_length > $width) { if ($token_length > $width) {
if ($cut) { if ($cut) {
$_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER, $_tokens = preg_split(
'!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER,
$_token, $_token,
-1, -1,
PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE); PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE
);
} }
} }
foreach ($_tokens as $token) { foreach ($_tokens as $token) {
$_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token); $_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token);
$token_length = mb_strlen($token, Smarty::$_CHARSET); $token_length = mb_strlen($token, Smarty::$_CHARSET);
$length += $token_length; $length += $token_length;
if ($length > $width) { if ($length > $width) {
// remove space before inserted break // remove space before inserted break
if ($_previous) { if ($_previous) {
$t = mb_substr($t, 0, -1, Smarty::$_CHARSET); $t = mb_substr($t, 0, -1, Smarty::$_CHARSET);
} }
if (!$_space) { if (!$_space) {
// add the break before the token // add the break before the token
if (!empty($t)) { if (!empty($t)) {
@ -70,6 +67,5 @@ function smarty_modifier_mb_wordwrap($str, $width = 75, $break = "\n", $cut = fa
$t .= $token; $t .= $token;
} }
} }
return $t; return $t;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifier * @subpackage PluginsModifier
*/ */
/** /**
* Smarty regex_replace modifier plugin * Smarty regex_replace modifier plugin
* Type: modifier * Type: modifier
@ -32,7 +31,6 @@ function smarty_modifier_regex_replace($string, $search, $replace, $limit = - 1)
} else { } else {
$search = _smarty_regex_replace_check($search); $search = _smarty_regex_replace_check($search);
} }
return preg_replace($search, $replace, $string, $limit); return preg_replace($search, $replace, $string, $limit);
} }
@ -53,6 +51,5 @@ function _smarty_regex_replace_check($search)
if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[ 1 ], 'e') !== false)) { if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[ 1 ], 'e') !== false)) {
$search = substr($search, 0, -strlen($match[ 1 ])) . preg_replace('![e\s]+!', '', $match[ 1 ]); $search = substr($search, 0, -strlen($match[ 1 ])) . preg_replace('![e\s]+!', '', $match[ 1 ]);
} }
return $search; return $search;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifier * @subpackage PluginsModifier
*/ */
/** /**
* Smarty replace modifier plugin * Smarty replace modifier plugin
* Type: modifier * Type: modifier
@ -28,12 +27,11 @@ function smarty_modifier_replace($string, $search, $replace)
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
if (!$is_loaded) { if (!$is_loaded) {
if (!is_callable('smarty_mb_str_replace')) { if (!is_callable('smarty_mb_str_replace')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php'); include_once SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php';
} }
$is_loaded = true; $is_loaded = true;
} }
return smarty_mb_str_replace($search, $replace, $string); return smarty_mb_str_replace($search, $replace, $string);
} }
return str_replace($search, $replace, $string); return str_replace($search, $replace, $string);
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifier * @subpackage PluginsModifier
*/ */
/** /**
* Smarty spacify modifier plugin * Smarty spacify modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifier * @subpackage PluginsModifier
*/ */
/** /**
* Smarty truncate modifier plugin * Smarty truncate modifier plugin
* Type: modifier * Type: modifier
@ -30,25 +29,24 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
if ($length === 0) { if ($length === 0) {
return ''; return '';
} }
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
if (mb_strlen($string, Smarty::$_CHARSET) > $length) { if (mb_strlen($string, Smarty::$_CHARSET) > $length) {
$length -= min($length, mb_strlen($etc, Smarty::$_CHARSET)); $length -= min($length, mb_strlen($etc, Smarty::$_CHARSET));
if (!$break_words && !$middle) { if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/' . Smarty::$_UTF8_MODIFIER, '', $string = preg_replace(
mb_substr($string, 0, $length + 1, Smarty::$_CHARSET)); '/\s+?(\S+)?$/' . Smarty::$_UTF8_MODIFIER,
'',
mb_substr($string, 0, $length + 1, Smarty::$_CHARSET)
);
} }
if (!$middle) { if (!$middle) {
return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc; return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc;
} }
return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc . return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc .
mb_substr($string, -$length / 2, $length, Smarty::$_CHARSET); mb_substr($string, -$length / 2, $length, Smarty::$_CHARSET);
} }
return $string; return $string;
} }
// no MBString fallback // no MBString fallback
if (isset($string[ $length ])) { if (isset($string[ $length ])) {
$length -= min($length, strlen($etc)); $length -= min($length, strlen($etc));
@ -58,9 +56,7 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
if (!$middle) { if (!$middle) {
return substr($string, 0, $length) . $etc; return substr($string, 0, $length) . $etc;
} }
return substr($string, 0, $length / 2) . $etc . substr($string, -$length / 2); return substr($string, 0, $length / 2) . $etc . substr($string, -$length / 2);
} }
return $string; return $string;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty cat modifier plugin * Smarty cat modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,14 +5,14 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty count_characters modifier plugin * Smarty count_characters modifier plugin
* Type: modifier * Type: modifier
* Name: count_characters * Name: count_characters
* Purpose: count the number of characters in a text * Purpose: count the number of characters in a text
* *
* @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual) * @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online
* manual)
* @author Uwe Tews * @author Uwe Tews
* *
* @param array $params parameters * @param array $params parameters

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty count_paragraphs modifier plugin * Smarty count_paragraphs modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty count_sentences modifier plugin * Smarty count_sentences modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty count_words modifier plugin * Smarty count_words modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty default modifier plugin * Smarty default modifier plugin
* Type: modifier * Type: modifier
@ -25,11 +24,9 @@ function smarty_modifiercompiler_default($params)
if (!isset($params[ 1 ])) { if (!isset($params[ 1 ])) {
$params[ 1 ] = "''"; $params[ 1 ] = "''";
} }
array_shift($params); array_shift($params);
foreach ($params as $param) { foreach ($params as $param) {
$output = '(($tmp = @' . $output . ')===null||$tmp===\'\' ? ' . $param . ' : $tmp)'; $output = '(($tmp = @' . $output . ')===null||$tmp===\'\' ? ' . $param . ' : $tmp)';
} }
return $output; return $output;
} }

View File

@ -24,21 +24,24 @@ function smarty_modifiercompiler_escape($params, Smarty_Internal_TemplateCompile
{ {
static $_double_encode = null; static $_double_encode = null;
static $is_loaded = false; static $is_loaded = false;
$compiler->template->_checkPlugins(array(array('function' => 'smarty_literal_compiler_param', $compiler->template->_checkPlugins(
'file' => SMARTY_PLUGINS_DIR . 'shared.literal_compiler_param.php'))); array(
array(
'function' => 'smarty_literal_compiler_param',
'file' => SMARTY_PLUGINS_DIR . 'shared.literal_compiler_param.php'
)
)
);
if ($_double_encode === null) { if ($_double_encode === null) {
$_double_encode = version_compare(PHP_VERSION, '5.2.3', '>='); $_double_encode = version_compare(PHP_VERSION, '5.2.3', '>=');
} }
try { try {
$esc_type = smarty_literal_compiler_param($params, 1, 'html'); $esc_type = smarty_literal_compiler_param($params, 1, 'html');
$char_set = smarty_literal_compiler_param($params, 2, Smarty::$_CHARSET); $char_set = smarty_literal_compiler_param($params, 2, Smarty::$_CHARSET);
$double_encode = smarty_literal_compiler_param($params, 3, true); $double_encode = smarty_literal_compiler_param($params, 3, true);
if (!$char_set) { if (!$char_set) {
$char_set = Smarty::$_CHARSET; $char_set = Smarty::$_CHARSET;
} }
switch ($esc_type) { switch ($esc_type) {
case 'html': case 'html':
if ($_double_encode) { if ($_double_encode) {
@ -49,7 +52,7 @@ function smarty_modifiercompiler_escape($params, Smarty_Internal_TemplateCompile
} else { } else {
// fall back to modifier.escape.php // fall back to modifier.escape.php
} }
// no break
case 'htmlall': case 'htmlall':
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
if ($_double_encode) { if ($_double_encode) {
@ -65,7 +68,6 @@ function smarty_modifiercompiler_escape($params, Smarty_Internal_TemplateCompile
// fall back to modifier.escape.php // fall back to modifier.escape.php
} }
} }
// no MBString fallback // no MBString fallback
if ($_double_encode) { if ($_double_encode) {
// php >=5.2.3 - go native // php >=5.2.3 - go native
@ -77,27 +79,23 @@ function smarty_modifiercompiler_escape($params, Smarty_Internal_TemplateCompile
} else { } else {
// fall back to modifier.escape.php // fall back to modifier.escape.php
} }
// no break
case 'url': case 'url':
return 'rawurlencode(' . $params[ 0 ] . ')'; return 'rawurlencode(' . $params[ 0 ] . ')';
case 'urlpathinfo': case 'urlpathinfo':
return 'str_replace("%2F", "/", rawurlencode(' . $params[ 0 ] . '))'; return 'str_replace("%2F", "/", rawurlencode(' . $params[ 0 ] . '))';
case 'quotes': case 'quotes':
// escape unescaped single quotes // escape unescaped single quotes
return 'preg_replace("%(?<!\\\\\\\\)\'%", "\\\'",' . $params[ 0 ] . ')'; return 'preg_replace("%(?<!\\\\\\\\)\'%", "\\\'",' . $params[ 0 ] . ')';
case 'javascript': case 'javascript':
// escape quotes and backslashes, newlines, etc. // escape quotes and backslashes, newlines, etc.
return 'strtr(' . $params[ 0 ] . return 'strtr(' .
$params[ 0 ] .
', array("\\\\" => "\\\\\\\\", "\'" => "\\\\\'", "\"" => "\\\\\"", "\\r" => "\\\\r", "\\n" => "\\\n", "</" => "<\/" ))'; ', array("\\\\" => "\\\\\\\\", "\'" => "\\\\\'", "\"" => "\\\\\"", "\\r" => "\\\\r", "\\n" => "\\\n", "</" => "<\/" ))';
} }
} } catch (SmartyException $e) {
catch (SmartyException $e) {
// pass through to regular plugin fallback // pass through to regular plugin fallback
} }
// could not optimize |escape call, so fallback to regular plugin // could not optimize |escape call, so fallback to regular plugin
if ($compiler->template->caching && ($compiler->tag_nocache | $compiler->nocache)) { if ($compiler->template->caching && ($compiler->tag_nocache | $compiler->nocache)) {
$compiler->required_plugins[ 'nocache' ][ 'escape' ][ 'modifier' ][ 'file' ] = $compiler->required_plugins[ 'nocache' ][ 'escape' ][ 'modifier' ][ 'file' ] =
@ -110,6 +108,5 @@ function smarty_modifiercompiler_escape($params, Smarty_Internal_TemplateCompile
$compiler->required_plugins[ 'compiled' ][ 'escape' ][ 'modifier' ][ 'function' ] = $compiler->required_plugins[ 'compiled' ][ 'escape' ][ 'modifier' ][ 'function' ] =
'smarty_modifier_escape'; 'smarty_modifier_escape';
} }
return 'smarty_modifier_escape(' . join(', ', $params) . ')'; return 'smarty_modifier_escape(' . join(', ', $params) . ')';
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty from_charset modifier plugin * Smarty from_charset modifier plugin
* Type: modifier * Type: modifier
@ -24,10 +23,8 @@ function smarty_modifiercompiler_from_charset($params)
// FIXME: (rodneyrehm) shouldn't this throw an error? // FIXME: (rodneyrehm) shouldn't this throw an error?
return $params[ 0 ]; return $params[ 0 ];
} }
if (!isset($params[ 1 ])) { if (!isset($params[ 1 ])) {
$params[ 1 ] = '"ISO-8859-1"'; $params[ 1 ] = '"ISO-8859-1"';
} }
return 'mb_convert_encoding(' . $params[ 0 ] . ', "' . addslashes(Smarty::$_CHARSET) . '", ' . $params[ 1 ] . ')'; return 'mb_convert_encoding(' . $params[ 0 ] . ', "' . addslashes(Smarty::$_CHARSET) . '", ' . $params[ 1 ] . ')';
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty indent modifier plugin * Smarty indent modifier plugin
* Type: modifier * Type: modifier
@ -19,7 +18,6 @@
* *
* @return string with compiled code * @return string with compiled code
*/ */
function smarty_modifiercompiler_indent($params) function smarty_modifiercompiler_indent($params)
{ {
if (!isset($params[ 1 ])) { if (!isset($params[ 1 ])) {
@ -28,6 +26,5 @@ function smarty_modifiercompiler_indent($params)
if (!isset($params[ 2 ])) { if (!isset($params[ 2 ])) {
$params[ 2 ] = "' '"; $params[ 2 ] = "' '";
} }
return 'preg_replace(\'!^!m\',str_repeat(' . $params[ 2 ] . ',' . $params[ 1 ] . '),' . $params[ 0 ] . ')'; return 'preg_replace(\'!^!m\',str_repeat(' . $params[ 2 ] . ',' . $params[ 1 ] . '),' . $params[ 0 ] . ')';
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty lower modifier plugin * Smarty lower modifier plugin
* Type: modifier * Type: modifier
@ -20,7 +19,6 @@
* *
* @return string with compiled code * @return string with compiled code
*/ */
function smarty_modifiercompiler_lower($params) function smarty_modifiercompiler_lower($params)
{ {
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty noprint modifier plugin * Smarty noprint modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty string_format modifier plugin * Smarty string_format modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty strip modifier plugin * Smarty strip modifier plugin
* Type: modifier * Type: modifier
@ -22,12 +21,10 @@
* *
* @return string with compiled code * @return string with compiled code
*/ */
function smarty_modifiercompiler_strip($params) function smarty_modifiercompiler_strip($params)
{ {
if (!isset($params[ 1 ])) { if (!isset($params[ 1 ])) {
$params[ 1 ] = "' '"; $params[ 1 ] = "' '";
} }
return "preg_replace('!\s+!" . Smarty::$_UTF8_MODIFIER . "', {$params[1]},{$params[0]})"; return "preg_replace('!\s+!" . Smarty::$_UTF8_MODIFIER . "', {$params[1]},{$params[0]})";
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty strip_tags modifier plugin * Smarty strip_tags modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty to_charset modifier plugin * Smarty to_charset modifier plugin
* Type: modifier * Type: modifier
@ -24,10 +23,8 @@ function smarty_modifiercompiler_to_charset($params)
// FIXME: (rodneyrehm) shouldn't this throw an error? // FIXME: (rodneyrehm) shouldn't this throw an error?
return $params[ 0 ]; return $params[ 0 ];
} }
if (!isset($params[ 1 ])) { if (!isset($params[ 1 ])) {
$params[ 1 ] = '"ISO-8859-1"'; $params[ 1 ] = '"ISO-8859-1"';
} }
return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 1 ] . ', "' . addslashes(Smarty::$_CHARSET) . '")'; return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 1 ] . ', "' . addslashes(Smarty::$_CHARSET) . '")';
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty unescape modifier plugin * Smarty unescape modifier plugin
* Type: modifier * Type: modifier
@ -28,22 +27,17 @@ function smarty_modifiercompiler_unescape($params)
} else { } else {
$params[ 2 ] = "'{$params[ 2 ]}'"; $params[ 2 ] = "'{$params[ 2 ]}'";
} }
switch (trim($params[ 1 ], '"\'')) { switch (trim($params[ 1 ], '"\'')) {
case 'entity': case 'entity':
case 'htmlall': case 'htmlall':
if (Smarty::$_MBSTRING) { if (Smarty::$_MBSTRING) {
return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 2 ] . ', \'HTML-ENTITIES\')'; return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 2 ] . ', \'HTML-ENTITIES\')';
} }
return 'html_entity_decode(' . $params[ 0 ] . ', ENT_NOQUOTES, ' . $params[ 2 ] . ')'; return 'html_entity_decode(' . $params[ 0 ] . ', ENT_NOQUOTES, ' . $params[ 2 ] . ')';
case 'html': case 'html':
return 'htmlspecialchars_decode(' . $params[ 0 ] . ', ENT_QUOTES)'; return 'htmlspecialchars_decode(' . $params[ 0 ] . ', ENT_QUOTES)';
case 'url': case 'url':
return 'rawurldecode(' . $params[ 0 ] . ')'; return 'rawurldecode(' . $params[ 0 ] . ')';
default: default:
return $params[ 0 ]; return $params[ 0 ];
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsModifierCompiler * @subpackage PluginsModifierCompiler
*/ */
/** /**
* Smarty upper modifier plugin * Smarty upper modifier plugin
* Type: modifier * Type: modifier

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsFilter * @subpackage PluginsFilter
*/ */
/** /**
* Smarty trimwhitespace outputfilter plugin * Smarty trimwhitespace outputfilter plugin
* Trim unnecessary whitespace from HTML markup. * Trim unnecessary whitespace from HTML markup.
@ -22,43 +21,46 @@ function smarty_outputfilter_trimwhitespace($source)
$store = array(); $store = array();
$_store = 0; $_store = 0;
$_offset = 0; $_offset = 0;
// Unify Line-Breaks to \n // Unify Line-Breaks to \n
$source = preg_replace('/\015\012|\015|\012/', "\n", $source); $source = preg_replace('/\015\012|\015|\012/', "\n", $source);
// capture Internet Explorer and KnockoutJS Conditional Comments // capture Internet Explorer and KnockoutJS Conditional Comments
if (preg_match_all('#<!--((\[[^\]]+\]>.*?<!\[[^\]]+\])|(\s*/?ko\s+.+))-->#is', $source, $matches, if (preg_match_all(
PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { '#<!--((\[[^\]]+\]>.*?<!\[[^\]]+\])|(\s*/?ko\s+.+))-->#is',
$source,
$matches,
PREG_OFFSET_CAPTURE | PREG_SET_ORDER
)
) {
foreach ($matches as $match) { foreach ($matches as $match) {
$store[] = $match[ 0 ][ 0 ]; $store[] = $match[ 0 ][ 0 ];
$_length = strlen($match[ 0 ][ 0 ]); $_length = strlen($match[ 0 ][ 0 ]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@'; $replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length); $source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length);
$_offset += $_length - strlen($replace); $_offset += $_length - strlen($replace);
$_store++; $_store++;
} }
} }
// Strip all HTML-Comments // Strip all HTML-Comments
// yes, even the ones in <script> - see http://stackoverflow.com/a/808850/515124 // yes, even the ones in <script> - see http://stackoverflow.com/a/808850/515124
$source = preg_replace('#<!--.*?-->#ms', '', $source); $source = preg_replace('#<!--.*?-->#ms', '', $source);
// capture html elements not to be messed with // capture html elements not to be messed with
$_offset = 0; $_offset = 0;
if (preg_match_all('#(<script[^>]*>.*?</script[^>]*>)|(<textarea[^>]*>.*?</textarea[^>]*>)|(<pre[^>]*>.*?</pre[^>]*>)#is', if (preg_match_all(
$source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { '#(<script[^>]*>.*?</script[^>]*>)|(<textarea[^>]*>.*?</textarea[^>]*>)|(<pre[^>]*>.*?</pre[^>]*>)#is',
$source,
$matches,
PREG_OFFSET_CAPTURE | PREG_SET_ORDER
)
) {
foreach ($matches as $match) { foreach ($matches as $match) {
$store[] = $match[ 0 ][ 0 ]; $store[] = $match[ 0 ][ 0 ];
$_length = strlen($match[ 0 ][ 0 ]); $_length = strlen($match[ 0 ][ 0 ]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@'; $replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length); $source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length);
$_offset += $_length - strlen($replace); $_offset += $_length - strlen($replace);
$_store++; $_store++;
} }
} }
$expressions = array(// replace multiple spaces between tags by a single space $expressions = array(// replace multiple spaces between tags by a single space
// can't remove them entirely, becaue that might break poorly implemented CSS display:inline-block elements // can't remove them entirely, becaue that might break poorly implemented CSS display:inline-block elements
'#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1 \2', '#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1 \2',
@ -66,24 +68,22 @@ function smarty_outputfilter_trimwhitespace($source)
'#(([a-z0-9]\s*=\s*("[^"]*?")|(\'[^\']*?\'))|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \5', '#(([a-z0-9]\s*=\s*("[^"]*?")|(\'[^\']*?\'))|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \5',
// note: for some very weird reason trim() seems to remove spaces inside attributes. // note: for some very weird reason trim() seems to remove spaces inside attributes.
// maybe a \0 byte or something is interfering? // maybe a \0 byte or something is interfering?
'#^\s+<#Ss' => '<', '#>\s+$#Ss' => '>',); '#^\s+<#Ss' => '<',
'#>\s+$#Ss' => '>',
);
$source = preg_replace(array_keys($expressions), array_values($expressions), $source); $source = preg_replace(array_keys($expressions), array_values($expressions), $source);
// note: for some very weird reason trim() seems to remove spaces inside attributes. // note: for some very weird reason trim() seems to remove spaces inside attributes.
// maybe a \0 byte or something is interfering? // maybe a \0 byte or something is interfering?
// $source = trim( $source ); // $source = trim( $source );
$_offset = 0; $_offset = 0;
if (preg_match_all('#@!@SMARTY:([0-9]+):SMARTY@!@#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { if (preg_match_all('#@!@SMARTY:([0-9]+):SMARTY@!@#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) { foreach ($matches as $match) {
$_length = strlen($match[ 0 ][ 0 ]); $_length = strlen($match[ 0 ][ 0 ]);
$replace = $store[ $match[ 1 ][ 0 ] ]; $replace = $store[ $match[ 1 ][ 0 ] ];
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] + $_offset, $_length); $source = substr_replace($source, $replace, $match[ 0 ][ 1 ] + $_offset, $_length);
$_offset += strlen($replace) - $_length; $_offset += strlen($replace) - $_length;
$_store++; $_store++;
} }
} }
return $source; return $source;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsShared * @subpackage PluginsShared
*/ */
/** /**
* escape_special_chars common function * escape_special_chars common function
* Function: smarty_function_escape_special_chars * Function: smarty_function_escape_special_chars
@ -29,6 +28,5 @@ function smarty_function_escape_special_chars($string)
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string); $string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
} }
} }
return $string; return $string;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsShared * @subpackage PluginsShared
*/ */
/** /**
* evaluate compiler parameter * evaluate compiler parameter
* *
@ -25,12 +24,12 @@ function smarty_literal_compiler_param($params, $index, $default = null)
} }
// test if param is a literal // test if param is a literal
if (!preg_match('/^([\'"]?)[a-zA-Z0-9-]+(\\1)$/', $params[ $index ])) { if (!preg_match('/^([\'"]?)[a-zA-Z0-9-]+(\\1)$/', $params[ $index ])) {
throw new SmartyException('$param[' . $index . throw new SmartyException(
'] is not a literal and is thus not evaluatable at compile time'); '$param[' . $index .
'] is not a literal and is thus not evaluatable at compile time'
);
} }
$t = null; $t = null;
eval("\$t = " . $params[ $index ] . ";"); eval("\$t = " . $params[ $index ] . ";");
return $t; return $t;
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsShared * @subpackage PluginsShared
*/ */
/** /**
* Function: smarty_make_timestamp * Function: smarty_make_timestamp
* Purpose: used by other smarty functions to make a timestamp from a string. * Purpose: used by other smarty functions to make a timestamp from a string.
@ -21,14 +20,20 @@ function smarty_make_timestamp($string)
if (empty($string)) { if (empty($string)) {
// use "now": // use "now":
return time(); return time();
} elseif ($string instanceof DateTime || } elseif ($string instanceof DateTime
(interface_exists('DateTimeInterface', false) && $string instanceof DateTimeInterface) || (interface_exists('DateTimeInterface', false) && $string instanceof DateTimeInterface)
) { ) {
return (int)$string->format('U'); // PHP 5.2 BC return (int)$string->format('U'); // PHP 5.2 BC
} elseif (strlen($string) === 14 && ctype_digit($string)) { } elseif (strlen($string) === 14 && ctype_digit($string)) {
// it is mysql timestamp format of YYYYMMDDHHMMSS? // it is mysql timestamp format of YYYYMMDDHHMMSS?
return mktime(substr($string, 8, 2), substr($string, 10, 2), substr($string, 12, 2), substr($string, 4, 2), return mktime(
substr($string, 6, 2), substr($string, 0, 4)); substr($string, 8, 2),
substr($string, 10, 2),
substr($string, 12, 2),
substr($string, 4, 2),
substr($string, 6, 2),
substr($string, 0, 4)
);
} elseif (is_numeric($string)) { } elseif (is_numeric($string)) {
// it is a numeric string, we handle it as timestamp // it is a numeric string, we handle it as timestamp
return (int)$string; return (int)$string;
@ -39,7 +44,6 @@ function smarty_make_timestamp($string)
// strtotime() was not able to parse $string, use "now": // strtotime() was not able to parse $string, use "now":
return time(); return time();
} }
return $time; return $time;
} }
} }

View File

@ -5,7 +5,6 @@
* @package Smarty * @package Smarty
* @subpackage PluginsShared * @subpackage PluginsShared
*/ */
/** /**
* convert characters to their decimal unicode equivalents * convert characters to their decimal unicode equivalents
* *
@ -24,7 +23,6 @@ function smarty_mb_to_unicode($string, $encoding = null)
} else { } else {
$expanded = mb_convert_encoding($string, 'UTF-32BE'); $expanded = mb_convert_encoding($string, 'UTF-32BE');
} }
return unpack('N*', $expanded); return unpack('N*', $expanded);
} }
@ -49,6 +47,5 @@ function smarty_mb_from_unicode($unicode, $encoding = null)
$character = pack('N*', $utf32be); $character = pack('N*', $utf32be);
$t .= mb_convert_encoding($character, $encoding, 'UTF-32BE'); $t .= mb_convert_encoding($character, $encoding, 'UTF-32BE');
} }
return $t; return $t;
} }

View File

@ -25,12 +25,12 @@ abstract class Smarty_CacheResource
/** /**
* populate Cached Object with meta data from Resource * populate Cached Object with meta data from Resource
* *
* @param Smarty_Template_Cached $cached cached object * @param \Smarty_Template_Cached $cached cached object
* @param Smarty_Internal_Template $_template template object * @param Smarty_Internal_Template $_template template object
* *
* @return void * @return void
*/ */
abstract public function populate(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template); abstract public function populate(\Smarty_Template_Cached $cached, Smarty_Internal_Template $_template);
/** /**
* populate Cached Object with timestamp and exists from Resource * populate Cached Object with timestamp and exists from Resource
@ -50,8 +50,11 @@ abstract class Smarty_CacheResource
* *
* @return boolean true or false if the cached content does not exist * @return boolean true or false if the cached content does not exist
*/ */
abstract public function process(Smarty_Internal_Template $_template, Smarty_Template_Cached $cached = null, abstract public function process(
$update = false); Smarty_Internal_Template $_template,
Smarty_Template_Cached $cached = null,
$update = false
);
/** /**
* Write the rendered template output to cache * Write the rendered template output to cache
@ -70,7 +73,7 @@ abstract class Smarty_CacheResource
* *
* @return string content * @return string content
*/ */
abstract function readCachedContent(Smarty_Internal_Template $_template); abstract public function readCachedContent(Smarty_Internal_Template $_template);
/** /**
* Return cached content * Return cached content
@ -87,7 +90,6 @@ abstract class Smarty_CacheResource
$unifunc($_template); $unifunc($_template);
return ob_get_clean(); return ob_get_clean();
} }
return null; return null;
} }
@ -133,7 +135,6 @@ abstract class Smarty_CacheResource
} }
sleep(1); sleep(1);
} }
return $hadLock; return $hadLock;
} }
@ -193,12 +194,10 @@ abstract class Smarty_CacheResource
if (!isset($type)) { if (!isset($type)) {
$type = $smarty->caching_type; $type = $smarty->caching_type;
} }
// try smarty's cache // try smarty's cache
if (isset($smarty->_cache[ 'cacheresource_handlers' ][ $type ])) { if (isset($smarty->_cache[ 'cacheresource_handlers' ][ $type ])) {
return $smarty->_cache[ 'cacheresource_handlers' ][ $type ]; return $smarty->_cache[ 'cacheresource_handlers' ][ $type ];
} }
// try registered resource // try registered resource
if (isset($smarty->registered_cache_resources[ $type ])) { if (isset($smarty->registered_cache_resources[ $type ])) {
// do not cache these instances as they may vary from instance to instance // do not cache these instances as they may vary from instance to instance

View File

@ -106,12 +106,17 @@ abstract class Smarty_CacheResource_Custom extends Smarty_CacheResource
if ($mtime !== null) { if ($mtime !== null) {
$cached->timestamp = $mtime; $cached->timestamp = $mtime;
$cached->exists = !!$cached->timestamp; $cached->exists = !!$cached->timestamp;
return; return;
} }
$timestamp = null; $timestamp = null;
$this->fetch($cached->filepath, $cached->source->name, $cached->cache_id, $cached->compile_id, $cached->content, $this->fetch(
$timestamp); $cached->filepath,
$cached->source->name,
$cached->cache_id,
$cached->compile_id,
$cached->content,
$timestamp
);
$cached->timestamp = isset($timestamp) ? $timestamp : false; $cached->timestamp = isset($timestamp) ? $timestamp : false;
$cached->exists = !!$cached->timestamp; $cached->exists = !!$cached->timestamp;
} }
@ -125,24 +130,31 @@ abstract class Smarty_CacheResource_Custom extends Smarty_CacheResource
* *
* @return boolean true or false if the cached content does not exist * @return boolean true or false if the cached content does not exist
*/ */
public function process(Smarty_Internal_Template $_smarty_tpl, Smarty_Template_Cached $cached = null, public function process(
$update = false) Smarty_Internal_Template $_smarty_tpl,
{ Smarty_Template_Cached $cached = null,
$update = false
) {
if (!$cached) { if (!$cached) {
$cached = $_smarty_tpl->cached; $cached = $_smarty_tpl->cached;
} }
$content = $cached->content ? $cached->content : null; $content = $cached->content ? $cached->content : null;
$timestamp = $cached->timestamp ? $cached->timestamp : null; $timestamp = $cached->timestamp ? $cached->timestamp : null;
if ($content === null || !$timestamp) { if ($content === null || !$timestamp) {
$this->fetch($_smarty_tpl->cached->filepath, $_smarty_tpl->source->name, $_smarty_tpl->cache_id, $this->fetch(
$_smarty_tpl->compile_id, $content, $timestamp); $_smarty_tpl->cached->filepath,
$_smarty_tpl->source->name,
$_smarty_tpl->cache_id,
$_smarty_tpl->compile_id,
$content,
$timestamp
);
} }
if (isset($content)) { if (isset($content)) {
eval('?>' . $content); eval('?>' . $content);
$cached->content = null; $cached->content = null;
return true; return true;
} }
return false; return false;
} }
@ -156,8 +168,14 @@ abstract class Smarty_CacheResource_Custom extends Smarty_CacheResource
*/ */
public function writeCachedContent(Smarty_Internal_Template $_template, $content) public function writeCachedContent(Smarty_Internal_Template $_template, $content)
{ {
return $this->save($_template->cached->filepath, $_template->source->name, $_template->cache_id, return $this->save(
$_template->compile_id, $_template->cache_lifetime, $content); $_template->cached->filepath,
$_template->source->name,
$_template->cache_id,
$_template->compile_id,
$_template->cache_lifetime,
$content
);
} }
/** /**
@ -173,8 +191,14 @@ abstract class Smarty_CacheResource_Custom extends Smarty_CacheResource
$timestamp = null; $timestamp = null;
if ($content === null) { if ($content === null) {
$timestamp = null; $timestamp = null;
$this->fetch($_template->cached->filepath, $_template->source->name, $_template->cache_id, $this->fetch(
$_template->compile_id, $content, $timestamp); $_template->cached->filepath,
$_template->source->name,
$_template->cache_id,
$_template->compile_id,
$content,
$timestamp
);
} }
if (isset($content)) { if (isset($content)) {
return $content; return $content;
@ -210,7 +234,6 @@ abstract class Smarty_CacheResource_Custom extends Smarty_CacheResource
public function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time) public function clear(Smarty $smarty, $resource_name, $cache_id, $compile_id, $exp_time)
{ {
$cache_name = null; $cache_name = null;
if (isset($resource_name)) { if (isset($resource_name)) {
$source = Smarty_Template_Source::load(null, $smarty, $resource_name); $source = Smarty_Template_Source::load(null, $smarty, $resource_name);
if ($source->exists) { if ($source->exists) {
@ -219,7 +242,6 @@ abstract class Smarty_CacheResource_Custom extends Smarty_CacheResource
return 0; return 0;
} }
} }
return $this->delete($cache_name, $cache_id, $compile_id, $exp_time); return $this->delete($cache_name, $cache_id, $compile_id, $exp_time);
} }
@ -235,7 +257,6 @@ abstract class Smarty_CacheResource_Custom extends Smarty_CacheResource
{ {
$id = $cached->lock_id; $id = $cached->lock_id;
$name = $cached->source->name . '.lock'; $name = $cached->source->name . '.lock';
$mtime = $this->fetchTimestamp($id, $name, $cached->cache_id, $cached->compile_id); $mtime = $this->fetchTimestamp($id, $name, $cached->cache_id, $cached->compile_id);
if ($mtime === null) { if ($mtime === null) {
$this->fetch($id, $name, $cached->cache_id, $cached->compile_id, $content, $mtime); $this->fetch($id, $name, $cached->cache_id, $cached->compile_id, $content, $mtime);

View File

@ -56,7 +56,6 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
{ {
$cached->filepath = $_template->source->uid . '#' . $this->sanitize($cached->source->resource) . '#' . $cached->filepath = $_template->source->uid . '#' . $this->sanitize($cached->source->resource) . '#' .
$this->sanitize($cached->cache_id) . '#' . $this->sanitize($cached->compile_id); $this->sanitize($cached->cache_id) . '#' . $this->sanitize($cached->compile_id);
$this->populateTimestamp($cached); $this->populateTimestamp($cached);
} }
@ -69,8 +68,15 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
*/ */
public function populateTimestamp(Smarty_Template_Cached $cached) public function populateTimestamp(Smarty_Template_Cached $cached)
{ {
if (!$this->fetch($cached->filepath, $cached->source->name, $cached->cache_id, $cached->compile_id, $content, if (!$this->fetch(
$timestamp, $cached->source->uid) $cached->filepath,
$cached->source->name,
$cached->cache_id,
$cached->compile_id,
$content,
$timestamp,
$cached->source->uid
)
) { ) {
return; return;
} }
@ -88,27 +94,34 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
* *
* @return boolean true or false if the cached content does not exist * @return boolean true or false if the cached content does not exist
*/ */
public function process(Smarty_Internal_Template $_smarty_tpl, Smarty_Template_Cached $cached = null, public function process(
$update = false) Smarty_Internal_Template $_smarty_tpl,
{ Smarty_Template_Cached $cached = null,
$update = false
) {
if (!$cached) { if (!$cached) {
$cached = $_smarty_tpl->cached; $cached = $_smarty_tpl->cached;
} }
$content = $cached->content ? $cached->content : null; $content = $cached->content ? $cached->content : null;
$timestamp = $cached->timestamp ? $cached->timestamp : null; $timestamp = $cached->timestamp ? $cached->timestamp : null;
if ($content === null || !$timestamp) { if ($content === null || !$timestamp) {
if (!$this->fetch($_smarty_tpl->cached->filepath, $_smarty_tpl->source->name, $_smarty_tpl->cache_id, if (!$this->fetch(
$_smarty_tpl->compile_id, $content, $timestamp, $_smarty_tpl->source->uid) $_smarty_tpl->cached->filepath,
$_smarty_tpl->source->name,
$_smarty_tpl->cache_id,
$_smarty_tpl->compile_id,
$content,
$timestamp,
$_smarty_tpl->source->uid
)
) { ) {
return false; return false;
} }
} }
if (isset($content)) { if (isset($content)) {
eval('?>' . $content); eval('?>' . $content);
return true; return true;
} }
return false; return false;
} }
@ -123,7 +136,6 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
public function writeCachedContent(Smarty_Internal_Template $_template, $content) public function writeCachedContent(Smarty_Internal_Template $_template, $content)
{ {
$this->addMetaTimestamp($content); $this->addMetaTimestamp($content);
return $this->write(array($_template->cached->filepath => $content), $_template->cache_lifetime); return $this->write(array($_template->cached->filepath => $content), $_template->cache_lifetime);
} }
@ -139,8 +151,15 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
$content = $_template->cached->content ? $_template->cached->content : null; $content = $_template->cached->content ? $_template->cached->content : null;
$timestamp = null; $timestamp = null;
if ($content === null) { if ($content === null) {
if (!$this->fetch($_template->cached->filepath, $_template->source->name, $_template->cache_id, if (!$this->fetch(
$_template->compile_id, $content, $timestamp, $_template->source->uid) $_template->cached->filepath,
$_template->source->name,
$_template->cache_id,
$_template->compile_id,
$content,
$timestamp,
$_template->source->uid
)
) { ) {
return false; return false;
} }
@ -204,7 +223,6 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
* *
* @return string filepath of cache file * @return string filepath of cache file
* @throws \SmartyException * @throws \SmartyException
*
*/ */
protected function getTemplateUid(Smarty $smarty, $resource_name) protected function getTemplateUid(Smarty $smarty, $resource_name)
{ {
@ -246,13 +264,18 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
* *
* @return boolean success * @return boolean success
*/ */
protected function fetch($cid, $resource_name = null, $cache_id = null, $compile_id = null, &$content = null, protected function fetch(
&$timestamp = null, $resource_uid = null) $cid,
{ $resource_name = null,
$cache_id = null,
$compile_id = null,
&$content = null,
&$timestamp = null,
$resource_uid = null
) {
$t = $this->read(array($cid)); $t = $this->read(array($cid));
$content = !empty($t[ $cid ]) ? $t[ $cid ] : null; $content = !empty($t[ $cid ]) ? $t[ $cid ] : null;
$timestamp = null; $timestamp = null;
if ($content && ($timestamp = $this->getMetaTimestamp($content))) { if ($content && ($timestamp = $this->getMetaTimestamp($content))) {
$invalidated = $invalidated =
$this->getLatestInvalidationTimestamp($cid, $resource_name, $cache_id, $compile_id, $resource_uid); $this->getLatestInvalidationTimestamp($cid, $resource_name, $cache_id, $compile_id, $resource_uid);
@ -261,7 +284,6 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
$content = null; $content = null;
} }
} }
return !!$content; return !!$content;
} }
@ -306,9 +328,13 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
* *
* @return void * @return void
*/ */
protected function invalidate($cid = null, $resource_name = null, $cache_id = null, $compile_id = null, protected function invalidate(
$resource_uid = null) $cid = null,
{ $resource_name = null,
$cache_id = null,
$compile_id = null,
$resource_uid = null
) {
$now = microtime(true); $now = microtime(true);
$key = null; $key = null;
// invalidate everything // invalidate everything
@ -347,9 +373,13 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
* *
* @return float the microtime the CacheID was invalidated * @return float the microtime the CacheID was invalidated
*/ */
protected function getLatestInvalidationTimestamp($cid, $resource_name = null, $cache_id = null, $compile_id = null, protected function getLatestInvalidationTimestamp(
$resource_uid = null) $cid,
{ $resource_name = null,
$cache_id = null,
$compile_id = null,
$resource_uid = null
) {
// abort if there is no CacheID // abort if there is no CacheID
if (false && !$cid) { if (false && !$cid) {
return 0; return 0;
@ -358,14 +388,12 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
if (!($_cid = $this->listInvalidationKeys($cid, $resource_name, $cache_id, $compile_id, $resource_uid))) { if (!($_cid = $this->listInvalidationKeys($cid, $resource_name, $cache_id, $compile_id, $resource_uid))) {
return 0; return 0;
} }
// there are no InValidationKeys // there are no InValidationKeys
if (!($values = $this->read($_cid))) { if (!($values = $this->read($_cid))) {
return 0; return 0;
} }
// make sure we're dealing with floats // make sure we're dealing with floats
$values = array_map('floatval', $values); $values = array_map('floatval', $values);
return max($values); return max($values);
} }
@ -382,9 +410,13 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
* @return array list of InvalidationKeys * @return array list of InvalidationKeys
* @uses $invalidationKeyPrefix to prepend to each InvalidationKey * @uses $invalidationKeyPrefix to prepend to each InvalidationKey
*/ */
protected function listInvalidationKeys($cid, $resource_name = null, $cache_id = null, $compile_id = null, protected function listInvalidationKeys(
$resource_uid = null) $cid,
{ $resource_name = null,
$cache_id = null,
$compile_id = null,
$resource_uid = null
) {
$t = array('IVK#ALL'); $t = array('IVK#ALL');
$_name = $_compile = '#'; $_name = $_compile = '#';
if ($resource_name) { if ($resource_name) {
@ -418,7 +450,6 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
// skip past delimiter position // skip past delimiter position
$i++; $i++;
} }
return $t; return $t;
} }
@ -434,7 +465,6 @@ abstract class Smarty_CacheResource_KeyValueStore extends Smarty_CacheResource
{ {
$key = 'LOCK#' . $cached->filepath; $key = 'LOCK#' . $cached->filepath;
$data = $this->read(array($key)); $data = $this->read(array($key));
return $data && time() - $data[ $key ] < $smarty->locking_timeout; return $data && time() - $data[ $key ] < $smarty->locking_timeout;
} }

View File

@ -22,7 +22,7 @@ class Smarty_Data extends Smarty_Internal_Data
* *
* @var int * @var int
*/ */
static $count = 0; public static $count = 0;
/** /**
* Data block name * Data block name

View File

@ -7,6 +7,7 @@
* @author Uwe Tews * @author Uwe Tews
* @author Rodney Rehm * @author Rodney Rehm
*/ */
/** /**
* This class does contain all necessary methods for the HTML cache on file system * This class does contain all necessary methods for the HTML cache on file system
* Implements the file system as resource for the HTML cache Version ussing nocache inserts. * Implements the file system as resource for the HTML cache Version ussing nocache inserts.
@ -32,11 +33,17 @@ class Smarty_Internal_CacheResource_File extends Smarty_CacheResource
$_filepath = sha1($source->uid . $smarty->_joined_template_dir); $_filepath = sha1($source->uid . $smarty->_joined_template_dir);
$cached->filepath = $smarty->getCacheDir(); $cached->filepath = $smarty->getCacheDir();
if (isset($_template->cache_id)) { if (isset($_template->cache_id)) {
$cached->filepath .= preg_replace(array('![^\w|]+!', $cached->filepath .= preg_replace(
'![|]+!'), array(
array('_', '![^\w|]+!',
$_compile_dir_sep), '![|]+!'
$_template->cache_id) . $_compile_dir_sep; ),
array(
'_',
$_compile_dir_sep
),
$_template->cache_id
) . $_compile_dir_sep;
} }
if (isset($_template->compile_id)) { if (isset($_template->compile_id)) {
$cached->filepath .= preg_replace('![^\w]+!', '_', $_template->compile_id) . $_compile_dir_sep; $cached->filepath .= preg_replace('![^\w]+!', '_', $_template->compile_id) . $_compile_dir_sep;
@ -87,10 +94,11 @@ class Smarty_Internal_CacheResource_File extends Smarty_CacheResource
* *
* @return boolean true or false if the cached content does not exist * @return boolean true or false if the cached content does not exist
*/ */
public function process(Smarty_Internal_Template $_smarty_tpl, public function process(
Smarty_Internal_Template $_smarty_tpl,
Smarty_Template_Cached $cached = null, Smarty_Template_Cached $cached = null,
$update = false) $update = false
{ ) {
$_smarty_tpl->cached->valid = false; $_smarty_tpl->cached->valid = false;
if ($update && defined('HHVM_VERSION')) { if ($update && defined('HHVM_VERSION')) {
eval('?>' . file_get_contents($_smarty_tpl->cached->filepath)); eval('?>' . file_get_contents($_smarty_tpl->cached->filepath));
@ -111,12 +119,14 @@ class Smarty_Internal_CacheResource_File extends Smarty_CacheResource
*/ */
public function writeCachedContent(Smarty_Internal_Template $_template, $content) public function writeCachedContent(Smarty_Internal_Template $_template, $content)
{ {
if ($_template->smarty->ext->_writeFile->writeFile($_template->cached->filepath, if ($_template->smarty->ext->_writeFile->writeFile(
$_template->cached->filepath,
$content, $content,
$_template->smarty) === true $_template->smarty
) === true
) { ) {
if (function_exists('opcache_invalidate') && if (function_exists('opcache_invalidate')
(!function_exists('ini_get') || strlen(ini_get('opcache.restrict_api'))) < 1 && (!function_exists('ini_get') || strlen(ini_get('opcache.restrict_api'))) < 1
) { ) {
opcache_invalidate($_template->cached->filepath, true); opcache_invalidate($_template->cached->filepath, true);
} elseif (function_exists('apc_compile_file')) { } elseif (function_exists('apc_compile_file')) {

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