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();
177 // lets try to get it from the session and/or the request vars
178 // we do this early on in case there is a fatal error in retrieving the
179 // key and/or session
181 = CRM_Utils_Request
::retrieve('entryURL', 'String', $this);
183 // add a unique validable key to the name
184 $name = CRM_Utils_System
::getClassName($this);
185 if ($name == 'CRM_Core_Controller_Simple' && !empty($scope)) {
186 // use form name if we have, since its a lot better and
187 // definitely different for different forms
190 $name = $name . '_' . $this->key($name, $addSequence, $ignoreKey);
191 $this->_title
= $title;
193 $this->_scope
= $scope;
196 $this->_scope
= CRM_Utils_System
::getClassName($this);
198 $this->_scope
= $this->_scope
. '_' . $this->_key
;
200 // only use the civicrm cache if we have a valid key
201 // else we clash with other users CRM-7059
202 if (!empty($this->_key
)) {
203 CRM_Core_Session
::registerAndRetrieveSessionObjects([
204 "_{$name}_container",
205 ['CiviCRM', $this->_scope
],
209 parent
::__construct($name, $modal);
211 $snippet = CRM_Utils_Array
::value('snippet', $_REQUEST);
214 $this->_print
= CRM_Core_Smarty
::PRINT_PDF
;
216 elseif ($snippet == 4) {
217 // this is used to embed fragments of a form
218 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
219 self
::$_template->assign('suppressForm', TRUE);
220 $this->_generateQFKey
= FALSE;
222 elseif ($snippet == 5) {
223 // mode deprecated in favor of json
224 // still used by dashlets, probably nothing else
225 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
227 // Respond with JSON if in AJAX context (also support legacy value '6')
228 elseif (in_array($snippet, [CRM_Core_Smarty
::PRINT_JSON
, 6])) {
229 $this->_print
= CRM_Core_Smarty
::PRINT_JSON
;
230 $this->_QFResponseType
= 'json';
233 $this->_print
= CRM_Core_Smarty
::PRINT_SNIPPET
;
237 // if the request has a reset value, initialize the controller session
238 if (!empty($_GET['reset'])) {
241 // in this case we'll also cache the url as a hidden form variable, this allows us to
242 // redirect in case the session has disappeared on us
243 $this->_entryURL
= CRM_Utils_System
::makeURL(NULL, TRUE, FALSE, NULL, TRUE);
244 $this->set('entryURL', $this->_entryURL
);
247 // set the key in the session
248 // do this at the end so we have initialized the object
249 // and created the scope etc
250 $this->set('qfKey', $this->_key
);
252 // also retrieve and store destination in session
253 $this->_destination
= CRM_Utils_Request
::retrieve(
254 'civicrmDestination',
263 public function fini() {
264 CRM_Core_BAO_Cache
::storeSessionToCache([
265 "_{$this->_name}_container",
266 ['CiviCRM', $this->_scope
],
271 * @param string $name
272 * @param bool $addSequence
273 * @param bool $ignoreKey
275 * @return mixed|string
277 public function key($name, $addSequence = FALSE, $ignoreKey = FALSE) {
278 $config = CRM_Core_Config
::singleton();
282 (isset($config->keyDisable
) && $config->keyDisable
)
287 $key = CRM_Utils_Array
::value('qfKey', $_REQUEST, NULL);
288 if (!$key && $_SERVER['REQUEST_METHOD'] === 'GET') {
289 $key = CRM_Core_Key
::get($name, $addSequence);
292 $key = CRM_Core_Key
::validate($key, $name, $addSequence);
305 * Process the request, overrides the default QFC run method
306 * This routine actually checks if the QFC is modal and if it
307 * is the first invalid page, if so it call the requested action
308 * if not, it calls the display action on the first invalid page
309 * avoids the issue of users hitting the back button and getting
312 * This run is basically a composition of the original run and the
317 public function run() {
318 // the names of the action and page should be saved
319 // note that this is split into two, because some versions of
320 // php 5.x core dump on the triple assignment :)
321 $this->_actionName
= $this->getActionName();
322 list($pageName, $action) = $this->_actionName
;
324 if ($this->isModal()) {
325 if (!$this->isValid($pageName)) {
326 $pageName = $this->findInvalid();
331 // note that based on action, control might not come back!!
332 // e.g. if action is a valid JUMP, u basically do a redirect
333 // to the appropriate place
334 $this->wizardHeader($pageName);
335 return $this->_pages
[$pageName]->handle($action);
341 public function validate() {
342 $this->_actionName
= $this->getActionName();
343 list($pageName, $action) = $this->_actionName
;
345 $page = &$this->_pages
[$pageName];
347 $data = &$this->container();
348 $this->applyDefaults($pageName);
349 $page->isFormBuilt() or $page->buildForm();
350 // We use defaults and constants as if they were submitted
351 $data['values'][$pageName] = $page->exportValues();
352 $page->loadValues($data['values'][$pageName]);
353 // Is the page now valid?
354 if (TRUE === ($data['valid'][$pageName] = $page->validate())) {
357 return $page->_errors
;
361 * Helper function to add all the needed default actions.
363 * Note that the framework redefines all of the default QFC actions.
365 * @param string $uploadDirectory to store all the uploaded files
366 * @param array $uploadNames for the various upload buttons (note u can have more than 1 upload)
368 public function addActions($uploadDirectory = NULL, $uploadNames = NULL) {
370 'display' => 'CRM_Core_QuickForm_Action_Display',
371 'next' => 'CRM_Core_QuickForm_Action_Next',
372 'back' => 'CRM_Core_QuickForm_Action_Back',
373 'process' => 'CRM_Core_QuickForm_Action_Process',
374 'cancel' => 'CRM_Core_QuickForm_Action_Cancel',
375 'refresh' => 'CRM_Core_QuickForm_Action_Refresh',
376 'reload' => 'CRM_Core_QuickForm_Action_Reload',
377 'done' => 'CRM_Core_QuickForm_Action_Done',
378 'jump' => 'CRM_Core_QuickForm_Action_Jump',
379 'submit' => 'CRM_Core_QuickForm_Action_Submit',
382 foreach ($names as $name => $classPath) {
383 $action = new $classPath($this->_stateMachine
);
384 $this->addAction($name, $action);
387 $this->addUploadAction($uploadDirectory, $uploadNames);
391 * Getter method for stateMachine.
393 * @return CRM_Core_StateMachine
395 public function getStateMachine() {
396 return $this->_stateMachine
;
400 * Setter method for stateMachine.
402 * @param CRM_Core_StateMachine $stateMachine
404 public function setStateMachine($stateMachine) {
405 $this->_stateMachine
= $stateMachine;
409 * Add pages to the controller. Note that the controller does not really care
410 * the order in which the pages are added
412 * @param CRM_Core_StateMachine $stateMachine
413 * @param \const|int $action the mode in which the state machine is operating
414 * typically this will be add/view/edit
416 public function addPages(&$stateMachine, $action = CRM_Core_Action
::NONE
) {
417 $pages = $stateMachine->getPages();
418 foreach ($pages as $name => $value) {
419 $className = CRM_Utils_Array
::value('className', $value, $name);
420 $title = CRM_Utils_Array
::value('title', $value);
421 $options = CRM_Utils_Array
::value('options', $value);
422 $stateName = CRM_Utils_String
::getClassName($className);
423 if (!empty($value['className'])) {
427 $formName = CRM_Utils_String
::getClassName($name);
430 $ext = CRM_Extension_System
::singleton()->getMapper();
431 if ($ext->isExtensionClass($className)) {
432 require_once $ext->classToPath($className);
435 require_once str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php';
437 $
$stateName = new $className($stateMachine->find($className), $action, 'post', $formName);
439 $
$stateName->setTitle($title);
442 $
$stateName->setOptions($options);
444 if (property_exists($
$stateName, 'urlPath')) {
445 $
$stateName->urlPath
= explode('/', (string) CRM_Utils_System
::getUrlPath());
447 $this->addPage($
$stateName);
448 $this->addAction($stateName, new HTML_QuickForm_Action_Direct());
450 //CRM-6342 -we need kill the reference here,
451 //as we have deprecated reference object creation.
457 * QFC does not provide native support to have different 'submit' buttons.
458 * We introduce this notion to QFC by using button specific data. Thus if
459 * we have two submit buttons, we could have one displayed as a button and
460 * the other as an image, both are of type 'submit'.
463 * the name of the button that has been pressed by the user
465 public function getButtonName() {
466 $data = &$this->container();
467 return $data['_qf_button_name'] ??
NULL;
471 * Destroy all the session state of the controller.
473 public function reset() {
474 $this->container(TRUE);
475 self
::$_session->resetScope($this->_scope
);
479 * Virtual function to do any processing of data.
481 * Sometimes it is useful for the controller to actually process data.
482 * This is typically used when we need the controller to figure out
483 * what pages are potentially involved in this wizard. (this is dynamic
484 * and can change based on the arguments
486 public function process() {
490 * Store the variable with the value in the form scope.
492 * @param string|array $name name of the variable or an assoc array of name/value pairs
493 * @param mixed $value
494 * Value of the variable if string.
496 public function set($name, $value = NULL) {
497 self
::$_session->set($name, $value, $this->_scope
);
501 * Get the variable from the form scope.
503 * @param string $name
504 * name of the variable.
508 public function get($name) {
509 return self
::$_session->get($name, $this->_scope
);
513 * Create the header for the wizard from the list of pages.
514 * Store the created header in smarty
516 * @param string $currentPageName
517 * Name of the page being displayed.
521 public function wizardHeader($currentPageName) {
523 $wizard['steps'] = [];
525 foreach ($this->_pages
as $name => $page) {
527 $wizard['steps'][] = [
529 'title' => $page->getTitle(),
530 //'link' => $page->getLink ( ),
534 'stepNumber' => $count,
535 'collapsed' => FALSE,
538 if ($name == $currentPageName) {
539 $wizard['currentStepNumber'] = $count;
540 $wizard['currentStepName'] = $name;
541 $wizard['currentStepTitle'] = $page->getTitle();
545 $wizard['stepCount'] = $count;
547 $this->addWizardStyle($wizard);
549 $this->assign('wizard', $wizard);
554 * @param array $wizard
556 public function addWizardStyle(&$wizard) {
559 'stepPrefixCurrent' => '»',
560 'stepPrefixPast' => '✔',
561 'stepPrefixFuture' => ' ',
562 'subStepPrefixCurrent' => ' ',
563 'subStepPrefixPast' => ' ',
564 'subStepPrefixFuture' => ' ',
570 * Assign value to name in template.
573 * @param mixed $value
576 public function assign($var, $value = NULL) {
577 self
::$_template->assign($var, $value);
581 * Assign value to name in template by reference.
584 * @param mixed $value
585 * (reference) value of variable.
587 public function assign_by_ref($var, &$value) {
588 self
::$_template->assign_by_ref($var, $value);
592 * Appends values to template variables.
594 * @param array|string $tpl_var the template variable name(s)
595 * @param mixed $value
596 * The value to append.
599 public function append($tpl_var, $value = NULL, $merge = FALSE) {
600 self
::$_template->append($tpl_var, $value, $merge);
604 * Returns an array containing template variables.
606 * @param string $name
610 public function get_template_vars($name = NULL) {
611 return self
::$_template->get_template_vars($name);
615 * Setter for embedded.
617 * @param bool $embedded
619 public function setEmbedded($embedded) {
620 $this->_embedded
= $embedded;
624 * Getter for embedded.
627 * return the embedded value
629 public function getEmbedded() {
630 return $this->_embedded
;
634 * Setter for skipRedirection.
636 * @param bool $skipRedirection
638 public function setSkipRedirection($skipRedirection) {
639 $this->_skipRedirection
= $skipRedirection;
643 * Getter for skipRedirection.
646 * return the skipRedirection value
648 public function getSkipRedirection() {
649 return $this->_skipRedirection
;
653 * @param null $fileName
655 public function setWord($fileName = NULL) {
656 //Mark as a CSV file.
657 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/vnd.ms-word');
659 //Force a download and name the file using the current timestamp.
661 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.doc';
663 CRM_Utils_System
::setHttpHeader("Content-Disposition", "attachment; filename=Contacts_$fileName");
667 * @param null $fileName
669 public function setExcel($fileName = NULL) {
670 //Mark as an excel file.
671 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/vnd.ms-excel');
673 //Force a download and name the file using the current timestamp.
675 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.xls';
678 CRM_Utils_System
::setHttpHeader("Content-Disposition", "attachment; filename=Contacts_$fileName");
686 public function setPrint($print) {
687 if ($print == "xls") {
690 elseif ($print == "doc") {
693 $this->_print
= $print;
700 * return the print value
702 public function getPrint() {
703 return $this->_print
;
709 public function getTemplateFile() {
711 if ($this->_print
== CRM_Core_Smarty
::PRINT_PAGE
) {
712 return 'CRM/common/print.tpl';
714 elseif ($this->_print
== 'xls' ||
$this->_print
== 'doc') {
715 return 'CRM/Contact/Form/Task/Excel.tpl';
718 return 'CRM/common/snippet.tpl';
722 $config = CRM_Core_Config
::singleton();
723 return 'CRM/common/' . strtolower($config->userFramework
) . '.tpl';
729 * @param $uploadNames
731 public function addUploadAction($uploadDir, $uploadNames) {
732 if (empty($uploadDir)) {
733 $config = CRM_Core_Config
::singleton();
734 $uploadDir = $config->uploadDir
;
737 if (empty($uploadNames)) {
738 $uploadNames = $this->get('uploadNames');
739 if (!empty($uploadNames)) {
740 $uploadNames = array_merge($uploadNames,
741 CRM_Core_BAO_File
::uploadNames()
745 $uploadNames = CRM_Core_BAO_File
::uploadNames();
749 $action = new CRM_Core_QuickForm_Action_Upload($this->_stateMachine
,
753 $this->addAction('upload', $action);
759 public function setParent($parent) {
760 $this->_parent
= $parent;
766 public function getParent() {
767 return $this->_parent
;
773 public function getDestination() {
774 return $this->_destination
;
779 * @param bool $setToReferer
781 public function setDestination($url = NULL, $setToReferer = FALSE) {
784 $url = $_SERVER['HTTP_REFERER'];
787 $config = CRM_Core_Config
::singleton();
788 $url = $config->userFrameworkBaseURL
;
792 $this->_destination
= $url;
793 $this->set('civicrmDestination', $this->_destination
);
799 public function cancelAction() {
800 $actionName = $this->getActionName();
801 list($pageName, $action) = $actionName;
802 return $this->_pages
[$pageName]->cancelAction();
806 * Write a simple fatal error message.
808 * Other controllers can decide to do something else and present the user a better message
809 * and/or redirect to the same page with a reset url
811 public function invalidKey() {
812 self
::invalidKeyCommon();
815 public function invalidKeyCommon() {
816 $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.');
817 CRM_Core_Error
::fatal($msg);
821 * Instead of outputting a fatal error message, we'll just redirect
822 * to the entryURL if present
824 public function invalidKeyRedirect() {
825 if ($this->_entryURL
&& $url_parts = parse_url($this->_entryURL
)) {
826 // CRM-16832: Ensure local redirects only.
827 if (!empty($url_parts['path'])) {
828 // Prepend a slash, but don't duplicate it.
829 $redirect_url = '/' . ltrim($url_parts['path'], '/');
830 if (!empty($url_parts['query'])) {
831 $redirect_url .= '?' . $url_parts['query'];
833 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.'));
834 return CRM_Utils_System
::redirect($redirect_url);
837 self
::invalidKeyCommon();