Example #1
0
 public function actionExternal()
 {
     $this->_assertPostOnly();
     $providerCode = $this->_input->filterSingle('provider', XenForo_Input::STRING);
     $provider = bdApiConsumer_Option::getProviderByCode($providerCode);
     if (empty($provider)) {
         return $this->responseNoPermission();
     }
     $externalUserId = $this->_input->filterSingle('external_user_id', XenForo_Input::UINT);
     if (empty($externalUserId)) {
         return $this->responseNoPermission();
     }
     if (!bdApiConsumer_Helper_Api::verifyJsSdkSignature($provider, $_REQUEST)) {
         return $this->responseNoPermission();
     }
     $userModel = $this->_getUserModel();
     /** @var bdApiConsumer_XenForo_Model_UserExternal $userExternalModel */
     $userExternalModel = $this->getModelFromCache('XenForo_Model_UserExternal');
     $existingAssoc = $userExternalModel->getExternalAuthAssociation($userExternalModel->bdApiConsumer_getProviderCode($provider), $externalUserId);
     if (!empty($existingAssoc)) {
         $accessToken = $userExternalModel->bdApiConsumer_getAccessTokenFromAuth($provider, $existingAssoc);
         if (empty($accessToken)) {
             // no access token in the auth, consider no auth at all
             $existingAssoc = null;
         }
     }
     if (empty($existingAssoc)) {
         $autoRegister = bdApiConsumer_Option::get('autoRegister');
         if ($autoRegister === 'on' or $autoRegister === 'id_sync') {
             // we have to do a refresh here
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('canonical:register/external', null, array('provider' => $providerCode, 'reg' => 1, 'redirect' => $this->getDynamicRedirect())), new XenForo_Phrase('bdapi_consumer_being_auto_login_auto_register_x', array('provider' => $provider['name'])));
         }
     }
     if (!$existingAssoc) {
         return $this->responseError(new XenForo_Phrase('bdapi_consumer_auto_login_with_x_failed', array('provider' => $provider['name'])));
     }
     $user = $userModel->getFullUserById($existingAssoc['user_id']);
     if (empty($user)) {
         return $this->responseError(new XenForo_Phrase('requested_user_not_found'));
     }
     if (XenForo_Application::$versionId > 1050000) {
         /** @var XenForo_ControllerHelper_Login $loginHelper */
         $loginHelper = $this->getHelper('Login');
         if ($loginHelper->userTfaConfirmationRequired($user)) {
             $loginHelper->setTfaSessionCheck($user['user_id']);
             return $this->responseMessage(new XenForo_Phrase('bdapi_consumer_auto_login_user_x_requires_tfa', array('username' => $user['username'], 'twoStepLink' => XenForo_Link::buildPublicLink('login/two-step', null, array('redirect' => $this->getDynamicRedirect(), 'remember' => 1)))));
         }
     }
     $userModel->setUserRememberCookie($user['user_id']);
     XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'login_api_consumer');
     $userModel->deleteSessionActivity(0, $this->_request->getClientIp(false));
     if (XenForo_Application::$versionId < 1050000) {
         XenForo_Application::getSession()->changeUserId($user['user_id']);
         XenForo_Visitor::setup($user['user_id']);
     } else {
         $visitor = XenForo_Visitor::setup($user['user_id']);
         XenForo_Application::getSession()->userLogin($user['user_id'], $visitor['password_date']);
     }
     return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(), new XenForo_Phrase('bdapi_consumer_auto_login_with_x_succeeded_y', array('provider' => $provider['name'], 'username' => $user['username'])));
 }
Example #2
0
 public function actionApi()
 {
     $input = $this->_input->filter(array('redirect' => XenForo_Input::STRING, 'timestamp' => XenForo_Input::UINT, 'user_id' => XenForo_Input::STRING));
     $userId = 0;
     if (!empty($input['user_id']) && !empty($input['timestamp'])) {
         try {
             $userId = intval(bdApi_Crypt::decryptTypeOne($input['user_id'], $input['timestamp']));
         } catch (XenForo_Exception $e) {
             if (XenForo_Application::debugMode()) {
                 $this->_response->setHeader('X-Api-Exception', $e->getMessage());
             }
         }
     }
     if ($userId > 0) {
         $this->_response->setHeader('X-Api-Login-User', $userId);
         $this->_getUserModel()->setUserRememberCookie($userId);
         XenForo_Model_Ip::log($userId, 'user', $userId, 'login_api');
         $this->_getUserModel()->deleteSessionActivity(0, $this->_request->getClientIp(false));
         $session = XenForo_Application::get('session');
         $session->changeUserId($userId);
         XenForo_Visitor::setup($userId);
     }
     if (empty($input['redirect'])) {
         $input['redirect'] = $this->getDynamicRedirectIfNot(XenForo_Link::buildPublicLink('login'));
     }
     return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $input['redirect']);
 }
Example #3
0
 public function login($username, $password)
 {
     /**
      * @var $loginModel XenForo_Model_Login
      * @var $userModel XenForo_Model_User
      * @var $session XenForo_Session
      */
     $loginModel = XenForo_Model::create('XenForo_Model_Login');
     $userModel = XenForo_Model::create('XenForo_Model_User');
     $userId = $userModel->validateAuthentication($username, $password, $this->error);
     //var_dump($userId);
     //die;
     if (!$userId) {
         $loginModel->logLoginAttempt($username);
         return false;
     }
     $loginModel->clearLoginAttempts($username);
     /* if ($data['remember'])
        {
        $userModel->setUserRememberCookie($userId);
        } */
     XenForo_Model_Ip::log($userId, 'user', $userId, 'login');
     $userModel->deleteSessionActivity(0, $this->getClientIp(false));
     $session = XenForo_Application::get('session');
     //die('aaabb');
     /*if(!$this->session){
           $this->session = XenForo_Application::get('session');
       }*/
     $session->changeUserId($userId);
     XenForo_Visitor::setup($userId);
     $this->visitor = XenForo_Visitor::getInstance();
     $userInfo = $userModel->getFullUserById($this->visitor->getUserId());
     return $userInfo;
 }
Example #4
0
 public static function createUser(array $data, array $provider, array $externalToken, array $externalVisitor, XenForo_Model_UserExternal $userExternalModel)
 {
     $user = null;
     /** @var bdApiConsumer_XenForo_Model_UserExternal $userExternalModel */
     $options = XenForo_Application::get('options');
     /** @var XenForo_DataWriter_User $writer */
     $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
     if ($options->registrationDefaults) {
         $writer->bulkSet($options->registrationDefaults, array('ignoreInvalidFields' => true));
     }
     if (!isset($data['timezone']) and isset($externalVisitor['user_timezone_offset'])) {
         $tzOffset = $externalVisitor['user_timezone_offset'];
         $tzName = timezone_name_from_abbr('', $tzOffset, 1);
         if ($tzName !== false) {
             $data['timezone'] = $tzName;
         }
     }
     if (!empty($data['user_id'])) {
         $writer->setImportMode(true);
     }
     $writer->bulkSet($data);
     if (!empty($data['user_id'])) {
         $writer->setImportMode(false);
     }
     $writer->set('email', $externalVisitor['user_email']);
     if (!empty($externalVisitor['user_gender'])) {
         $writer->set('gender', $externalVisitor['user_gender']);
     }
     if (!empty($externalVisitor['user_dob_day']) && !empty($externalVisitor['user_dob_month']) && !empty($externalVisitor['user_dob_year'])) {
         $writer->set('dob_day', $externalVisitor['user_dob_day']);
         $writer->set('dob_month', $externalVisitor['user_dob_month']);
         $writer->set('dob_year', $externalVisitor['user_dob_year']);
     }
     if (!empty($externalVisitor['user_register_date'])) {
         $writer->set('register_date', $externalVisitor['user_register_date']);
     }
     $userExternalModel->bdApiConsumer_syncUpOnRegistration($writer, $externalToken, $externalVisitor);
     $auth = XenForo_Authentication_Abstract::create('XenForo_Authentication_NoPassword');
     $writer->set('scheme_class', $auth->getClassName());
     $writer->set('data', $auth->generate(''), 'xf_user_authenticate');
     $writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
     $writer->set('language_id', XenForo_Visitor::getInstance()->get('language_id'));
     $writer->advanceRegistrationUserState(false);
     // TODO: option for extra user group
     $writer->preSave();
     if ($writer->hasErrors()) {
         return $user;
     }
     try {
         $writer->save();
         $user = $writer->getMergedData();
         $userExternalModel->bdApiConsumer_updateExternalAuthAssociation($provider, $externalVisitor['user_id'], $user['user_id'], array_merge($externalVisitor, array('token' => $externalToken)));
         XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'register_api_consumer');
     } catch (XenForo_Exception $e) {
         XenForo_Error::logException($e, false);
     }
     return $user;
 }
Example #5
0
 public function actionLogin()
 {
     if (!$this->_request->isPost()) {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::RESOURCE_CANONICAL, XenForo_Link::buildAdminLink('index'));
     }
     $data = $this->_input->filter(array('login' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'redirect' => XenForo_Input::STRING, 'cookie_check' => XenForo_Input::UINT));
     $redirect = $data['redirect'] ? $data['redirect'] : XenForo_Link::buildAdminLink('index');
     $loginModel = $this->_getLoginModel();
     if ($data['cookie_check'] && count($_COOKIE) == 0) {
         // login came from a page, so we should at least have a session cookie.
         // if we don't, assume that cookies are disabled
         return $this->responseError(new XenForo_Phrase('cookies_required_to_log_in_to_site'));
     }
     $needCaptcha = $loginModel->requireLoginCaptcha($data['login']);
     if ($needCaptcha) {
         // just block logins here instead of using the captcha
         return $this->responseError(new XenForo_Phrase('your_account_has_temporarily_been_locked_due_to_failed_login_attempts'));
     }
     $userModel = $this->_getUserModel();
     $userId = $userModel->validateAuthentication($data['login'], $data['password'], $error);
     if (!$userId) {
         $loginModel->logLoginAttempt($data['login']);
         if ($loginModel->requireLoginCaptcha($data['login'])) {
             return $this->responseError(new XenForo_Phrase('your_account_has_temporarily_been_locked_due_to_failed_login_attempts'));
         }
         if ($this->_input->filterSingle('upgrade', XenForo_Input::UINT)) {
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
         } else {
             // note - JSON view will return responseError($text)
             return $this->responseView('XenForo_ViewAdmin_Login_Error', 'login_form', array('text' => $error, 'defaultLogin' => $data['login'], 'redirect' => $redirect), array('containerTemplate' => 'LOGIN_PAGE'));
         }
     }
     $loginModel->clearLoginAttempts($data['login']);
     XenForo_Model_Ip::log($userId, 'user', $userId, 'login_admin');
     $visitor = XenForo_Visitor::setup($userId);
     XenForo_Application::getSession()->userLogin($userId, $visitor['password_date']);
     // if guest on front-end, login there too
     $class = XenForo_Application::resolveDynamicClass('XenForo_Session');
     $publicSession = new $class();
     $publicSession->start();
     if (!$publicSession->get('user_id')) {
         $publicSession->userLogin($userId, $visitor['password_date']);
         $publicSession->save();
     }
     // now check that the user will be able to get into the ACP (is_admin)
     if (!$visitor->is_admin) {
         return $this->responseError(new XenForo_Phrase('your_account_does_not_have_admin_privileges'));
     }
     if ($this->_input->filterSingle('repost', XenForo_Input::UINT)) {
         $postVars = $this->_input->filterSingle('postVars', XenForo_Input::JSON_ARRAY);
         $postVars['_xfToken'] = $visitor['csrf_token_page'];
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect, '', array('repost' => 1, 'postVars' => $postVars));
     } else {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
     }
 }
Example #6
0
 /**
  * Fetches the current IP for the specified online guest
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionGuestIp()
 {
     if (!$this->_getUserModel()->canViewIps($errorPhraseKey)) {
         throw $this->getErrorOrNoPermissionResponseException($errorPhraseKey);
     }
     $ip = preg_replace('#[^0-9]#', '', $this->_input->filterSingle('ip', XenForo_Input::STRING));
     $ip = long2ip($ip);
     $viewParams = array('ip' => $ip, 'host' => XenForo_Model_Ip::getHost($ip));
     return $this->responseView('XenForo_ViewPublic_Online_GuestIp', 'online_guest_ip', $viewParams);
 }
Example #7
0
 public function actionLogin()
 {
     $data = $this->_input->filter(array('login' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'remember' => XenForo_Input::UINT, 'register' => XenForo_Input::UINT, 'redirect' => XenForo_Input::STRING, 'cookie_check' => XenForo_Input::UINT, 'postData' => XenForo_Input::JSON_ARRAY));
     if ($data['register'] || $data['password'] === '') {
         return $this->responseReroute('XenForo_ControllerPublic_Register', 'index');
     }
     $redirect = $data['redirect'] ? $data['redirect'] : $this->getDynamicRedirectIfNot(XenForo_Link::buildPublicLink('login'));
     if (XenForo_Visitor::getUserId()) {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
     }
     $this->_assertPostOnly();
     $loginModel = $this->_getLoginModel();
     if ($data['cookie_check'] && count($_COOKIE) == 0) {
         // login came from a page, so we should at least have a session cookie.
         // if we don't, assume that cookies are disabled
         return $this->_loginErrorResponse(new XenForo_Phrase('cookies_required_to_log_in_to_site'), $data['login'], true, $redirect);
     }
     $needCaptcha = $loginModel->requireLoginCaptcha($data['login']);
     if ($needCaptcha) {
         switch (XenForo_Application::getOptions()->loginLimit) {
             case 'captcha':
                 if (!XenForo_Captcha_Abstract::validateDefault($this->_input, true)) {
                     return $this->_loginErrorResponse(new XenForo_Phrase('did_not_complete_the_captcha_verification_properly'), $data['login'], true, $redirect, $data['postData']);
                 }
                 break;
             case 'block':
                 return $this->_loginErrorResponse(new XenForo_Phrase('your_account_has_temporarily_been_locked_due_to_failed_login_attempts'), $data['login'], true, $redirect, $data['postData']);
                 break;
         }
     }
     $userModel = $this->_getUserModel();
     $userId = $userModel->validateAuthentication($data['login'], $data['password'], $error);
     if (!$userId) {
         $loginModel->logLoginAttempt($data['login']);
         return $this->_loginErrorResponse($error, $data['login'], $needCaptcha || $loginModel->requireLoginCaptcha($data['login']), $redirect, $data['postData']);
     }
     $loginModel->clearLoginAttempts($data['login']);
     if ($data['remember']) {
         $userModel->setUserRememberCookie($userId);
     }
     XenForo_Model_Ip::log($userId, 'user', $userId, 'login');
     $userModel->deleteSessionActivity(0, $this->_request->getClientIp(false));
     $visitor = XenForo_Visitor::setup($userId);
     XenForo_Application::getSession()->userLogin($userId, $visitor['password_date']);
     if ($data['postData']) {
         return $this->responseView('XenForo_ViewPublic_Login_PostRedirect', 'login_post_redirect', array('postData' => $data['postData'], 'redirect' => $redirect));
     } else {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
     }
 }
 public function actionIndex()
 {
     $userModel = $this->_getUserModel();
     $userId = $this->_input->filterSingle('user_id', XenForo_Input::UINT);
     $user = $userModel->getUserById($userId, array('join' => XenForo_Model_User::FETCH_LAST_ACTIVITY));
     if (!$user) {
         return $this->responseError(new XenForo_Phrase('requested_member_not_found'), 404);
     }
     if (!$userModel->couldBeSpammer($user, $errorKey)) {
         return $this->responseError(new XenForo_Phrase($errorKey));
     }
     $canViewIps = $userModel->canViewIps();
     $noredirect = $this->_input->filterSingle('noredirect', XenForo_Input::UINT);
     if ($this->isConfirmedPost()) {
         $options = $this->_input->filter(array('action_threads' => XenForo_Input::STRING, 'delete_messages' => XenForo_Input::UINT, 'delete_conversations' => XenForo_Input::UINT, 'ban_user' => XenForo_Input::UINT, 'check_ips' => XenForo_Input::UINT, 'email_user' => XenForo_Input::UINT, 'email' => XenForo_Input::STRING));
         $spamCleanerModel = $this->_getSpamCleanerModel();
         if (!($log = $spamCleanerModel->cleanUp($user, $options, $log, $errorKey))) {
             return $this->responseError(new XenForo_Phrase($errorKey));
         }
         if ($options['check_ips'] && $canViewIps) {
             $users = $spamCleanerModel->checkIps($user['user_id'], XenForo_Application::get('options')->spamCheckIpsDaysLimit);
             $viewParams = array('user' => $user, 'spammer' => $user, 'users' => $users, 'noredirect' => $noredirect);
             return $this->responseView('XenForo_ViewPublic_SpamCleaner_CheckIps', 'spam_cleaner_check_ips', $viewParams);
         } else {
             $redirect = $this->getDynamicRedirect();
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(), new XenForo_Phrase('spam_deleted'));
         }
     } else {
         if ($ipId = $this->_input->filterSingle('ip_id', XenForo_Input::UINT)) {
             $contentIpRecord = XenForo_Model_Ip::getById($ipId);
             $contentIp = $contentIpRecord['ip_address'];
         } else {
             $contentIp = '';
         }
         $options = XenForo_Application::get('options');
         $contactUrl = $options->contactUrl;
         if ($contactUrl['type'] == 'default') {
             $contactUrl = XenForo_Link::buildPublicLink('canonical:misc/contact');
         } else {
             if ($contactUrl['type'] == 'custom') {
                 $contactUrl = $contactUrl['custom'];
             } else {
                 $contactUrl = '';
             }
         }
         $emailText = strtr($options->spamEmailText, array('{username}' => $user['username'], '{boardTitle}' => $options->boardTitle, '{contactUrl}' => $contactUrl));
         $viewParams = array('user' => $user, 'canViewIps' => $canViewIps, 'registrationIps' => $userModel->getRegistrationIps($user['user_id']), 'contentIp' => $contentIp, 'emailText' => $emailText, 'noredirect' => $noredirect);
         return $this->responseView('XenForo_ViewPublic_SpamCleaner', 'spam_cleaner', $viewParams);
     }
 }
Example #9
0
 public static function login($id)
 {
     self::start();
     if (self::userLoad()) {
         return;
     }
     $loginModel = XenForo_Model::create('XenForo_Model_Login');
     $userModel = XenForo_Model::create('XenForo_Model_User');
     $userModel->setUserRememberCookie($id);
     XenForo_Model_Ip::log($id, 'user', $id, 'login');
     $userModel->deleteSessionActivity(0, GetRealIp());
     $session = XenForo_Application::get('session');
     $session->changeUserId($id);
     XenForo_Visitor::setup($id);
 }
Example #10
0
 public function actionExternal()
 {
     $this->_assertPostOnly();
     $providerCode = $this->_input->filterSingle('provider', XenForo_Input::STRING);
     $provider = bdApiConsumer_Option::getProviderByCode($providerCode);
     if (empty($provider)) {
         return $this->responseNoPermission();
     }
     $externalUserId = $this->_input->filterSingle('external_user_id', XenForo_Input::UINT);
     if (empty($externalUserId)) {
         return $this->responseNoPermission();
     }
     if (!bdApiConsumer_Helper_Api::verifyJsSdkSignature($provider, $_REQUEST)) {
         return $this->responseNoPermission();
     }
     $userModel = $this->_getUserModel();
     $userExternalModel = $this->getModelFromCache('XenForo_Model_UserExternal');
     $existingAssoc = $userExternalModel->getExternalAuthAssociation($userExternalModel->bdApiConsumer_getProviderCode($provider), $externalUserId);
     if (!empty($existingAssoc)) {
         $accessToken = $userExternalModel->bdApiConsumer_getAccessTokenFromAuth($provider, $existingAssoc);
         if (empty($accessToken)) {
             // no access token in the auth, consider no auth at all
             $existingAssoc = null;
         }
     }
     if (empty($existingAssoc)) {
         $autoRegister = bdApiConsumer_Option::get('autoRegister');
         if ($autoRegister === 'on' or $autoRegister === 'id_sync') {
             // we have to do a refresh here
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('canonical:register/external', null, array('provider' => $providerCode, 'reg' => 1, 'redirect' => $this->getDynamicRedirect())), new XenForo_Phrase('bdapi_consumer_being_auto_login_auto_register_x', array('provider' => $provider['name'])));
         }
     }
     if ($existingAssoc and $user = $userModel->getUserById($existingAssoc['user_id'])) {
         $userModel->setUserRememberCookie($user['user_id']);
         XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'login_api_consumer');
         $userModel->deleteSessionActivity(0, $this->_request->getClientIp(false));
         $session = XenForo_Application::get('session');
         $session->changeUserId($user['user_id']);
         XenForo_Visitor::setup($user['user_id']);
         $message = new XenForo_Phrase('bdapi_consumer_auto_login_with_x_succeeded_y', array('provider' => $provider['name'], 'username' => $user['username']));
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(), $message);
     } else {
         return $this->responseError(new XenForo_Phrase('bdapi_consumer_auto_login_with_x_failed', array('provider' => $provider['name'])));
     }
 }
Example #11
0
 /**
  * Fetches the current IP for the specified online guest
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionGuestIp()
 {
     if (!$this->_getUserModel()->canViewIps($errorPhraseKey)) {
         throw $this->getErrorOrNoPermissionResponseException($errorPhraseKey);
     }
     $ip = preg_replace('#[^0-9a-f]#', '', $this->_input->filterSingle('ip', XenForo_Input::STRING));
     try {
         $ip = XenForo_Helper_Ip::convertIpBinaryToString(XenForo_Helper_Ip::convertHexToBin($ip));
     } catch (Exception $e) {
         $ip = false;
     }
     if (!$ip) {
         // likely given an invalid IP
         return $this->responseError(new XenForo_Phrase('unexpected_error_occurred'));
     }
     $viewParams = array('ip' => $ip, 'host' => XenForo_Model_Ip::getHost($ip));
     return $this->responseView('XenForo_ViewPublic_Online_GuestIp', 'online_guest_ip', $viewParams);
 }
 /**
  * Handles email confirmation.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionEmail()
 {
     $userId = $this->_input->filterSingle('user_id', XenForo_Input::UINT);
     if (!$userId) {
         return $this->responseError(new XenForo_Phrase('no_account_specified'));
     }
     $confirmationModel = $this->_getUserConfirmationModel();
     $confirmation = $confirmationModel->getUserConfirmationRecord($userId, 'email');
     if (!$confirmation) {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('index'));
     }
     $confirmationKey = $this->_input->filterSingle('c', XenForo_Input::STRING);
     if ($confirmationKey) {
         $accountConfirmed = $confirmationModel->validateUserConfirmationRecord($confirmationKey, $confirmation);
     } else {
         $accountConfirmed = false;
     }
     if ($accountConfirmed) {
         $dw = XenForo_DataWriter::create('XenForo_DataWriter_User');
         $dw->setExistingData($userId);
         if ($dw->get('user_state') == 'email_confirm') {
             // don't log when changing from initial confirm state as it creates a lot of noise
             $dw->setOption(XenForo_DataWriter_User::OPTION_LOG_CHANGES, false);
         }
         $dw->advanceRegistrationUserState();
         $dw->save();
         $confirmationModel->deleteUserConfirmationRecord($userId, 'email');
         $user = $dw->getMergedData();
         /** @var XenForo_Model_User $userModel */
         $userModel = $this->getModelFromCache('XenForo_Model_User');
         $userModel->sendWelcomeContact($user, $dw->getExisting('user_state'));
         // log the IP of the user
         XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'account-confirmation');
         $visitor = XenForo_Visitor::getInstance();
         if ($visitor['user_id'] == $user['user_id']) {
             $visitor['user_state'] = $user['user_state'];
         }
         $viewParams = array('user' => $user, 'oldUserState' => $dw->getExisting('user_state'), 'canEditProfile' => $visitor->canEditProfile());
         return $this->responseView('XenForo_ViewPublic_Register_Confirm', 'register_confirm', $viewParams);
     } else {
         return $this->responseError(new XenForo_Phrase('your_account_could_not_be_confirmed'));
         // TODO: users need to be able to do something
     }
 }
Example #13
0
 /**
  * Shows a list of moderated users and allows them to be managed.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionModerated()
 {
     $visitor = XenForo_Visitor::getInstance();
     if (!XenForo_Permission::hasPermission($visitor['permissions'], 'general', 'userModFrontEnd')) {
         return $this->responseNoPermission();
     }
     $users = $this->_getUserModel()->getUsers(array('user_state' => 'moderated'), array('limit' => 30));
     $class = XenForo_Application::resolveDynamicClass('XenForo_Session');
     /**
      * @var $publicSession XenForo_Session
      */
     $publicSession = new $class();
     $publicSession->start();
     if ($publicSession->get('user_id') == XenForo_Visitor::getUserId()) {
         $sessionCounts = $publicSession->get('userModerationCounts');
         if (!is_array($sessionCounts) || $sessionCounts['total'] != count($users)) {
             $publicSession->remove('userModerationCounts');
             $publicSession->save();
             $this->getModelFromCache('XenForo_Model_User')->rebuildUserModerationQueueCache();
         }
     }
     if (!$users) {
         return $this->responseMessage(new XenForo_Phrase('no_users_awaiting_approval'));
     }
     /**
      * @var XenForo_Model_SpamPrevention $spamPreventionModel
      */
     $spamPreventionModel = $this->getModelFromCache('XenForo_Model_SpamPrevention');
     $spamLogs = $spamPreventionModel->getSpamTriggerLogsByContentIds('user', array_keys($users));
     $spamLogs = $spamPreventionModel->prepareSpamTriggerLogs($spamLogs);
     foreach ($users as &$user) {
         $ips = $this->_getUserModel()->getRegistrationIps($user['user_id']);
         $user['ip'] = $ips ? reset($ips) : false;
         $user['ipHost'] = $user['ip'] ? XenForo_Model_Ip::getHost($user['ip']) : false;
         if (isset($spamLogs[$user['user_id']])) {
             $user['spamDetails'] = $spamLogs[$user['user_id']]['detailsPrintable'];
         } else {
             $user['spamDetails'] = false;
         }
     }
     $viewParams = array('users' => $users, 'userEditFrontEnd' => $this->_userEditFrontEndCheck());
     return $this->responseView('XenForo_ViewAdmin_User_Moderated', 'th_user_moderated_usermodfrontend', $viewParams);
 }
Example #14
0
 /**
  * Validates the callback request is valid. If failure happens, the response should
  * tell the processor to retry.
  *
  * @param string $errorString Output error string
  *
  * @return boolean
  */
 public function validateRequest(&$errorString)
 {
     try {
         if ($this->_filtered['test_ipn'] && XenForo_Application::debugMode()) {
             $validator = XenForo_Helper_Http::getClient('https://www.sandbox.paypal.com/cgi-bin/webscr');
         } else {
             $validator = XenForo_Helper_Http::getClient('https://www.paypal.com/cgi-bin/webscr');
         }
         $validator->setParameterPost('cmd', '_notify-validate');
         $validator->setParameterPost($_POST);
         $validatorResponse = $validator->request('POST');
         if (!$validatorResponse || $validatorResponse->getBody() != 'VERIFIED' || $validatorResponse->getStatus() != 200) {
             $host = XenForo_Model_Ip::getHost($this->_request->getClientIp(false));
             if (preg_match('#(^|\\.)paypal.com$#i', $host)) {
                 $errorString = 'Request not validated';
             } else {
                 $errorString = array(false, 'Request not validated (from unknown source)');
             }
             return false;
         }
     } catch (Zend_Http_Client_Exception $e) {
         $errorString = 'Connection to PayPal failed';
         return false;
     }
     $business = strtolower($this->_filtered['business']);
     $receiverEmail = strtolower($this->_filtered['receiver_email']);
     $options = XenForo_Application::get('options');
     $accounts = preg_split('#\\r?\\n#', $options->payPalAlternateAccounts, -1, PREG_SPLIT_NO_EMPTY);
     $accounts[] = $options->payPalPrimaryAccount;
     $matched = false;
     foreach ($accounts as $account) {
         $account = trim(strtolower($account));
         if ($account && ($business == $account || $receiverEmail == $account)) {
             $matched = true;
             break;
         }
     }
     if (!$matched) {
         $errorString = 'Invalid business or receiver_email';
         return false;
     }
     return true;
 }
Example #15
0
 public function actionLogin()
 {
     $this->_assertPostOnly();
     $data = $this->_input->filter(array('login' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'remember' => XenForo_Input::UINT, 'register' => XenForo_Input::UINT, 'redirect' => XenForo_Input::STRING, 'cookie_check' => XenForo_Input::UINT));
     if ($data['register'] || $data['password'] === '') {
         return $this->responseReroute('XenForo_ControllerPublic_Register', 'index');
     }
     $redirect = $data['redirect'] ? $data['redirect'] : $this->getDynamicRedirect();
     $loginModel = $this->_getLoginModel();
     if ($data['cookie_check'] && count($_COOKIE) == 0) {
         // login came from a page, so we should at least have a session cookie.
         // if we don't, assume that cookies are disabled
         return $this->_loginErrorResponse(new XenForo_Phrase('cookies_required_to_log_in_to_site'), $data['login'], true, $redirect);
     }
     $needCaptcha = $loginModel->requireLoginCaptcha($data['login']);
     if ($needCaptcha) {
         if (!XenForo_Captcha_Abstract::validateDefault($this->_input, true)) {
             $loginModel->logLoginAttempt($data['login']);
             return $this->_loginErrorResponse(new XenForo_Phrase('did_not_complete_the_captcha_verification_properly'), $data['login'], true, $redirect);
         }
     }
     $userModel = $this->_getUserModel();
     $userId = $userModel->validateAuthentication($data['login'], $data['password'], $error);
     if (!$userId) {
         $loginModel->logLoginAttempt($data['login']);
         return $this->_loginErrorResponse($error, $data['login'], $needCaptcha || $loginModel->requireLoginCaptcha($data['login']), $redirect);
     }
     $loginModel->clearLoginAttempts($data['login']);
     if ($data['remember']) {
         $userModel->setUserRememberCookie($userId);
     }
     XenForo_Model_Ip::log($userId, 'user', $userId, 'login');
     $userModel->deleteSessionActivity(0, $this->_request->getClientIp(false));
     $session = XenForo_Application::get('session');
     $session->changeUserId($userId);
     XenForo_Visitor::setup($userId);
     return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
 }
 /**
  * Handles email confirmation.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionEmail()
 {
     $userId = $this->_input->filterSingle('user_id', XenForo_Input::UINT);
     if (!$userId) {
         return $this->responseError(new XenForo_Phrase('no_account_specified'));
     }
     $confirmationModel = $this->_getUserConfirmationModel();
     $confirmation = $confirmationModel->getUserConfirmationRecord($userId, 'email');
     if (!$confirmation) {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('index'));
     }
     $confirmationKey = $this->_input->filterSingle('c', XenForo_Input::STRING);
     if ($confirmationKey) {
         $accountConfirmed = $confirmationModel->validateUserConfirmationRecord($confirmationKey, $confirmation);
     } else {
         $accountConfirmed = false;
     }
     if ($accountConfirmed) {
         $dw = XenForo_DataWriter::create('XenForo_DataWriter_User');
         $dw->setExistingData($userId);
         $dw->advanceRegistrationUserState();
         $dw->save();
         $confirmationModel->deleteUserConfirmationRecord($userId, 'email');
         $user = $dw->getMergedData();
         // log the IP of the user
         XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'account-confirmation');
         $viewParams = array('user' => $user, 'oldUserState' => $dw->getExisting('user_state'));
         $visitor = XenForo_Visitor::getInstance();
         if ($visitor['user_id'] == $user['user_id']) {
             $visitor['user_state'] = $user['user_state'];
         }
         return $this->responseView('XenForo_ViewPublic_Register_Confirm', 'register_confirm', $viewParams);
     } else {
         return $this->responseError(new XenForo_Phrase('your_account_could_not_be_confirmed'));
         // TODO: users need to be able to do something
     }
 }
Example #17
0
 public function completeLogin($userId, $redirect, array $postVars = array())
 {
     XenForo_Model_Ip::log($userId, 'user', $userId, 'login_admin');
     $visitor = XenForo_Visitor::setup($userId);
     XenForo_Application::getSession()->userLogin($userId, $visitor['password_date']);
     // if guest on front-end, login there too
     $class = XenForo_Application::resolveDynamicClass('XenForo_Session');
     $publicSession = new $class();
     $publicSession->start();
     if (!$publicSession->get('user_id')) {
         $publicSession->userLogin($userId, $visitor['password_date']);
         $publicSession->save();
     }
     if ($postVars) {
         $postVars['_xfToken'] = $visitor['csrf_token_page'];
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect, '', array('repost' => 1, 'postVars' => $postVars));
     } else {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
     }
 }
Example #18
0
 /**
  * TODO
  */
 public function register($user_data)
 {
     if (empty($user_data['username'])) {
         // Username was empty, return error.
         return array('error' => 10, 'errors' => 'Missing required parameter: username');
     } else {
         if (empty($user_data['password'])) {
             // Password was empty, return error.
             return array('error' => 10, 'errors' => 'Missing required parameter: password');
         } else {
             if (empty($user_data['email'])) {
                 // Email was empty, return error.
                 return array('error' => 10, 'errors' => 'Missing required parameter: email');
             }
         }
     }
     $usr = $this->getUser($user_data['username']);
     if ($usr->isRegistered()) {
         if ($usr->getEmail() != $user_data['email']) {
             $edit_results = $this->editUser($usr, array('email' => $user_data['email'], 'user_state' => 'email_confirm'));
             if (!empty($edit_results['error'])) {
                 return $edit_results;
             } else {
                 $user = $this->getUser($user_data['username']);
                 XenForo_Model::create('XenForo_Model_UserConfirmation')->sendEmailConfirmation($user->getData());
                 return $user->getData();
             }
         } else {
             return array('error' => 40, 'errors' => 'User already exists');
         }
     } else {
         // Create a new variable for the password.
         $password = $user_data['password'];
         // Unset the password from the user data array.
         unset($user_data['password']);
         if (!empty($user_data['ip_address'])) {
             // Create a new variable for the ip address.
             $ip_address = $user_data['ip_address'];
             // Unset the ip address from the user data array.
             unset($user_data['ip_address']);
         }
         // Get the default options from XenForo.
         $options = XenForo_Application::get('options');
         // Create the data writer object for registrations, and set the defaults.
         $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
         if ($options->registrationDefaults) {
             // Set the default registration options if it's set in the XenForo options.
             $writer->bulkSet($options->registrationDefaults, array('ignoreInvalidFields' => TRUE));
         }
         if (!empty($user_data['group_id'])) {
             // Group ID is set.
             $writer->set('user_group_id', $user_data['group_id']);
             // We need to unset the group id as we don't want it to be included into the bulk set.
             unset($user_data['group_id']);
         } else {
             // Group ID is not set, default back to default.
             $writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
         }
         if (!empty($user_data['user_state'])) {
             // User state is set.
             $writer->set('user_state', $user_data['user_state']);
         } else {
             // User state is not set, default back to default.
             $writer->advanceRegistrationUserState();
         }
         if (!empty($user_data['language_id'])) {
             // Language ID is set.
             $writer->set('language_id', $user_data['language_id']);
         } else {
             // Language ID is not set, default back to default.
             $writer->set('language_id', $options->defaultLanguageId);
         }
         if (!empty($user_data['custom_fields'])) {
             // Custom fields are set.
             // Check if there are any custom fields in the data array.
             if (count($user_data['custom_fields']) > 0) {
                 // There were one or more custom fields set, set them in the writer.
                 $writer->setCustomFields($user_data['custom_fields']);
             }
             // We need to unset the custom fields as we don't want it to be included into the bulk set.
             unset($user_data['custom_fields']);
         }
         if (!empty($user_data['add_groups'])) {
             // Add group is set.
             // Check if there are any custom fields in the data array.
             if (!is_array($user_data['add_groups']) || count($user_data['add_groups']) == 0) {
                 // The edit failed, return errors.
                 return array('error' => 7, 'errors' => 'The add_groups parameter needs to be an array and have at least 1 item.');
             }
             // Set the secondary group(s) of the user.
             $writer->setSecondaryGroups($user_data['add_groups']);
             // We need to unset the group id as we don't want it to be included into the bulk set.
             unset($user_data['add_groups']);
         }
         // Check if Gravatar is enabled, set the gravatar if it is and there's a gravatar for the email.
         if ($options->gravatarEnable && XenForo_Model_Avatar::gravatarExists($data['email'])) {
             $writer->set('gravatar', $user_data['email']);
         }
         // Set the data for the data writer.
         $writer->bulkSet($user_data);
         // Set the password for the data writer.
         $writer->setPassword($password, $password);
         // Pre save the data.
         $writer->preSave();
         if ($writer->hasErrors()) {
             // The registration failed, return errors.
             return array('error' => TRUE, 'errors' => $writer->getErrors());
         }
         // Save the user to the database.
         $writer->save();
         // Get the User as a variable:
         $user = $writer->getMergedData();
         // Check if IP is set.
         if (!empty($user_data['ip_address'])) {
             // Log the IP of the user that registered.
             XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'register', $ip_address);
         }
         if ($user['user_state'] == 'email_confirm') {
             XenForo_Model::create('XenForo_Model_UserConfirmation')->sendEmailConfirmation($user);
         } else {
             if ($user['user_state'] == 'valid') {
                 XenForo_Model::create('XenForo_Model_UserConfirmation')->resetPassword($user['user_id'], true);
             }
         }
         return $user;
     }
 }
Example #19
0
 protected function _postSave()
 {
     $this->updateCustomFields();
     $this->_updateTaggingVisibility();
     if ($this->isInsert()) {
         $this->updateUserMediaCount();
         if ($albumId = $this->isAlbumMedia()) {
             $this->updateAlbumCountAndDate();
             $album = $this->_getAlbumModel()->getAlbumById($albumId);
             $this->_db->update('xengallery_media', array('media_privacy' => $album['access_type']), 'media_id = ' . $this->get('media_id'));
             if ($album['album_default_order'] == 'custom') {
                 $this->_db->query("\n\t\t\t\t\t\tUPDATE xengallery_media\n\t\t\t\t\t\tSET position = position + 1\n\t\t\t\t\t\tWHERE album_id = ?\n\t\t\t\t\t\tAND media_id != ?\n\t\t\t\t\t", array($albumId, $this->get('media_id')));
             }
         } else {
             $this->updateCategoryMediaCount();
         }
         $this->_getNewsFeedModel()->publish($this->get('user_id'), $this->get('username'), 'xengallery_media', $this->get('media_id'), 'insert');
         $ipId = XenForo_Model_Ip::log($this->get('user_id'), 'xengallery_media', $this->get('media_id'), 'insert');
         $this->_db->update('xengallery_media', array('ip_id' => $ipId), 'media_id = ' . $this->get('media_id'));
         $this->_getMediaModel()->markMediaViewed(array('media_id' => $this->get('media_id')));
     }
     $media = $this->_getMediaModel()->getMediaById($this->get('media_id'), array('join' => XenGallery_Model_Media::FETCH_ATTACHMENT));
     $indexer = new XenForo_Search_Indexer();
     $dataHandler = XenForo_Search_DataHandler_Abstract::create('XenGallery_Search_DataHandler_Media');
     $dataHandler->insertIntoIndex($indexer, $this->getMergedData(), $media);
     $this->_updateDeletionLog();
     if ($this->isChanged('media_state') || $this->isInsert()) {
         if ($this->get('media_state') == 'deleted') {
             $this->_deleteTagsForMedia();
             $this->updateUserMediaCount(false);
             $this->updateUserMediaQuota(false);
             if ($this->isAlbumMedia()) {
                 $this->updateAlbumCountAndDate(false);
             } else {
                 $this->updateCategoryMediaCount(false);
             }
             $this->getModelFromCache('XenForo_Model_Alert')->deleteAlerts('xengallery_media', $this->get('media_id'));
         }
         if ($this->getExisting('media_state') == 'deleted') {
             $this->updateUserMediaCount();
             $this->updateUserMediaQuota();
             if ($this->isAlbumMedia()) {
                 $this->updateAlbumCountAndDate();
             } else {
                 $this->updateCategoryMediaCount();
             }
         }
         $this->_updateModerationQueue($media);
     }
     if ($this->isChanged('category_id') && $this->isChanged('album_id')) {
         if ($this->getExisting('category_id') && $this->get('album_id')) {
             // From category to album
             $this->updateCategoryMediaCount(false, $this->getExisting('category_id'));
             $this->updateAlbumCountAndDate();
             $albumId = $this->get('album_id');
         }
         if ($this->getExisting('album_id') && $this->get('category_id')) {
             // From album to category
             $this->updateAlbumCountAndDate(false, $this->getExisting('album_id'));
             $this->updateCategoryMediaCount();
             $albumId = $this->getExisting('album_id');
         }
         $this->_updateAlbumCache($albumId);
     } else {
         if ($this->isChanged('album_id') && $this->isAlbumMedia()) {
             $this->_originalAlbumId = $this->getExisting('album_id');
         }
         if ($this->isChanged('category_id') && !$this->isAlbumMedia()) {
             $this->_originalCategoryId = $this->getExisting('category_id');
         }
     }
 }
Example #20
0
 public function actionLogin()
 {
     if ($this->_getUpgradeModel()->setupVisitorFromUpgradeCookie()) {
         $visitor = XenForo_Visitor::getInstance();
         if ($visitor['is_admin'] && $visitor->hasAdminPermission('upgradeXenForo')) {
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::RESOURCE_CANONICAL, 'index.php?upgrade/');
         }
     }
     $error = '';
     if ($this->isConfirmedPost()) {
         $data = $this->_input->filter(array('login' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'redirect' => XenForo_Input::STRING));
         $redirect = $data['redirect'] ? $data['redirect'] : 'index.php?upgrade/';
         /** @var $loginModel XenForo_Model_Login */
         $loginModel = $this->getModelFromCache('XenForo_Model_Login');
         if ($loginModel->requireLoginCaptcha($data['login'])) {
             // just block logins here instead of using the captcha
             return $this->responseError(new XenForo_Phrase('your_account_has_temporarily_been_locked_due_to_failed_login_attempts'));
         }
         /** @var $userModel XenForo_Model_User */
         $userModel = $this->getModelFromCache('XenForo_Model_User');
         $userId = false;
         $user = $userModel->getUserByNameOrEmail($data['login']);
         if ($user) {
             $authentication = $userModel->getUserAuthenticationObjectByUserId($user['user_id']);
             if ($authentication && $authentication->authenticate($user['user_id'], $data['password'])) {
                 $userId = $user['user_id'];
             } else {
                 $error = new XenForo_Phrase('incorrect_password');
             }
         } else {
             $error = new XenForo_Phrase('requested_user_x_not_found', array('name' => $data['login']));
         }
         if (!$userId) {
             try {
                 $loginModel->logLoginAttempt($data['login']);
                 if ($loginModel->requireLoginCaptcha($data['login'])) {
                     return $this->responseError(new XenForo_Phrase('your_account_has_temporarily_been_locked_due_to_failed_login_attempts'));
                 }
             } catch (Exception $e) {
             }
         } else {
             try {
                 $loginModel->clearLoginAttempts($data['login']);
                 XenForo_Model_Ip::log($userId, 'user', $userId, 'login_upgrade');
             } catch (Exception $e) {
             }
             XenForo_Visitor::setup($userId);
             $visitor = XenForo_Visitor::getInstance();
             if (!$visitor->is_admin) {
                 return $this->responseError(new XenForo_Phrase('your_account_does_not_have_admin_privileges'));
             }
             if (!$visitor->hasAdminPermission('upgradeXenForo')) {
                 return $this->responseError(new XenForo_Phrase('you_do_not_have_permission_upgrade'));
             }
             $this->_getUpgradeModel()->setUpgradeCookie($userId);
             return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
         }
     }
     return $this->responseView('XenForo_Install_View_Upgrade_Login', 'upgrade_login', array('error' => $error));
 }
Example #21
0
File: User.php Project: sushj/bdApi
 public function actionPostIndex()
 {
     /* @var $oauth2Model bdApi_Model_OAuth2 */
     $oauth2Model = $this->getModelFromCache('bdApi_Model_OAuth2');
     /* @var $userConfirmationModel XenForo_Model_UserConfirmation */
     $userConfirmationModel = $this->getModelFromCache('XenForo_Model_UserConfirmation');
     /* @var $session bdApi_Session */
     $session = XenForo_Application::getSession();
     $clientId = $session->getOAuthClientId();
     $clientSecret = $session->getOAuthClientSecret();
     if (empty($clientId) or empty($clientSecret)) {
         $clientId = $this->_input->filterSingle('client_id', XenForo_Input::STRING);
         $client = $oauth2Model->getClientModel()->getClientById($clientId);
         if (empty($client)) {
             return $this->responseError(new XenForo_Phrase('bdapi_post_slash_users_requires_client_id'), 400);
         }
         $clientSecret = $client['client_secret'];
     }
     $input = $this->_input->filter(array('user_email' => XenForo_Input::STRING, 'username' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'password_algo' => XenForo_Input::STRING, 'user_dob_day' => XenForo_Input::UINT, 'user_dob_month' => XenForo_Input::UINT, 'user_dob_year' => XenForo_Input::UINT));
     if (empty($input['user_email'])) {
         // backward compatibility
         $input['user_email'] = $this->_input->filterSingle('email', XenForo_Input::STRING);
     }
     $extraInput = $this->_input->filter(array('extra_data' => XenForo_Input::STRING, 'extra_timestamp' => XenForo_Input::UINT));
     if (!empty($extraInput['extra_data'])) {
         $extraData = bdApi_Crypt::decryptTypeOne($extraInput['extra_data'], $extraInput['extra_timestamp']);
         if (!empty($extraData)) {
             $extraData = @unserialize($extraData);
         }
         if (empty($extraData)) {
             $extraData = array();
         }
     }
     $userModel = $this->_getUserModel();
     $options = XenForo_Application::getOptions();
     $session = XenForo_Application::getSession();
     $visitor = XenForo_Visitor::getInstance();
     /* @var $writer XenForo_DataWriter_User */
     $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
     $registrationDefaults = $options->get('registrationDefaults');
     if (!empty($registrationDefaults)) {
         $writer->bulkSet($registrationDefaults, array('ignoreInvalidFields' => true));
     }
     $writer->set('email', $input['user_email']);
     $writer->set('username', $input['username']);
     $password = bdApi_Crypt::decrypt($input['password'], $input['password_algo'], $clientSecret);
     if (!empty($password)) {
         $writer->setPassword($password, $password);
     } else {
         // no password or unable to decrypt password
         // create new user with no password auth scheme
         $auth = XenForo_Authentication_Abstract::create('XenForo_Authentication_NoPassword');
         $writer->set('scheme_class', $auth->getClassName());
         $writer->set('data', $auth->generate(''), 'xf_user_authenticate');
     }
     if ($options->get('gravatarEnable') && XenForo_Model_Avatar::gravatarExists($input['user_email'])) {
         $writer->set('gravatar', $input['user_email']);
     }
     $writer->set('dob_day', $input['user_dob_day']);
     $writer->set('dob_month', $input['user_dob_month']);
     $writer->set('dob_year', $input['user_dob_year']);
     $writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
     $writer->set('language_id', XenForo_Visitor::getInstance()->get('language_id'));
     $allowEmailConfirm = true;
     if (!empty($extraData['user_email']) && $extraData['user_email'] == $writer->get('email')) {
         // the email address has been validated by some other mean (external provider?)
         // do not require email confirmation again to avoid complication
         $allowEmailConfirm = false;
     }
     $writer->advanceRegistrationUserState($allowEmailConfirm);
     if ($visitor->hasAdminPermission('user') and $session->checkScope(bdApi_Model_OAuth2::SCOPE_MANAGE_SYSTEM)) {
         $writer->set('user_state', 'valid');
     }
     $writer->save();
     $user = $writer->getMergedData();
     // log the ip of the user registering
     XenForo_Model_Ip::log(XenForo_Visitor::getUserId() ? XenForo_Visitor::getUserId() : $user['user_id'], 'user', $user['user_id'], 'register');
     if ($user['user_state'] == 'email_confirm') {
         $userConfirmationModel->sendEmailConfirmation($user);
     }
     if (!empty($extraData['external_provider']) && !empty($extraData['external_provider_key'])) {
         /* @var $userExternalModel XenForo_Model_UserExternal */
         $userExternalModel = $this->getModelFromCache('XenForo_Model_UserExternal');
         $userExternalModel->updateExternalAuthAssociation($extraData['external_provider'], $extraData['external_provider_key'], $user['user_id']);
     }
     if (XenForo_Visitor::getUserId() == 0) {
         XenForo_Visitor::setup($user['user_id']);
     }
     $scopes = $oauth2Model->getSystemSupportedScopes();
     $scopes = bdApi_Template_Helper_Core::getInstance()->scopeJoin($scopes);
     $token = $oauth2Model->getServer()->createAccessToken($clientId, $user['user_id'], $scopes);
     $user = $userModel->getUserById($user['user_id'], $userModel->getFetchOptionsToPrepareApiData());
     $data = array('user' => $this->_filterDataSingle($this->_getUserModel()->prepareApiDataForUser($user)), '_user' => $user, 'token' => $token);
     return $this->responseData('bdApi_ViewApi_User_Single', $data);
 }
 /**
  * Upates the IP data.
  */
 protected function _updateIpData()
 {
     if (!empty($this->_extraData['ipAddress'])) {
         $ipAddress = $this->_extraData['ipAddress'];
     } else {
         $ipAddress = null;
     }
     $ipId = XenForo_Model_Ip::log($this->get('user_id'), 'profile_post_comment', $this->get('profile_post_comment_id'), 'insert', $ipAddress);
     $this->set('ip_id', $ipId, '', array('setAfterPreSave' => true));
     $this->_db->update('xf_profile_post_comment', array('ip_id' => $ipId), 'profile_post_comment_id = ' . $this->_db->quote($this->get('profile_post_comment_id')));
 }
Example #23
0
 protected function _postSave()
 {
     if ($this->isInsert()) {
         $contentId = $this->get('content_id');
         $contentType = $this->get('content_type');
         $userId = XenForo_Visitor::getUserId();
         $draftKey = $contentType . '-' . $contentId;
         $draftModel = $this->_getDraftModel();
         $draft = $draftModel->getDraftByUserKey($draftKey, $userId);
         if ($draft) {
             $draftModel->deleteDraft($draftKey, array());
         }
         if ($contentType == 'media') {
             $mediaWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Media');
             $mediaWriter->setExistingData($contentId);
             $commentCount = $mediaWriter->getExisting('comment_count');
             $mediaWriter->set('comment_count', $commentCount + 1);
             $mediaWriter->set('last_comment_date', XenForo_Application::$time);
             $mediaWriter->save();
             $content = $this->_getMediaModel()->getMediaById($contentId, array('join' => XenGallery_Model_Media::FETCH_USER | XenGallery_Model_Media::FETCH_USER_OPTION | XenGallery_Model_Media::FETCH_ALBUM));
             $this->_getMediaModel()->markMediaViewed($content);
         } else {
             $albumWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Album');
             $albumWriter->setExistingData($contentId);
             $commentCount = $albumWriter->getExisting('album_comment_count');
             $newValue = $commentCount + 1;
             if (intval($newValue) < 1) {
                 $newValue = 0;
             }
             $albumWriter->set('album_comment_count', $newValue);
             $albumWriter->set('album_last_comment_date', XenForo_Application::$time);
             $albumWriter->save();
             $content = $this->_getAlbumModel()->getAlbumById($contentId, array('join' => XenGallery_Model_Album::FETCH_USER | XenGallery_Model_Album::FETCH_USER_OPTION));
         }
         $commentUser = array('user_id' => $this->get('user_id'), 'username' => $this->get('username'));
         $commentId = $this->get('comment_id');
         $maxTagged = $this->getOption(self::OPTION_MAX_TAGGED_USERS);
         if ($maxTagged && $this->_taggedUsers) {
             if ($maxTagged > 0) {
                 $alertTagged = array_slice($this->_taggedUsers, 0, $maxTagged, true);
             } else {
                 $alertTagged = $this->_taggedUsers;
             }
             $this->_alertedUsers = $this->_getCommentModel()->alertTaggedMembers($this->_getCommentModel()->getCommentById($commentId, array('join' => XenGallery_Model_Comment::FETCH_MEDIA | XenGallery_Model_Comment::FETCH_ALBUM)), $alertTagged);
         }
         if ($content && XenForo_Model_Alert::userReceivesAlert($content, 'xengallery_comment', 'insert') && $content['user_id'] != $commentUser['user_id']) {
             if (!in_array($content['user_id'], $this->_alertedUsers)) {
                 XenForo_Model_Alert::alert($content['user_id'], $commentUser['user_id'], $commentUser['username'], 'xengallery_comment', $commentId, 'insert');
             }
             $this->_alertedUsers[] = $content['user_id'];
         }
         $this->_getNewsFeedModel()->publish($commentUser['user_id'], $commentUser['username'], 'xengallery_comment', $commentId, 'insert');
         $ipId = XenForo_Model_Ip::log($this->get('user_id'), 'xengallery_comment', $this->get('comment_id'), 'insert');
         $this->_db->update('xengallery_comment', array('ip_id' => $ipId), 'comment_id = ' . $this->get('comment_id'));
     }
     if ($this->isChanged('comment_state') && $this->getExisting('comment_state') == 'deleted' || $this->getExisting('comment_state') == 'moderated') {
         $this->updateCommentCount();
         $this->_updateLastCommentDate();
     }
     if ($this->isUpdate() && $this->isChanged('comment_state')) {
         $this->_updateLastCommentDate();
         // $this->_updateMessagePositionList();
     }
     if ($this->isChanged('comment_state') && $this->getExisting('comment_state') == 'visible') {
         $this->updateCommentCount(false);
         $this->_updateLastCommentDate();
         $this->getModelFromCache('XenForo_Model_Alert')->deleteAlerts('xengallery_comment', $this->get('comment_id'));
     }
     $this->_updateModerationQueue($this->getMergedData());
     $this->_updateDeletionLog(true);
 }
Example #24
0
 public function completeLogin($userId, $remember, $redirect, array $postData = array())
 {
     $userModel = $this->_getUserModel();
     if ($remember) {
         $userModel->setUserRememberCookie($userId);
     }
     XenForo_Model_Ip::log($userId, 'user', $userId, 'login');
     $userModel->deleteSessionActivity(0, $this->_request->getClientIp(false));
     $visitor = XenForo_Visitor::setup($userId);
     XenForo_Application::getSession()->userLogin($userId, $visitor['password_date']);
     if ($postData) {
         return $this->responseView('XenForo_ViewPublic_Login_PostRedirect', 'login_post_redirect', array('postData' => $postData, 'redirect' => $redirect));
     } else {
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect, '');
     }
 }
Example #25
0
 public function actionRegister()
 {
     $this->_assertRegistrationActive();
     $vals = $this->_input->filter(array('username' => XenForo_Input::STRING, 'email' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'password_md5' => XenForo_Input::STRING, 'birthday' => XenForo_Input::STRING, 'timezone_name' => XenForo_Input::STRING));
     $options = XenForo_Application::get('options');
     if (!$options->forumrunnerRegistration) {
         $p = new XenForo_Phrase('do_not_have_permission');
         json_error($p->render());
     }
     $out = array();
     if ($vals['username']) {
         $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
         if ($options->registrationDefaults) {
             $writer->bulkSet($options->registrationDefaults, array('ignoreInvalidFields' => true));
         }
         $day = $month = $year = '';
         if ($vals['birthday']) {
             $parts = preg_split('#/#', $vals['birthday']);
             if ($parts[0]) {
                 $month = intval($parts[0]);
             }
             if ($parts[1]) {
                 $day = intval($parts[1]);
             }
             if ($parts[2]) {
                 $year = intval($parts[2]);
             }
         }
         // Figure out Time Zone
         $data = array('username' => $vals['username'], 'email' => $vals['email'], 'gender' => '', 'dob_day' => $day, 'dob_month' => $month, 'dob_year' => $year, 'timezone' => $vals['timezone_name']);
         $writer->bulkSet($data);
         $writer->setPassword($vals['password'], $vals['password']);
         // verified by client
         // if the email corresponds to an existing Gravatar, use it
         if ($options->gravatarEnable && XenForo_Model_Avatar::gravatarExists($data['email'])) {
             $writer->set('gravatar', $data['email']);
         }
         $writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
         $writer->set('language_id', XenForo_Visitor::getInstance()->get('language_id'));
         $writer->advanceRegistrationUserState();
         $writer->preSave();
         if ($options->get('registrationSetup', 'requireDob')) {
             // dob required
             if (!$data['dob_day'] || !$data['dob_month'] || !$data['dob_year']) {
                 $p = new XenForo_Phrase('please_enter_valid_date_of_birth');
                 json_error($p->render());
             }
             $userAge = $this->_getUserProfileModel()->getUserAge($writer->getMergedData(), true);
             if ($userAge < 1) {
                 $p = new XenForo_Phrase('please_enter_valid_date_of_birth');
                 json_error($p->render());
             }
             if ($userAge < intval($options->get('registrationSetup', 'minimumAge'))) {
                 $p = new XenForo_Phrase('sorry_you_too_young_to_create_an_account');
                 json_error($p->render());
             }
         }
         $errors = $writer->getErrors();
         if (count($errors)) {
             // only show first
             $errors = array_values($errors);
             json_error($errors[0]->render());
         }
         $writer->save();
         $user = $writer->getMergedData();
         // log the ip of the user registering
         XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'register');
         if ($user['user_state'] == 'email_confirm') {
             $this->_getUserConfirmationModel()->sendEmailConfirmation($user);
             $out['emailverify'] = true;
         } else {
             $out['emailverify'] = false;
         }
         XenForo_Visitor::setup(0);
     } else {
         $p = new XenForo_Phrase('fr_register_forum_rules');
         $out += array('rules' => preg_replace('/<a href=\\"(.*?)\\">(.*?)<\\/a>/', "\\2", $p->render()), 'birthday' => $options->get('registrationSetup', 'requireDob') ? true : false);
     }
     return $out;
 }
Example #26
0
 /**
  * Registers a new account (or associates with an existing one) using Facebook.
  *
  * @return XenForo_ControllerResponse_Abstract
  */
 public function actionFacebookRegister()
 {
     $this->_assertPostOnly();
     $fbToken = $this->_input->filterSingle('fb_token', XenForo_Input::STRING);
     $fbUser = XenForo_Helper_Facebook::getUserInfo($fbToken);
     if (empty($fbUser['id'])) {
         return $this->responseError(new XenForo_Phrase('error_occurred_while_connecting_with_facebook'));
     }
     $userModel = $this->_getUserModel();
     $userExternalModel = $this->_getUserExternalModel();
     $doAssoc = $this->_input->filterSingle('associate', XenForo_Input::STRING) || $this->_input->filterSingle('force_assoc', XenForo_Input::UINT);
     if ($doAssoc) {
         $associate = $this->_input->filter(array('associate_login' => XenForo_Input::STRING, 'associate_password' => XenForo_Input::STRING));
         $loginModel = $this->_getLoginModel();
         if ($loginModel->requireLoginCaptcha($associate['associate_login'])) {
             return $this->responseError(new XenForo_Phrase('your_account_has_temporarily_been_locked_due_to_failed_login_attempts'));
         }
         $userId = $userModel->validateAuthentication($associate['associate_login'], $associate['associate_password'], $error);
         if (!$userId) {
             $loginModel->logLoginAttempt($associate['associate_login']);
             return $this->responseError($error);
         }
         $userExternalModel->updateExternalAuthAssociation('facebook', $fbUser['id'], $userId);
         XenForo_Helper_Facebook::setUidCookie($fbUser['id']);
         XenForo_Application::get('session')->changeUserId($userId);
         XenForo_Visitor::setup($userId);
         $redirect = XenForo_Application::get('session')->get('fbRedirect');
         XenForo_Application::get('session')->remove('fbRedirect');
         if (!$redirect) {
             $redirect = $this->getDynamicRedirect(false, false);
         }
         return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect);
     }
     $this->_assertRegistrationActive();
     $data = $this->_input->filter(array('username' => XenForo_Input::STRING, 'timezone' => XenForo_Input::STRING));
     if (XenForo_Dependencies_Public::getTosUrl() && !$this->_input->filterSingle('agree', XenForo_Input::UINT)) {
         return $this->responseError(new XenForo_Phrase('you_must_agree_to_terms_of_service'));
     }
     $options = XenForo_Application::get('options');
     $gender = '';
     if (isset($fbUser['gender'])) {
         switch ($fbUser['gender']) {
             case 'man':
             case 'male':
                 $gender = 'male';
                 break;
             case 'woman':
             case 'female':
                 $gender = 'female';
                 break;
         }
     }
     $writer = XenForo_DataWriter::create('XenForo_DataWriter_User');
     if ($options->registrationDefaults) {
         $writer->bulkSet($options->registrationDefaults, array('ignoreInvalidFields' => true));
     }
     $writer->bulkSet($data);
     $writer->bulkSet(array('gender' => $gender, 'email' => $fbUser['email'], 'location' => isset($fbUser['location']['name']) ? $fbUser['location']['name'] : ''));
     if (!empty($fbUser['birthday'])) {
         $birthdayParts = explode('/', $fbUser['birthday']);
         if (count($birthdayParts) == 3) {
             list($month, $day, $year) = $birthdayParts;
             $userAge = $this->_getUserProfileModel()->calculateAge($year, $month, $day);
             if ($userAge < intval($options->get('registrationSetup', 'minimumAge'))) {
                 // TODO: set a cookie to prevent re-registration attempts
                 return $this->responseError(new XenForo_Phrase('sorry_you_too_young_to_create_an_account'));
             }
             $writer->bulkSet(array('dob_year' => $year, 'dob_month' => $month, 'dob_day' => $day));
         }
     }
     if (!empty($fbUser['website'])) {
         list($website) = preg_split('/\\r?\\n/', $fbUser['website']);
         if ($website && Zend_Uri::check($website)) {
             $writer->set('homepage', $website);
         }
     }
     $auth = XenForo_Authentication_Abstract::create('XenForo_Authentication_NoPassword');
     $writer->set('scheme_class', $auth->getClassName());
     $writer->set('data', $auth->generate(''), 'xf_user_authenticate');
     $writer->set('user_group_id', XenForo_Model_User::$defaultRegisteredGroupId);
     $writer->set('language_id', XenForo_Visitor::getInstance()->get('language_id'));
     $writer->advanceRegistrationUserState(false);
     $writer->preSave();
     // TODO: option for extra user group
     $writer->save();
     $user = $writer->getMergedData();
     $avatarFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
     if ($avatarFile) {
         $data = XenForo_Helper_Facebook::getUserPicture($fbToken);
         if ($data && $data[0] != '{') {
             file_put_contents($avatarFile, $data);
             try {
                 $user = array_merge($user, $this->getModelFromCache('XenForo_Model_Avatar')->applyAvatar($user['user_id'], $avatarFile));
             } catch (XenForo_Exception $e) {
             }
         }
         @unlink($avatarFile);
     }
     $userExternalModel->updateExternalAuthAssociation('facebook', $fbUser['id'], $user['user_id']);
     XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'register');
     XenForo_Helper_Facebook::setUidCookie($fbUser['id']);
     XenForo_Application::get('session')->changeUserId($user['user_id']);
     XenForo_Visitor::setup($user['user_id']);
     $redirect = $this->_input->filterSingle('redirect', XenForo_Input::STRING);
     $viewParams = array('user' => $user, 'redirect' => $redirect ? XenForo_Link::convertUriToAbsoluteUri($redirect) : '', 'facebook' => true);
     return $this->responseView('XenForo_ViewPublic_Register_Process', 'register_process', $viewParams, $this->_getRegistrationContainerParams());
 }
Example #27
0
 protected function _completeRegistration(array $user, array $extraParams = array())
 {
     XenForo_Model_Ip::log($user['user_id'], 'user', $user['user_id'], 'register');
     $userModel = $this->_getUserModel();
     $userModel->sendWelcomeContact($user);
     $visitor = XenForo_Visitor::setup($user['user_id']);
     XenForo_Application::getSession()->userLogin($user['user_id'], $visitor['password_date']);
     $this->_executePromotionUpdate(true);
     $this->_executeTrophyUpdate(true);
     // keep the user logged in for a while - more friendly for new users
     $userModel->setUserRememberCookie($user['user_id']);
     $redirect = $this->_input->filterSingle('redirect', XenForo_Input::STRING);
     $visitor = XenForo_Visitor::getInstance();
     $viewParams = $extraParams + array('user' => $visitor->toArray(), 'canEditProfile' => $visitor->canEditProfile(), 'redirect' => $redirect ? XenForo_Link::convertUriToAbsoluteUri($redirect) : '');
     return $this->responseView('XenForo_ViewPublic_Register_Process', 'register_process', $viewParams, $this->_getRegistrationContainerParams());
 }
Example #28
0
 public function actionLogin()
 {
     global $fr_version, $fr_platform;
     $vals = $this->_input->filter(array('username' => XenForo_Input::STRING, 'password' => XenForo_Input::STRING, 'md5_password' => XenForo_Input::STRING, 'fr_username' => XenForo_Input::STRING, 'fr_b' => XenForo_Input::UINT, 'token' => XenForo_Input::STRING));
     $login_model = $this->_getLoginModel();
     $user_model = $this->_getUserModel();
     $options = XenForo_Application::get('options');
     $navbg = '';
     $style = $options->forumrunnerColor;
     if ($style) {
         // Convert to right style.  iPhone needs r,g,b.  Android needs #rrggbb.
         $color = convert_color($style);
         if (is_iphone() && strlen($color) == 7) {
             $r = hexdec(substr($color, 1, 2));
             $g = hexdec(substr($color, 3, 2));
             $b = hexdec(substr($color, 5, 2));
             $color = "{$r},{$g},{$b}";
         }
         $navbg = $color;
     }
     $authenticated = false;
     $requires_authentication = false;
     $out = array();
     if (!$vals['username'] || !$vals['password'] && !$vals['md5_password']) {
         if (!XenForo_Visitor::getInstance()->hasPermission('general', 'view')) {
             $requires_authentication = true;
         }
         $options = XenForo_Application::get('options');
         if (!$options->boardActive && !XenForo_Visitor::getInstance()->get('is_admin')) {
             $requires_authentication = true;
         }
     } else {
         $user_id = $user_model->validateAuthentication($vals['username'], $vals['password'], $error);
         if (!$user_id) {
             $login_model->logLoginAttempt($vals['username']);
             json_error($error->render(), RV_BAD_PASSWORD);
         }
         $login_model->clearLoginAttempts($vals['username']);
         $user_model->setUserRememberCookie($user_id);
         XenForo_Model_Ip::log($user_id, 'user', $user_id, 'login');
         XenForo_Application::get('session')->changeUserId($user_id);
         XenForo_Visitor::setup($user_id);
         $out['username'] = prepare_utf8_string(XenForo_Visitor::getInstance()->get('username'));
         $authenticated = true;
     }
     $out += array('authenticated' => $authenticated, 'v' => $fr_version, 'p' => $fr_platform, 'requires_authentication' => $requires_authentication);
     if ($navbg != '') {
         $out['navbg'] = $navbg;
     }
     if (is_iphone() && $options->forumrunnerAdsAdMobPublisherIDiPhone) {
         $out['admob'] = $options->forumrunnerAdsAdMobPublisherIDiPhone;
     } else {
         if (is_android() && $options->forumrunnerAdsAdMobPublisherIDAndroid) {
             $out['admob'] = $options->forumrunnerAdsAdMobPublisherIDAndroid;
         }
     }
     if ($options->forumrunnerGoogleAnalyticsID && $options->forumrunnerGoogleAnalyticsID != '') {
         $out['gan'] = $options->forumrunnerGoogleAnalyticsID;
     }
     if ($options->forumrunnerFacebookApplicationID && $options->forumrunnerFacebookApplicationID != '') {
         $out['fb'] = $options->forumrunnerFacebookApplicationID;
     }
     if ($options->forumrunnerRegistration) {
         $out['reg'] = true;
     }
     fr_update_push_user($vals['fr_username'], $vals['fr_b'], $vals['token']);
     return $out;
 }
Example #29
0
 public function login($user, $remember = false)
 {
     $userModel = XenForo_Model::create('XenForo_Model_User');
     // Set cookie if needed
     if ($remember) {
         $userModel->setUserRememberCookie($user);
     }
     // Log IP
     XenForo_Model_Ip::log($user, 'user', $user, 'login');
     // delete current session
     $userModel->deleteSessionActivity(0, $_SERVER['REMOTE_ADDR']);
     $this->getSession()->changeUserId($user);
     $this->getVisitor()->setup($user);
     return $user;
 }
Example #30
0
 /**
  * Upates the IP data.
  */
 protected function _updateIpData()
 {
     if (!empty($this->_extraData['ipAddress'])) {
         $ipAddress = $this->_extraData['ipAddress'];
     } else {
         $ipAddress = null;
     }
     $ipId = XenForo_Model_Ip::log($this->get('user_id'), $this->getContentType(), $this->getDiscussionMessageId(), 'insert', $ipAddress);
     $this->set('ip_id', $ipId, '', array('setAfterPreSave' => true));
     // TODO: ideally, this can be consolidated with other post-save message updates (see associateAttachments)
     $this->_db->update($this->getDiscussionMessageTableName(), array('ip_id' => $ipId), $this->getDiscussionMessageKeyName() . ' = ' . $this->_db->quote($this->getDiscussionMessageId()));
 }