]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/MVC/SugarApplication.php
Release 6.5.6
[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-2012 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 authenticate.
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', 'LoggedOut');
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
108                         if(!empty($this->controller->action)){
109                             if(strtolower($this->controller->action) == 'delete')
110                                 $this->controller->action = 'DetailView';
111                             elseif(strtolower($this->controller->action) == 'save')
112                                 $this->controller->action = 'EditView';
113                 elseif(strtolower($this->controller->action) == 'quickcreate') {
114                     $this->controller->action = 'index';
115                     $this->controller->module = 'home';
116                 }
117                             elseif(isset($_REQUEST['massupdate'])|| isset($_GET['massupdate']) || isset($_POST['massupdate']))
118                                 $this->controller->action = 'index';
119                             elseif($this->isModifyAction())
120                                 $this->controller->action = 'index';
121                         }
122
123                         header('Location: index.php?action=Login&module=Users'.$this->createLoginVars());
124                         exit ();
125                 }
126
127                 $authController = new AuthenticationController((!empty($GLOBALS['sugar_config']['authenticationClass'])? $GLOBALS['sugar_config']['authenticationClass'] : 'SugarAuthenticate'));
128                 $GLOBALS['current_user'] = new User();
129                 if(isset($_SESSION['authenticated_user_id'])){
130                         // set in modules/Users/Authenticate.php
131                         if(!$authController->sessionAuthenticate()){
132                                  // if the object we get back is null for some reason, this will break - like user prefs are corrupted
133                                 $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.');
134                                 session_destroy();
135                                 SugarApplication::redirect('index.php?action=Login&module=Users');
136                                 die();
137                         }//fi
138                 }elseif(!($this->controller->module == 'Users' && in_array($this->controller->action, $allowed_actions))){
139                         session_destroy();
140                         SugarApplication::redirect('index.php?action=Login&module=Users');
141                         die();
142                 }
143                 $GLOBALS['log']->debug('Current user is: '.$GLOBALS['current_user']->user_name);
144
145                 //set cookies
146                 if(isset($_SESSION['authenticated_user_id'])){
147                         $GLOBALS['log']->debug("setting cookie ck_login_id_20 to ".$_SESSION['authenticated_user_id']);
148                         self::setCookie('ck_login_id_20', $_SESSION['authenticated_user_id'], time() + 86400 * 90);
149                 }
150                 if(isset($_SESSION['authenticated_user_theme'])){
151                         $GLOBALS['log']->debug("setting cookie ck_login_theme_20 to ".$_SESSION['authenticated_user_theme']);
152                         self::setCookie('ck_login_theme_20', $_SESSION['authenticated_user_theme'], time() + 86400 * 90);
153                 }
154                 if(isset($_SESSION['authenticated_user_theme_color'])){
155                         $GLOBALS['log']->debug("setting cookie ck_login_theme_color_20 to ".$_SESSION['authenticated_user_theme_color']);
156                         self::setCookie('ck_login_theme_color_20', $_SESSION['authenticated_user_theme_color'], time() + 86400 * 90);
157                 }
158                 if(isset($_SESSION['authenticated_user_theme_font'])){
159                         $GLOBALS['log']->debug("setting cookie ck_login_theme_font_20 to ".$_SESSION['authenticated_user_theme_font']);
160                         self::setCookie('ck_login_theme_font_20', $_SESSION['authenticated_user_theme_font'], time() + 86400 * 90);
161                 }
162                 if(isset($_SESSION['authenticated_user_language'])){
163                         $GLOBALS['log']->debug("setting cookie ck_login_language_20 to ".$_SESSION['authenticated_user_language']);
164                         self::setCookie('ck_login_language_20', $_SESSION['authenticated_user_language'], time() + 86400 * 90);
165                 }
166                 //check if user can access
167
168         }
169
170         function ACLFilter(){
171                 ACLController :: filterModuleList($GLOBALS['moduleList']);
172         }
173
174         /**
175          * setupResourceManagement
176          * This function initialize the ResourceManager and calls the setup method
177          * on the ResourceManager instance.
178          *
179          */
180         function setupResourceManagement($module) {
181                 require_once('include/resource/ResourceManager.php');
182                 $resourceManager = ResourceManager::getInstance();
183                 $resourceManager->setup($module);
184         }
185
186         function setupPrint() {
187                 $GLOBALS['request_string'] = '';
188
189                 // merge _GET and _POST, but keep the results local
190                 // this handles the issues where values come in one way or the other
191                 // without affecting the main super globals
192                 $merged = array_merge($_GET, $_POST);
193                 foreach ($merged as $key => $val)
194                 {
195                    if(is_array($val))
196                    {
197                        foreach ($val as $k => $v)
198                        {
199                            //If an array, then skip the urlencoding. This should be handled with stringify instead.
200                            if(is_array($v))
201                                 continue;
202
203                            $GLOBALS['request_string'] .= urlencode($key).'['.$k.']='.urlencode($v).'&';
204                        }
205                    }
206                    else
207                    {
208                        $GLOBALS['request_string'] .= urlencode($key).'='.urlencode($val).'&';
209                    }
210                 }
211                 $GLOBALS['request_string'] .= 'print=true';
212         }
213
214         function preProcess(){
215             $config = new Administration;
216             $config->retrieveSettings();
217                 if(!empty($_SESSION['authenticated_user_id'])){
218                         if(isset($_SESSION['hasExpiredPassword']) && $_SESSION['hasExpiredPassword'] == '1'){
219                                 if( $this->controller->action!= 'Save' && $this->controller->action != 'Logout') {
220                         $this->controller->module = 'Users';
221                         $this->controller->action = 'ChangePassword';
222                         $record = $GLOBALS['current_user']->id;
223                      }else{
224                                         $this->handleOfflineClient();
225                                  }
226                         }else{
227                                 $ut = $GLOBALS['current_user']->getPreference('ut');
228                             if(empty($ut)
229                                     && $this->controller->action != 'AdminWizard'
230                                     && $this->controller->action != 'EmailUIAjax'
231                                     && $this->controller->action != 'Wizard'
232                                     && $this->controller->action != 'SaveAdminWizard'
233                                     && $this->controller->action != 'SaveUserWizard'
234                                     && $this->controller->action != 'SaveTimezone'
235                                     && $this->controller->action != 'Logout') {
236                                         $this->controller->module = 'Users';
237                                         $this->controller->action = 'SetTimezone';
238                                         $record = $GLOBALS['current_user']->id;
239                                 }else{
240                                         if($this->controller->action != 'AdminWizard'
241                                     && $this->controller->action != 'EmailUIAjax'
242                                     && $this->controller->action != 'Wizard'
243                                     && $this->controller->action != 'SaveAdminWizard'
244                                     && $this->controller->action != 'SaveUserWizard'){
245                                                         $this->handleOfflineClient();
246                                     }
247                                 }
248                         }
249                 }
250                 $this->handleAccessControl();
251         }
252
253         function handleOfflineClient(){
254                 if(isset($GLOBALS['sugar_config']['disc_client']) && $GLOBALS['sugar_config']['disc_client']){
255                         if(isset($_REQUEST['action']) && $_REQUEST['action'] != 'SaveTimezone'){
256                                 if (!file_exists('modules/Sync/file_config.php')){
257                                         if($_REQUEST['action'] != 'InitialSync' && $_REQUEST['action'] != 'Logout' &&
258                                            ($_REQUEST['action'] != 'Popup' && $_REQUEST['module'] != 'Sync')){
259                                                 //echo $_REQUEST['action'];
260                                                 //die();
261                                                         $this->controller->module = 'Sync';
262                                                         $this->controller->action = 'InitialSync';
263                                                 }
264                         }else{
265                                 require_once ('modules/Sync/file_config.php');
266                                 if(isset($file_sync_info['is_first_sync']) && $file_sync_info['is_first_sync']){
267                                         if($_REQUEST['action'] != 'InitialSync' && $_REQUEST['action'] != 'Logout' &&
268                                            ( $_REQUEST['action'] != 'Popup' && $_REQUEST['module'] != 'Sync')){
269                                                                 $this->controller->module = 'Sync';
270                                                                 $this->controller->action = 'InitialSync';
271                                                 }
272                                 }
273                         }
274                         }
275                         global $moduleList, $sugar_config, $sync_modules;
276                         require_once('modules/Sync/SyncController.php');
277                         $GLOBALS['current_user']->is_admin = '0'; //No admins for disc client
278                 }
279         }
280
281         /**
282          * Handles everything related to authorization.
283          */
284         function handleAccessControl(){
285                 if($GLOBALS['current_user']->isDeveloperForAnyModule())
286                         return;
287             if(!empty($_REQUEST['action']) && $_REQUEST['action']=="RetrieveEmail")
288             return;
289                 if(!is_admin($GLOBALS['current_user']) && !empty($GLOBALS['adminOnlyList'][$this->controller->module])
290                 && !empty($GLOBALS['adminOnlyList'][$this->controller->module]['all'])
291                 && (empty($GLOBALS['adminOnlyList'][$this->controller->module][$this->controller->action]) || $GLOBALS['adminOnlyList'][$this->controller->module][$this->controller->action] != 'allow')) {
292                         $this->controller->hasAccess = false;
293                         return;
294                 }
295
296                 // Bug 20916 - Special case for check ACL access rights for Subpanel QuickCreates
297                 if(isset($_POST['action']) && $_POST['action'] == 'SubpanelCreates') {
298             $actual_module = $_POST['target_module'];
299             if(!empty($GLOBALS['modListHeader']) && !in_array($actual_module,$GLOBALS['modListHeader'])) {
300                 $this->controller->hasAccess = false;
301             }
302             return;
303         }
304
305
306                 if(!empty($GLOBALS['current_user']) && empty($GLOBALS['modListHeader']))
307                         $GLOBALS['modListHeader'] = query_module_access_list($GLOBALS['current_user']);
308
309                 if(in_array($this->controller->module, $GLOBALS['modInvisList']) &&
310                         ((in_array('Activities', $GLOBALS['moduleList'])              &&
311                         in_array('Calendar',$GLOBALS['moduleList']))                 &&
312                         in_array($this->controller->module, $GLOBALS['modInvisListActivities']))
313                         ){
314                                 $this->controller->hasAccess = false;
315                                 return;
316                 }
317         }
318
319         /**
320          * Load only bare minimum of language that can be done before user init and MVC stuff
321          */
322         static function preLoadLanguages()
323         {
324                 if(!empty($_SESSION['authenticated_user_language'])) {
325                         $GLOBALS['current_language'] = $_SESSION['authenticated_user_language'];
326                 }
327                 else {
328                         $GLOBALS['current_language'] = $GLOBALS['sugar_config']['default_language'];
329                 }
330                 $GLOBALS['log']->debug('current_language is: '.$GLOBALS['current_language']);
331                 //set module and application string arrays based upon selected language
332                 $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
333         }
334
335         /**
336          * Load application wide languages as well as module based languages so they are accessible
337          * from the module.
338          */
339         function loadLanguages(){
340                 if(!empty($_SESSION['authenticated_user_language'])) {
341                         $GLOBALS['current_language'] = $_SESSION['authenticated_user_language'];
342                 }
343                 else {
344                         $GLOBALS['current_language'] = $GLOBALS['sugar_config']['default_language'];
345                 }
346                 $GLOBALS['log']->debug('current_language is: '.$GLOBALS['current_language']);
347                 //set module and application string arrays based upon selected language
348                 $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
349                 if(empty($GLOBALS['current_user']->id))$GLOBALS['app_strings']['NTC_WELCOME'] = '';
350                 if(!empty($GLOBALS['system_config']->settings['system_name']))$GLOBALS['app_strings']['LBL_BROWSER_TITLE'] = $GLOBALS['system_config']->settings['system_name'];
351                 $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
352                 $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], $this->controller->module);
353         }
354         /**
355         * checkDatabaseVersion
356         * Check the db version sugar_version.php and compare to what the version is stored in the config table.
357         * Ensure that both are the same.
358         */
359         function checkDatabaseVersion($dieOnFailure = true)
360         {
361             $row_count = sugar_cache_retrieve('checkDatabaseVersion_row_count');
362             if ( empty($row_count) )
363             {
364             $version_query = "SELECT count(*) as the_count FROM config WHERE category='info' AND name='sugar_version' AND ".
365             $GLOBALS['db']->convert('value', 'text2char')." = ".$GLOBALS['db']->quoted($GLOBALS['sugar_db_version']);
366
367             $result = $GLOBALS['db']->query($version_query);
368             $row = $GLOBALS['db']->fetchByAssoc($result);
369             $row_count = $row['the_count'];
370             sugar_cache_put('checkDatabaseVersion_row_count', $row_count);
371         }
372
373                 if ($row_count == 0 && empty($GLOBALS['sugar_config']['disc_client']))
374                 {
375                         if ( $dieOnFailure )
376                         {
377                                 $replacementStrings = array(
378                                         0 => $GLOBALS['sugar_version'],
379                                         1 => $GLOBALS['sugar_db_version'],
380                                 );
381                                 sugar_die(string_format($GLOBALS['app_strings']['ERR_DB_VERSION'], $replacementStrings));
382                         }
383                         else
384                         {
385                             return false;
386                         }
387                 }
388
389                 return true;
390         }
391
392         /**
393          * Load the themes/images.
394          */
395         function loadDisplaySettings()
396     {
397         global $theme;
398
399         // load the user's default theme
400         $theme = $GLOBALS['current_user']->getPreference('user_theme');
401
402         if (is_null($theme)) {
403             $theme = $GLOBALS['sugar_config']['default_theme'];
404             if(!empty($_SESSION['authenticated_user_theme'])){
405                 $theme = $_SESSION['authenticated_user_theme'];
406             }
407             else if(!empty($_COOKIE['sugar_user_theme'])){
408                 $theme = $_COOKIE['sugar_user_theme'];
409             }
410
411                         if(isset($_SESSION['authenticated_user_theme']) && $_SESSION['authenticated_user_theme'] != '') {
412                                 $_SESSION['theme_changed'] = false;
413                         }
414                 }
415
416         if(!is_null($theme) && !headers_sent())
417         {
418             setcookie('sugar_user_theme', $theme, time() + 31536000); // expires in a year
419         }
420
421         SugarThemeRegistry::set($theme);
422         require_once('include/utils/layout_utils.php');
423         $GLOBALS['image_path'] = SugarThemeRegistry::current()->getImagePath().'/';
424         if ( defined('TEMPLATE_URL') )
425             $GLOBALS['image_path'] = TEMPLATE_URL . '/'. $GLOBALS['image_path'];
426
427         if ( isset($GLOBALS['current_user']) ) {
428             $GLOBALS['gridline'] = (int) ($GLOBALS['current_user']->getPreference('gridline') == 'on');
429             $GLOBALS['current_user']->setPreference('user_theme', $theme, 0, 'global');
430         }
431         }
432
433         function loadLicense(){
434                 loadLicense();
435                 global $user_unique_key, $server_unique_key;
436                 $user_unique_key = (isset($_SESSION['unique_key'])) ? $_SESSION['unique_key'] : '';
437                 $server_unique_key = (isset($sugar_config['unique_key'])) ? $sugar_config['unique_key'] : '';
438         }
439
440         function loadGlobals(){
441                 global $currentModule;
442                 $currentModule = $this->controller->module;
443                 if($this->controller->module == $this->default_module){
444                         $_REQUEST['module'] = $this->controller->module;
445                         if(empty($_REQUEST['action']))
446                         $_REQUEST['action'] = $this->default_action;
447                 }
448         }
449
450         /**
451          * Actions that modify data in this controller's instance and thus require referrers
452          * @var array
453          */
454         protected $modifyActions = array();
455         /**
456          * Actions that always modify data and thus require referrers
457          * save* and delete* hardcoded as modified
458          * @var array
459          */
460         private $globalModifyActions = array(
461                 'massupdate', 'configuredashlet', 'import', 'importvcardsave', 'inlinefieldsave',
462             'wlsave', 'quicksave'
463         );
464
465         /**
466          * Modules that modify data and thus require referrers for all actions
467          */
468         private $modifyModules = array(
469                 'Administration' => true,
470                 'UpgradeWizard' => true,
471                 'Configurator' => true,
472                 'Studio' => true,
473                 'ModuleBuilder' => true,
474                 'Emails' => true,
475             'DCETemplates' => true,
476                 'DCEInstances' => true,
477                 'DCEActions' => true,
478                 'Trackers' => array('trackersettings'),
479             'SugarFavorites' => array('tag'),
480             'Import' => array('last', 'undo'),
481             'Users' => array('changepassword', "generatepassword"),
482         );
483
484         protected function isModifyAction()
485         {
486             $action = strtolower($this->controller->action);
487             if(substr($action, 0, 4) == "save" || substr($action, 0, 6) == "delete") {
488                 return true;
489             }
490             if(isset($this->modifyModules[$this->controller->module])) {
491                 if($this->modifyModules[$this->controller->module] === true) {
492                     return true;
493                 }
494                 if(in_array($this->controller->action, $this->modifyModules[$this->controller->module])) {
495                     return true;
496
497                 }
498             }
499             if(in_array($this->controller->action, $this->globalModifyActions)) {
500             return true;
501         }
502             if(in_array($this->controller->action, $this->modifyActions)) {
503             return true;
504         }
505         return false;
506         }
507
508     /**
509      * The list of the actions excepted from referer checks by default
510      * @var array
511      */
512         protected $whiteListActions = array('index', 'ListView', 'DetailView', 'EditView', 'oauth', 'authorize', 'Authenticate', 'Login', 'SupportPortal');
513
514         /**
515          *
516          * Checks a request to ensure the request is coming from a valid source or it is for one of the white listed actions
517          */
518         protected function checkHTTPReferer($dieIfInvalid = true)
519         {
520                 global $sugar_config;
521                 if(!empty($sugar_config['http_referer']['actions'])) {
522                     $this->whiteListActions = array_merge($sugar_config['http_referer']['actions'], $this->whiteListActions);
523                 }
524
525                 $strong = empty($sugar_config['http_referer']['weak']);
526
527                 // Bug 39691 - Make sure localhost and 127.0.0.1 are always valid HTTP referers
528                 $whiteListReferers = array('127.0.0.1','localhost');
529                 if(!empty($_SERVER['SERVER_ADDR']))$whiteListReferers[]  = $_SERVER['SERVER_ADDR'];
530                 if ( !empty($sugar_config['http_referer']['list']) ) {
531                         $whiteListReferers = array_merge($whiteListReferers,$sugar_config['http_referer']['list']);
532                 }
533
534                 if($strong && empty($_SERVER['HTTP_REFERER']) && !in_array($this->controller->action, $this->whiteListActions ) && $this->isModifyAction()) {
535                     $http_host = explode(':', $_SERVER['HTTP_HOST']);
536             $whiteListActions = $this->whiteListActions;
537                         $whiteListActions[] = $this->controller->action;
538                         $whiteListString = "'" . implode("', '", $whiteListActions) . "'";
539             if ( $dieIfInvalid ) {
540                 header("Cache-Control: no-cache, must-revalidate");
541                 $ss = new Sugar_Smarty;
542                 $ss->assign('host', $http_host[0]);
543                 $ss->assign('action',$this->controller->action);
544                 $ss->assign('whiteListString',$whiteListString);
545                 $ss->display('include/MVC/View/tpls/xsrf.tpl');
546                 sugar_cleanup(true);
547             }
548             return false;
549                 } else
550                 if(!empty($_SERVER['HTTP_REFERER']) && !empty($_SERVER['SERVER_NAME'])){
551                         $http_ref = parse_url($_SERVER['HTTP_REFERER']);
552                         if($http_ref['host'] !== $_SERVER['SERVER_NAME']  && !in_array($this->controller->action, $this->whiteListActions) &&
553
554                                 (empty($whiteListReferers) || !in_array($http_ref['host'], $whiteListReferers))){
555                 if ( $dieIfInvalid ) {
556                     header("Cache-Control: no-cache, must-revalidate");
557                     $whiteListActions = $this->whiteListActions;
558                     $whiteListActions[] = $this->controller->action;
559                     $whiteListString = "'" . implode("', '", $whiteListActions) . "'";
560
561                     $ss = new Sugar_Smarty;
562                     $ss->assign('host',$http_ref['host']);
563                     $ss->assign('action',$this->controller->action);
564                     $ss->assign('whiteListString',$whiteListString);
565                     $ss->display('include/MVC/View/tpls/xsrf.tpl');
566                     sugar_cleanup(true);
567                 }
568                 return false;
569                         }
570                 }
571          return true;
572         }
573         function startSession()
574         {
575             $sessionIdCookie = isset($_COOKIE['PHPSESSID']) ? $_COOKIE['PHPSESSID'] : null;
576             if(isset($_REQUEST['MSID'])) {
577                         session_id($_REQUEST['MSID']);
578                         session_start();
579             if(!isset($_SESSION['user_id'])){
580                                 if(isset($_COOKIE['PHPSESSID'])){
581                                 self::setCookie('PHPSESSID', '', time()-42000, '/');
582                         }
583                         sugar_cleanup(false);
584                         session_destroy();
585                         exit('Not a valid entry method');
586                         }
587                 }else{
588                         if(can_start_session()){
589                                 session_start();
590                         }
591                 }
592
593                 if ( isset($_REQUEST['login_module']) && isset($_REQUEST['login_action'])
594                         && !($_REQUEST['login_module'] == 'Home' && $_REQUEST['login_action'] == 'index') ) {
595             if ( !is_null($sessionIdCookie) && empty($_SESSION) ) {
596                 self::setCookie('loginErrorMessage', 'LBL_SESSION_EXPIRED', time()+30, '/');
597             }
598         }
599
600
601         LogicHook::initialize()->call_custom_logic('', 'after_session_start');
602         }
603
604
605
606
607         function endSession(){
608                 session_destroy();
609         }
610         /**
611          * Redirect to another URL
612          *
613          * @access      public
614          * @param       string  $url    The URL to redirect to
615          */
616         function redirect(
617             $url
618             )
619         {
620                 /*
621                  * If the headers have been sent, then we cannot send an additional location header
622                  * so we will output a javascript redirect statement.
623                  */
624                 if (!empty($_REQUEST['ajax_load']))
625         {
626             ob_get_clean();
627             $ajax_ret = array(
628                  'content' => "<script>SUGAR.ajaxUI.loadContent('$url');</script>\n",
629                  'menu' => array(
630                      'module' => $_REQUEST['module'],
631                      'label' => translate($_REQUEST['module']),
632                  ),
633             );
634             $json = getJSONobj();
635             echo $json->encode($ajax_ret);
636         } else {
637             if (headers_sent()) {
638                 echo "<script>SUGAR.ajaxUI.loadContent('$url');</script>\n";
639             } else {
640                 //@ob_end_clean(); // clear output buffer
641                 session_write_close();
642                 header( 'HTTP/1.1 301 Moved Permanently' );
643                 header( "Location: ". $url );
644             }
645         }
646                 exit();
647         }
648
649     /**
650          * Redirect to another URL
651          *
652          * @access      public
653          * @param       string  $url    The URL to redirect to
654          */
655         public static function appendErrorMessage($error_message)
656         {
657         if (empty($_SESSION['user_error_message']) || !is_array($_SESSION['user_error_message'])){
658             $_SESSION['user_error_message'] = array();
659         }
660                 $_SESSION['user_error_message'][] = $error_message;
661         }
662
663     public static function getErrorMessages()
664         {
665                 if (isset($_SESSION['user_error_message']) && is_array($_SESSION['user_error_message']) ) {
666             $msgs = $_SESSION['user_error_message'];
667             unset($_SESSION['user_error_message']);
668             return $msgs;
669         }else{
670             return array();
671         }
672         }
673
674         /**
675          * Wrapper for the PHP setcookie() function, to handle cases where headers have
676          * already been sent
677          */
678         public static function setCookie(
679             $name,
680             $value,
681             $expire = 0,
682             $path = '/',
683             $domain = null,
684             $secure = false,
685             $httponly = false
686             )
687         {
688             if ( is_null($domain) )
689                 if ( isset($_SERVER["HTTP_HOST"]) )
690                     $domain = $_SERVER["HTTP_HOST"];
691                 else
692                     $domain = 'localhost';
693
694             if (!headers_sent())
695                 setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
696
697             $_COOKIE[$name] = $value;
698         }
699
700         protected $redirectVars = array('module', 'action', 'record', 'token', 'oauth_token', 'mobile');
701
702         /**
703          * Create string to attach to login URL with vars to preserve post-login
704          * @return string URL part with login vars
705          */
706         public function createLoginVars()
707         {
708             $ret = array();
709         foreach($this->redirectVars as $var) {
710             if(!empty($this->controller->$var)) {
711                 $ret["login_".$var] = $this->controller->$var;
712                 continue;
713             }
714             if(!empty($_REQUEST[$var])) {
715                 $ret["login_".$var] = $_REQUEST[$var];
716             }
717         }
718         if(isset($_REQUEST['mobile'])) {
719             $ret['mobile'] = $_REQUEST['mobile'];
720         }
721         if(isset($_REQUEST['no_saml'])) {
722             $ret['no_saml'] = $_REQUEST['no_saml'];
723         }
724         if(empty($ret)) return '';
725         return "&".http_build_query($ret);
726         }
727
728         /**
729          * Get the list of vars passed with login form
730          * @param bool $add_empty Add empty vars to the result?
731          * @return array List of vars passed with login
732          */
733         public function getLoginVars($add_empty = true)
734         {
735             $ret = array();
736         foreach($this->redirectVars as $var) {
737             if(!empty($_REQUEST['login_'.$var]) || $add_empty) {
738                 $ret["login_".$var] = isset($_REQUEST['login_'.$var])?$_REQUEST['login_'.$var]:'';
739             }
740         }
741             return $ret;
742         }
743
744         /**
745          * Get URL to redirect after the login
746          * @return string the URL to redirect to
747          */
748         public function getLoginRedirect()
749         {
750         $vars = array();
751         foreach($this->redirectVars as $var) {
752             if(!empty($_REQUEST['login_'.$var])) $vars[$var] = $_REQUEST['login_'.$var];
753         }
754         if(isset($_REQUEST['mobile'])) {
755             $vars['mobile'] = $_REQUEST['mobile'];
756         }
757
758         if(isset($_REQUEST['mobile']))
759         {
760                       $vars['mobile'] = $_REQUEST['mobile'];
761         }
762         if(empty($vars)) {
763             return "index.php?module=Home&action=index";
764         } else {
765             return "index.php?".http_build_query($vars);
766         }
767         }
768 }