Merge pull request #22022 from jaapjansma/issue2948
[civicrm-core.git] / CRM / Core / Page.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 * A Page is basically data in a nice pretty format.
20 *
21 * Pages should not have any form actions / elements in them. If they
22 * do, make sure you use CRM_Core_Form and the related structures. You can
23 * embed simple forms in Page and do your own form handling.
24 *
25 */
26 class CRM_Core_Page {
27
28 /**
29 * The name of the page (auto generated from class name)
30 *
31 * @var string
32 */
33 protected $_name;
34
35 /**
36 * The title associated with this page.
37 *
38 * @var object
39 */
40 protected $_title;
41
42 /**
43 * A page can have multiple modes. (i.e. displays
44 * a different set of data based on the input
45 * @var int
46 */
47 protected $_mode;
48
49 /**
50 * Is this object being embedded in another object. If
51 * so the display routine needs to not do any work. (The
52 * parent object takes care of the display)
53 *
54 * @var bool
55 */
56 protected $_embedded = FALSE;
57
58 /**
59 * Are we in print mode? if so we need to modify the display
60 * functionality to do a minimal display :)
61 *
62 * @var bool
63 */
64 protected $_print = FALSE;
65
66 /**
67 * Cache the smarty template for efficiency reasons
68 *
69 * @var CRM_Core_Smarty
70 */
71 static protected $_template;
72
73 /**
74 * Cache the session for efficiency reasons
75 *
76 * @var CRM_Core_Session
77 */
78 static protected $_session;
79
80 /**
81 * What to return to the client if in ajax mode (snippet=json)
82 *
83 * @var array
84 */
85 public $ajaxResponse = [];
86
87 /**
88 * Url path used to reach this page
89 *
90 * @var array
91 */
92 public $urlPath = [];
93
94 /**
95 * Should crm.livePage.js be added to the page?
96 * @var bool
97 */
98 public $useLivePageJS;
99
100 /**
101 * Variables smarty expects to have set.
102 *
103 * We ensure these are assigned (value = NULL) when Smarty is instantiated in
104 * order to avoid e-notices / having to use empty or isset in the template layer.
105 *
106 * @var string[]
107 */
108 public $expectedSmartyVariables = [
109 'breadcrumb',
110 'pageTitle',
111 'isForm',
112 'hookContent',
113 'hookContentPlacement',
114 // required for footer.tpl
115 'contactId',
116 // required for info.tpl
117 'infoMessage',
118 'infoTitle',
119 'infoType',
120 'infoOptions',
121 // required for Summary.tpl (contact summary) but seems
122 // likely to be used more broadly to warrant inclusion here.
123 'context',
124 ];
125
126 /**
127 * Class constructor.
128 *
129 * @param string $title
130 * Title of the page.
131 * @param int $mode
132 * Mode of the page.
133 *
134 * @return CRM_Core_Page
135 */
136 public function __construct($title = NULL, $mode = NULL) {
137 $this->_name = CRM_Utils_System::getClassName($this);
138 $this->_title = $title;
139 $this->_mode = $mode;
140
141 // let the constructor initialize this, should happen only once
142 if (!isset(self::$_template)) {
143 self::$_template = CRM_Core_Smarty::singleton();
144 self::$_session = CRM_Core_Session::singleton();
145 }
146 // Smarty $_template is a static var which persists between tests, so
147 // if something calls clearTemplateVars(), the static still exists but
148 // our ensured variables get blown away, so we need to set them even if
149 // it's already been initialized.
150 self::$_template->ensureVariablesAreAssigned($this->expectedSmartyVariables);
151
152 // FIXME - why are we messing with 'snippet'? Why not just pass it directly into $this->_print?
153 if (!empty($_REQUEST['snippet'])) {
154 if ($_REQUEST['snippet'] == CRM_Core_Smarty::PRINT_PDF) {
155 $this->_print = CRM_Core_Smarty::PRINT_PDF;
156 }
157 // FIXME - why does this number not match the constant?
158 elseif ($_REQUEST['snippet'] == 5) {
159 $this->_print = CRM_Core_Smarty::PRINT_NOFORM;
160 }
161 // Support 'json' as well as legacy value '6'
162 elseif (in_array($_REQUEST['snippet'], [CRM_Core_Smarty::PRINT_JSON, 6])) {
163 $this->_print = CRM_Core_Smarty::PRINT_JSON;
164 }
165 else {
166 $this->_print = CRM_Core_Smarty::PRINT_SNIPPET;
167 }
168 }
169
170 // if the request has a reset value, initialize the controller session
171 if (!empty($_REQUEST['reset'])) {
172 $this->reset();
173 }
174 }
175
176 /**
177 * This function takes care of all the things common to all pages.
178 *
179 * This typically involves assigning the appropriate smarty variables :)
180 */
181 public function run() {
182 if ($this->_embedded) {
183 return NULL;
184 }
185
186 self::$_template->assign('mode', $this->_mode);
187
188 $pageTemplateFile = $this->getHookedTemplateFileName();
189 self::$_template->assign('tplFile', $pageTemplateFile);
190
191 // invoke the pagRun hook, CRM-3906
192 CRM_Utils_Hook::pageRun($this);
193
194 if ($this->_print) {
195 if (in_array($this->_print, [
196 CRM_Core_Smarty::PRINT_SNIPPET,
197 CRM_Core_Smarty::PRINT_PDF,
198 CRM_Core_Smarty::PRINT_NOFORM,
199 CRM_Core_Smarty::PRINT_JSON,
200 ])) {
201 $content = self::$_template->fetch('CRM/common/snippet.tpl');
202 }
203 else {
204 $content = self::$_template->fetch('CRM/common/print.tpl');
205 }
206
207 CRM_Utils_System::appendTPLFile($pageTemplateFile,
208 $content,
209 $this->overrideExtraTemplateFileName()
210 );
211
212 //its time to call the hook.
213 CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this);
214
215 if ($this->_print == CRM_Core_Smarty::PRINT_PDF) {
216 CRM_Utils_PDF_Utils::html2pdf($content, "{$this->_name}.pdf", FALSE,
217 ['paper_size' => 'a3', 'orientation' => 'landscape']
218 );
219 }
220 elseif ($this->_print == CRM_Core_Smarty::PRINT_JSON) {
221 $this->ajaxResponse['content'] = $content;
222 CRM_Core_Page_AJAX::returnJsonResponse($this->ajaxResponse);
223 }
224 else {
225 echo $content;
226 }
227 CRM_Utils_System::civiExit();
228 }
229
230 $config = CRM_Core_Config::singleton();
231
232 // @fixme this is probably the wrong place for this. It is required by jsortable.tpl which is inherited from many page templates.
233 // So we have to add it here to deprecate $config->defaultCurrencySymbol
234 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
235
236 // Intermittent alert to admins
237 CRM_Utils_Check::singleton()->showPeriodicAlerts();
238
239 if ($this->useLivePageJS && Civi::settings()->get('ajaxPopupsEnabled')) {
240 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
241 }
242
243 $content = self::$_template->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl');
244
245 // Render page header
246 if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) {
247 CRM_Utils_System::addHTMLHead($region->render(''));
248 }
249 CRM_Utils_System::appendTPLFile($pageTemplateFile, $content);
250
251 //its time to call the hook.
252 CRM_Utils_Hook::alterContent($content, 'page', $pageTemplateFile, $this);
253
254 echo CRM_Utils_System::theme($content, $this->_print);
255 }
256
257 /**
258 * Store the variable with the value in the form scope.
259 *
260 * @param string|array $name name of the variable or an assoc array of name/value pairs
261 * @param mixed $value
262 * Value of the variable if string.
263 */
264 public function set($name, $value = NULL) {
265 self::$_session->set($name, $value, $this->_name);
266 }
267
268 /**
269 * Get the variable from the form scope.
270 *
271 * @param string $name name of the variable
272 *
273 * @return mixed
274 */
275 public function get($name) {
276 return self::$_session->get($name, $this->_name);
277 }
278
279 /**
280 * Assign value to name in template.
281 *
282 * @param string $var
283 * @param mixed $value
284 * Value of variable.
285 */
286 public function assign($var, $value = NULL) {
287 self::$_template->assign($var, $value);
288 }
289
290 /**
291 * Assign value to name in template by reference.
292 *
293 * @param string $var
294 * @param mixed $value
295 * (reference) value of variable.
296 */
297 public function assign_by_ref($var, &$value) {
298 self::$_template->assign_by_ref($var, $value);
299 }
300
301 /**
302 * Appends values to template variables.
303 *
304 * @param array|string $tpl_var the template variable name(s)
305 * @param mixed $value
306 * The value to append.
307 * @param bool $merge
308 */
309 public function append($tpl_var, $value = NULL, $merge = FALSE) {
310 self::$_template->append($tpl_var, $value, $merge);
311 }
312
313 /**
314 * Returns an array containing template variables.
315 *
316 * @param string $name
317 *
318 * @return array
319 */
320 public function get_template_vars($name = NULL) {
321 return self::$_template->get_template_vars($name);
322 }
323
324 /**
325 * Destroy all the session state of this page.
326 */
327 public function reset() {
328 self::$_session->resetScope($this->_name);
329 }
330
331 /**
332 * Use the form name to create the tpl file name.
333 *
334 * @return string
335 */
336 public function getTemplateFileName() {
337 return strtr(
338 CRM_Utils_System::getClassName($this),
339 [
340 '_' => DIRECTORY_SEPARATOR,
341 '\\' => DIRECTORY_SEPARATOR,
342 ]
343 ) . '.tpl';
344 }
345
346 /**
347 * A wrapper for getTemplateFileName that includes calling the hook to
348 * prevent us from having to copy & paste the logic of calling the hook
349 */
350 public function getHookedTemplateFileName() {
351 $pageTemplateFile = $this->getTemplateFileName();
352 CRM_Utils_Hook::alterTemplateFile(get_class($this), $this, 'page', $pageTemplateFile);
353 return $pageTemplateFile;
354 }
355
356 /**
357 * Default extra tpl file basically just replaces .tpl with .extra.tpl
358 * i.e. we dont override
359 *
360 * @return string
361 */
362 public function overrideExtraTemplateFileName() {
363 return NULL;
364 }
365
366 /**
367 * Setter for embedded.
368 *
369 * @param bool $embedded
370 */
371 public function setEmbedded($embedded) {
372 $this->_embedded = $embedded;
373 }
374
375 /**
376 * Getter for embedded.
377 *
378 * @return bool
379 * return the embedded value
380 */
381 public function getEmbedded() {
382 return $this->_embedded;
383 }
384
385 /**
386 * Setter for print.
387 *
388 * @param bool $print
389 */
390 public function setPrint($print) {
391 $this->_print = $print;
392 }
393
394 /**
395 * Getter for print.
396 *
397 * @return bool
398 * return the print value
399 */
400 public function getPrint() {
401 return $this->_print;
402 }
403
404 /**
405 * @return CRM_Core_Smarty
406 */
407 public static function &getTemplate() {
408 return self::$_template;
409 }
410
411 /**
412 * @param string $name
413 *
414 * @return null
415 */
416 public function getVar($name) {
417 return $this->$name ?? NULL;
418 }
419
420 /**
421 * @param string $name
422 * @param $value
423 */
424 public function setVar($name, $value) {
425 $this->$name = $value;
426 }
427
428 /**
429 * Assign metadata about fields to the template.
430 *
431 * In order to allow the template to format fields we assign information about them to the template.
432 *
433 * At this stage only date field metadata is assigned as that is the only use-case in play and
434 * we don't want to assign a lot of unneeded data.
435 *
436 * @param string $entity
437 * The entity being queried.
438 *
439 * @throws \CiviCRM_API3_Exception
440 */
441 protected function assignFieldMetadataToTemplate($entity) {
442 $fields = civicrm_api3($entity, 'getfields', ['action' => 'get']);
443 $dateFields = [];
444 foreach ($fields['values'] as $fieldName => $fieldMetaData) {
445 if (isset($fieldMetaData['html']) && CRM_Utils_Array::value('type', $fieldMetaData['html']) == 'Select Date') {
446 $dateFields[$fieldName] = CRM_Utils_Date::addDateMetadataToField($fieldMetaData, $fieldMetaData);
447 }
448 }
449 $this->assign('fields', $dateFields);
450 }
451
452 /**
453 * Handy helper to produce the standard markup for an icon with alternative
454 * text for a title and screen readers.
455 *
456 * See also the smarty block function `icon`
457 *
458 * @param string $icon
459 * The class name of the icon to display.
460 * @param string $text
461 * The translated text to display.
462 * @param bool $condition
463 * Whether to display anything at all. This helps simplify code when a
464 * checkmark should appear if something is true.
465 * @param array $attribs
466 * Attributes to set or override on the icon element. Any standard
467 * attribute can be unset by setting the value to an empty string.
468 *
469 * @return string
470 * The whole bit to drop in.
471 */
472 public static function crmIcon($icon, $text = NULL, $condition = TRUE, $attribs = []) {
473 if (!$condition) {
474 return '';
475 }
476
477 // Add icon classes to any that might exist in $attribs
478 $classes = array_key_exists('class', $attribs) ? explode(' ', $attribs['class']) : [];
479 $classes[] = 'crm-i';
480 $classes[] = $icon;
481 $attribs['class'] = implode(' ', array_unique($classes));
482
483 $standardAttribs = ['aria-hidden' => 'true'];
484 if ($text === NULL || $text === '') {
485 $title = $sr = '';
486 }
487 else {
488 $standardAttribs['title'] = $text;
489 $sr = "<span class=\"sr-only\">$text</span>";
490 }
491
492 // Assemble attribs
493 $attribString = '';
494 // Strip out title if $attribs specifies a blank title
495 $attribs = array_merge($standardAttribs, $attribs);
496 foreach ($attribs as $attrib => $val) {
497 if (strlen($val)) {
498 $val = htmlspecialchars($val);
499 $attribString .= " $attrib=\"$val\"";
500 }
501 }
502
503 return "<i$attribString></i>$sr";
504 }
505
506 }