]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/MVC/SugarApplication.php
Release 6.4.0
[Github/sugarcrm.git] / include / MVC / SugarApplication.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License version 3 as published by the
8  * Free Software Foundation with the addition of the following permission added
9  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12  * 
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
16  * details.
17  * 
18  * You should have received a copy of the GNU Affero General Public License along with
19  * this program; if not, see http://www.gnu.org/licenses or write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  * 02110-1301 USA.
22  * 
23  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25  * 
26  * The interactive user interfaces in modified source and object code versions
27  * of this program must display Appropriate Legal Notices, as required under
28  * Section 5 of the GNU Affero General Public License version 3.
29  * 
30  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31  * these Appropriate Legal Notices must retain the display of the "Powered by
32  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33  * technical reasons, the Appropriate Legal Notices must display the words
34  * "Powered by SugarCRM".
35  ********************************************************************************/
36
37 /*
38  * Created on Mar 21, 2007
39  *
40  * To change the template for this generated file go to
41  * Window - Preferences - PHPeclipse - PHP - Code Templates
42  */
43 require_once('include/MVC/Controller/ControllerFactory.php');
44 require_once('include/MVC/View/ViewFactory.php');
45
46 /**
47  * SugarCRM application
48  * @api
49  */
50 class SugarApplication
51 {
52         var $controller = null;
53         var $headerDisplayed = false;
54         var $default_module = 'Home';
55         var $default_action = 'index';
56
57         function SugarApplication()
58         {}
59
60         /**
61          * Perform execution of the application. This method is called from index2.php
62          */
63         function execute(){
64                 global $sugar_config;
65                 if(!empty($sugar_config['default_module']))
66                         $this->default_module = $sugar_config['default_module'];
67                 $module = $this->default_module;
68                 if(!empty($_REQUEST['module']))$module = $_REQUEST['module'];
69                 insert_charset_header();
70                 $this->setupPrint();
71                 $this->controller = ControllerFactory::getController($module);
72         // if the entry point is defined to not need auth, then don't authenicate
73                 if( empty($_REQUEST['entryPoint'])
74                 || $this->controller->checkEntryPointRequiresAuth($_REQUEST['entryPoint']) ){
75             $this->loadUser();
76             $this->ACLFilter();
77             $this->preProcess();
78             $this->controller->preProcess();
79             $this->checkHTTPReferer();
80         }
81
82         SugarThemeRegistry::buildRegistry();
83         $this->loadLanguages();
84                 $this->checkDatabaseVersion();
85                 $this->loadDisplaySettings();
86                 $this->loadLicense();
87                 $this->loadGlobals();
88                 $this->setupResourceManagement($module);
89                 $this->controller->execute();
90                 sugar_cleanup();
91         }
92
93         /**
94          * Load the authenticated user. If there is not an authenticated user then redirect to login screen.
95          */
96         function loadUser(){
97                 global $authController, $sugar_config;
98                 // Double check the server's unique key is in the session.  Make sure this is not an attempt to hijack a session
99                 $user_unique_key = (isset($_SESSION['unique_key'])) ? $_SESSION['unique_key'] : '';
100                 $server_unique_key = (isset($sugar_config['unique_key'])) ? $sugar_config['unique_key'] : '';
101                 $allowed_actions = (!empty($this->controller->allowed_actions)) ? $this->controller->allowed_actions : $allowed_actions = array('Authenticate', 'Login',);
102
103                 if(($user_unique_key != $server_unique_key) && (!in_array($this->controller->action, $allowed_actions)) &&
104                    (!isset($_SESSION['login_error'])))
105                    {
106                         session_destroy();
107                         $post_login_nav = '';
108
109                         if(!empty($this->controller->module)){
110                                 $post_login_nav .= '&login_module='.$this->controller->module;
111                         }
112                         if(!empty($this->controller->action)){
113                             if(in_array(strtolower($this->controller->action), array('delete')))
114                                 $post_login_nav .= '&login_action=DetailView';
115                             elseif(in_array(strtolower($this->controller->action), array('save')))
116                                 $post_login_nav .= '&login_action=EditView';
117                             elseif(isset($_REQUEST['massupdate'])|| isset($_GET['massupdate']) || isset($_POST['massupdate']))
118                                 $post_login_nav .= '&login_action=index';
119                             else
120                                     $post_login_nav .= '&login_action='.$this->controller->action;
121                         }
122                         if(!empty($this->controller->record)){
123                                 $post_login_nav .= '&login_record='.$this->controller->record;
124                         }
125
126                         header('Location: index.php?action=Login&module=Users'.$post_login_nav);
127                         exit ();
128                 }
129
130                 $authController = new AuthenticationController((!empty($GLOBALS['sugar_config']['authenticationClass'])? $GLOBALS['sugar_config']['authenticationClass'] : 'SugarAuthenticate'));
131                 $GLOBALS['current_user'] = new User();
132                 if(isset($_SESSION['authenticated_user_id'])){
133                         // set in modules/Users/Authenticate.php
134                         if(!$authController->sessionAuthenticate()){
135                                  // if the object we get back is null for some reason, this will break - like user prefs are corrupted
136                                 $GLOBALS['log']->fatal('User retrieval for ID: ('.$_SESSION['authenticated_user_id'].') does not exist in database or retrieval failed catastrophically.  Calling session_destroy() and sending user to Login page.');
137                                 session_destroy();
138                                 SugarApplication::redirect('index.php?action=Login&module=Users');
139                                 die();
140                         }//fi
141                 }elseif(!($this->controller->module == 'Users' && in_array($this->controller->action, $allowed_actions))){
142                         session_destroy();
143                         SugarApplication::redirect('index.php?action=Login&module=Users');
144                         die();
145                 }
146                 $GLOBALS['log']->debug('Current user is: '.$GLOBALS['current_user']->user_name);
147
148                 //set cookies
149                 if(isset($_SESSION['authenticated_user_id'])){
150                         $GLOBALS['log']->debug("setting cookie ck_login_id_20 to ".$_SESSION['authenticated_user_id']);
151                         self::setCookie('ck_login_id_20', $_SESSION['authenticated_user_id'], time() + 86400 * 90);
152                 }
153                 if(isset($_SESSION['authenticated_user_theme'])){
154                         $GLOBALS['log']->debug("setting cookie ck_login_theme_20 to ".$_SESSION['authenticated_user_theme']);
155                         self::setCookie('ck_login_theme_20', $_SESSION['authenticated_user_theme'], time() + 86400 * 90);
156                 }
157                 if(isset($_SESSION['authenticated_user_theme_color'])){
158                         $GLOBALS['log']->debug("setting cookie ck_login_theme_color_20 to ".$_SESSION['authenticated_user_theme_color']);
159                         self::setCookie('ck_login_theme_color_20', $_SESSION['authenticated_user_theme_color'], time() + 86400 * 90);
160                 }
161                 if(isset($_SESSION['authenticated_user_theme_font'])){
162                         $GLOBALS['log']->debug("setting cookie ck_login_theme_font_20 to ".$_SESSION['authenticated_user_theme_font']);
163                         self::setCookie('ck_login_theme_font_20', $_SESSION['authenticated_user_theme_font'], time() + 86400 * 90);
164                 }
165                 if(isset($_SESSION['authenticated_user_language'])){
166                         $GLOBALS['log']->debug("setting cookie ck_login_language_20 to ".$_SESSION['authenticated_user_language']);
167                         self::setCookie('ck_login_language_20', $_SESSION['authenticated_user_language'], time() + 86400 * 90);
168                 }
169                 //check if user can access
170
171         }
172
173         function ACLFilter(){
174                 ACLController :: filterModuleList($GLOBALS['moduleList']);
175         }
176
177         /**
178          * setupResourceManagement
179          * This function initialize the ResourceManager and calls the setup method
180          * on the ResourceManager instance.
181          *
182          */
183         function setupResourceManagement($module) {
184                 require_once('include/resource/ResourceManager.php');
185                 $resourceManager = ResourceManager::getInstance();
186                 $resourceManager->setup($module);
187         }
188
189         function setupPrint() {
190                 $GLOBALS['request_string'] = '';
191
192                 // merge _GET and _POST, but keep the results local
193                 // this handles the issues where values come in one way or the other
194                 // without affecting the main super globals
195                 $merged = array_merge($_GET, $_POST);
196                 foreach ($merged as $key => $val)
197                 {
198                    if(is_array($val))
199                    {
200                        foreach ($val as $k => $v)
201                        {
202                            //If an array, then skip the urlencoding. This should be handled with stringify instead.
203                            if(is_array($v))
204                                 continue;
205
206                            $GLOBALS['request_string'] .= urlencode($key).'['.$k.']='.urlencode($v).'&';
207                        }
208                    }
209                    else
210                    {
211                        $GLOBALS['request_string'] .= urlencode($key).'='.urlencode($val).'&';
212                    }
213                 }
214                 $GLOBALS['request_string'] .= 'print=true';
215         }
216
217         function preProcess(){
218             $config = new Administration;
219             $config->retrieveSettings();
220                 if(!empty($_SESSION['authenticated_user_id'])){
221                         if(isset($_SESSION['hasExpiredPassword']) && $_SESSION['hasExpiredPassword'] == '1'){
222                                 if( $this->controller->action!= 'Save' && $this->controller->action != 'Logout') {
223                         $this->controller->module = 'Users';
224                         $this->controller->action = 'ChangePassword';
225                         $record = $GLOBALS['current_user']->id;
226                      }else{
227                                         $this->handleOfflineClient();
228                                  }
229                         }else{
230                                 $ut = $GLOBALS['current_user']->getPreference('ut');
231                             if(empty($ut)
232                                     && $this->controller->action != 'AdminWizard'
233                                     && $this->controller->action != 'EmailUIAjax'
234                                     && $this->controller->action != 'Wizard'
235                                     && $this->controller->action != 'SaveAdminWizard'
236                                     && $this->controller->action != 'SaveUserWizard'
237                                     && $this->controller->action != 'SaveTimezone'
238                                     && $this->controller->action != 'Logout') {
239                                         $this->controller->module = 'Users';
240                                         $this->controller->action = 'SetTimezone';
241                                         $record = $GLOBALS['current_user']->id;
242                                 }else{
243                                         if($this->controller->action != 'AdminWizard'
244                                     && $this->controller->action != 'EmailUIAjax'
245                                     && $this->controller->action != 'Wizard'
246                                     && $this->controller->action != 'SaveAdminWizard'
247                                     && $this->controller->action != 'SaveUserWizard'){
248                                                         $this->handleOfflineClient();
249                                     }
250                                 }
251                         }
252                 }
253                 $this->handleAccessControl();
254         }
255
256         function handleOfflineClient(){
257                 if(isset($GLOBALS['sugar_config']['disc_client']) && $GLOBALS['sugar_config']['disc_client']){
258                         if(isset($_REQUEST['action']) && $_REQUEST['action'] != 'SaveTimezone'){
259                                 if (!file_exists('modules/Sync/file_config.php')){
260                                         if($_REQUEST['action'] != 'InitialSync' && $_REQUEST['action'] != 'Logout' &&
261                                            ($_REQUEST['action'] != 'Popup' && $_REQUEST['module'] != 'Sync')){
262                                                 //echo $_REQUEST['action'];
263                                                 //die();
264                                                         $this->controller->module = 'Sync';
265                                                         $this->controller->action = 'InitialSync';
266                                                 }
267                         }else{
268                                 require_once ('modules/Sync/file_config.php');
269                                 if(isset($file_sync_info['is_first_sync']) && $file_sync_info['is_first_sync']){
270                                         if($_REQUEST['action'] != 'InitialSync' && $_REQUEST['action'] != 'Logout' &&
271                                            ( $_REQUEST['action'] != 'Popup' && $_REQUEST['module'] != 'Sync')){
272                                                                 $this->controller->module = 'Sync';
273                                                                 $this->controller->action = 'InitialSync';
274                                                 }
275                                 }
276                         }
277                         }
278                         global $moduleList, $sugar_config, $sync_modules;
279                         require_once('modules/Sync/SyncController.php');
280                         $GLOBALS['current_user']->is_admin = '0'; //No admins for disc client
281                 }
282         }
283
284         /**
285          * Handles everything related to authorization.
286          */
287         function handleAccessControl(){
288                 if($GLOBALS['current_user']->isDeveloperForAnyModule())
289                         return;
290             if(!empty($_REQUEST['action']) && $_REQUEST['action']=="RetrieveEmail")
291             return;
292                 if(!is_admin($GLOBALS['current_user']) && !empty($GLOBALS['adminOnlyList'][$this->controller->module])
293                 && !empty($GLOBALS['adminOnlyList'][$this->controller->module]['all'])
294                 && (empty($GLOBALS['adminOnlyList'][$this->controller->module][$this->controller->action]) || $GLOBALS['adminOnlyList'][$this->controller->module][$this->controller->action] != 'allow')) {
295                         $this->controller->hasAccess = false;
296                         return;
297                 }
298
299                 // Bug 20916 - Special case for check ACL access rights for Subpanel QuickCreates
300                 if(isset($_POST['action']) && $_POST['action'] == 'SubpanelCreates') {
301             $actual_module = $_POST['target_module'];
302             if(!empty($GLOBALS['modListHeader']) && !in_array($actual_module,$GLOBALS['modListHeader'])) {
303                 $this->controller->hasAccess = false;
304             }
305             return;
306         }
307
308
309                 if(!empty($GLOBALS['current_user']) && empty($GLOBALS['modListHeader']))
310                         $GLOBALS['modListHeader'] = query_module_access_list($GLOBALS['current_user']);
311
312                 if(in_array($this->controller->module, $GLOBALS['modInvisList']) &&
313                         ((in_array('Activities', $GLOBALS['moduleList'])              &&
314                         in_array('Calendar',$GLOBALS['moduleList']))                 &&
315                         in_array($this->controller->module, $GLOBALS['modInvisListActivities']))
316                         ){
317                                 $this->controller->hasAccess = false;
318                                 return;
319                 }
320         }
321
322         /**
323          * Load only bare minimum of language that can be done before user init and MVC stuff
324          */
325         static function preLoadLanguages()
326         {
327                 if(!empty($_SESSION['authenticated_user_language'])) {
328                         $GLOBALS['current_language'] = $_SESSION['authenticated_user_language'];
329                 }
330                 else {
331                         $GLOBALS['current_language'] = $GLOBALS['sugar_config']['default_language'];
332                 }
333                 $GLOBALS['log']->debug('current_language is: '.$GLOBALS['current_language']);
334                 //set module and application string arrays based upon selected language
335                 $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
336         }
337
338         /**
339          * Load application wide languages as well as module based languages so they are accessible
340          * from the module.
341          */
342         function loadLanguages(){
343                 if(!empty($_SESSION['authenticated_user_language'])) {
344                         $GLOBALS['current_language'] = $_SESSION['authenticated_user_language'];
345                 }
346                 else {
347                         $GLOBALS['current_language'] = $GLOBALS['sugar_config']['default_language'];
348                 }
349                 $GLOBALS['log']->debug('current_language is: '.$GLOBALS['current_language']);
350                 //set module and application string arrays based upon selected language
351                 $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
352                 if(empty($GLOBALS['current_user']->id))$GLOBALS['app_strings']['NTC_WELCOME'] = '';
353                 if(!empty($GLOBALS['system_config']->settings['system_name']))$GLOBALS['app_strings']['LBL_BROWSER_TITLE'] = $GLOBALS['system_config']->settings['system_name'];
354                 $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
355                 $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], $this->controller->module);
356         }
357         /**
358         * checkDatabaseVersion
359         * Check the db version sugar_version.php and compare to what the version is stored in the config table.
360         * Ensure that both are the same.
361         */
362         function checkDatabaseVersion($dieOnFailure = true)
363         {
364             $row_count = sugar_cache_retrieve('checkDatabaseVersion_row_count');
365             if ( empty($row_count) ) {
366             global $sugar_db_version;
367             $version_query = "SELECT count(*) as the_count FROM config WHERE category='info' AND name='sugar_version' AND ".
368                 $GLOBALS['db']->convert('value', 'text2char')." = ".$GLOBALS['db']->quoted($sugar_db_version);
369
370             $result = $GLOBALS['db']->query($version_query);
371             $row = $GLOBALS['db']->fetchByAssoc($result);
372             $row_count = $row['the_count'];
373             sugar_cache_put('checkDatabaseVersion_row_count', $row_count);
374         }
375
376                 if($row_count == 0 && empty($GLOBALS['sugar_config']['disc_client'])){
377                         $sugar_version = $GLOBALS['sugar_version'];
378                         if ( $dieOnFailure )
379                                 sugar_die("Sugar CRM $sugar_version Files May Only Be Used With A Sugar CRM $sugar_db_version Database.");
380                         else
381                             return false;
382                 }
383
384                 return true;
385         }
386
387         /**
388          * Load the themes/images.
389          */
390         function loadDisplaySettings()
391     {
392         global $theme;
393
394         // load the user's default theme
395         $theme = $GLOBALS['current_user']->getPreference('user_theme');
396
397         if (is_null($theme)) {
398             $theme = $GLOBALS['sugar_config']['default_theme'];
399             if(!empty($_SESSION['authenticated_user_theme'])){
400                 $theme = $_SESSION['authenticated_user_theme'];
401             }
402             else if(!empty($_COOKIE['sugar_user_theme'])){
403                 $theme = $_COOKIE['sugar_user_theme'];
404             }
405
406                         if(isset($_SESSION['authenticated_user_theme']) && $_SESSION['authenticated_user_theme'] != '') {
407                                 $_SESSION['theme_changed'] = false;
408                         }
409                 }
410
411         if(!is_null($theme) && !headers_sent())
412         {
413             setcookie('sugar_user_theme', $theme, time() + 31536000); // expires in a year
414         }
415
416         SugarThemeRegistry::set($theme);
417         require_once('include/utils/layout_utils.php');
418         $GLOBALS['image_path'] = SugarThemeRegistry::current()->getImagePath().'/';
419         if ( defined('TEMPLATE_URL') )
420             $GLOBALS['image_path'] = TEMPLATE_URL . '/'. $GLOBALS['image_path'];
421
422         if ( isset($GLOBALS['current_user']) ) {
423             $GLOBALS['gridline'] = (int) ($GLOBALS['current_user']->getPreference('gridline') == 'on');
424             $GLOBALS['current_user']->setPreference('user_theme', $theme, 0, 'global');
425         }
426         }
427
428         function loadLicense(){
429                 loadLicense();
430                 global $user_unique_key, $server_unique_key;
431                 $user_unique_key = (isset($_SESSION['unique_key'])) ? $_SESSION['unique_key'] : '';
432                 $server_unique_key = (isset($sugar_config['unique_key'])) ? $sugar_config['unique_key'] : '';
433         }
434
435         function loadGlobals(){
436                 global $currentModule;
437                 $currentModule = $this->controller->module;
438                 if($this->controller->module == $this->default_module){
439                         $_REQUEST['module'] = $this->controller->module;
440                         if(empty($_REQUEST['action']))
441                         $_REQUEST['action'] = $this->default_action;
442                 }
443         }
444
445         /**
446          * Actions that modify data in this controller's instance and thus require referrers
447          * @var array
448          */
449         protected $modifyActions = array();
450         /**
451          * Actions that always modify data and thus require referrers
452          * save* and delete* hardcoded as modified
453          * @var array
454          */
455         private $globalModifyActions = array(
456                 'massupdate', 'configuredashlet', 'import', 'importvcardsave', 'inlinefieldsave',
457             'wlsave', 'quicksave'
458         );
459
460         /**
461          * Modules that modify data and thus require referrers for all actions
462          */
463         private $modifyModules = array(
464                 'Administration' => true,
465                 'UpgradeWizard' => true,
466                 'Configurator' => true,
467                 'Studio' => true,
468                 'ModuleBuilder' => true,
469                 'Emails' => true,
470             'DCETemplates' => true,
471                 'DCEInstances' => true,
472                 'DCEActions' => true,
473                 'Trackers' => array('trackersettings'),
474             'SugarFavorites' => array('tag'),
475             'Import' => array('last', 'undo'),
476         );
477
478         protected function isModifyAction()
479         {
480             $action = strtolower($this->controller->action);
481             if(substr($action, 0, 4) == "save" || substr($action, 0, 6) == "delete") {
482                 return true;
483             }
484             if(isset($this->modifyModules[$this->controller->module])) {
485                 if($this->modifyModules[$this->controller->module] == true) {
486                     return true;
487                 }
488                 if(in_array($this->controller->action, $this->modifyModules[$this->controller->module])) {
489                     return true;
490
491                 }
492             }
493             if(in_array($this->controller->action, $this->globalModifyActions)) {
494             return true;
495         }
496             if(in_array($this->controller->action, $this->modifyActions)) {
497             return true;
498         }
499         return false;
500         }
501
502         /**
503          *
504          * Checks a request to ensure the request is coming from a valid source or it is for one of the white listed actions
505          */
506         protected function checkHTTPReferer($dieIfInvalid = true)
507         {
508                 global $sugar_config;
509                 $whiteListActions = (!empty($sugar_config['http_referer']['actions']))?$sugar_config['http_referer']['actions']:array('index', 'ListView', 'DetailView', 'EditView','oauth', 'Authenticate', 'Login', 'SupportPortal');
510
511                 $strong = empty($sugar_config['http_referer']['weak']);
512
513                 // Bug 39691 - Make sure localhost and 127.0.0.1 are always valid HTTP referers
514                 $whiteListReferers = array('127.0.0.1','localhost');
515                 if(!empty($_SERVER['SERVER_ADDR']))$whiteListReferers[]  = $_SERVER['SERVER_ADDR'];
516                 if ( !empty($sugar_config['http_referer']['list']) ) {
517                         $whiteListReferers = array_merge($whiteListReferers,$sugar_config['http_referer']['list']);
518                 }
519
520                 if($strong && empty($_SERVER['HTTP_REFERER']) && !in_array($this->controller->action, $whiteListActions) && $this->isModifyAction()) {
521                     $http_host = explode(':', $_SERVER['HTTP_HOST']);
522
523                         $whiteListActions[] = $this->controller->action;
524                         $whiteListString = "'" . implode("', '", $whiteListActions) . "'";
525             if ( $dieIfInvalid ) {
526                 header("Cache-Control: no-cache, must-revalidate");
527                 $ss = new Sugar_Smarty;
528                 $ss->assign('host', $http_host[0]);
529                 $ss->assign('action',$this->controller->action);
530                 $ss->assign('whiteListString',$whiteListString);
531                 $ss->display('include/MVC/View/tpls/xsrf.tpl');
532                 sugar_cleanup(true);
533             }
534             return false;
535                 } else
536                 if(!empty($_SERVER['HTTP_REFERER']) && !empty($_SERVER['SERVER_NAME'])){
537                         $http_ref = parse_url($_SERVER['HTTP_REFERER']);
538                         if($http_ref['host'] !== $_SERVER['SERVER_NAME']  && !in_array($this->controller->action, $whiteListActions) &&
539
540                                 (empty($whiteListReferers) || !in_array($http_ref['host'], $whiteListReferers))){
541                 if ( $dieIfInvalid ) {
542                     header("Cache-Control: no-cache, must-revalidate");
543                     $whiteListActions[] = $this->controller->action;
544                     $whiteListString = "'" . implode("', '", $whiteListActions) . "'";
545
546                     $ss = new Sugar_Smarty;
547                     $ss->assign('host',$http_ref['host']);
548                     $ss->assign('action',$this->controller->action);
549                     $ss->assign('whiteListString',$whiteListString);
550                     $ss->display('include/MVC/View/tpls/xsrf.tpl');
551                     sugar_cleanup(true);
552                 }
553                 return false;
554                         }
555                 }
556          return true;
557         }
558         function startSession()
559         {
560             $sessionIdCookie = isset($_COOKIE['PHPSESSID']) ? $_COOKIE['PHPSESSID'] : null;
561             if(isset($_REQUEST['MSID'])) {
562                         session_id($_REQUEST['MSID']);
563                         session_start();
564                         if(isset($_SESSION['user_id']) && isset($_SESSION['seamless_login'])){
565                                 unset ($_SESSION['seamless_login']);
566                         }else{
567                                 if(isset($_COOKIE['PHPSESSID'])){
568                                 self::setCookie('PHPSESSID', '', time()-42000, '/');
569                         }
570                         sugar_cleanup(false);
571                         session_destroy();
572                         exit('Not a valid entry method');
573                         }
574                 }else{
575                         if(can_start_session()){
576                                 session_start();
577                         }
578                 }
579
580                 if ( isset($_REQUEST['login_module']) && isset($_REQUEST['login_action'])
581                         && !($_REQUEST['login_module'] == 'Home' && $_REQUEST['login_action'] == 'index') ) {
582             if ( !is_null($sessionIdCookie) && empty($_SESSION) ) {
583                 self::setCookie('loginErrorMessage', 'LBL_SESSION_EXPIRED', time()+30, '/');
584             }
585         }
586
587         }
588
589         function endSession(){
590                 session_destroy();
591         }
592         /**
593          * Redirect to another URL
594          *
595          * @access      public
596          * @param       string  $url    The URL to redirect to
597          */
598         function redirect(
599             $url
600             )
601         {
602                 /*
603                  * If the headers have been sent, then we cannot send an additional location header
604                  * so we will output a javascript redirect statement.
605                  */
606                 if (!empty($_REQUEST['ajax_load']))
607         {
608             ob_get_clean();
609             $ajax_ret = array(
610                  'content' => "<script>SUGAR.ajaxUI.loadContent('$url');</script>\n",
611                  'menu' => array(
612                      'module' => $_REQUEST['module'],
613                      'label' => translate($_REQUEST['module']),
614                  ),
615             );
616             $json = getJSONobj();
617             echo $json->encode($ajax_ret);
618         } else {
619             if (headers_sent()) {
620                 echo "<script>SUGAR.ajaxUI.loadContent('$url');</script>\n";
621             } else {
622                 //@ob_end_clean(); // clear output buffer
623                 session_write_close();
624                 header( 'HTTP/1.1 301 Moved Permanently' );
625                 header( "Location: ". $url );
626             }
627         }
628                 exit();
629         }
630
631     /**
632          * Redirect to another URL
633          *
634          * @access      public
635          * @param       string  $url    The URL to redirect to
636          */
637         public static function appendErrorMessage($error_message)
638         {
639         if (empty($_SESSION['user_error_message']) || !is_array($_SESSION['user_error_message'])){
640             $_SESSION['user_error_message'] = array();
641         }
642                 $_SESSION['user_error_message'][] = $error_message;
643         }
644
645     public static function getErrorMessages()
646         {
647                 if (isset($_SESSION['user_error_message']) && is_array($_SESSION['user_error_message']) ) {
648             $msgs = $_SESSION['user_error_message'];
649             unset($_SESSION['user_error_message']);
650             return $msgs;
651         }else{
652             return array();
653         }
654         }
655
656         /**
657          * Wrapper for the PHP setcookie() function, to handle cases where headers have
658          * already been sent
659          */
660         public static function setCookie(
661             $name,
662             $value,
663             $expire = 0,
664             $path = '/',
665             $domain = null,
666             $secure = false,
667             $httponly = false
668             )
669         {
670             if ( is_null($domain) )
671                 if ( isset($_SERVER["HTTP_HOST"]) )
672                     $domain = $_SERVER["HTTP_HOST"];
673                 else
674                     $domain = 'localhost';
675
676             if (!headers_sent())
677                 setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
678
679             $_COOKIE[$name] = $value;
680         }
681 }