3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
46 require_once 'HTML/QuickForm/Controller.php';
47 require_once 'HTML/QuickForm/Action/Direct.php';
50 * Class CRM_Core_Controller
52 class CRM_Core_Controller
extends HTML_QuickForm_Controller
{
55 * The title associated with this controller
62 * The key associated with this controller
69 * The name of the session scope where values are stored
76 * The state machine associated with this controller
80 protected $_stateMachine;
83 * Is this object being embedded in another object. If
84 * so the display routine needs to not do any work. (The
85 * parent object takes care of the display)
89 protected $_embedded = FALSE;
92 * After entire form execution complete,
93 * do we want to skip control redirection.
94 * Default - It get redirect to user context.
96 * Useful when we run form in non civicrm context
97 * and we need to transfer control back.(eg. drupal)
101 protected $_skipRedirection = FALSE;
104 * Are we in print mode? if so we need to modify the display
105 * functionality to do a minimal display :)
112 * Should we generate a qfKey, true by default
116 public $_generateQFKey = TRUE;
121 public $_QFResponseType = 'html';
124 * Cache the smarty template for efficiency reasons
126 * @var CRM_Core_Smarty
128 static protected $_template;
131 * Cache the session for efficiency reasons
133 * @var CRM_Core_Session
135 static protected $_session;
138 * The parent of this form if embedded
142 protected $_parent = NULL;
145 * The destination if set will override the destination the code wants to send it to
149 public $_destination = NULL;
152 * The entry url for a top level form or wizard. Typically the URL with a reset=1
153 * used to redirect back to when we land into some session wierdness
157 public $_entryURL = NULL;
160 * All CRM single or multi page pages should inherit from this class.
162 * @param string $title descriptive title of the controller
163 * @param bool $modal whether controller is modal
165 * @param string $scope name of session if we want unique scope, used only by Controller_Simple
166 * @param bool $addSequence should we add a unique sequence number to the end of the key
167 * @param bool $ignoreKey should we not set a qfKey for this controller (for standalone forms)
170 * @return CRM_Core_Controller
172 function __construct(
177 $addSequence = FALSE,
180 // this has to true for multiple tab session fix
183 // let the constructor initialize this, should happen only once
184 if (!isset(self
::$_template)) {
185 self
::$_template = CRM_Core_Smarty
::singleton();
186 self
::$_session = CRM_Core_Session
::singleton();
189 // lets try to get it from the session and/or the request vars
190 // we do this early on in case there is a fatal error in retrieving the
191 // key and/or session
193 CRM_Utils_Request
::retrieve('entryURL', 'String', $this);
195 // add a unique validable key to the name
196 $name = CRM_Utils_System
::getClassName($this);
197 if ($name == 'CRM_Core_Controller_Simple' && !empty($scope)) {
198 // use form name if we have, since its a lot better and
199 // definitely different for different forms
202 $name = $name . '_' . $this->key($name, $addSequence, $ignoreKey);
203 $this->_title
= $title;
205 $this->_scope
= $scope;
208 $this->_scope
= CRM_Utils_System
::getClassName($this);
210 $this->_scope
= $this->_scope
. '_' . $this->_key
;
212 // only use the civicrm cache if we have a valid key
213 // else we clash with other users CRM-7059
214 if (!empty($this->_key
)) {
215 CRM_Core_Session
::registerAndRetrieveSessionObjects(array(
216 "_{$name}_container",
217 array('CiviCRM', $this->_scope
),
221 $this->HTML_QuickForm_Controller($name, $modal);
223 $snippet = CRM_Utils_Array
::value('snippet', $_REQUEST);
226 $this->_print
= CRM_Core_Smarty
::PRINT_PDF
;
228 elseif ($snippet == 4) {
229 // this is used to embed fragments of a form
230 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
231 self
::$_template->assign('suppressForm', TRUE);
232 $this->_generateQFKey
= FALSE;
234 elseif ($snippet == 5) {
235 // mode deprecated in favor of json
236 // still used by dashlets, probably nothing else
237 $this->_print
= CRM_Core_Smarty
::PRINT_NOFORM
;
239 // Respond with JSON if in AJAX context (also support legacy value '6')
240 elseif (in_array($snippet, array(CRM_Core_Smarty
::PRINT_JSON
, 6))) {
241 $this->_print
= CRM_Core_Smarty
::PRINT_JSON
;
242 $this->_QFResponseType
= 'json';
245 $this->_print
= CRM_Core_Smarty
::PRINT_SNIPPET
;
249 // if the request has a reset value, initialize the controller session
250 if (!empty($_GET['reset'])) {
253 // in this case we'll also cache the url as a hidden form variable, this allows us to
254 // redirect in case the session has disappeared on us
255 $this->_entryURL
= CRM_Utils_System
::makeURL(NULL, TRUE, FALSE, NULL, TRUE);
256 $this->set('entryURL', $this->_entryURL
);
259 // set the key in the session
260 // do this at the end so we have initialized the object
261 // and created the scope etc
262 $this->set('qfKey', $this->_key
);
265 // also retrieve and store destination in session
266 $this->_destination
= CRM_Utils_Request
::retrieve(
267 'civicrmDestination',
276 public function fini() {
277 CRM_Core_BAO_Cache
::storeSessionToCache(array(
278 "_{$this->_name}_container",
279 array('CiviCRM', $this->_scope
),
286 * @param string $name
287 * @param bool $addSequence
288 * @param bool $ignoreKey
290 * @return mixed|string
292 public function key($name, $addSequence = FALSE, $ignoreKey = FALSE) {
293 $config = CRM_Core_Config
::singleton();
297 (isset($config->keyDisable
) && $config->keyDisable
)
302 $key = CRM_Utils_Array
::value('qfKey', $_REQUEST, NULL);
303 if (!$key && $_SERVER['REQUEST_METHOD'] === 'GET') {
304 $key = CRM_Core_Key
::get($name, $addSequence);
307 $key = CRM_Core_Key
::validate($key, $name, $addSequence);
320 * Process the request, overrides the default QFC run method
321 * This routine actually checks if the QFC is modal and if it
322 * is the first invalid page, if so it call the requested action
323 * if not, it calls the display action on the first invalid page
324 * avoids the issue of users hitting the back button and getting
327 * This run is basically a composition of the original run and the
331 public function run() {
332 // the names of the action and page should be saved
333 // note that this is split into two, because some versions of
334 // php 5.x core dump on the triple assignment :)
335 $this->_actionName
= $this->getActionName();
336 list($pageName, $action) = $this->_actionName
;
338 if ($this->isModal()) {
339 if (!$this->isValid($pageName)) {
340 $pageName = $this->findInvalid();
345 // note that based on action, control might not come back!!
346 // e.g. if action is a valid JUMP, u basically do a redirect
347 // to the appropriate place
348 $this->wizardHeader($pageName);
349 return $this->_pages
[$pageName]->handle($action);
355 public function validate() {
356 $this->_actionName
= $this->getActionName();
357 list($pageName, $action) = $this->_actionName
;
359 $page = &$this->_pages
[$pageName];
361 $data = &$this->container();
362 $this->applyDefaults($pageName);
363 $page->isFormBuilt() or $page->buildForm();
364 // We use defaults and constants as if they were submitted
365 $data['values'][$pageName] = $page->exportValues();
366 $page->loadValues($data['values'][$pageName]);
367 // Is the page now valid?
368 if (TRUE === ($data['valid'][$pageName] = $page->validate())) {
371 return $page->_errors
;
375 * Helper function to add all the needed default actions. Note that the framework
376 * redefines all of the default QFC actions
378 * @param string directory to store all the uploaded files
379 * @param array names for the various upload buttons (note u can have more than 1 upload)
385 public function addActions($uploadDirectory = NULL, $uploadNames = NULL) {
387 'display' => 'CRM_Core_QuickForm_Action_Display',
388 'next' => 'CRM_Core_QuickForm_Action_Next',
389 'back' => 'CRM_Core_QuickForm_Action_Back',
390 'process' => 'CRM_Core_QuickForm_Action_Process',
391 'cancel' => 'CRM_Core_QuickForm_Action_Cancel',
392 'refresh' => 'CRM_Core_QuickForm_Action_Refresh',
393 'reload' => 'CRM_Core_QuickForm_Action_Reload',
394 'done' => 'CRM_Core_QuickForm_Action_Done',
395 'jump' => 'CRM_Core_QuickForm_Action_Jump',
396 'submit' => 'CRM_Core_QuickForm_Action_Submit',
399 foreach ($names as $name => $classPath) {
400 $action = new $classPath($this->_stateMachine
);
401 $this->addAction($name, $action);
404 $this->addUploadAction($uploadDirectory, $uploadNames);
408 * Getter method for stateMachine
410 * @return CRM_Core_StateMachine
412 public function getStateMachine() {
413 return $this->_stateMachine
;
417 * Setter method for stateMachine
419 * @param CRM_Core_StateMachine $stateMachine
423 public function setStateMachine($stateMachine) {
424 $this->_stateMachine
= $stateMachine;
428 * Add pages to the controller. Note that the controller does not really care
429 * the order in which the pages are added
431 * @param CRM_Core_StateMachine $stateMachine
432 * @param \const|int $action the mode in which the state machine is operating
433 * typicaly this will be add/view/edit
437 public function addPages(&$stateMachine, $action = CRM_Core_Action
::NONE
) {
438 $pages = $stateMachine->getPages();
439 foreach ($pages as $name => $value) {
440 $className = CRM_Utils_Array
::value('className', $value, $name);
441 $title = CRM_Utils_Array
::value('title', $value);
442 $options = CRM_Utils_Array
::value('options', $value);
443 $stateName = CRM_Utils_String
::getClassName($className);
444 if (!empty($value['className'])) {
448 $formName = CRM_Utils_String
::getClassName($name);
451 $ext = CRM_Extension_System
::singleton()->getMapper();
452 if ($ext->isExtensionClass($className)) {
453 require_once ($ext->classToPath($className));
456 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $className) . '.php');
458 $
$stateName = new $className($stateMachine->find($className), $action, 'post', $formName);
460 $
$stateName->setTitle($title);
463 $
$stateName->setOptions($options);
465 if (property_exists($
$stateName, 'urlPath') && isset($_GET[CRM_Core_Config
::singleton()->userFrameworkURLVar
])) {
466 $
$stateName->urlPath
= explode('/', $_GET[CRM_Core_Config
::singleton()->userFrameworkURLVar
]);
468 $this->addPage($
$stateName);
469 $this->addAction($stateName, new HTML_QuickForm_Action_Direct());
471 //CRM-6342 -we need kill the reference here,
472 //as we have deprecated reference object creation.
478 * QFC does not provide native support to have different 'submit' buttons.
479 * We introduce this notion to QFC by using button specific data. Thus if
480 * we have two submit buttons, we could have one displayed as a button and
481 * the other as an image, both are of type 'submit'.
483 * @return string the name of the button that has been pressed by the user
485 public function getButtonName() {
486 $data = &$this->container();
487 return CRM_Utils_Array
::value('_qf_button_name', $data);
491 * Destroy all the session state of the controller.
496 public function reset() {
497 $this->container(TRUE);
498 self
::$_session->resetScope($this->_scope
);
502 * Virtual function to do any processing of data.
503 * Sometimes it is useful for the controller to actually process data.
504 * This is typically used when we need the controller to figure out
505 * what pages are potentially involved in this wizard. (this is dynamic
506 * and can change based on the arguments
510 public function process() {}
513 * Store the variable with the value in the form scope
515 * @param string|array $name name of the variable or an assoc array of name/value pairs
516 * @param mixed $value value of the variable if string
522 public function set($name, $value = NULL) {
523 self
::$_session->set($name, $value, $this->_scope
);
527 * Get the variable from the form scope
529 * @param string $name : name of the variable
536 public function get($name) {
537 return self
::$_session->get($name, $this->_scope
);
541 * Create the header for the wizard from the list of pages
542 * Store the created header in smarty
544 * @param string $currentPageName name of the page being displayed
548 public function wizardHeader($currentPageName) {
550 $wizard['steps'] = array();
552 foreach ($this->_pages
as $name => $page) {
554 $wizard['steps'][] = array(
556 'title' => $page->getTitle(),
557 //'link' => $page->getLink ( ),
561 'stepNumber' => $count,
562 'collapsed' => FALSE,
565 if ($name == $currentPageName) {
566 $wizard['currentStepNumber'] = $count;
567 $wizard['currentStepName'] = $name;
568 $wizard['currentStepTitle'] = $page->getTitle();
572 $wizard['stepCount'] = $count;
574 $this->addWizardStyle($wizard);
576 $this->assign('wizard', $wizard);
581 * @param array $wizard
583 public function addWizardStyle(&$wizard) {
584 $wizard['style'] = array(
586 'stepPrefixCurrent' => '»',
587 'stepPrefixPast' => '√',
588 'stepPrefixFuture' => ' ',
589 'subStepPrefixCurrent' => ' ',
590 'subStepPrefixPast' => ' ',
591 'subStepPrefixFuture' => ' ',
597 * Assign value to name in template
600 * @param mixed $value value of varaible
604 public function assign($var, $value = NULL) {
605 self
::$_template->assign($var, $value);
609 * Assign value to name in template by reference
612 * @param mixed $value (reference) value of varaible
616 public function assign_by_ref($var, &$value) {
617 self
::$_template->assign_by_ref($var, $value);
621 * Appends values to template variables
623 * @param array|string $tpl_var the template variable name(s)
624 * @param mixed $value the value to append
627 public function append($tpl_var, $value=NULL, $merge=FALSE) {
628 self
::$_template->append($tpl_var, $value, $merge);
632 * Returns an array containing template variables
634 * @param string $name
638 public function get_template_vars($name=null) {
639 return self
::$_template->get_template_vars($name);
643 * Setter for embedded
645 * @param boolean $embedded
649 public function setEmbedded($embedded) {
650 $this->_embedded
= $embedded;
654 * Getter for embedded
656 * @return boolean return the embedded value
658 public function getEmbedded() {
659 return $this->_embedded
;
663 * Setter for skipRedirection
665 * @param boolean $skipRedirection
669 public function setSkipRedirection($skipRedirection) {
670 $this->_skipRedirection
= $skipRedirection;
674 * Getter for skipRedirection
676 * @return boolean return the skipRedirection value
678 public function getSkipRedirection() {
679 return $this->_skipRedirection
;
683 * @param null $fileName
685 public function setWord($fileName = NULL) {
686 //Mark as a CSV file.
687 header('Content-Type: application/vnd.ms-word');
689 //Force a download and name the file using the current timestamp.
691 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.doc';
693 header("Content-Disposition: attachment; filename=Contacts_$fileName");
697 * @param null $fileName
699 public function setExcel($fileName = NULL) {
700 //Mark as an excel file.
701 header('Content-Type: application/vnd.ms-excel');
703 //Force a download and name the file using the current timestamp.
705 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.xls';
708 header("Content-Disposition: attachment; filename=Contacts_$fileName");
714 * @param boolean $print
718 public function setPrint($print) {
719 if ($print == "xls") {
722 elseif ($print == "doc") {
725 $this->_print
= $print;
731 * @return boolean return the print value
733 public function getPrint() {
734 return $this->_print
;
740 public function getTemplateFile() {
742 if ($this->_print
== CRM_Core_Smarty
::PRINT_PAGE
) {
743 return 'CRM/common/print.tpl';
745 elseif ($this->_print
== 'xls' ||
$this->_print
== 'doc') {
746 return 'CRM/Contact/Form/Task/Excel.tpl';
749 return 'CRM/common/snippet.tpl';
753 $config = CRM_Core_Config
::singleton();
754 return 'CRM/common/' . strtolower($config->userFramework
) . '.tpl';
760 * @param $uploadNames
762 public function addUploadAction($uploadDir, $uploadNames) {
763 if (empty($uploadDir)) {
764 $config = CRM_Core_Config
::singleton();
765 $uploadDir = $config->uploadDir
;
768 if (empty($uploadNames)) {
769 $uploadNames = $this->get('uploadNames');
770 if (!empty($uploadNames)) {
771 $uploadNames = array_merge($uploadNames,
772 CRM_Core_BAO_File
::uploadNames()
776 $uploadNames = CRM_Core_BAO_File
::uploadNames();
780 $action = new CRM_Core_QuickForm_Action_Upload($this->_stateMachine
,
784 $this->addAction('upload', $action);
790 public function setParent($parent) {
791 $this->_parent
= $parent;
797 public function getParent() {
798 return $this->_parent
;
804 public function getDestination() {
805 return $this->_destination
;
810 * @param bool $setToReferer
812 public function setDestination($url = NULL, $setToReferer = FALSE) {
815 $url = $_SERVER['HTTP_REFERER'];
818 $config = CRM_Core_Config
::singleton();
819 $url = $config->userFrameworkBaseURL
;
823 $this->_destination
= $url;
824 $this->set('civicrmDestination', $this->_destination
);
830 public function cancelAction() {
831 $actionName = $this->getActionName();
832 list($pageName, $action) = $actionName;
833 return $this->_pages
[$pageName]->cancelAction();
837 * Write a simple fatal error message. Other controllers can decide to do something else
838 * and present the user a better message and/or redirect to the same page with a reset url
843 public function invalidKey() {
844 self
::invalidKeyCommon();
847 public function invalidKeyCommon() {
848 $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.');
849 CRM_Core_Error
::fatal($msg);
853 * Instead of outputting a fatal error message, we'll just redirect to the entryURL if present
857 public function invalidKeyRedirect() {
858 if ($this->_entryURL
) {
859 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.'));
860 return CRM_Utils_System
::redirect($this->_entryURL
);
863 self
::invalidKeyCommon();