Merge pull request #1814 from dlobo/MiscFixes
[civicrm-core.git] / CRM / Core / Controller.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
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.
34 *
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
39 *
40 * @package CRM
41 * @copyright CiviCRM LLC (c) 2004-2013
42 * $Id$
43 *
44 */
45
46require_once 'HTML/QuickForm/Controller.php';
47require_once 'HTML/QuickForm/Action/Direct.php';
48
49class CRM_Core_Controller extends HTML_QuickForm_Controller {
50
51 /**
52 * the title associated with this controller
53 *
54 * @var string
55 */
56 protected $_title;
57
58 /**
59 * The key associated with this controller
60 *
61 * @var string
62 */
63 public $_key;
64
65 /**
66 * the name of the session scope where values are stored
67 *
68 * @var object
69 */
70 protected $_scope;
71
72 /**
73 * the state machine associated with this controller
74 *
75 * @var object
76 */
77 protected $_stateMachine;
78
79 /**
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)
83 *
84 * @var boolean
85 */
86 protected $_embedded = FALSE;
87
88 /**
89 * After entire form execution complete,
90 * do we want to skip control redirection.
91 * Default - It get redirect to user context.
92 *
93 * Useful when we run form in non civicrm context
94 * and we need to transfer control back.(eg. drupal)
95 *
96 * @var boolean
97 */
98 protected $_skipRedirection = FALSE;
99
100 /**
101 * Are we in print mode? if so we need to modify the display
102 * functionality to do a minimal display :)
103 *
104 * @var boolean
105 */
106 public $_print = 0;
107
108 /**
109 * Should we generate a qfKey, true by default
110 *
111 * @var boolean
112 */
113 public $_generateQFKey = TRUE;
114
115 /**
116 * QF response type
117 */
118 public $_QFResponseType = 'html';
119
120 /**
121 * cache the smarty template for efficiency reasons
122 *
123 * @var CRM_Core_Smarty
124 */
125 static protected $_template;
126
127 /**
128 * cache the session for efficiency reasons
129 *
130 * @var CRM_Core_Session
131 */
132 static protected $_session;
133
134 /**
135 * The parent of this form if embedded
136 *
137 * @var object
138 */
139 protected $_parent = NULL;
140
141 /**
142 * The destination if set will override the destination the code wants to send it to
143 *
144 * @var string;
145 */
146 public $_destination = NULL;
147
148 /**
149 * All CRM single or multi page pages should inherit from this class.
150 *
151 * @param string title descriptive title of the controller
152 * @param boolean whether controller is modal
153 * @param string scope name of session if we want unique scope, used only by Controller_Simple
154 * @param boolean addSequence should we add a unique sequence number to the end of the key
155 * @param boolean ignoreKey should we not set a qfKey for this controller (for standalone forms)
156 *
157 * @access public
158 *
159 * @return void
160 *
161 */
162 function __construct(
163 $title = NULL,
164 $modal = TRUE,
165 $mode = NULL,
166 $scope = NULL,
167 $addSequence = FALSE,
168 $ignoreKey = FALSE
169 ) {
170 // this has to true for multiple tab session fix
171 $addSequence = TRUE;
172
173 // let the constructor initialize this, should happen only once
174 if (!isset(self::$_template)) {
175 self::$_template = CRM_Core_Smarty::singleton();
176 self::$_session = CRM_Core_Session::singleton();
177 }
178
179 // add a unique validable key to the name
180 $name = CRM_Utils_System::getClassName($this);
181 if ($name == 'CRM_Core_Controller_Simple' && !empty($scope)) {
182 // use form name if we have, since its a lot better and
183 // definitely different for different forms
184 $name = $scope;
185 }
186 $name = $name . '_' . $this->key($name, $addSequence, $ignoreKey);
187 $this->_title = $title;
188 if ($scope) {
189 $this->_scope = $scope;
190 }
191 else {
192 $this->_scope = CRM_Utils_System::getClassName($this);
193 }
194 $this->_scope = $this->_scope . '_' . $this->_key;
195
196 // only use the civicrm cache if we have a valid key
197 // else we clash with other users CRM-7059
198 if (!empty($this->_key)) {
199 CRM_Core_Session::registerAndRetrieveSessionObjects(array(
200 "_{$name}_container",
201 array('CiviCRM', $this->_scope),
202 ));
203 }
204
205 $this->HTML_QuickForm_Controller($name, $modal);
206
207 $snippet = CRM_Utils_Array::value('snippet', $_REQUEST);
208 if ($snippet) {
209 if ($snippet == 3) {
210 $this->_print = CRM_Core_Smarty::PRINT_PDF;
211 }
212 elseif ($snippet == 4) {
213 // this is used to embed fragments of a form
214 $this->_print = CRM_Core_Smarty::PRINT_NOFORM;
215 self::$_template->assign('suppressForm', TRUE);
216 $this->_generateQFKey = FALSE;
217 }
218 elseif ($snippet == 5) {
219 // this is used for popups and inlined ajax forms
220 // also used for the various tabs via TabHeader
221 $this->_print = CRM_Core_Smarty::PRINT_NOFORM;
222 }
223 elseif ($snippet == 6) {
224 $this->_print = CRM_Core_Smarty::PRINT_NOFORM;
225 $this->_QFResponseType = 'json';
226 }
227 else {
228 $this->_print = CRM_Core_Smarty::PRINT_SNIPPET;
229 }
230 }
231
232 // if the request has a reset value, initialize the controller session
233 if (CRM_Utils_Array::value('reset', $_GET)) {
234 $this->reset();
235 }
236
237 // set the key in the session
238 // do this at the end so we have initialized the object
239 // and created the scope etc
240 $this->set('qfKey', $this->_key);
241
242
243 // also retrieve and store destination in session
244 $this->_destination = CRM_Utils_Request::retrieve('civicrmDestination', 'String', $this,
245 FALSE, NULL, $_REQUEST
246 );
247 }
248
249 function fini() {
250 CRM_Core_BAO_Cache::storeSessionToCache(array(
251 "_{$this->_name}_container",
252 array('CiviCRM', $this->_scope),
253 ),
254 TRUE
255 );
256 }
257
258 function key($name, $addSequence = FALSE, $ignoreKey = FALSE) {
259 $config = CRM_Core_Config::singleton();
260
261 if (
262 $ignoreKey ||
263 (isset($config->keyDisable) && $config->keyDisable)
264 ) {
265 return NULL;
266 }
267
268 $key = CRM_Utils_Array::value('qfKey', $_REQUEST, NULL);
269 if (!$key && $_SERVER['REQUEST_METHOD'] === 'GET') {
270 $key = CRM_Core_Key::get($name, $addSequence);
271 }
272 else {
273 $key = CRM_Core_Key::validate($key, $name, $addSequence);
274 }
275
276 if (!$key) {
c02edd0e 277 $this->invalidKey();
6a488035
TO
278 }
279
280 $this->_key = $key;
281
282 return $key;
283 }
284
285 /**
286 * Process the request, overrides the default QFC run method
287 * This routine actually checks if the QFC is modal and if it
288 * is the first invalid page, if so it call the requested action
289 * if not, it calls the display action on the first invalid page
290 * avoids the issue of users hitting the back button and getting
291 * a broken page
292 *
293 * This run is basically a composition of the original run and the
294 * jump action
295 *
296 */
297 function run() {
298 // the names of the action and page should be saved
299 // note that this is split into two, because some versions of
300 // php 5.x core dump on the triple assignment :)
301 $this->_actionName = $this->getActionName();
302 list($pageName, $action) = $this->_actionName;
303
304 if ($this->isModal()) {
305 if (!$this->isValid($pageName)) {
306 $pageName = $this->findInvalid();
307 $action = 'display';
308 }
309 }
310
311 // note that based on action, control might not come back!!
312 // e.g. if action is a valid JUMP, u basically do a redirect
313 // to the appropriate place
314 $this->wizardHeader($pageName);
315 return $this->_pages[$pageName]->handle($action);
316 }
317
318 function validate() {
319 $this->_actionName = $this->getActionName();
320 list($pageName, $action) = $this->_actionName;
321
322 $page = &$this->_pages[$pageName];
323
324 $data = &$this->container();
325 $this->applyDefaults($pageName);
326 $page->isFormBuilt() or $page->buildForm();
327 // We use defaults and constants as if they were submitted
328 $data['values'][$pageName] = $page->exportValues();
329 $page->loadValues($data['values'][$pageName]);
330 // Is the page now valid?
331 if (TRUE === ($data['valid'][$pageName] = $page->validate())) {
332 return TRUE;
333 }
334 return $page->_errors;
335 }
336
337 /**
338 * Helper function to add all the needed default actions. Note that the framework
339 * redefines all of the default QFC actions
340 *
341 * @param string directory to store all the uploaded files
342 * @param array names for the various upload buttons (note u can have more than 1 upload)
343 *
344 * @access private
345 *
346 * @return void
347 *
348 */
349 function addActions($uploadDirectory = NULL, $uploadNames = NULL) {
350 $names = array(
351 'display' => 'CRM_Core_QuickForm_Action_Display',
352 'next' => 'CRM_Core_QuickForm_Action_Next',
353 'back' => 'CRM_Core_QuickForm_Action_Back',
354 'process' => 'CRM_Core_QuickForm_Action_Process',
355 'cancel' => 'CRM_Core_QuickForm_Action_Cancel',
356 'refresh' => 'CRM_Core_QuickForm_Action_Refresh',
357 'reload' => 'CRM_Core_QuickForm_Action_Reload',
358 'done' => 'CRM_Core_QuickForm_Action_Done',
359 'jump' => 'CRM_Core_QuickForm_Action_Jump',
360 'submit' => 'CRM_Core_QuickForm_Action_Submit',
361 );
362
363 foreach ($names as $name => $classPath) {
364 $action = new $classPath($this->_stateMachine);
365 $this->addAction($name, $action);
366 }
367
368 $this->addUploadAction($uploadDirectory, $uploadNames);
369 }
370
371 /**
372 * getter method for stateMachine
373 *
374 * @return object
375 * @access public
376 */
377 function getStateMachine() {
378 return $this->_stateMachine;
379 }
380
381 /**
382 * setter method for stateMachine
383 *
384 * @param object a stateMachineObject
385 *
386 * @return void
387 * @access public
388 */
389 function setStateMachine($stateMachine) {
390 $this->_stateMachine = $stateMachine;
391 }
392
393 /**
394 * add pages to the controller. Note that the controller does not really care
395 * the order in which the pages are added
396 *
397 * @param object $stateMachine the state machine object
398 * @param int $action the mode in which the state machine is operating
399 * typicaly this will be add/view/edit
400 *
401 * @return void
402 * @access public
403 *
404 */
405 function addPages(&$stateMachine, $action = CRM_Core_Action::NONE) {
406 $pages = $stateMachine->getPages();
407 foreach ($pages as $name => $value) {
408 $className = CRM_Utils_Array::value('className', $value, $name);
409 $title = CRM_Utils_Array::value('title', $value);
410 $options = CRM_Utils_Array::value('options', $value);
411 $stateName = CRM_Utils_String::getClassName($className);
412 if (CRM_Utils_Array::value('className', $value)) {
413 $formName = $name;
414 }
415 else {
416 $formName = CRM_Utils_String::getClassName($name);
417 }
418
419 $ext = CRM_Extension_System::singleton()->getMapper();
420 if ($ext->isExtensionClass($className)) {
421 require_once ($ext->classToPath($className));
422 }
423 else {
424 require_once (str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php');
425 }
426 $$stateName = new $className($stateMachine->find($className), $action, 'post', $formName);
427 if ($title) {
428 $$stateName->setTitle($title);
429 }
430 if ($options) {
431 $$stateName->setOptions($options);
432 }
433 $this->addPage($$stateName);
434 $this->addAction($stateName, new HTML_QuickForm_Action_Direct());
435
436 //CRM-6342 -we need kill the reference here,
437 //as we have deprecated reference object creation.
438 unset($$stateName);
439 }
440 }
441
442 /**
443 * QFC does not provide native support to have different 'submit' buttons.
444 * We introduce this notion to QFC by using button specific data. Thus if
445 * we have two submit buttons, we could have one displayed as a button and
446 * the other as an image, both are of type 'submit'.
447 *
448 * @return string the name of the button that has been pressed by the user
449 * @access public
450 */
451 function getButtonName() {
452 $data = &$this->container();
453 return CRM_Utils_Array::value('_qf_button_name', $data);
454 }
455
456 /**
457 * function to destroy all the session state of the controller.
458 *
459 * @access public
460 *
461 * @return void
462 */
463 function reset() {
464 $this->container(TRUE);
465 self::$_session->resetScope($this->_scope);
466 }
467
468 /**
469 * virtual function to do any processing of data.
470 * Sometimes it is useful for the controller to actually process data.
471 * This is typically used when we need the controller to figure out
472 * what pages are potentially involved in this wizard. (this is dynamic
473 * and can change based on the arguments
474 *
475 * @return void
476 * @access public
477 */
478 function process() {}
479
480 /**
481 * Store the variable with the value in the form scope
482 *
483 * @param string|array $name name of the variable or an assoc array of name/value pairs
484 * @param mixed $value value of the variable if string
485 *
486 * @access public
487 *
488 * @return void
489 *
490 */
491 function set($name, $value = NULL) {
492 self::$_session->set($name, $value, $this->_scope);
493 }
494
495 /**
496 * Get the variable from the form scope
497 *
498 * @param string name : name of the variable
499 *
500 * @access public
501
502 *
503 * @return mixed
504 *
505 */
506 function get($name) {
507 return self::$_session->get($name, $this->_scope);
508 }
509
510 /**
511 * Create the header for the wizard from the list of pages
512 * Store the created header in smarty
513 *
514 * @param string $currentPageName name of the page being displayed
515 *
516 * @return array
517 * @access public
518 */
519 function wizardHeader($currentPageName) {
520 $wizard = array();
521 $wizard['steps'] = array();
522 $count = 0;
523 foreach ($this->_pages as $name => $page) {
524 $count++;
525 $wizard['steps'][] = array(
526 'name' => $name,
527 'title' => $page->getTitle(),
528 //'link' => $page->getLink ( ),
529 'link' => NULL,
530 'step' => TRUE,
531 'valid' => TRUE,
532 'stepNumber' => $count,
533 'collapsed' => FALSE,
534 );
535
536 if ($name == $currentPageName) {
537 $wizard['currentStepNumber'] = $count;
538 $wizard['currentStepName'] = $name;
539 $wizard['currentStepTitle'] = $page->getTitle();
540 }
541 }
542
543 $wizard['stepCount'] = $count;
544
545 $this->addWizardStyle($wizard);
546
547 $this->assign('wizard', $wizard);
548 return $wizard;
549 }
550
551 function addWizardStyle(&$wizard) {
552 $wizard['style'] = array(
553 'barClass' => '',
554 'stepPrefixCurrent' => '&raquo;',
555 'stepPrefixPast' => '&radic;',
556 'stepPrefixFuture' => ' ',
557 'subStepPrefixCurrent' => '&nbsp;&nbsp;',
558 'subStepPrefixPast' => '&nbsp;&nbsp;',
559 'subStepPrefixFuture' => '&nbsp;&nbsp;',
560 'showTitle' => 1,
561 );
562 }
563
564 /**
565 * assign value to name in template
566 *
567 * @param array|string $name name of variable
568 * @param mixed $value value of varaible
569 *
570 * @return void
571 * @access public
572 */
573 function assign($var, $value = NULL) {
574 self::$_template->assign($var, $value);
575 }
576
577 function assign_by_ref($var, &$value) {
578 self::$_template->assign_by_ref($var, $value);
579 }
580
581 /**
582 * setter for embedded
583 *
584 * @param boolean $embedded
585 *
586 * @return void
587 * @access public
588 */
589 function setEmbedded($embedded) {
590 $this->_embedded = $embedded;
591 }
592
593 /**
594 * getter for embedded
595 *
596 * @return boolean return the embedded value
597 * @access public
598 */
599 function getEmbedded() {
600 return $this->_embedded;
601 }
602
603 /**
604 * setter for skipRedirection
605 *
606 * @param boolean $skipRedirection
607 *
608 * @return void
609 * @access public
610 */
611 function setSkipRedirection($skipRedirection) {
612 $this->_skipRedirection = $skipRedirection;
613 }
614
615 /**
616 * getter for skipRedirection
617 *
618 * @return boolean return the skipRedirection value
619 * @access public
620 */
621 function getSkipRedirection() {
622 return $this->_skipRedirection;
623 }
624
625 function setWord($fileName = NULL) {
626 //Mark as a CSV file.
627 header('Content-Type: application/vnd.ms-word');
628
629 //Force a download and name the file using the current timestamp.
630 if (!$fileName) {
631 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.doc';
632 }
633 header("Content-Disposition: attachment; filename=Contacts_$fileName");
634 }
635
636 function setExcel($fileName = NULL) {
637 //Mark as an excel file.
638 header('Content-Type: application/vnd.ms-excel');
639
640 //Force a download and name the file using the current timestamp.
641 if (!$fileName) {
642 $fileName = 'Contacts_' . $_SERVER['REQUEST_TIME'] . '.xls';
643 }
644
645 header("Content-Disposition: attachment; filename=Contacts_$fileName");
646 }
647
648 /**
649 * setter for print
650 *
651 * @param boolean $print
652 *
653 * @return void
654 * @access public
655 */
656 function setPrint($print) {
657 if ($print == "xls") {
658 $this->setExcel();
659 }
660 elseif ($print == "doc") {
661 $this->setWord();
662 }
663 $this->_print = $print;
664 }
665
666 /**
667 * getter for print
668 *
669 * @return boolean return the print value
670 * @access public
671 */
672 function getPrint() {
673 return $this->_print;
674 }
675
676 function getTemplateFile() {
677 if ($this->_print) {
678 if ($this->_print == CRM_Core_Smarty::PRINT_PAGE) {
679 return 'CRM/common/print.tpl';
680 }
681 elseif ($this->_print == 'xls' || $this->_print == 'doc') {
682 return 'CRM/Contact/Form/Task/Excel.tpl';
683 }
684 else {
685 return 'CRM/common/snippet.tpl';
686 }
687 }
688 else {
689 $config = CRM_Core_Config::singleton();
690 return 'CRM/common/' . strtolower($config->userFramework) . '.tpl';
691 }
692 }
693
694 public function addUploadAction($uploadDir, $uploadNames) {
695 if (empty($uploadDir)) {
696 $config = CRM_Core_Config::singleton();
697 $uploadDir = $config->uploadDir;
698 }
699
700 if (empty($uploadNames)) {
701 $uploadNames = $this->get('uploadNames');
702 if (!empty($uploadNames)) {
703 $uploadNames = array_merge($uploadNames,
704 CRM_Core_BAO_File::uploadNames()
705 );
706 }
707 else {
708 $uploadNames = CRM_Core_BAO_File::uploadNames();
709 }
710 }
711
712 $action = new CRM_Core_QuickForm_Action_Upload($this->_stateMachine,
713 $uploadDir,
714 $uploadNames
715 );
716 $this->addAction('upload', $action);
717 }
718
719 public function setParent($parent) {
720 $this->_parent = $parent;
721 }
722
723 public function getParent() {
724 return $this->_parent;
725 }
726
727 public function getDestination() {
728 return $this->_destination;
729 }
730
731 public function setDestination($url = NULL, $setToReferer = FALSE) {
732 if (empty($url)) {
733 if ($setToReferer) {
734 $url = $_SERVER['HTTP_REFERER'];
735 }
736 else {
737 $config = CRM_Core_Config::singleton();
738 $url = $config->userFrameworkBaseURL;
739 }
740 }
741
742 $this->_destination = $url;
743 $this->set('civicrmDestination', $this->_destination);
744 }
745
746 public function cancelAction() {
747 $actionName = $this->getActionName();
748 list($pageName, $action) = $actionName;
749 return $this->_pages[$pageName]->cancelAction();
750 }
6a488035 751
c02edd0e
DL
752 /**
753 * Write a simple fatal error message. Other controllers can decide to do something else
754 * and present the user a better message and/or redirect to the same page with a reset url
755 *
756 * @return void
757 *
758 */
759 public function invalidKey() {
760 $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.');
761 CRM_Core_Error::fatal($msg);
762 }
763
764}