Use null variables rather than isset in Core_Block
[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 $this->load_filter('pre', 'resetExtScope');
142
143 $this->assign('crmPermissions', new CRM_Core_Smarty_Permissions());
144
145 if ($config->debug) {
146 $this->error_reporting = E_ALL;
147 }
148 }
149
150 /**
151 * Static instance provider.
152 *
153 * Method providing static instance of SmartTemplate, as
154 * in Singleton pattern.
155 *
156 * @return \CRM_Core_Smarty
157 */
158 public static function &singleton() {
159 if (!isset(self::$_singleton)) {
160 self::$_singleton = new CRM_Core_Smarty();
161 self::$_singleton->initialize();
162
163 self::registerStringResource();
164 }
165 return self::$_singleton;
166 }
167
168 /**
169 * Executes & returns or displays the template results
170 *
171 * @param string $resource_name
172 * @param string $cache_id
173 * @param string $compile_id
174 * @param bool $display
175 *
176 * @return bool|mixed|string
177 */
178 public function fetch($resource_name, $cache_id = NULL, $compile_id = NULL, $display = FALSE) {
179 if (preg_match('/^(\s+)?string:/', $resource_name)) {
180 $old_security = $this->security;
181 $this->security = TRUE;
182 }
183 $output = parent::fetch($resource_name, $cache_id, $compile_id, $display);
184 if (isset($old_security)) {
185 $this->security = $old_security;
186 }
187 return $output;
188 }
189
190 /**
191 * Ensure these variables are set to make it easier to access them without e-notice.
192 *
193 * @param array $variables
194 */
195 public function ensureVariablesAreAssigned(array $variables): void {
196 foreach ($variables as $variable) {
197 if (!isset($this->get_template_vars()[$variable])) {
198 $this->assign($variable);
199 }
200 }
201 }
202
203 /**
204 * Fetch a template (while using certain variables)
205 *
206 * @param string $resource_name
207 * @param array $vars
208 * (string $name => mixed $value) variables to export to Smarty.
209 * @throws Exception
210 * @return bool|mixed|string
211 */
212 public function fetchWith($resource_name, $vars) {
213 $this->pushScope($vars);
214 try {
215 $result = $this->fetch($resource_name);
216 }
217 catch (Exception $e) {
218 // simulate try { ... } finally { ... }
219 $this->popScope();
220 throw $e;
221 }
222 $this->popScope();
223 return $result;
224 }
225
226 /**
227 * @param string $name
228 * @param $value
229 */
230 public function appendValue($name, $value) {
231 $currentValue = $this->get_template_vars($name);
232 if (!$currentValue) {
233 $this->assign($name, $value);
234 }
235 else {
236 if (strpos($currentValue, $value) === FALSE) {
237 $this->assign($name, $currentValue . $value);
238 }
239 }
240 }
241
242 public function clearTemplateVars() {
243 foreach (array_keys($this->_tpl_vars) as $key) {
244 if ($key == 'config' || $key == 'session') {
245 continue;
246 }
247 unset($this->_tpl_vars[$key]);
248 }
249 }
250
251 public static function registerStringResource() {
252 require_once 'CRM/Core/Smarty/resources/String.php';
253 civicrm_smarty_register_string_resource();
254 }
255
256 /**
257 * @param $path
258 */
259 public function addTemplateDir($path) {
260 if (is_array($this->template_dir)) {
261 array_unshift($this->template_dir, $path);
262 }
263 else {
264 $this->template_dir = [$path, $this->template_dir];
265 }
266
267 }
268
269 /**
270 * Temporarily assign a list of variables.
271 *
272 * ```
273 * $smarty->pushScope(array(
274 * 'first_name' => 'Alice',
275 * 'last_name' => 'roberts',
276 * ));
277 * $html = $smarty->fetch('view-contact.tpl');
278 * $smarty->popScope();
279 * ```
280 *
281 * @param array $vars
282 * (string $name => mixed $value).
283 * @return CRM_Core_Smarty
284 * @see popScope
285 */
286 public function pushScope($vars) {
287 $oldVars = $this->get_template_vars();
288 $backupFrame = [];
289 foreach ($vars as $key => $value) {
290 $backupFrame[$key] = $oldVars[$key] ?? NULL;
291 }
292 $this->backupFrames[] = $backupFrame;
293
294 $this->assignAll($vars);
295
296 return $this;
297 }
298
299 /**
300 * Remove any values that were previously pushed.
301 *
302 * @return CRM_Core_Smarty
303 * @see pushScope
304 */
305 public function popScope() {
306 $this->assignAll(array_pop($this->backupFrames));
307 return $this;
308 }
309
310 /**
311 * @param array $vars
312 * (string $name => mixed $value).
313 * @return CRM_Core_Smarty
314 */
315 public function assignAll($vars) {
316 foreach ($vars as $key => $value) {
317 $this->assign($key, $value);
318 }
319 return $this;
320 }
321
322 /**
323 * Get the locale for translation.
324 *
325 * @return string
326 */
327 private function getLocale() {
328 $tsLocale = CRM_Core_I18n::getLocale();
329 if (!empty($tsLocale)) {
330 return $tsLocale;
331 }
332
333 $config = CRM_Core_Config::singleton();
334 if (!empty($config->lcMessages)) {
335 return $config->lcMessages;
336 }
337
338 return 'en_US';
339 }
340
341 /**
342 * Get the compile_check value.
343 *
344 * @return bool
345 */
346 private function isCheckSmartyIsCompiled() {
347 // check for define in civicrm.settings.php as FALSE, otherwise returns TRUE
348 return CRM_Utils_Constant::value('CIVICRM_TEMPLATE_COMPILE_CHECK', TRUE);
349 }
350
351 }