Merge pull request #22056 from eileenmcnaughton/context
[civicrm-core.git] / CRM / Core / Smarty.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
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
21 */
22 if (!class_exists('Smarty')) {
23 require_once 'Smarty/Smarty.class.php';
24 }
25
26 /**
27 *
28 */
29 class CRM_Core_Smarty extends Smarty {
30 const
31 // use print.tpl and bypass the CMS. Civi prints a valid html file
32 PRINT_PAGE = 1,
33 // this and all the below bypasses the CMS html surrounding it and assumes we will embed this within other pages
34 PRINT_SNIPPET = 2,
35 // sends the generated html to the chosen pdf engine
36 PRINT_PDF = 3,
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
40 PRINT_NOFORM = 4,
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?
43 PRINT_QFKEY = 5,
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
47 PRINT_JSON = 'json';
48
49 /**
50 * We only need one instance of this object. So we use the singleton
51 * pattern and cache the instance in this variable
52 *
53 * @var object
54 */
55 static private $_singleton = NULL;
56
57 /**
58 * Backup frames.
59 *
60 * A list of variables ot save temporarily in format (string $name => mixed $value).
61 *
62 * @var array
63 */
64 private $backupFrames = [];
65
66 /**
67 * Class constructor.
68 *
69 * @return CRM_Core_Smarty
70 */
71 public function __construct() {
72 parent::__construct();
73 }
74
75 private function initialize() {
76 $config = CRM_Core_Config::singleton();
77
78 if (isset($config->customTemplateDir) && $config->customTemplateDir) {
79 $this->template_dir = array_merge([$config->customTemplateDir],
80 $config->templateDir
81 );
82 }
83 else {
84 $this->template_dir = $config->templateDir;
85 }
86 $this->compile_dir = CRM_Utils_File::addTrailingSlash(CRM_Utils_File::addTrailingSlash($config->templateCompileDir) . $this->getLocale());
87 CRM_Utils_File::createDir($this->compile_dir);
88 CRM_Utils_File::restrictAccess($this->compile_dir);
89
90 // check and ensure it is writable
91 // else we sometime suppress errors quietly and this results
92 // in blank emails etc
93 if (!is_writable($this->compile_dir)) {
94 echo "CiviCRM does not have permission to write temp files in {$this->compile_dir}, Exiting";
95 exit();
96 }
97
98 $this->use_sub_dirs = TRUE;
99
100 $customPluginsDir = NULL;
101 if (isset($config->customPHPPathDir)) {
102 $customPluginsDir
103 = $config->customPHPPathDir . DIRECTORY_SEPARATOR .
104 'CRM' . DIRECTORY_SEPARATOR .
105 'Core' . DIRECTORY_SEPARATOR .
106 'Smarty' . DIRECTORY_SEPARATOR .
107 'plugins' . DIRECTORY_SEPARATOR;
108 if (!file_exists($customPluginsDir)) {
109 $customPluginsDir = NULL;
110 }
111 }
112
113 $pkgsDir = Civi::paths()->getVariable('civicrm.packages', 'path');
114 $smartyDir = $pkgsDir . DIRECTORY_SEPARATOR . 'Smarty' . DIRECTORY_SEPARATOR;
115 $pluginsDir = __DIR__ . DIRECTORY_SEPARATOR . 'Smarty' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR;
116
117 if ($customPluginsDir) {
118 $this->plugins_dir = [$customPluginsDir, $smartyDir . 'plugins', $pluginsDir];
119 }
120 else {
121 $this->plugins_dir = [$smartyDir . 'plugins', $pluginsDir];
122 }
123
124 $this->compile_check = $this->isCheckSmartyIsCompiled();
125
126 // add the session and the config here
127 $session = CRM_Core_Session::singleton();
128
129 $this->assign_by_ref('config', $config);
130 $this->assign_by_ref('session', $session);
131
132 $tsLocale = CRM_Core_I18n::getLocale();
133 $this->assign('tsLocale', $tsLocale);
134
135 // CRM-7163 hack: we don’t display langSwitch on upgrades anyway
136 if (!CRM_Core_Config::isUpgradeMode()) {
137 $this->assign('langSwitch', CRM_Core_I18n::uiLanguages());
138 }
139
140 $this->register_function('crmURL', ['CRM_Utils_System', 'crmURL']);
141 if (CRM_Utils_Constant::value('CIVICRM_SMARTY_DEFAULT_ESCAPE')) {
142 if (!isset($this->_plugins['modifier']['escape'])) {
143 $this->register_modifier('escape', ['CRM_Core_Smarty', 'escape']);
144 }
145 $this->default_modifiers[] = 'escape:"htmlall"';
146 }
147 $this->load_filter('pre', 'resetExtScope');
148
149 $this->assign('crmPermissions', new CRM_Core_Smarty_Permissions());
150
151 if ($config->debug) {
152 $this->error_reporting = E_ALL;
153 }
154 }
155
156 /**
157 * Static instance provider.
158 *
159 * Method providing static instance of SmartTemplate, as
160 * in Singleton pattern.
161 *
162 * @return \CRM_Core_Smarty
163 */
164 public static function &singleton() {
165 if (!isset(self::$_singleton)) {
166 self::$_singleton = new CRM_Core_Smarty();
167 self::$_singleton->initialize();
168
169 self::registerStringResource();
170 }
171 return self::$_singleton;
172 }
173
174 /**
175 * Executes & returns or displays the template results
176 *
177 * @param string $resource_name
178 * @param string $cache_id
179 * @param string $compile_id
180 * @param bool $display
181 *
182 * @return bool|mixed|string
183 */
184 public function fetch($resource_name, $cache_id = NULL, $compile_id = NULL, $display = FALSE) {
185 if (preg_match('/^(\s+)?string:/', $resource_name)) {
186 $old_security = $this->security;
187 $this->security = TRUE;
188 }
189 $output = parent::fetch($resource_name, $cache_id, $compile_id, $display);
190 if (isset($old_security)) {
191 $this->security = $old_security;
192 }
193 return $output;
194 }
195
196 /**
197 * Ensure these variables are set to make it easier to access them without e-notice.
198 *
199 * @param array $variables
200 */
201 public function ensureVariablesAreAssigned(array $variables): void {
202 foreach ($variables as $variable) {
203 if (!isset($this->get_template_vars()[$variable])) {
204 $this->assign($variable);
205 }
206 }
207 }
208
209 /**
210 * Fetch a template (while using certain variables)
211 *
212 * @param string $resource_name
213 * @param array $vars
214 * (string $name => mixed $value) variables to export to Smarty.
215 * @throws Exception
216 * @return bool|mixed|string
217 */
218 public function fetchWith($resource_name, $vars) {
219 $this->pushScope($vars);
220 try {
221 $result = $this->fetch($resource_name);
222 }
223 catch (Exception $e) {
224 // simulate try { ... } finally { ... }
225 $this->popScope();
226 throw $e;
227 }
228 $this->popScope();
229 return $result;
230 }
231
232 /**
233 * @param string $name
234 * @param $value
235 */
236 public function appendValue($name, $value) {
237 $currentValue = $this->get_template_vars($name);
238 if (!$currentValue) {
239 $this->assign($name, $value);
240 }
241 else {
242 if (strpos($currentValue, $value) === FALSE) {
243 $this->assign($name, $currentValue . $value);
244 }
245 }
246 }
247
248 public function clearTemplateVars() {
249 foreach (array_keys($this->_tpl_vars) as $key) {
250 if ($key == 'config' || $key == 'session') {
251 continue;
252 }
253 unset($this->_tpl_vars[$key]);
254 }
255 }
256
257 public static function registerStringResource() {
258 require_once 'CRM/Core/Smarty/resources/String.php';
259 civicrm_smarty_register_string_resource();
260 }
261
262 /**
263 * @param $path
264 */
265 public function addTemplateDir($path) {
266 if (is_array($this->template_dir)) {
267 array_unshift($this->template_dir, $path);
268 }
269 else {
270 $this->template_dir = [$path, $this->template_dir];
271 }
272
273 }
274
275 /**
276 * Temporarily assign a list of variables.
277 *
278 * ```
279 * $smarty->pushScope(array(
280 * 'first_name' => 'Alice',
281 * 'last_name' => 'roberts',
282 * ));
283 * $html = $smarty->fetch('view-contact.tpl');
284 * $smarty->popScope();
285 * ```
286 *
287 * @param array $vars
288 * (string $name => mixed $value).
289 * @return CRM_Core_Smarty
290 * @see popScope
291 */
292 public function pushScope($vars) {
293 $oldVars = $this->get_template_vars();
294 $backupFrame = [];
295 foreach ($vars as $key => $value) {
296 $backupFrame[$key] = $oldVars[$key] ?? NULL;
297 }
298 $this->backupFrames[] = $backupFrame;
299
300 $this->assignAll($vars);
301
302 return $this;
303 }
304
305 /**
306 * Remove any values that were previously pushed.
307 *
308 * @return CRM_Core_Smarty
309 * @see pushScope
310 */
311 public function popScope() {
312 $this->assignAll(array_pop($this->backupFrames));
313 return $this;
314 }
315
316 /**
317 * @param array $vars
318 * (string $name => mixed $value).
319 * @return CRM_Core_Smarty
320 */
321 public function assignAll($vars) {
322 foreach ($vars as $key => $value) {
323 $this->assign($key, $value);
324 }
325 return $this;
326 }
327
328 /**
329 * Get the locale for translation.
330 *
331 * @return string
332 */
333 private function getLocale() {
334 $tsLocale = CRM_Core_I18n::getLocale();
335 if (!empty($tsLocale)) {
336 return $tsLocale;
337 }
338
339 $config = CRM_Core_Config::singleton();
340 if (!empty($config->lcMessages)) {
341 return $config->lcMessages;
342 }
343
344 return 'en_US';
345 }
346
347 /**
348 * Get the compile_check value.
349 *
350 * @return bool
351 */
352 private function isCheckSmartyIsCompiled() {
353 // check for define in civicrm.settings.php as FALSE, otherwise returns TRUE
354 return CRM_Utils_Constant::value('CIVICRM_TEMPLATE_COMPILE_CHECK', TRUE);
355 }
356
357 /**
358 * Smarty escape modifier plugin.
359 *
360 * This replaces the core smarty modifier and basically does a lot of
361 * early-returning before calling the core function.
362 *
363 * It early returns on patterns that are common 'no-escape' patterns
364 * in CiviCRM - this list can be honed over time.
365 *
366 * It also logs anything that is actually escaped. Since this only kicks
367 * in when CIVICRM_SMARTY_DEFAULT_ESCAPE is defined it is ok to be aggressive
368 * about logging as we mostly care about developers using it at this stage.
369 *
370 * Note we don't actually use 'htmlall' anywhere in our tpl layer yet so
371 * anything coming in with this be happening because of the default modifier.
372 *
373 * Also note the right way to opt a field OUT of escaping is
374 * ``{$fieldName|smarty:nodefaults}``
375 * This should be used for fields with known html AND for fields where
376 * we are doing empty or isset checks - as otherwise the value is passed for
377 * escaping first so you still get an enotice for 'empty' or a fatal for 'isset'
378 *
379 * Type: modifier<br>
380 * Name: escape<br>
381 * Purpose: Escape the string according to escapement type
382 *
383 * @link http://smarty.php.net/manual/en/language.modifier.escape.php
384 * escape (Smarty online manual)
385 * @author Monte Ohrt <monte at ohrt dot com>
386 *
387 * @param string $string
388 * @param string $esc_type
389 * @param string $char_set
390 *
391 * @return string
392 */
393 public static function escape($string, $esc_type = 'html', $char_set = 'ISO-8859-1') {
394 // CiviCRM variables are often arrays - just handle them.
395 // The early return on booleans & numbers is mostly to prevent them being
396 // logged as 'changed' when they are cast to a string.
397 if (!is_scalar($string) || empty($string) || is_bool($string) || is_numeric($string) || $esc_type === 'none') {
398 return $string;
399 }
400 if ($esc_type === 'htmlall') {
401 // 'htmlall' is the nothing-specified default.
402 // Don't escape things we think quickform added.
403 if (strpos($string, '<input') === 0
404 || strpos($string, '<select') === 0
405 // Not handling as yet but these ones really should get some love.
406 || strpos($string, '<label') === 0
407 || strpos($string, '<button') === 0
408 || strpos($string, '<span class="crm-frozen-field">') === 0
409 || strpos($string, '<textarea') === 0
410
411 // The ones below this point are hopefully here short term.
412 || strpos($string, '<a') === 0
413 // Not sure how big a pattern this is - used in Pledge view tab
414 // not sure if it needs escaping
415 || strpos($string, ' action="/civicrm/') === 0
416 // This seems to be urls...
417 || strpos($string, '/civicrm/') === 0
418 // Validation error message - eg. <span class="crm-error">Tournament Fees is a required field.</span>
419 || strpos($string, '
420 <span class="crm-error">') === 0
421 // e.g from participant tab class="action-item" href=/civicrm/contact/view/participant?reset=1&amp;action=add&amp;cid=142&amp;context=participant
422 || strpos($string, 'class="action-item" href=/civicrm/"') === 0
423 ) {
424 // Do not escape the above common patterns.
425 return $string;
426 }
427 }
428 require_once 'Smarty/plugins/modifier.escape.php';
429 $value = smarty_modifier_escape($string, $esc_type, $char_set);
430 if ($value !== $string) {
431 Civi::log()->debug('smarty escaping original {original}, escaped {escaped} type {type} charset {charset}', [
432 'original' => $string,
433 'escaped' => $value,
434 'type' => $esc_type,
435 'charset' => $char_set,
436 ]);
437 }
438 return $value;
439 }
440
441 }