3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * This class acts as our base controller class and adds additional
30 * functionality and smarts to the base QFC. Specifically we create
31 * our own action classes and handle the transitions ourselves by
32 * simulating a state machine. We also create direct jump links to any
33 * page that can be used universally.
35 * This concept has been discussed on the PEAR list and the QFC FAQ
36 * goes into a few details. Please check
37 * http://pear.php.net/manual/en/package.html.html-quickform-controller.faq.php
38 * for other useful tips and suggestions
41 * @copyright CiviCRM LLC (c) 2004-2013
46 require_once 'HTML/QuickForm/Controller.php';
47 require_once 'HTML/QuickForm/Action/Direct.php';
49 class CRM_Core_Controller
extends HTML_QuickForm_Controller
{
52 * the title associated with this controller
59 * The key associated with this controller
66 * the name of the session scope where values are stored
73 * the state machine associated with this controller
77 protected $_stateMachine;
80 * Is this object being embedded in another object. If
81 * so the display routine needs to not do any work. (The
82 * parent object takes care of the display)
86 protected $_embedded = FALSE;
89 * After entire form execution complete,
90 * do we want to skip control redirection.
91 * Default - It get redirect to user context.
93 * Useful when we run form in non civicrm context
94 * and we need to transfer control back.(eg. drupal)
98 protected $_skipRedirection = FALSE;
101 * Are we in print mode? if so we need to modify the display
102 * functionality to do a minimal display :)
109 * Should we generate a qfKey, true by default
113 public $_generateQFKey = TRUE;
118 public $_QFResponseType = 'html';
121 * cache the smarty template for efficiency reasons
123 * @var CRM_Core_Smarty
125 static protected $_template;
128 * cache the session for efficiency reasons
130 * @var CRM_Core_Session
132 static protected $_session;
135 * The parent of this form if embedded
139 protected $_parent = NULL;
142 * The destination if set will override the destination the code wants to send it to
146 public $_destination = NULL;
149 * The entry url for a top level form or wizard. Typically the URL with a reset=1
150 * used to redirect back to when we land into some session wierdness
154 public $_entryURL = NULL;
157 * All CRM single or multi page pages should inherit from this class.
159 * @param string title descriptive title of the controller
160 * @param boolean whether controller is modal
161 * @param string scope name of session if we want unique scope, used only by Controller_Simple
162 * @param boolean addSequence should we add a unique sequence number to the end of the key
163 * @param boolean ignoreKey should we not set a qfKey for this controller (for standalone forms)
170 function __construct(
175 $addSequence = FALSE,
178 // this has to true for multiple tab session fix
181 // let the constructor initialize this, should happen only once
182 if (!isset(self
::$_template)) {
183 self
::$_template = CRM_Core_Smarty
::singleton();
184 self
::$_session = CRM_Core_Session
::singleton();
187 // lets try to get it from the session and/or the request vars
188 // we do this early on in case there is a fatal error in retrieving the
189 // key and/or session
191 CRM_Utils_Request
::retrieve('entryURL', 'String', $this);
193 // add a unique validable key to the name
194 $name = CRM_Utils_System
::getClassName($this);
195 if ($name == 'CRM_Core_Controller_Simple' && !empty($scope)) {
196 // use form name if we have, since its a lot better and
197 // definitely different for different forms
200 $name = $name . '_' . $this->key($name, $addSequence, $ignoreKey);
201 $this->_title
= $title;
203 $this->_scope
= $scope;
206 $this->_scope
= CRM_Utils_System
::getClassName($this);
208 $this->_scope
= $this->_scope
. '_' . $this->_key
;
210 // only use the civicrm cache if we have a valid key
211 // else we clash with other users CRM-7059
212 if (!empty($this->_key
)) {
213 CRM_Core_Session
::registerAndRetrieveSessionObjects(array(
214 "_{$name}_container",
215 array('CiviCRM', $this->_scope
),
219 $this->HTML_QuickForm_Controller($name, $modal);
221 $snippet = CRM_Utils_Array
::value('snippet', $_REQUEST);
224 $this->_print
= CRM_Core_Smarty
::PRINT_PDF
;
226 elseif ($snippet == 4) {
227 // this is used to embed fragments of a form
228 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
229 self
::$_template->assign('suppressForm', TRUE);
230 $this->_generateQFKey
= FALSE;
232 elseif ($snippet == 5) {
233 // this is used for popups and inlined ajax forms
234 // also used for the various tabs via TabHeader
235 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
237 elseif ($snippet == 6) {
238 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
239 $this->_QFResponseType
= 'json';
242 $this->_print
= CRM_Core_Smarty
::PRINT_SNIPPET
;
246 // if the request has a reset value, initialize the controller session
247 if (CRM_Utils_Array
::value('reset', $_GET)) {
250 // in this case we'll also cache the url as a hidden form variable, this allows us to
251 // redirect in case the session has disappeared on us
252 $this->_entryURL
= CRM_Utils_System
::makeURL(NULL, TRUE, FALSE, NULL, TRUE);
253 $this->set('entryURL', $this->_entryURL
);
256 // set the key in the session
257 // do this at the end so we have initialized the object
258 // and created the scope etc
259 $this->set('qfKey', $this->_key
);
262 // also retrieve and store destination in session
263 $this->_destination
= CRM_Utils_Request
::retrieve(
264 'civicrmDestination',
274 CRM_Core_BAO_Cache
::storeSessionToCache(array(
275 "_{$this->_name}_container",
276 array('CiviCRM', $this->_scope
),
282 function key($name, $addSequence = FALSE, $ignoreKey = FALSE) {
283 $config = CRM_Core_Config
::singleton();
287 (isset($config->keyDisable
) && $config->keyDisable
)
292 $key = CRM_Utils_Array
::value('qfKey', $_REQUEST, NULL);
293 if (!$key && $_SERVER['REQUEST_METHOD'] === 'GET') {
294 $key = CRM_Core_Key
::get($name, $addSequence);
297 $key = CRM_Core_Key
::validate($key, $name, $addSequence);
310 * Process the request, overrides the default QFC run method
311 * This routine actually checks if the QFC is modal and if it
312 * is the first invalid page, if so it call the requested action
313 * if not, it calls the display action on the first invalid page
314 * avoids the issue of users hitting the back button and getting
317 * This run is basically a composition of the original run and the
322 // the names of the action and page should be saved
323 // note that this is split into two, because some versions of
324 // php 5.x core dump on the triple assignment :)
325 $this->_actionName
= $this->getActionName();
326 list($pageName, $action) = $this->_actionName
;
328 if ($this->isModal()) {
329 if (!$this->isValid($pageName)) {
330 $pageName = $this->findInvalid();
335 // note that based on action, control might not come back!!
336 // e.g. if action is a valid JUMP, u basically do a redirect
337 // to the appropriate place
338 $this->wizardHeader($pageName);
339 return $this->_pages
[$pageName]->handle($action);
342 function validate() {
343 $this->_actionName
= $this->getActionName();
344 list($pageName, $action) = $this->_actionName
;
346 $page = &$this->_pages
[$pageName];
348 $data = &$this->container();
349 $this->applyDefaults($pageName);
350 $page->isFormBuilt() or $page->buildForm();
351 // We use defaults and constants as if they were submitted
352 $data['values'][$pageName] = $page->exportValues();
353 $page->loadValues($data['values'][$pageName]);
354 // Is the page now valid?
355 if (TRUE === ($data['valid'][$pageName] = $page->validate())) {
358 return $page->_errors
;
362 * Helper function to add all the needed default actions. Note that the framework
363 * redefines all of the default QFC actions
365 * @param string directory to store all the uploaded files
366 * @param array names for the various upload buttons (note u can have more than 1 upload)
373 function addActions($uploadDirectory = NULL, $uploadNames = NULL) {
375 'display' => 'CRM_Core_QuickForm_Action_Display',
376 'next' => 'CRM_Core_QuickForm_Action_Next',
377 'back' => 'CRM_Core_QuickForm_Action_Back',
378 'process' => 'CRM_Core_QuickForm_Action_Process',
379 'cancel' => 'CRM_Core_QuickForm_Action_Cancel',
380 'refresh' => 'CRM_Core_QuickForm_Action_Refresh',
381 'reload' => 'CRM_Core_QuickForm_Action_Reload',
382 'done' => 'CRM_Core_QuickForm_Action_Done',
383 'jump' => 'CRM_Core_QuickForm_Action_Jump',
384 'submit' => 'CRM_Core_QuickForm_Action_Submit',
387 foreach ($names as $name => $classPath) {
388 $action = new $classPath($this->_stateMachine
);
389 $this->addAction($name, $action);
392 $this->addUploadAction($uploadDirectory, $uploadNames);
396 * getter method for stateMachine
401 function getStateMachine() {
402 return $this->_stateMachine
;
406 * setter method for stateMachine
408 * @param object a stateMachineObject
413 function setStateMachine($stateMachine) {
414 $this->_stateMachine
= $stateMachine;
418 * add pages to the controller. Note that the controller does not really care
419 * the order in which the pages are added
421 * @param object $stateMachine the state machine object
422 * @param int $action the mode in which the state machine is operating
423 * typicaly this will be add/view/edit
429 function addPages(&$stateMachine, $action = CRM_Core_Action
::NONE
) {
430 $pages = $stateMachine->getPages();
431 foreach ($pages as $name => $value) {
432 $className = CRM_Utils_Array
::value('className', $value, $name);
433 $title = CRM_Utils_Array
::value('title', $value);
434 $options = CRM_Utils_Array
::value('options', $value);
435 $stateName = CRM_Utils_String
::getClassName($className);
436 if (CRM_Utils_Array
::value('className', $value)) {
440 $formName = CRM_Utils_String
::getClassName($name);
443 $ext = CRM_Extension_System
::singleton()->getMapper();
444 if ($ext->isExtensionClass($className)) {
445 require_once ($ext->classToPath($className));
448 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php');
450 $
$stateName = new $className($stateMachine->find($className), $action, 'post', $formName);
452 $
$stateName->setTitle($title);
455 $
$stateName->setOptions($options);
457 $this->addPage($
$stateName);
458 $this->addAction($stateName, new HTML_QuickForm_Action_Direct());
460 //CRM-6342 -we need kill the reference here,
461 //as we have deprecated reference object creation.
467 * QFC does not provide native support to have different 'submit' buttons.
468 * We introduce this notion to QFC by using button specific data. Thus if
469 * we have two submit buttons, we could have one displayed as a button and
470 * the other as an image, both are of type 'submit'.
472 * @return string the name of the button that has been pressed by the user
475 function getButtonName() {
476 $data = &$this->container();
477 return CRM_Utils_Array
::value('_qf_button_name', $data);
481 * function to destroy all the session state of the controller.
488 $this->container(TRUE);
489 self
::$_session->resetScope($this->_scope
);
493 * virtual function to do any processing of data.
494 * Sometimes it is useful for the controller to actually process data.
495 * This is typically used when we need the controller to figure out
496 * what pages are potentially involved in this wizard. (this is dynamic
497 * and can change based on the arguments
502 function process() {}
505 * Store the variable with the value in the form scope
507 * @param string|array $name name of the variable or an assoc array of name/value pairs
508 * @param mixed $value value of the variable if string
515 function set($name, $value = NULL) {
516 self
::$_session->set($name, $value, $this->_scope
);
520 * Get the variable from the form scope
522 * @param string name : name of the variable
530 function get($name) {
531 return self
::$_session->get($name, $this->_scope
);
535 * Create the header for the wizard from the list of pages
536 * Store the created header in smarty
538 * @param string $currentPageName name of the page being displayed
543 function wizardHeader($currentPageName) {
545 $wizard['steps'] = array();
547 foreach ($this->_pages
as $name => $page) {
549 $wizard['steps'][] = array(
551 'title' => $page->getTitle(),
552 //'link' => $page->getLink ( ),
556 'stepNumber' => $count,
557 'collapsed' => FALSE,
560 if ($name == $currentPageName) {
561 $wizard['currentStepNumber'] = $count;
562 $wizard['currentStepName'] = $name;
563 $wizard['currentStepTitle'] = $page->getTitle();
567 $wizard['stepCount'] = $count;
569 $this->addWizardStyle($wizard);
571 $this->assign('wizard', $wizard);
575 function addWizardStyle(&$wizard) {
576 $wizard['style'] = array(
578 'stepPrefixCurrent' => '»',
579 'stepPrefixPast' => '√',
580 'stepPrefixFuture' => ' ',
581 'subStepPrefixCurrent' => ' ',
582 'subStepPrefixPast' => ' ',
583 'subStepPrefixFuture' => ' ',
589 * assign value to name in template
591 * @param array|string $name name of variable
592 * @param mixed $value value of varaible
597 function assign($var, $value = NULL) {
598 self
::$_template->assign($var, $value);
602 * assign value to name in template by reference
604 * @param array|string $name name of variable
605 * @param mixed $value (reference) value of varaible
610 function assign_by_ref($var, &$value) {
611 self
::$_template->assign_by_ref($var, $value);
615 * appends values to template variables
617 * @param array|string $tpl_var the template variable name(s)
618 * @param mixed $value the value to append
621 function append($tpl_var, $value=NULL, $merge=FALSE) {
622 self
::$_template->append($tpl_var, $value, $merge);
626 * Returns an array containing template variables
628 * @param string $name
629 * @param string $type
632 function get_template_vars($name=null) {
633 return self
::$_template->get_template_vars($name);
637 * setter for embedded
639 * @param boolean $embedded
644 function setEmbedded($embedded) {
645 $this->_embedded
= $embedded;
649 * getter for embedded
651 * @return boolean return the embedded value
654 function getEmbedded() {
655 return $this->_embedded
;
659 * setter for skipRedirection
661 * @param boolean $skipRedirection
666 function setSkipRedirection($skipRedirection) {
667 $this->_skipRedirection
= $skipRedirection;
671 * getter for skipRedirection
673 * @return boolean return the skipRedirection value
676 function getSkipRedirection() {
677 return $this->_skipRedirection
;
680 function setWord($fileName = NULL) {
681 //Mark as a CSV file.
682 header('Content-Type: application/vnd.ms-word');
684 //Force a download and name the file using the current timestamp.
686 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.doc';
688 header("Content-Disposition: attachment; filename=Contacts_$fileName");
691 function setExcel($fileName = NULL) {
692 //Mark as an excel file.
693 header('Content-Type: application/vnd.ms-excel');
695 //Force a download and name the file using the current timestamp.
697 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.xls';
700 header("Content-Disposition: attachment; filename=Contacts_$fileName");
706 * @param boolean $print
711 function setPrint($print) {
712 if ($print == "xls") {
715 elseif ($print == "doc") {
718 $this->_print
= $print;
724 * @return boolean return the print value
727 function getPrint() {
728 return $this->_print
;
731 function getTemplateFile() {
733 if ($this->_print
== CRM_Core_Smarty
::PRINT_PAGE
) {
734 return 'CRM/common/print.tpl';
736 elseif ($this->_print
== 'xls' ||
$this->_print
== 'doc') {
737 return 'CRM/Contact/Form/Task/Excel.tpl';
740 return 'CRM/common/snippet.tpl';
744 $config = CRM_Core_Config
::singleton();
745 return 'CRM/common/' . strtolower($config->userFramework
) . '.tpl';
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);
774 public function setParent($parent) {
775 $this->_parent
= $parent;
778 public function getParent() {
779 return $this->_parent
;
782 public function getDestination() {
783 return $this->_destination
;
786 public function setDestination($url = NULL, $setToReferer = FALSE) {
789 $url = $_SERVER['HTTP_REFERER'];
792 $config = CRM_Core_Config
::singleton();
793 $url = $config->userFrameworkBaseURL
;
797 $this->_destination
= $url;
798 $this->set('civicrmDestination', $this->_destination
);
801 public function cancelAction() {
802 $actionName = $this->getActionName();
803 list($pageName, $action) = $actionName;
804 return $this->_pages
[$pageName]->cancelAction();
808 * Write a simple fatal error message. Other controllers can decide to do something else
809 * and present the user a better message and/or redirect to the same page with a reset url
814 public function invalidKey() {
815 self
::invalidKeyCommon();
818 public function invalidKeyCommon() {
819 $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 adminstrator 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.');
820 CRM_Core_Error
::fatal($msg);
824 * Instead of outputting a fatal error message, we'll just redirect to the entryURL if present
828 public function invalidKeyRedirect() {
829 if ($this->_entryURL
) {
830 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.'));
831 return CRM_Utils_System
::redirect($this->_entryURL
);
834 self
::invalidKeyCommon();