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