3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 * This class acts as our base controller class and adds additional
14 * functionality and smarts to the base QFC. Specifically we create
15 * our own action classes and handle the transitions ourselves by
16 * simulating a state machine. We also create direct jump links to any
17 * page that can be used universally.
19 * This concept has been discussed on the PEAR list and the QFC FAQ
20 * goes into a few details. Please check
21 * http://pear.php.net/manual/en/package.html.html-quickform-controller.faq.php
22 * for other useful tips and suggestions
25 * @copyright CiviCRM LLC https://civicrm.org/licensing
28 require_once 'HTML/QuickForm/Controller.php';
29 require_once 'HTML/QuickForm/Action/Direct.php';
32 * Class CRM_Core_Controller
34 class CRM_Core_Controller
extends HTML_QuickForm_Controller
{
37 * The title associated with this controller.
44 * The key associated with this controller.
51 * The name of the session scope where values are stored.
58 * The state machine associated with this controller.
62 protected $_stateMachine;
65 * Is this object being embedded in another object. If
66 * so the display routine needs to not do any work. (The
67 * parent object takes care of the display)
71 protected $_embedded = FALSE;
74 * After entire form execution complete,
75 * do we want to skip control redirection.
76 * Default - It get redirect to user context.
78 * Useful when we run form in non civicrm context
79 * and we need to transfer control back.(eg. drupal)
83 protected $_skipRedirection = FALSE;
86 * Are we in print mode? if so we need to modify the display
87 * functionality to do a minimal display :)
94 * Should we generate a qfKey, true by default
98 public $_generateQFKey = TRUE;
105 public $_QFResponseType = 'html';
108 * Cache the smarty template for efficiency reasons.
110 * @var CRM_Core_Smarty
112 static protected $_template;
115 * Cache the session for efficiency reasons.
117 * @var CRM_Core_Session
119 static protected $_session;
122 * The parent of this form if embedded.
126 protected $_parent = NULL;
129 * The destination if set will override the destination the code wants to send it to.
133 public $_destination = NULL;
136 * The entry url for a top level form or wizard. Typically the URL with a reset=1
137 * used to redirect back to when we land into some session wierdness
141 public $_entryURL = NULL;
144 * All CRM single or multi page pages should inherit from this class.
146 * @param string $title
147 * Descriptive title of the controller.
149 * Whether controller is modal.
151 * @param string $scope
152 * Name of session if we want unique scope, used only by Controller_Simple.
153 * @param bool $addSequence
154 * Should we add a unique sequence number to the end of the key.
155 * @param bool $ignoreKey
156 * Should we not set a qfKey for this controller (for standalone forms).
158 * @throws \CRM_Core_Exception
160 public function __construct(
165 $addSequence = FALSE,
168 // this has to true for multiple tab session fix
171 // let the constructor initialize this, should happen only once
172 if (!isset(self
::$_template)) {
173 self
::$_template = CRM_Core_Smarty
::singleton();
174 self
::$_session = CRM_Core_Session
::singleton();
175 self
::$_template->ensureVariablesAreAssigned(['formTpl']);
178 // lets try to get it from the session and/or the request vars
179 // we do this early on in case there is a fatal error in retrieving the
180 // key and/or session
182 = CRM_Utils_Request
::retrieve('entryURL', 'String', $this);
184 // add a unique validable key to the name
185 $name = CRM_Utils_System
::getClassName($this);
186 if ($name == 'CRM_Core_Controller_Simple' && !empty($scope)) {
187 // use form name if we have, since its a lot better and
188 // definitely different for different forms
191 $name = $name . '_' . $this->key($name, $addSequence, $ignoreKey);
192 $this->_title
= $title;
194 $this->_scope
= $scope;
197 $this->_scope
= CRM_Utils_System
::getClassName($this);
199 $this->_scope
= $this->_scope
. '_' . $this->_key
;
201 // only use the civicrm cache if we have a valid key
202 // else we clash with other users CRM-7059
203 if (!empty($this->_key
)) {
204 CRM_Core_Session
::registerAndRetrieveSessionObjects([
205 "_{$name}_container",
206 ['CiviCRM', $this->_scope
],
210 parent
::__construct($name, $modal);
212 $snippet = $_REQUEST['snippet'] ??
NULL;
215 $this->_print
= CRM_Core_Smarty
::PRINT_PDF
;
217 elseif ($snippet == 4) {
218 // this is used to embed fragments of a form
219 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
220 self
::$_template->assign('suppressForm', TRUE);
221 $this->_generateQFKey
= FALSE;
223 elseif ($snippet == 5) {
224 // mode deprecated in favor of json
225 // still used by dashlets, probably nothing else
226 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
228 // Respond with JSON if in AJAX context (also support legacy value '6')
229 elseif (in_array($snippet, [CRM_Core_Smarty
::PRINT_JSON
, 6])) {
230 $this->_print
= CRM_Core_Smarty
::PRINT_JSON
;
231 $this->_QFResponseType
= 'json';
234 $this->_print
= CRM_Core_Smarty
::PRINT_SNIPPET
;
238 // if the request has a reset value, initialize the controller session
239 if (!empty($_GET['reset'])) {
242 // in this case we'll also cache the url as a hidden form variable, this allows us to
243 // redirect in case the session has disappeared on us
244 $this->_entryURL
= CRM_Utils_System
::makeURL(NULL, TRUE, FALSE, NULL, TRUE);
245 // In WordPress Shortcodes the standard entryURL generated via makeURL doesn't generally have id=x&reset=1 included so we add them here
246 // This prevents infinite loops caused when the session has timed out.
247 if (stripos($this->_entryURL
, 'id') === FALSE && (stripos($this->_entryURL
, 'transact') !== FALSE ||
stripos($this->_entryURL
, 'register') !== FALSE)) {
248 $this->_entryURL
.= '&id=' . CRM_Utils_Request
::retrieveValue('id', 'Positive') . '&reset=1';
250 $this->set('entryURL', $this->_entryURL
);
253 // set the key in the session
254 // do this at the end so we have initialized the object
255 // and created the scope etc
256 $this->set('qfKey', $this->_key
);
258 // also retrieve and store destination in session
259 $this->_destination
= CRM_Utils_Request
::retrieve(
260 'civicrmDestination',
269 public function fini() {
270 CRM_Core_BAO_Cache
::storeSessionToCache([
271 "_{$this->_name}_container",
272 ['CiviCRM', $this->_scope
],
277 * @param string $name
278 * @param bool $addSequence
279 * @param bool $ignoreKey
281 * @return mixed|string
283 public function key($name, $addSequence = FALSE, $ignoreKey = FALSE) {
284 $config = CRM_Core_Config
::singleton();
288 (isset($config->keyDisable
) && $config->keyDisable
)
293 // We need a form key. Check _POST first, then _GET.
294 // @todo Note: we currently have to check $_REQUEST, too, since that
295 // is currently overwritten by civicrm_api3_contribution_page_validate.
296 // It's bad form to use $_REQUEST because it's ambiguous; and it's bad form
297 // to change superglobals anyway. If PR
298 // https://github.com/civicrm/civicrm-core/pull/17324
299 // and/or related get merged, then we should remove the REQUEST reference here.
300 $key = $_POST['qfKey'] ??
$_GET['qfKey'] ??
$_REQUEST['qfKey'] ??
NULL;
301 if (!$key && in_array($_SERVER['REQUEST_METHOD'], ['GET', 'HEAD'])) {
302 // Generate a key if this is an initial request without one.
303 // We allow HEAD here because it is used by bots to validate URLs, so if
304 // we issue a 500 server error to them they may think the site is broken.
305 $key = CRM_Core_Key
::get($name, $addSequence);
308 // Other requests that usually change data (POST, but feasibly DELETE,
309 // PUT, PATCH...) always require a valid key.
310 $key = CRM_Core_Key
::validate($key, $name, $addSequence);
323 * Process the request, overrides the default QFC run method
324 * This routine actually checks if the QFC is modal and if it
325 * is the first invalid page, if so it call the requested action
326 * if not, it calls the display action on the first invalid page
327 * avoids the issue of users hitting the back button and getting
330 * This run is basically a composition of the original run and the
335 public function run() {
336 // the names of the action and page should be saved
337 // note that this is split into two, because some versions of
338 // php 5.x core dump on the triple assignment :)
339 $this->_actionName
= $this->getActionName();
340 list($pageName, $action) = $this->_actionName
;
342 if ($this->isModal()) {
343 if (!$this->isValid($pageName)) {
344 $pageName = $this->findInvalid();
349 // note that based on action, control might not come back!!
350 // e.g. if action is a valid JUMP, u basically do a redirect
351 // to the appropriate place
352 $this->wizardHeader($pageName);
353 return $this->_pages
[$pageName]->handle($action);
359 public function validate() {
360 $this->_actionName
= $this->getActionName();
361 list($pageName, $action) = $this->_actionName
;
363 $page = &$this->_pages
[$pageName];
365 $data = &$this->container();
366 $this->applyDefaults($pageName);
367 $page->isFormBuilt() or $page->buildForm();
368 // We use defaults and constants as if they were submitted
369 $data['values'][$pageName] = $page->exportValues();
370 $page->loadValues($data['values'][$pageName]);
371 // Is the page now valid?
372 if (TRUE === ($data['valid'][$pageName] = $page->validate())) {
375 return $page->_errors
;
379 * Helper function to add all the needed default actions.
381 * Note that the framework redefines all of the default QFC actions.
383 * @param string $uploadDirectory to store all the uploaded files
384 * @param array $uploadNames for the various upload buttons (note u can have more than 1 upload)
386 public function addActions($uploadDirectory = NULL, $uploadNames = NULL) {
388 'display' => 'CRM_Core_QuickForm_Action_Display',
389 'next' => 'CRM_Core_QuickForm_Action_Next',
390 'back' => 'CRM_Core_QuickForm_Action_Back',
391 'process' => 'CRM_Core_QuickForm_Action_Process',
392 'cancel' => 'CRM_Core_QuickForm_Action_Cancel',
393 'refresh' => 'CRM_Core_QuickForm_Action_Refresh',
394 'reload' => 'CRM_Core_QuickForm_Action_Reload',
395 'done' => 'CRM_Core_QuickForm_Action_Done',
396 'jump' => 'CRM_Core_QuickForm_Action_Jump',
397 'submit' => 'CRM_Core_QuickForm_Action_Submit',
400 foreach ($names as $name => $classPath) {
401 $action = new $classPath($this->_stateMachine
);
402 $this->addAction($name, $action);
405 $this->addUploadAction($uploadDirectory, $uploadNames);
409 * Getter method for stateMachine.
411 * @return CRM_Core_StateMachine
413 public function getStateMachine() {
414 return $this->_stateMachine
;
418 * Setter method for stateMachine.
420 * @param CRM_Core_StateMachine $stateMachine
422 public function setStateMachine($stateMachine) {
423 $this->_stateMachine
= $stateMachine;
427 * Add pages to the controller. Note that the controller does not really care
428 * the order in which the pages are added
430 * @param CRM_Core_StateMachine $stateMachine
431 * @param \const|int $action the mode in which the state machine is operating
432 * typically this will be add/view/edit
434 public function addPages(&$stateMachine, $action = CRM_Core_Action
::NONE
) {
435 $pages = $stateMachine->getPages();
436 foreach ($pages as $name => $value) {
437 $className = CRM_Utils_Array
::value('className', $value, $name);
438 $title = $value['title'] ??
NULL;
439 $options = $value['options'] ??
NULL;
440 $stateName = CRM_Utils_String
::getClassName($className);
441 if (!empty($value['className'])) {
445 $formName = CRM_Utils_String
::getClassName($name);
448 $ext = CRM_Extension_System
::singleton()->getMapper();
449 if ($ext->isExtensionClass($className)) {
450 require_once $ext->classToPath($className);
453 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
455 $
$stateName = new $className($stateMachine->find($className), $action, 'post', $formName);
457 $
$stateName->setTitle($title);
460 $
$stateName->setOptions($options);
462 if (property_exists($
$stateName, 'urlPath')) {
463 $
$stateName->urlPath
= explode('/', (string) CRM_Utils_System
::currentPath());
465 $this->addPage($
$stateName);
466 $this->addAction($stateName, new HTML_QuickForm_Action_Direct());
468 //CRM-6342 -we need kill the reference here,
469 //as we have deprecated reference object creation.
475 * QFC does not provide native support to have different 'submit' buttons.
476 * We introduce this notion to QFC by using button specific data. Thus if
477 * we have two submit buttons, we could have one displayed as a button and
478 * the other as an image, both are of type 'submit'.
481 * the name of the button that has been pressed by the user
483 public function getButtonName() {
484 $data = &$this->container();
485 return $data['_qf_button_name'] ??
NULL;
489 * Destroy all the session state of the controller.
491 public function reset() {
492 $this->container(TRUE);
493 self
::$_session->resetScope($this->_scope
);
497 * Virtual function to do any processing of data.
499 * Sometimes it is useful for the controller to actually process data.
500 * This is typically used when we need the controller to figure out
501 * what pages are potentially involved in this wizard. (this is dynamic
502 * and can change based on the arguments
504 public function process() {
508 * Store the variable with the value in the form scope.
510 * @param string|array $name name of the variable or an assoc array of name/value pairs
511 * @param mixed $value
512 * Value of the variable if string.
514 public function set($name, $value = NULL) {
515 self
::$_session->set($name, $value, $this->_scope
);
519 * Get the variable from the form scope.
521 * @param string $name
522 * name of the variable.
526 public function get($name) {
527 return self
::$_session->get($name, $this->_scope
);
531 * Create the header for the wizard from the list of pages.
532 * Store the created header in smarty
534 * @param string $currentPageName
535 * Name of the page being displayed.
539 public function wizardHeader($currentPageName) {
541 $wizard['steps'] = [];
543 foreach ($this->_pages
as $name => $page) {
545 $wizard['steps'][] = [
547 'title' => $page->getTitle(),
548 //'link' => $page->getLink ( ),
552 'stepNumber' => $count,
553 'collapsed' => FALSE,
556 if ($name == $currentPageName) {
557 $wizard['currentStepNumber'] = $count;
558 $wizard['currentStepName'] = $name;
559 $wizard['currentStepTitle'] = $page->getTitle();
563 $wizard['stepCount'] = $count;
565 $this->addWizardStyle($wizard);
567 $this->assign('wizard', $wizard);
572 * @param array $wizard
574 public function addWizardStyle(&$wizard) {
577 'stepPrefixCurrent' => '<i class="crm-i fa-chevron-right" aria-hidden="true"></i> ',
578 'stepPrefixPast' => '<i class="crm-i fa-check" aria-hidden="true"></i> ',
579 'stepPrefixFuture' => ' ',
580 'subStepPrefixCurrent' => ' ',
581 'subStepPrefixPast' => ' ',
582 'subStepPrefixFuture' => ' ',
588 * Assign value to name in template.
591 * @param mixed $value
594 public function assign($var, $value = NULL) {
595 self
::$_template->assign($var, $value);
599 * Assign value to name in template by reference.
602 * @param mixed $value
603 * (reference) value of variable.
605 public function assign_by_ref($var, &$value) {
606 self
::$_template->assign_by_ref($var, $value);
610 * Appends values to template variables.
612 * @param array|string $tpl_var the template variable name(s)
613 * @param mixed $value
614 * The value to append.
617 public function append($tpl_var, $value = NULL, $merge = FALSE) {
618 self
::$_template->append($tpl_var, $value, $merge);
622 * Returns an array containing template variables.
624 * @param string $name
628 public function get_template_vars($name = NULL) {
629 return self
::$_template->get_template_vars($name);
633 * Setter for embedded.
635 * @param bool $embedded
637 public function setEmbedded($embedded) {
638 $this->_embedded
= $embedded;
642 * Getter for embedded.
645 * return the embedded value
647 public function getEmbedded() {
648 return $this->_embedded
;
652 * Setter for skipRedirection.
654 * @param bool $skipRedirection
656 public function setSkipRedirection($skipRedirection) {
657 $this->_skipRedirection
= $skipRedirection;
661 * Getter for skipRedirection.
664 * return the skipRedirection value
666 public function getSkipRedirection() {
667 return $this->_skipRedirection
;
671 * @param null $fileName
673 public function setWord($fileName = NULL) {
674 //Mark as a CSV file.
675 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/vnd.ms-word');
677 //Force a download and name the file using the current timestamp.
679 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.doc';
681 CRM_Utils_System
::setHttpHeader("Content-Disposition", "attachment; filename=Contacts_$fileName");
685 * @param null $fileName
687 public function setExcel($fileName = NULL) {
688 //Mark as an excel file.
689 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/vnd.ms-excel');
691 //Force a download and name the file using the current timestamp.
693 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.xls';
696 CRM_Utils_System
::setHttpHeader("Content-Disposition", "attachment; filename=Contacts_$fileName");
704 public function setPrint($print) {
705 if ($print == "xls") {
708 elseif ($print == "doc") {
711 $this->_print
= $print;
718 * return the print value
720 public function getPrint() {
721 return $this->_print
;
727 public function getTemplateFile() {
729 if ($this->_print
== CRM_Core_Smarty
::PRINT_PAGE
) {
730 return 'CRM/common/print.tpl';
732 elseif ($this->_print
== 'xls' ||
$this->_print
== 'doc') {
733 return 'CRM/Contact/Form/Task/Excel.tpl';
736 return 'CRM/common/snippet.tpl';
740 $config = CRM_Core_Config
::singleton();
741 return 'CRM/common/' . strtolower($config->userFramework
) . '.tpl';
747 * @param $uploadNames
749 public function addUploadAction($uploadDir, $uploadNames) {
750 if (empty($uploadDir)) {
751 $config = CRM_Core_Config
::singleton();
752 $uploadDir = $config->uploadDir
;
755 if (empty($uploadNames)) {
756 $uploadNames = $this->get('uploadNames');
757 if (!empty($uploadNames)) {
758 $uploadNames = array_merge($uploadNames,
759 CRM_Core_BAO_File
::uploadNames()
763 $uploadNames = CRM_Core_BAO_File
::uploadNames();
767 $action = new CRM_Core_QuickForm_Action_Upload($this->_stateMachine
,
771 $this->addAction('upload', $action);
777 public function setParent($parent) {
778 $this->_parent
= $parent;
784 public function getParent() {
785 return $this->_parent
;
791 public function getDestination() {
792 return $this->_destination
;
797 * @param bool $setToReferer
799 public function setDestination($url = NULL, $setToReferer = FALSE) {
802 $url = $_SERVER['HTTP_REFERER'];
805 $config = CRM_Core_Config
::singleton();
806 $url = $config->userFrameworkBaseURL
;
810 $this->_destination
= $url;
811 $this->set('civicrmDestination', $this->_destination
);
817 public function cancelAction() {
818 $actionName = $this->getActionName();
819 list($pageName, $action) = $actionName;
820 return $this->_pages
[$pageName]->cancelAction();
824 * Write a simple fatal error message.
826 * Other controllers can decide to do something else and present the user a better message
827 * and/or redirect to the same page with a reset url
829 public function invalidKey() {
830 self
::invalidKeyCommon();
833 public function invalidKeyCommon() {
834 $msg = ts("We can't load the requested web page. This page requires cookies to be enabled in your browser settings. Please check this setting and enable cookies (if they are not enabled). Then try again. If this error persists, contact the site administrator for assistance.") . '<br /><br />' . ts('Site Administrators: This error may indicate that users are accessing this page using a domain or URL other than the configured Base URL. EXAMPLE: Base URL is http://example.org, but some users are accessing the page via http://www.example.org or a domain alias like http://myotherexample.org.') . '<br /><br />' . ts('Error type: Could not find a valid session key.');
835 throw new CRM_Core_Exception($msg);
839 * Instead of outputting a fatal error message, we'll just redirect
840 * to the entryURL if present
842 public function invalidKeyRedirect() {
843 if ($this->_entryURL
&& $url_parts = parse_url($this->_entryURL
)) {
844 // CRM-16832: Ensure local redirects only.
845 if (!empty($url_parts['path'])) {
846 // Prepend a slash, but don't duplicate it.
847 $redirect_url = '/' . ltrim($url_parts['path'], '/');
848 if (!empty($url_parts['query'])) {
849 $redirect_url .= '?' . $url_parts['query'];
851 CRM_Core_Session
::setStatus(ts('Your browser session has expired and we are unable to complete your form submission. We have returned you to the initial step so you can complete and resubmit the form. If you experience continued difficulties, please contact us for assistance.'));
852 return CRM_Utils_System
::redirect($redirect_url);
855 self
::invalidKeyCommon();