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