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