3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Fix for bug CRM-392. Not sure if this is the best fix or it will impact
20 * other similar PEAR packages. doubt it
22 if (!class_exists('Smarty')) {
23 require_once 'Smarty/Smarty.class.php';
29 class CRM_Core_Smarty
extends Smarty
{
31 // use print.tpl and bypass the CMS. Civi prints a valid html file
33 // this and all the below bypasses the CMS html surrounding it and assumes we will embed this within other pages
35 // sends the generated html to the chosen pdf engine
37 // this options also skips the enclosing form html and does not
38 // generate any of the hidden fields, most notably qfKey
39 // this is typically used in ajax scripts to embed form snippets based on user choices
41 // this prints a complete form and also generates a qfKey, can we replace this with
42 // snippet = 2?? Does the constant _NOFFORM do anything?
44 // Note: added in v 4.3 with the value '6'
45 // Value changed in 4.5 to 'json' for better readability
46 // @see CRM_Core_Page_AJAX::returnJsonResponse
50 * We only need one instance of this object. So we use the singleton
51 * pattern and cache the instance in this variable
55 static private $_singleton = NULL;
60 * A list of variables ot save temporarily in format (string $name => mixed $value).
64 private $backupFrames = [];
66 private function initialize() {
67 $config = CRM_Core_Config
::singleton();
69 if (isset($config->customTemplateDir
) && $config->customTemplateDir
) {
70 $this->template_dir
= array_merge([$config->customTemplateDir
],
75 $this->template_dir
= $config->templateDir
;
77 $this->compile_dir
= CRM_Utils_File
::addTrailingSlash(CRM_Utils_File
::addTrailingSlash($config->templateCompileDir
) . $this->getLocale());
78 CRM_Utils_File
::createDir($this->compile_dir
);
79 CRM_Utils_File
::restrictAccess($this->compile_dir
);
81 // check and ensure it is writable
82 // else we sometime suppress errors quietly and this results
83 // in blank emails etc
84 if (!is_writable($this->compile_dir
)) {
85 echo "CiviCRM does not have permission to write temp files in {$this->compile_dir}, Exiting";
89 $this->use_sub_dirs
= TRUE;
91 $customPluginsDir = NULL;
92 if (!empty($config->customPHPPathDir
) ||
$config->customPHPPathDir
=== '0') {
94 = $config->customPHPPathDir
. DIRECTORY_SEPARATOR
.
95 'CRM' . DIRECTORY_SEPARATOR
.
96 'Core' . DIRECTORY_SEPARATOR
.
97 'Smarty' . DIRECTORY_SEPARATOR
.
98 'plugins' . DIRECTORY_SEPARATOR
;
99 if (!file_exists($customPluginsDir)) {
100 $customPluginsDir = NULL;
104 $pkgsDir = Civi
::paths()->getVariable('civicrm.packages', 'path');
105 $smartyDir = $pkgsDir . DIRECTORY_SEPARATOR
. 'Smarty' . DIRECTORY_SEPARATOR
;
106 $pluginsDir = __DIR__
. DIRECTORY_SEPARATOR
. 'Smarty' . DIRECTORY_SEPARATOR
. 'plugins' . DIRECTORY_SEPARATOR
;
108 if ($customPluginsDir) {
109 $this->plugins_dir
= [$customPluginsDir, $smartyDir . 'plugins', $pluginsDir];
112 $this->plugins_dir
= [$smartyDir . 'plugins', $pluginsDir];
115 $this->compile_check
= $this->isCheckSmartyIsCompiled();
117 // add the session and the config here
118 $session = CRM_Core_Session
::singleton();
120 $this->assign_by_ref('config', $config);
121 $this->assign_by_ref('session', $session);
123 $tsLocale = CRM_Core_I18n
::getLocale();
124 $this->assign('tsLocale', $tsLocale);
126 // CRM-7163 hack: we don’t display langSwitch on upgrades anyway
127 if (!CRM_Core_Config
::isUpgradeMode()) {
128 $this->assign('langSwitch', CRM_Core_I18n
::uiLanguages());
131 $this->register_function('crmURL', ['CRM_Utils_System', 'crmURL']);
132 if (CRM_Utils_Constant
::value('CIVICRM_SMARTY_DEFAULT_ESCAPE')) {
133 // When default escape is enabled if the core escape is called before
134 // any custom escaping is done the modifier_escape function is not
135 // found, so require_once straight away. Note this was hit on the basic
136 // contribution dashboard from RecentlyViewed.tpl
137 require_once 'Smarty/plugins/modifier.escape.php';
138 if (!isset($this->_plugins
['modifier']['escape'])) {
139 $this->register_modifier('escape', ['CRM_Core_Smarty', 'escape']);
141 $this->default_modifiers
[] = 'escape:"htmlall"';
143 $this->load_filter('pre', 'resetExtScope');
145 $this->assign('crmPermissions', new CRM_Core_Smarty_Permissions());
147 if ($config->debug
) {
148 $this->error_reporting
= E_ALL
;
153 * Static instance provider.
155 * Method providing static instance of SmartTemplate, as
156 * in Singleton pattern.
158 * @return \CRM_Core_Smarty
160 public static function &singleton() {
161 if (!isset(self
::$_singleton)) {
162 self
::$_singleton = new CRM_Core_Smarty();
163 self
::$_singleton->initialize();
165 self
::registerStringResource();
167 return self
::$_singleton;
171 * Executes & returns or displays the template results
173 * @param string $resource_name
174 * @param string $cache_id
175 * @param string $compile_id
176 * @param bool $display
178 * @return bool|mixed|string
180 public function fetch($resource_name, $cache_id = NULL, $compile_id = NULL, $display = FALSE) {
181 if (preg_match('/^(\s+)?string:/', $resource_name)) {
182 $old_security = $this->security
;
183 $this->security
= TRUE;
185 $output = parent
::fetch($resource_name, $cache_id, $compile_id, $display);
186 if (isset($old_security)) {
187 $this->security
= $old_security;
193 * Ensure these variables are set to make it easier to access them without e-notice.
195 * @param array $variables
197 public function ensureVariablesAreAssigned(array $variables): void
{
198 foreach ($variables as $variable) {
199 if (!isset($this->get_template_vars()[$variable])) {
200 $this->assign($variable);
206 * Avoid e-notices on pages with tabs,
207 * by ensuring tabHeader items contain the necessary keys
209 public function addExpectedTabHeaderKeys(): void
{
218 $tabs = $this->get_template_vars('tabHeader');
219 foreach ((array) $tabs as $i => $tab) {
220 $tabs[$i] = array_merge($defaults, $tab);
222 $this->assign('tabHeader', $tabs);
226 * Fetch a template (while using certain variables)
228 * @param string $resource_name
230 * (string $name => mixed $value) variables to export to Smarty.
232 * @return bool|mixed|string
234 public function fetchWith($resource_name, $vars) {
235 $this->pushScope($vars);
237 $result = $this->fetch($resource_name);
239 catch (Exception
$e) {
240 // simulate try { ... } finally { ... }
249 * @param string $name
252 public function appendValue($name, $value) {
253 $currentValue = $this->get_template_vars($name);
254 if (!$currentValue) {
255 $this->assign($name, $value);
258 if (strpos($currentValue, $value) === FALSE) {
259 $this->assign($name, $currentValue . $value);
264 public function clearTemplateVars() {
265 foreach (array_keys($this->_tpl_vars
) as $key) {
266 if ($key == 'config' ||
$key == 'session') {
269 unset($this->_tpl_vars
[$key]);
273 public static function registerStringResource() {
274 require_once 'CRM/Core/Smarty/resources/String.php';
275 civicrm_smarty_register_string_resource();
281 public function addTemplateDir($path) {
282 if (is_array($this->template_dir
)) {
283 array_unshift($this->template_dir
, $path);
286 $this->template_dir
= [$path, $this->template_dir
];
292 * Temporarily assign a list of variables.
295 * $smarty->pushScope(array(
296 * 'first_name' => 'Alice',
297 * 'last_name' => 'roberts',
299 * $html = $smarty->fetch('view-contact.tpl');
300 * $smarty->popScope();
304 * (string $name => mixed $value).
305 * @return CRM_Core_Smarty
308 public function pushScope($vars) {
309 $oldVars = $this->get_template_vars();
311 foreach ($vars as $key => $value) {
312 $backupFrame[$key] = $oldVars[$key] ??
NULL;
314 $this->backupFrames
[] = $backupFrame;
316 $this->assignAll($vars);
322 * Remove any values that were previously pushed.
324 * @return CRM_Core_Smarty
327 public function popScope() {
328 $this->assignAll(array_pop($this->backupFrames
));
334 * (string $name => mixed $value).
335 * @return CRM_Core_Smarty
337 public function assignAll($vars) {
338 foreach ($vars as $key => $value) {
339 $this->assign($key, $value);
345 * Get the locale for translation.
349 private function getLocale() {
350 $tsLocale = CRM_Core_I18n
::getLocale();
351 if (!empty($tsLocale)) {
355 $config = CRM_Core_Config
::singleton();
356 if (!empty($config->lcMessages
)) {
357 return $config->lcMessages
;
364 * Get the compile_check value.
368 private function isCheckSmartyIsCompiled() {
369 // check for define in civicrm.settings.php as FALSE, otherwise returns TRUE
370 return CRM_Utils_Constant
::value('CIVICRM_TEMPLATE_COMPILE_CHECK', TRUE);
374 * Smarty escape modifier plugin.
376 * This replaces the core smarty modifier and basically does a lot of
377 * early-returning before calling the core function.
379 * It early returns on patterns that are common 'no-escape' patterns
380 * in CiviCRM - this list can be honed over time.
382 * It also logs anything that is actually escaped. Since this only kicks
383 * in when CIVICRM_SMARTY_DEFAULT_ESCAPE is defined it is ok to be aggressive
384 * about logging as we mostly care about developers using it at this stage.
386 * Note we don't actually use 'htmlall' anywhere in our tpl layer yet so
387 * anything coming in with this be happening because of the default modifier.
389 * Also note the right way to opt a field OUT of escaping is
390 * ``{$fieldName|smarty:nodefaults}``
391 * This should be used for fields with known html AND for fields where
392 * we are doing empty or isset checks - as otherwise the value is passed for
393 * escaping first so you still get an enotice for 'empty' or a fatal for 'isset'
397 * Purpose: Escape the string according to escapement type
399 * @link http://smarty.php.net/manual/en/language.modifier.escape.php
400 * escape (Smarty online manual)
401 * @author Monte Ohrt <monte at ohrt dot com>
403 * @param string $string
404 * @param string $esc_type
405 * @param string $char_set
409 public static function escape($string, $esc_type = 'html', $char_set = 'UTF-8') {
410 // CiviCRM variables are often arrays - just handle them.
411 // The early return on booleans & numbers is mostly to prevent them being
412 // logged as 'changed' when they are cast to a string.
413 if (!is_scalar($string) ||
empty($string) ||
is_bool($string) ||
is_numeric($string) ||
$esc_type === 'none') {
416 if ($esc_type === 'htmlall') {
417 // 'htmlall' is the nothing-specified default.
418 // Don't escape things we think quickform added.
419 if (strpos($string, '<input') === 0
420 ||
strpos($string, '<select') === 0
421 // Not handling as yet but these ones really should get some love.
422 ||
strpos($string, '<label') === 0
423 ||
strpos($string, '<button') === 0
424 ||
strpos($string, '<span class="crm-frozen-field">') === 0
425 ||
strpos($string, '<textarea') === 0
427 // The ones below this point are hopefully here short term.
428 ||
strpos($string, '<a') === 0
429 // Message templates screen
430 ||
strpos($string, '<span><a href') === 0
431 // Not sure how big a pattern this is - used in Pledge view tab
432 // not sure if it needs escaping
433 ||
strpos($string, ' action="/civicrm/') === 0
434 // eg. Tag edit page, civicrm/admin/financial/financialType/accounts?action=add&reset=1&aid=1
435 ||
strpos($string, ' action="" method="post"') === 0
436 // This seems to be urls...
437 ||
strpos($string, '/civicrm/') === 0
438 // Validation error message - eg. <span class="crm-error">Tournament Fees is a required field.</span>
440 <span class="crm-error">') === 0
441 // e.g from participant tab class="action-item" href=/civicrm/contact/view/participant?reset=1&action=add&cid=142&context=participant
442 ||
strpos($string, 'class="action-item" href=/civicrm/"') === 0
444 // Do not escape the above common patterns.
449 $value = smarty_modifier_escape($string, $esc_type, $char_set);
450 if ($value !== $string) {
451 Civi
::log()->debug('smarty escaping original {original}, escaped {escaped} type {type} charset {charset}', [
452 'original' => $string,
455 'charset' => $char_set,