public function testquery_client_ip()
 {
     //test without setting any server parameters
     $this->assertSame(null, query_client_ip());
     //test with server params set
     $_SERVER['REMOTE_ADDR'] = '1.1.1.3';
     $this->assertSame('1.1.1.3', query_client_ip());
     $_SERVER['HTTP_FROM'] = '1.1.1.2';
     $this->assertSame('1.1.1.2', query_client_ip());
     $_SERVER['HTTP_CLIENT_IP'] = '1.1.1.1';
     $this->assertSame('1.1.1.1', query_client_ip());
 }
 /**
  * Log the user into the application
  *
  * @param UserAuth array $user_auth -- Set user_name and password (password needs to be
  *      in the right encoding for the type of authentication the user is setup for.  For Base
  *      sugar validation, password is the MD5 sum of the plain text password.
  * @param String $application -- The name of the application you are logging in from.  (Currently unused).
  * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported
  * @return Array - id - String id is the session_id of the session that was created.
  * 				 - module_name - String - module name of user
  * 				 - name_value_list - Array - The name value pair of user_id, user_name, user_language, user_currency_id, user_currency_name,
  *                                         - user_default_team_id, user_is_admin, user_default_dateformat, user_default_timeformat
  * @exception 'SoapFault' -- The SOAP error, if any
  */
 public function login($user_auth, $application, $name_value_list = array())
 {
     $GLOBALS['log']->info("Begin: SugarWebServiceImpl->login({$user_auth['user_name']}, {$application}, " . print_r($name_value_list, true) . ")");
     global $sugar_config, $system_config;
     $error = new SoapError();
     $user = new User();
     $success = false;
     //rrs
     $system_config = new Administration();
     $system_config->retrieveSettings('system');
     $authController = new AuthenticationController(!empty($sugar_config['authenticationClass']) ? $sugar_config['authenticationClass'] : 'SugarAuthenticate');
     //rrs
     if (!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN' && $authController->authController->userAuthenticateClass != "LDAPAuthenticateUser") {
         $user_auth['password'] = md5($user_auth['password']);
     }
     $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true));
     $usr_id = $user->retrieve_user_id($user_auth['user_name']);
     if ($usr_id) {
         $user->retrieve($usr_id);
     }
     if ($isLoginSuccess) {
         if ($_SESSION['hasExpiredPassword'] == '1') {
             $error->set_error('password_expired');
             $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']);
             LogicHook::initialize();
             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
             self::$helperObject->setFaultObject($error);
             return;
         }
         if (!empty($user) && !empty($user->id) && !$user->is_group) {
             $success = true;
             global $current_user;
             $current_user = $user;
         }
     } else {
         if ($usr_id && isset($user->user_name) && $user->getPreference('lockout') == '1') {
             $error->set_error('lockout_reached');
             $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']);
             LogicHook::initialize();
             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
             self::$helperObject->setFaultObject($error);
             return;
         } else {
             if (function_exists('mcrypt_cbc') && $authController->authController->userAuthenticateClass == "LDAPAuthenticateUser" && (empty($user_auth['encryption']) || $user_auth['encryption'] !== 'PLAIN')) {
                 $password = self::$helperObject->decrypt_string($user_auth['password']);
                 $authController->loggedIn = false;
                 // reset login attempt to try again with decrypted password
                 if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) {
                     $success = true;
                 }
             } else {
                 if ($authController->authController->userAuthenticateClass == "LDAPAuthenticateUser" && (empty($user_auth['encryption']) || $user_auth['encryption'] == 'PLAIN')) {
                     $authController->loggedIn = false;
                     // reset login attempt to try again with md5 password
                     if ($authController->login($user_auth['user_name'], md5($user_auth['password']), array('passwordEncrypted' => true)) && isset($_SESSION['authenticated_user_id'])) {
                         $success = true;
                     } else {
                         $error->set_error('ldap_error');
                         LogicHook::initialize();
                         $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
                         self::$helperObject->setFaultObject($error);
                         return;
                     }
                 }
             }
         }
     }
     if ($success) {
         session_start();
         global $current_user;
         //$current_user = $user;
         self::$helperObject->login_success($name_value_list);
         $current_user->loadPreferences();
         $_SESSION['is_valid_session'] = true;
         $_SESSION['ip_address'] = query_client_ip();
         $_SESSION['user_id'] = $current_user->id;
         $_SESSION['type'] = 'user';
         $_SESSION['avail_modules'] = self::$helperObject->get_user_module_list($current_user);
         $_SESSION['authenticated_user_id'] = $current_user->id;
         $_SESSION['unique_key'] = $sugar_config['unique_key'];
         $GLOBALS['log']->info('End: SugarWebServiceImpl->login - successful login');
         $current_user->call_custom_logic('after_login');
         $nameValueArray = array();
         global $current_language;
         $nameValueArray['user_id'] = self::$helperObject->get_name_value('user_id', $current_user->id);
         $nameValueArray['user_name'] = self::$helperObject->get_name_value('user_name', $current_user->user_name);
         $nameValueArray['user_language'] = self::$helperObject->get_name_value('user_language', $current_language);
         $cur_id = $current_user->getPreference('currency');
         $nameValueArray['user_currency_id'] = self::$helperObject->get_name_value('user_currency_id', $cur_id);
         $nameValueArray['user_is_admin'] = self::$helperObject->get_name_value('user_is_admin', is_admin($current_user));
         $nameValueArray['user_default_team_id'] = self::$helperObject->get_name_value('user_default_team_id', $current_user->default_team);
         $nameValueArray['user_default_dateformat'] = self::$helperObject->get_name_value('user_default_dateformat', $current_user->getPreference('datef'));
         $nameValueArray['user_default_timeformat'] = self::$helperObject->get_name_value('user_default_timeformat', $current_user->getPreference('timef'));
         $num_grp_sep = $current_user->getPreference('num_grp_sep');
         $dec_sep = $current_user->getPreference('dec_sep');
         $nameValueArray['user_number_seperator'] = self::$helperObject->get_name_value('user_number_seperator', empty($num_grp_sep) ? $sugar_config['default_number_grouping_seperator'] : $num_grp_sep);
         $nameValueArray['user_decimal_seperator'] = self::$helperObject->get_name_value('user_decimal_seperator', empty($dec_sep) ? $sugar_config['default_decimal_seperator'] : $dec_sep);
         $nameValueArray['mobile_max_list_entries'] = self::$helperObject->get_name_value('mobile_max_list_entries', $sugar_config['wl_list_max_entries_per_page']);
         $nameValueArray['mobile_max_subpanel_entries'] = self::$helperObject->get_name_value('mobile_max_subpanel_entries', $sugar_config['wl_list_max_entries_per_subpanel']);
         $currencyObject = new Currency();
         $currencyObject->retrieve($cur_id);
         $nameValueArray['user_currency_name'] = self::$helperObject->get_name_value('user_currency_name', $currencyObject->name);
         $_SESSION['user_language'] = $current_language;
         return array('id' => session_id(), 'module_name' => 'Users', 'name_value_list' => $nameValueArray);
     }
     LogicHook::initialize();
     $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
     $error->set_error('invalid_login');
     self::$helperObject->setFaultObject($error);
     $GLOBALS['log']->error('End: SugarWebServiceImpl->login - failed login');
 }
 /**
  * Log the user into the application
  *
  * @param UserAuth array $user_auth -- Set user_name and password (password needs to be
  *      in the right encoding for the type of authentication the user is setup for.  For Base
  *      sugar validation, password is the MD5 sum of the plain text password.
  * @param String $application -- The name of the application you are logging in from.  (Currently unused).
  * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported
  * @return Array - id - String id is the session_id of the session that was created.
  * 				 - module_name - String - module name of user
  * 				 - name_value_list - Array - The name value pair of user_id, user_name, user_language, user_currency_id, user_currency_name,
  *                                         - user_default_team_id, user_is_admin, user_default_dateformat, user_default_timeformat
  * @exception 'SoapFault' -- The SOAP error, if any
  */
 public function login($user_auth, $application, $name_value_list)
 {
     $GLOBALS['log']->info('Begin: SugarWebServiceImpl->login');
     global $sugar_config, $system_config;
     $error = new SoapError();
     $user = new User();
     $success = false;
     if (!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN') {
         $user_auth['password'] = md5($user_auth['password']);
     }
     //rrs
     $system_config = new Administration();
     $system_config->retrieveSettings('system');
     $authController = new AuthenticationController();
     //rrs
     $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true));
     $usr_id = $user->retrieve_user_id($user_auth['user_name']);
     if ($usr_id) {
         $user->retrieve($usr_id);
     }
     if ($isLoginSuccess) {
         if ($_SESSION['hasExpiredPassword'] == '1') {
             $error->set_error('password_expired');
             $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']);
             LogicHook::initialize();
             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
             self::$helperObject->setFaultObject($error);
             return;
         }
         if (!empty($user) && !empty($user->id) && !$user->is_group) {
             $success = true;
             global $current_user;
             $current_user = $user;
         }
     } else {
         if ($usr_id && isset($user->user_name) && $user->getPreference('lockout') == '1') {
             $error->set_error('lockout_reached');
             $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']);
             LogicHook::initialize();
             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
             self::$helperObject->setFaultObject($error);
             return;
         } else {
             if (function_exists('mcrypt_cbc')) {
                 $password = self::$helperObject->decrypt_string($user_auth['password']);
                 if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) {
                     $success = true;
                 }
             }
         }
     }
     if ($success) {
         session_start();
         global $current_user;
         //$current_user = $user;
         self::$helperObject->login_success($name_value_list);
         $current_user->loadPreferences();
         $_SESSION['is_valid_session'] = true;
         $_SESSION['ip_address'] = query_client_ip();
         $_SESSION['user_id'] = $current_user->id;
         $_SESSION['type'] = 'user';
         $_SESSION['avail_modules'] = self::$helperObject->get_user_module_list($current_user);
         $_SESSION['authenticated_user_id'] = $current_user->id;
         $_SESSION['unique_key'] = $sugar_config['unique_key'];
         $current_user->call_custom_logic('after_login');
         $GLOBALS['log']->info('End: SugarWebServiceImpl->login - succesful login');
         $nameValueArray = array();
         global $current_language;
         $nameValueArray['user_id'] = self::$helperObject->get_name_value('user_id', $current_user->id);
         $nameValueArray['user_name'] = self::$helperObject->get_name_value('user_name', $current_user->user_name);
         $nameValueArray['user_language'] = self::$helperObject->get_name_value('user_language', $current_language);
         $cur_id = $current_user->getPreference('currency');
         $nameValueArray['user_currency_id'] = self::$helperObject->get_name_value('user_currency_id', $cur_id);
         $nameValueArray['user_is_admin'] = self::$helperObject->get_name_value('user_is_admin', is_admin($current_user));
         $nameValueArray['user_default_team_id'] = self::$helperObject->get_name_value('user_default_team_id', $current_user->default_team);
         $nameValueArray['user_default_dateformat'] = self::$helperObject->get_name_value('user_default_dateformat', $current_user->getPreference('datef'));
         $nameValueArray['user_default_timeformat'] = self::$helperObject->get_name_value('user_default_timeformat', $current_user->getPreference('timef'));
         $currencyObject = new Currency();
         $currencyObject->retrieve($cur_id);
         $nameValueArray['user_currency_name'] = self::$helperObject->get_name_value('user_currency_name', $currencyObject->name);
         $_SESSION['user_language'] = $current_language;
         return array('id' => session_id(), 'module_name' => 'Users', 'name_value_list' => $nameValueArray);
     }
     LogicHook::initialize();
     $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
     $error->set_error('invalid_login');
     self::$helperObject->setFaultObject($error);
     $GLOBALS['log']->info('End: SugarWebServiceImpl->login - failed login');
 }
 /**
  * Make sure a user isn't stealing sessions so check the ip to ensure that the ip address hasn't dramatically changed
  *
  */
 function validateIP()
 {
     global $sugar_config;
     // grab client ip address
     $clientIP = query_client_ip();
     $classCheck = 0;
     // check to see if config entry is present, if not, verify client ip
     if (!isset($sugar_config['verify_client_ip']) || $sugar_config['verify_client_ip'] == true) {
         // check to see if we've got a current ip address in $_SESSION
         // and check to see if the session has been hijacked by a foreign ip
         if (isset($_SESSION["ipaddress"])) {
             $session_parts = explode(".", $_SESSION["ipaddress"]);
             $client_parts = explode(".", $clientIP);
             if (count($session_parts) < 4) {
                 $classCheck = 0;
             } else {
                 // match class C IP addresses
                 for ($i = 0; $i < 3; $i++) {
                     if ($session_parts[$i] == $client_parts[$i]) {
                         $classCheck = 1;
                         continue;
                     } else {
                         $classCheck = 0;
                         break;
                     }
                 }
             }
             // we have a different IP address
             if ($_SESSION["ipaddress"] != $clientIP && empty($classCheck)) {
                 $GLOBALS['log']->fatal("IP Address mismatch: SESSION IP: {$_SESSION['ipaddress']} CLIENT IP: {$clientIP}");
                 session_destroy();
                 die("Your session was terminated due to a significant change in your IP address.  <a href=\"{$sugar_config['site_url']}\">Return to Home</a>");
             }
         } else {
             $_SESSION["ipaddress"] = $clientIP;
         }
     }
 }
 /**
  * Use the same logic as in SugarAuthenticate to validate the ip address
  *
  * @param string $session_var
  * @return bool - true if the ip address is valid, false otherwise.
  */
 function is_valid_ip_address($session_var)
 {
     global $sugar_config;
     // grab client ip address
     $clientIP = query_client_ip();
     $classCheck = 0;
     // check to see if config entry is present, if not, verify client ip
     if (!isset($sugar_config['verify_client_ip']) || $sugar_config['verify_client_ip'] == true) {
         // check to see if we've got a current ip address in $_SESSION
         // and check to see if the session has been hijacked by a foreign ip
         if (isset($_SESSION[$session_var])) {
             $session_parts = explode(".", $_SESSION[$session_var]);
             $client_parts = explode(".", $clientIP);
             if (count($session_parts) < 4) {
                 $classCheck = 0;
             } else {
                 // match class C IP addresses
                 for ($i = 0; $i < 3; $i++) {
                     if ($session_parts[$i] == $client_parts[$i]) {
                         $classCheck = 1;
                         continue;
                     } else {
                         $classCheck = 0;
                         break;
                     }
                 }
             }
             // we have a different IP address
             if ($_SESSION[$session_var] != $clientIP && empty($classCheck)) {
                 $GLOBALS['log']->fatal("IP Address mismatch: SESSION IP: {$_SESSION[$session_var]} CLIENT IP: {$clientIP}");
                 return false;
             }
         } else {
             return false;
         }
     }
     return true;
 }
 /**
  * Log the user into the application
  *
  * @param UserAuth array $user_auth -- Set user_name and password (password needs to be
  *      in the right encoding for the type of authentication the user is setup for.  For Base
  *      sugar validation, password is the MD5 sum of the plain text password.
  * @param String $application -- The name of the application you are logging in from.  (Currently unused).
  * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported
  * @return Array - id - String id is the session_id of the session that was created.
  * 				 - module_name - String - module name of user
  * 				 - name_value_list - Array - The name value pair of user_id, user_name, user_language, user_currency_id, user_currency_name,
  *                                         - user_default_team_id, user_is_admin, user_default_dateformat, user_default_timeformat
  * @exception 'SoapFault' -- The SOAP error, if any
  */
 public function login($user_auth, $application, $name_value_list = array())
 {
     $GLOBALS['log']->info('Begin: SugarWebServiceImpl->login');
     global $sugar_config;
     $error = new SoapError();
     $user = BeanFactory::getBean('Users');
     $success = false;
     $authController = AuthenticationController::getInstance();
     if (!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN' && $authController->authController->userAuthenticateClass != "LDAPAuthenticateUser") {
         $user_auth['password'] = md5($user_auth['password']);
     }
     $isLoginSuccess = $authController->login($user_auth['user_name'], $user_auth['password'], array('passwordEncrypted' => true));
     $usr_id = $user->retrieve_user_id($user_auth['user_name']);
     if ($usr_id) {
         $user->retrieve($usr_id);
     }
     if ($isLoginSuccess) {
         if ($_SESSION['hasExpiredPassword'] == '1') {
             $error->set_error('password_expired');
             $GLOBALS['log']->fatal('password expired for user ' . $user_auth['user_name']);
             LogicHook::initialize();
             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
             self::$helperObject->setFaultObject($error);
             return;
         }
         if (!empty($user) && !empty($user->id) && !$user->is_group) {
             $success = true;
             global $current_user;
             $current_user = $user;
         }
     } else {
         if ($usr_id && isset($user->user_name) && $user->getPreference('lockout') == '1') {
             $error->set_error('lockout_reached');
             $GLOBALS['log']->fatal('Lockout reached for user ' . $user_auth['user_name']);
             LogicHook::initialize();
             $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
             self::$helperObject->setFaultObject($error);
             return;
         } else {
             if ($authController->authController->userAuthenticateClass == "LDAPAuthenticateUser" && (empty($user_auth['encryption']) || $user_auth['encryption'] !== 'PLAIN')) {
                 $error->set_error('ldap_error');
                 LogicHook::initialize();
                 $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
                 self::$helperObject->setFaultObject($error);
                 return;
             } else {
                 if (function_exists('mcrypt_cbc')) {
                     $password = self::$helperObject->decrypt_string($user_auth['password']);
                     if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) {
                         $success = true;
                     }
                 }
             }
         }
     }
     if ($success) {
         session_start();
         global $current_user;
         //$current_user = $user;
         self::$helperObject->login_success($name_value_list);
         $current_user->loadPreferences();
         $_SESSION['is_valid_session'] = true;
         $_SESSION['ip_address'] = query_client_ip();
         $_SESSION['user_id'] = $current_user->id;
         $_SESSION['type'] = 'user';
         $_SESSION['avail_modules'] = self::$helperObject->get_user_module_list($current_user);
         $_SESSION['authenticated_user_id'] = $current_user->id;
         $_SESSION['unique_key'] = $sugar_config['unique_key'];
         $current_user->call_custom_logic('after_login');
         $GLOBALS['log']->info('End: SugarWebServiceImpl->login - succesful login');
         $nameValueArray = array();
         global $current_language;
         $nameValueArray['user_id'] = self::$helperObject->get_name_value('user_id', $current_user->id);
         $nameValueArray['user_name'] = self::$helperObject->get_name_value('user_name', $current_user->user_name);
         $nameValueArray['user_language'] = self::$helperObject->get_name_value('user_language', $current_language);
         $cur_id = $current_user->getPreference('currency');
         $nameValueArray['user_currency_id'] = self::$helperObject->get_name_value('user_currency_id', $cur_id);
         $nameValueArray['user_is_admin'] = self::$helperObject->get_name_value('user_is_admin', is_admin($current_user));
         $nameValueArray['user_default_team_id'] = self::$helperObject->get_name_value('user_default_team_id', $current_user->default_team);
         $nameValueArray['user_default_dateformat'] = self::$helperObject->get_name_value('user_default_dateformat', $current_user->getPreference('datef'));
         $nameValueArray['user_default_timeformat'] = self::$helperObject->get_name_value('user_default_timeformat', $current_user->getPreference('timef'));
         $num_grp_sep = $current_user->getPreference('num_grp_sep');
         $dec_sep = $current_user->getPreference('dec_sep');
         $nameValueArray['user_number_seperator'] = self::$helperObject->get_name_value('user_number_seperator', empty($num_grp_sep) ? $sugar_config['default_number_grouping_seperator'] : $num_grp_sep);
         $nameValueArray['user_decimal_seperator'] = self::$helperObject->get_name_value('user_decimal_seperator', empty($dec_sep) ? $sugar_config['default_decimal_seperator'] : $dec_sep);
         $nameValueArray['mobile_max_list_entries'] = self::$helperObject->get_name_value('mobile_max_list_entries', $sugar_config['wl_list_max_entries_per_page']);
         $nameValueArray['mobile_max_subpanel_entries'] = self::$helperObject->get_name_value('mobile_max_subpanel_entries', $sugar_config['wl_list_max_entries_per_subpanel']);
         if ($application == 'mobile') {
             $modules = $availModuleNames = array();
             $availModules = array_keys($_SESSION['avail_modules']);
             //ACL check already performed.
             $modules = self::$helperObject->get_visible_mobile_modules($availModules);
             $nameValueArray['available_modules'] = $modules;
             //Get the vardefs md5
             foreach ($modules as $mod_def) {
                 $availModuleNames[] = $mod_def['module_key'];
             }
             $nameValueArray['vardefs_md5'] = self::get_module_fields_md5(session_id(), $availModuleNames);
         }
         $currencyObject = BeanFactory::getBean('Currencies', $cur_id);
         $nameValueArray['user_currency_name'] = self::$helperObject->get_name_value('user_currency_name', $currencyObject->name);
         $_SESSION['user_language'] = $current_language;
         return array('id' => session_id(), 'module_name' => 'Users', 'name_value_list' => $nameValueArray);
     }
     LogicHook::initialize();
     $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
     $error->set_error('invalid_login');
     self::$helperObject->setFaultObject($error);
     $GLOBALS['log']->info('End: SugarWebServiceImpl->login - failed login');
 }
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/
require_once 'include/formbase.php';
require_once 'modules/Leads/LeadFormBase.php';
global $app_strings, $app_list_strings, $sugar_config, $timedate, $current_user;
$mod_strings = return_module_language($sugar_config['default_language'], 'Leads');
$app_list_strings['record_type_module'] = array('Contact' => 'Contacts', 'Account' => 'Accounts', 'Opportunity' => 'Opportunities', 'Case' => 'Cases', 'Note' => 'Notes', 'Call' => 'Calls', 'Email' => 'Emails', 'Meeting' => 'Meetings', 'Task' => 'Tasks', 'Lead' => 'Leads', 'Bug' => 'Bugs');
/**
 * To make your changes upgrade safe create a file called leadCapture_override.php and place the changes there
 */
$users = array('PUT A RANDOM KEY FROM THE WEBSITE HERE' => array('name' => 'PUT THE USER_NAME HERE', 'pass' => 'PUT THE USER_HASH FOR THE RESPECTIVE USER HERE'));
if (isset($_POST['campaign_id']) && !empty($_POST['campaign_id'])) {
    //adding the client ip address
    $_POST['client_id_address'] = query_client_ip();
    $campaign_id = $_POST['campaign_id'];
    $campaign = new Campaign();
    $camp_query = "select name,id from campaigns where id='{$campaign_id}'";
    $camp_query .= " and deleted=0";
    $camp_result = $campaign->db->query($camp_query);
    $camp_data = $campaign->db->fetchByAssoc($camp_result);
    if (isset($_REQUEST['assigned_user_id']) && !empty($_REQUEST['assigned_user_id'])) {
        $current_user = new User();
        $current_user->retrieve($_REQUEST['assigned_user_id']);
    }
    if (isset($camp_data) && $camp_data != null) {
        $leadForm = new LeadFormBase();
        $lead = new Lead();
        $prefix = '';
        if (!empty($_POST['prefix'])) {
 /**
  * Store the supplied access token values to storage.
  *
  * We need to store access token data as we create and verify tokens.
  *
  * @param $oauth_token
  * oauth_token to be stored.
  * @param $client_id
  * Client identifier to be stored.
  * @param $user_id
  * User identifier to be stored.
  * @param $expires
  * Expiration to be stored.
  * @param $scope
  * (optional) Scopes to be stored in space-separated string.
  *
  * @ingroup oauth2_section_4
  */
 public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = NULL)
 {
     global $sugar_config;
     $clientInfo = $this->getClientDetails($client_id);
     if ($clientInfo === false) {
         return false;
     }
     // Get the user bean if there is one to be found
     $userBean = $this->getUserBean($user_id);
     if ($userBean == null) {
         return false;
     }
     $this->userBean = $userBean;
     $this->userType = $this->getUserType();
     // Handle the session now
     if (session_id() != '' && session_id() != $oauth_token) {
         // Oh, we are in trouble, we have a session and it's the wrong one.
         // Let's close this session and start a new one with the correct ID.
         session_write_close();
     }
     session_id($oauth_token);
     // Disable cookies
     ini_set("session.use_cookies", false);
     session_start();
     // Clear out the old session data
     $_SESSION = array();
     // Since we have to setup the session for oauth2 here, we might as well
     // set up the rest of the session, but only if we have what is needed
     if ($this->canStartSession()) {
         $GLOBALS['current_user'] = $this->userBean;
         $_SESSION['is_valid_session'] = true;
         $_SESSION['ip_address'] = query_client_ip();
         $_SESSION['user_id'] = $this->userBean->id;
         $_SESSION['type'] = 'user';
         $_SESSION['authenticated_user_id'] = $this->userBean->id;
         $_SESSION['unique_key'] = $sugar_config['unique_key'];
         $_SESSION['platform'] = $this->platform;
         //$this->setPlatformStore($_SESSION['platform']);
         $this->fillInAddedSessionData();
         $_SESSION['oauth2'] = array('client_id' => $client_id, 'user_id' => $user_id, 'expires' => $expires);
         return true;
     }
     throw new SugarApiException('Could not start session because client type was not found');
 }
 public function checkOAuthAccess($errorObject)
 {
     require_once "include/SugarOAuthServer.php";
     try {
         $oauth = new SugarOAuthServer();
         $token = $oauth->authorizedToken();
         if (empty($token) || empty($token->assigned_user_id)) {
             return false;
         }
     } catch (OAuthException $e) {
         $GLOBALS['log']->debug("OAUTH Exception: {$e}");
         $errorObject->set_error('invalid_login');
         $this->setFaultObject($errorObject);
         return false;
     } catch (Zend_Oauth_Exception $e) {
         $GLOBALS['log']->debug("Zend_Oauth_Exception: {$e}");
         $errorObject->set_error('invalid_login');
         $this->setFaultObject($errorObject);
         return false;
     }
     $user = BeanFactory::getBean('Users', $token->assigned_user_id);
     if (empty($user->id)) {
         return false;
     }
     global $current_user;
     $current_user = $user;
     ini_set("session.use_cookies", 0);
     // disable cookies to prevent session ID from going out
     session_start();
     session_regenerate_id();
     $_SESSION['oauth'] = $oauth->authorization();
     $_SESSION['avail_modules'] = $this->get_user_module_list($user);
     // TODO: handle role
     // handle session
     $_SESSION['is_valid_session'] = true;
     $_SESSION['ip_address'] = query_client_ip();
     $_SESSION['user_id'] = $current_user->id;
     $_SESSION['type'] = 'user';
     $_SESSION['authenticated_user_id'] = $current_user->id;
     return session_id();
 }
function portal_validate_authenticated($session_id)
{
    $old_error_reporting = error_reporting(0);
    session_id($session_id);
    // This little construct checks to see if the session validated
    if (session_start()) {
        $valid_session = true;
        if (!empty($_SESSION['is_valid_session']) && $_SESSION['ip_address'] == query_client_ip() && $valid_session != null && ($_SESSION['type'] == 'contact' || $_SESSION['type'] == 'lead' || $_SESSION['type'] == 'portal')) {
            global $current_user;
            $current_user = new User();
            $current_user->retrieve($_SESSION['portal_id']);
            login_success();
            error_reporting($old_error_reporting);
            return true;
        }
    }
    session_destroy();
    $GLOBALS['log']->fatal('SECURITY: The session ID is invalid');
    error_reporting($old_error_reporting);
    return false;
}
 /**
  * Validate the provided session information is correct and current.  Load the session.
  *
  * @param String $session_id -- The session ID that was returned by a call to login.
  * @return true -- If the session is valid and loaded.
  * @return false -- if the session is not valid.
  */
 function validate_authenticated($session_id)
 {
     $GLOBALS['log']->info('Begin: SoapHelperWebServices->validate_authenticated');
     if (!empty($session_id)) {
         session_id($session_id);
         session_start();
         if (!empty($_SESSION['is_valid_session']) && $_SESSION['ip_address'] == query_client_ip() && $_SESSION['type'] == 'user') {
             global $current_user;
             require_once 'modules/Users/User.php';
             $current_user = new User();
             $current_user->retrieve($_SESSION['user_id']);
             $this->login_success();
             $GLOBALS['log']->info('Begin: SoapHelperWebServices->validate_authenticated - passed');
             $GLOBALS['log']->info('End: SoapHelperWebServices->validate_authenticated');
             return true;
         }
         $GLOBALS['log']->debug("calling destroy");
         session_destroy();
     }
     LogicHook::initialize();
     $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
     $GLOBALS['log']->info('End: SoapHelperWebServices->validate_authenticated - validation failed');
     return false;
 }
 /**
  * Log the user into the application
  *
  * @param UserAuth array $user_auth -- Set user_name and password (password needs to be
  *      in the right encoding for the type of authentication the user is setup for.  For Base
  *      sugar validation, password is the MD5 sum of the plain text password.
  * @param String $application -- The name of the application you are logging in from.  (Currently unused).
  * @param array $name_value_list -- Array of name value pair of extra parameters. As of today only 'language' and 'notifyonsave' is supported
  * @return Array - id - String id is the session_id of the session that was created.
  * 				 - module_name - String - module name of user
  * 				 - name_value_list - Array - The name value pair of user_id, user_name, user_language
  * @exception 'SoapFault' -- The SOAP error, if any
  */
 public function login($user_auth, $application, $name_value_list)
 {
     $GLOBALS['log']->info('Begin: SugarWebServiceImpl->login');
     global $sugar_config, $system_config;
     $error = new SoapError();
     $user = new User();
     $success = false;
     if (!empty($user_auth['encryption']) && $user_auth['encryption'] === 'PLAIN') {
         $user_auth['password'] = md5($user_auth['password']);
     }
     //rrs
     $system_config = new Administration();
     $system_config->retrieveSettings('system');
     $authController = new AuthenticationController(!empty($sugar_config['authenticationClass']) ? $sugar_config['authenticationClass'] : 'SugarAuthenticate');
     //rrs
     $user = $user->retrieve_by_string_fields(array('user_name' => $user_auth['user_name'], 'user_hash' => $user_auth['password'], 'deleted' => 0, 'status' => 'Active', 'portal_only' => 0));
     if (!empty($user) && !empty($user->id) && !$user->is_group) {
         $success = true;
         global $current_user;
         $current_user = $user;
     } else {
         if (function_exists('mcrypt_cbc')) {
             $password = self::$helperObject->decrypt_string($user_auth['password']);
             if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) {
                 $success = true;
             }
             // if
         }
     }
     // else if
     if ($success) {
         session_start();
         global $current_user;
         //$current_user = $user;
         self::$helperObject->login_success($name_value_list);
         $current_user->loadPreferences();
         $_SESSION['is_valid_session'] = true;
         $_SESSION['ip_address'] = query_client_ip();
         $_SESSION['user_id'] = $current_user->id;
         $_SESSION['type'] = 'user';
         $_SESSION['avail_modules'] = self::$helperObject->get_user_module_list($current_user);
         $_SESSION['authenticated_user_id'] = $current_user->id;
         $_SESSION['unique_key'] = $sugar_config['unique_key'];
         $current_user->call_custom_logic('after_login');
         $GLOBALS['log']->info('End: SugarWebServiceImpl->login - succesful login');
         $nameValueArray = array();
         global $current_language;
         $nameValueArray[] = self::$helperObject->get_name_value('user_id', $current_user->id);
         $nameValueArray[] = self::$helperObject->get_name_value('user_name', $current_user->user_name);
         $nameValueArray[] = self::$helperObject->get_name_value('user_language', $current_language);
         $_SESSION['user_language'] = $current_language;
         return array('id' => session_id(), 'module_name' => 'Users', 'name_value_list' => $nameValueArray);
     }
     // if
     LogicHook::initialize();
     $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
     $error->set_error('invalid_login');
     self::$helperObject->setFaultObject($error);
     $GLOBALS['log']->info('End: SugarWebServiceImpl->login - failed login');
 }
function portal_validate_authenticated($session_id)
{
    $old_error_reporting = error_reporting(0);
    session_id($session_id);
    // This little construct checks to see if the session validated
    if (session_start()) {
        $valid_session = true;
        $valid_session = SessionManager::getValidSession($session_id);
        if (!empty($_SESSION['is_valid_session']) && $_SESSION['ip_address'] == query_client_ip() && $valid_session != null && ($_SESSION['type'] == 'contact' || $_SESSION['type'] == 'lead' || $_SESSION['type'] == 'portal')) {
            global $current_user;
            $valid_session->last_request_time = TimeDate::getInstance()->nowDb();
            $valid_session->save();
            $current_user = BeanFactory::getBean('Users', $_SESSION['portal_id']);
            login_success();
            error_reporting($old_error_reporting);
            return true;
        }
    }
    session_destroy();
    $GLOBALS['log']->fatal('SECURITY: The session ID is invalid');
    error_reporting($old_error_reporting);
    return false;
}
/**
 * Log the user into the application
 *
 * @param UserAuth array $user_auth -- Set user_name and password (password needs to be
 *      in the right encoding for the type of authentication the user is setup for.  For Base
 *      sugar validation, password is the MD5 sum of the plain text password.
 * @param String $application -- The name of the application you are logging in from.  (Currently unused).
 * @return Array(session_id) -- session_id is the id of the session that was created.
 * @exception 'SoapFault' -- The SOAP error, if any
 */
function new_login($user_auth, $application)
{
    global $sugar_config, $system_config;
    $error = new SoapError();
    $user = new User();
    $success = false;
    //rrs
    $system_config = new Administration();
    $system_config->retrieveSettings('system');
    $authController = new AuthenticationController(!empty($sugar_config['authenticationClass']) ? $sugar_config['authenticationClass'] : 'SugarAuthenticate');
    //rrs
    $user = $user->retrieve_by_string_fields(array('user_name' => $user_auth['user_name'], 'user_hash' => $user_auth['password'], 'deleted' => 0, 'status' => 'Active', 'portal_only' => 0));
    if (!empty($user) && !empty($user->id)) {
        $success = true;
        global $current_user;
        $current_user = $user;
    } else {
        if (function_exists('mcrypt_cbc')) {
            $password = decrypt_string($user_auth['password']);
            if ($authController->login($user_auth['user_name'], $password) && isset($_SESSION['authenticated_user_id'])) {
                $success = true;
            }
            // if
        }
    }
    // else if
    if ($success) {
        session_start();
        global $current_user;
        //$current_user = $user;
        login_success();
        $current_user->loadPreferences();
        $_SESSION['is_valid_session'] = true;
        $_SESSION['ip_address'] = query_client_ip();
        $_SESSION['user_id'] = $current_user->id;
        $_SESSION['type'] = 'user';
        $_SESSION['avail_modules'] = get_user_module_list($current_user);
        $_SESSION['authenticated_user_id'] = $current_user->id;
        $_SESSION['unique_key'] = $sugar_config['unique_key'];
        $current_user->call_custom_logic('after_login');
        return array('id' => session_id());
    }
    // if
    LogicHook::initialize();
    $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
    $error->set_error('invalid_login');
    setFaultObject($error);
}