/**
  * Processes the registration form
  *
  * @access	public
  * @return	void
  */
 public function registerProcessForm()
 {
     $form_errors = array();
     $coppa = $this->request['coppa_user'] == 1 ? 1 : 0;
     $in_password = trim($this->request['PassWord']);
     $in_email = strtolower(trim($this->request['EmailAddress']));
     $_SFS_FOUND = FALSE;
     /* Check */
     if ($this->settings['no_reg'] == 1) {
         $this->registry->output->showError('registration_disabled', 2016, true);
     }
     /* Custom profile field stuff */
     require_once IPS_ROOT_PATH . 'sources/classes/customfields/profileFields.php';
     $custom_fields = new customProfileFields();
     $custom_fields->initData('edit');
     $custom_fields->parseToSave($this->request, 'register');
     /* Check */
     if ($custom_fields->error_messages) {
         $form_errors['general'] = $custom_fields->error_messages;
     }
     /* Check the email address */
     if (!$in_email or strlen($in_email) < 6 or !IPSText::checkEmailAddress($in_email)) {
         $form_errors['email'][$this->lang->words['err_invalid_email']] = $this->lang->words['err_invalid_email'];
     }
     if (trim($this->request['PassWord_Check']) != $in_password) {
         $form_errors['password'][$this->lang->words['passwords_not_match']] = $this->lang->words['passwords_not_match'];
     }
     /* Test email address */
     $this->request['EmailAddress_two'] = strtolower(trim($this->request['EmailAddress_two']));
     $this->request['EmailAddress'] = strtolower(trim($this->request['EmailAddress']));
     if (!IPSText::checkEmailAddress($this->request['EmailAddress_two'])) {
         $form_errors['email'][$this->lang->words['reg_error_email_invalid']] = $this->lang->words['reg_error_email_invalid'];
     } else {
         if ($in_email and $this->request['EmailAddress_two'] != $in_email) {
             $form_errors['email'][$this->lang->words['reg_error_email_nm']] = $this->lang->words['reg_error_email_nm'];
         }
     }
     /* Need username? */
     $uses_name = false;
     foreach ($this->cache->getCache('login_methods') as $method) {
         if ($method['login_user_id'] == 'username') {
             $uses_name = true;
         }
     }
     if (!$uses_name) {
         $_REQUEST['UserName'] = $_REQUEST['members_display_name'];
         $this->request['UserName'] = $this->request['members_display_name'];
     }
     /* Check the username */
     $user_check = IPSMember::getFunction()->cleanAndCheckName($this->request['UserName'], array(), 'name');
     if ($this->settings['auth_allow_dnames']) {
         $disp_check = IPSMember::getFunction()->cleanAndCheckName($this->request['members_display_name'], array(), 'members_display_name');
     }
     if (is_array($user_check['errors']) && count($user_check['errors'])) {
         foreach ($user_check['errors'] as $key => $error) {
             $form_errors[$key][] = $error;
         }
     }
     if ($this->settings['auth_allow_dnames'] and is_array($disp_check['errors']) && count($disp_check['errors'])) {
         foreach ($disp_check['errors'] as $key => $error) {
             $form_errors[$key][] = $error;
         }
     }
     /* CHECK 1: Any errors (missing fields, etc)? */
     if (count($form_errors)) {
         $this->registerForm($form_errors);
         return;
     }
     /* Is this email addy taken? */
     if (IPSMember::checkByEmail($in_email) == TRUE) {
         $form_errors['email'][$this->lang->words['reg_error_email_taken']] = $this->lang->words['reg_error_email_taken'];
     }
     /* Load handler... */
     require_once IPS_ROOT_PATH . 'sources/handlers/han_login.php';
     $this->han_login = new han_login($this->registry);
     $this->han_login->init();
     $this->han_login->emailExistsCheck($in_email);
     if ($this->han_login->return_code and $this->han_login->return_code != 'METHOD_NOT_DEFINED' and $this->han_login->return_code != 'EMAIL_NOT_IN_USE') {
         $form_errors['email'][$this->lang->words['reg_error_email_taken']] = $this->lang->words['reg_error_email_taken'];
     }
     /* Are they banned [EMAIL]? */
     if (IPSMember::isBanned('email', $in_email) === TRUE) {
         $form_errors['email'][$this->lang->words['reg_error_email_ban']] = $this->lang->words['reg_error_email_ban'];
     }
     /* Check the CAPTCHA */
     if ($this->settings['bot_antispam']) {
         if ($this->registry->getClass('class_captcha')->validate() !== TRUE) {
             $form_errors['general'][$this->lang->words['err_reg_code']] = $this->lang->words['err_reg_code'];
         }
     }
     /* Check the Q and A */
     if ($this->settings['registration_qanda']) {
         $qanda = intval($this->request['qanda_id']);
         $pass = false;
         if ($qanda) {
             $data = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'question_and_answer', 'where' => 'qa_id=' . $qanda));
             if ($data['qa_id']) {
                 $answers = explode("\n", str_replace("\r", "", $data['qa_answers']));
                 if (count($answers)) {
                     foreach ($answers as $answer) {
                         if (strtolower($answer) == strtolower($this->request['qa_answer'])) {
                             $pass = true;
                             break;
                         }
                     }
                 }
             }
         } else {
             //-----------------------------------------
             // Do we have any questions?
             //-----------------------------------------
             $data = $this->DB->buildAndFetch(array('select' => 'COUNT(*) as questions', 'from' => 'question_and_answer'));
             if (!$data['questions']) {
                 $pass = true;
             }
         }
         if (!$pass) {
             $form_errors['general'][$this->lang->words['err_q_and_a']] = $this->lang->words['err_q_and_a'];
         }
     }
     /* CHECK 2: Any errors ? */
     if (count($form_errors)) {
         $this->registerForm($form_errors);
         return;
     }
     /* Build up the hashes */
     $mem_group = $this->settings['member_group'];
     /* Are we asking the member or admin to preview? */
     if ($this->settings['reg_auth_type']) {
         $mem_group = $this->settings['auth_group'];
     } else {
         if ($coppa == 1) {
             $mem_group = $this->settings['auth_group'];
         }
     }
     /* Create member */
     $member = array('name' => $this->request['UserName'], 'password' => $in_password, 'members_display_name' => $this->settings['auth_allow_dnames'] ? $this->request['members_display_name'] : $this->request['UserName'], 'email' => $in_email, 'member_group_id' => $mem_group, 'joined' => time(), 'ip_address' => $this->member->ip_address, 'time_offset' => $this->request['time_offset'], 'coppa_user' => $coppa, 'members_auto_dst' => intval($this->request['dst']), 'allow_admin_mails' => intval($this->request['allow_admin_mail']), 'hide_email' => $this->request['allow_member_mail'] ? 0 : 1);
     /* Spam Service */
     $spamCode = 0;
     if ($this->settings['spam_service_enabled'] && $this->settings['spam_service_api_key']) {
         /* Query the service */
         $spamCode = IPSMember::querySpamService($in_email);
         /* Action to perform */
         $action = $this->settings['spam_service_action_' . $spamCode];
         /* Perform Action */
         switch ($action) {
             /* Proceed with registraction */
             case 1:
                 break;
                 /* Flag for admin approval */
             /* Flag for admin approval */
             case 2:
                 $member['member_group_id'] = $this->settings['auth_group'];
                 $this->settings['reg_auth_type'] = 'admin';
                 break;
                 /* Approve the account, but ban it */
             /* Approve the account, but ban it */
             case 3:
                 $member['member_banned'] = 1;
                 $member['member_group_id'] = $this->settings['banned_group'];
                 $this->settings['reg_auth_type'] = '';
                 break;
         }
     }
     //-----------------------------------------
     // Create the account
     //-----------------------------------------
     $member = IPSMember::create(array('members' => $member, 'pfields_content' => $this->request));
     //-----------------------------------------
     // Login handler create account callback
     //-----------------------------------------
     $this->han_login->createAccount(array('email' => $member['email'], 'joined' => $member['joined'], 'password' => $in_password, 'ip_address' => $this->member->ip_address, 'username' => $member['members_display_name']));
     //-----------------------------------------
     // We'll just ignore if this fails - it shouldn't hold up IPB anyways
     //-----------------------------------------
     /*if ( $han_login->return_code AND ( $han_login->return_code != 'METHOD_NOT_DEFINED' AND $han_login->return_code != 'SUCCESS' ) )
     		{
     			$this->registry->output->showError( 'han_login_create_failed', 2017, true );
     		}*/
     //-----------------------------------------
     // Validation
     //-----------------------------------------
     $validate_key = md5(IPSLib::makePassword() . time());
     $time = time();
     if ($coppa != 1) {
         if ($this->settings['reg_auth_type'] == 'user' or $this->settings['reg_auth_type'] == 'admin' or $this->settings['reg_auth_type'] == 'admin_user') {
             //-----------------------------------------
             // We want to validate all reg's via email,
             // after email verificiation has taken place,
             // we restore their previous group and remove the validate_key
             //-----------------------------------------
             $this->DB->insert('validating', array('vid' => $validate_key, 'member_id' => $member['member_id'], 'real_group' => $this->settings['member_group'], 'temp_group' => $this->settings['auth_group'], 'entry_date' => $time, 'coppa_user' => $coppa, 'new_reg' => 1, 'ip_address' => $member['ip_address']));
             if ($this->settings['reg_auth_type'] == 'user' or $this->settings['reg_auth_type'] == 'admin_user') {
                 IPSText::getTextClass('email')->getTemplate("reg_validate");
                 IPSText::getTextClass('email')->buildMessage(array('THE_LINK' => $this->settings['base_url'] . "app=core&module=global&section=register&do=auto_validate&uid=" . urlencode($member['member_id']) . "&aid=" . urlencode($validate_key), 'NAME' => $member['members_display_name'], 'MAN_LINK' => $this->settings['base_url'] . "app=core&module=global&section=register&do=05", 'EMAIL' => $member['email'], 'ID' => $member['member_id'], 'CODE' => $validate_key));
                 IPSText::getTextClass('email')->subject = $this->lang->words['new_registration_email'] . $this->settings['board_name'];
                 IPSText::getTextClass('email')->to = $member['email'];
                 IPSText::getTextClass('email')->sendMail();
                 $this->output = $this->registry->output->getTemplate('register')->showAuthorize($member);
             } else {
                 if ($this->settings['reg_auth_type'] == 'admin') {
                     $this->output = $this->registry->output->getTemplate('register')->showPreview($member);
                 }
             }
             if ($this->settings['new_reg_notify']) {
                 $date = $this->registry->class_localization->getDate(time(), 'LONG', 1);
                 IPSText::getTextClass('email')->getTemplate('admin_newuser');
                 IPSText::getTextClass('email')->buildMessage(array('DATE' => $date, 'MEMBER_NAME' => $member['members_display_name']));
                 IPSText::getTextClass('email')->subject = $this->lang->words['new_registration_email1'] . $this->settings['board_name'];
                 IPSText::getTextClass('email')->to = $this->settings['email_in'];
                 IPSText::getTextClass('email')->sendMail();
             }
             $this->registry->output->setTitle($this->lang->words['reg_success']);
             $this->registry->output->addNavigation($this->lang->words['nav_reg'], '');
         } else {
             /* We don't want to preview, or get them to validate via email. */
             $stat_cache = $this->caches['stats'];
             if ($member['members_display_name'] and $member['member_id']) {
                 $stat_cache['last_mem_name'] = $member['members_display_name'];
                 $stat_cache['last_mem_id'] = $member['member_id'];
             }
             $stat_cache['mem_count'] += 1;
             $this->cache->setCache('stats', $stat_cache, array('array' => 1, 'deletefirst' => 0));
             if ($this->settings['new_reg_notify']) {
                 $date = $this->registry->class_localization->getDate(time(), 'LONG', 1);
                 IPSText::getTextClass('email')->getTemplate('admin_newuser');
                 IPSText::getTextClass('email')->buildMessage(array('DATE' => $date, 'MEMBER_NAME' => $member['members_display_name']));
                 IPSText::getTextClass('email')->subject = $this->lang->words['new_registration_email1'] . $this->settings['board_name'];
                 IPSText::getTextClass('email')->to = $this->settings['email_in'];
                 IPSText::getTextClass('email')->sendMail();
             }
             IPSCookie::set('pass_hash', $member['member_login_key'], 1);
             IPSCookie::set('member_id', $member['member_id'], 1);
             //-----------------------------------------
             // Fix up session
             //-----------------------------------------
             $privacy = $this->request['Privacy'] ? 1 : 0;
             if ($member['g_hide_online_list']) {
                 $privacy = 1;
             }
             $this->member->sessionClass()->convertGuestToMember(array('member_name' => $member['members_display_name'], 'member_id' => $member['member_id'], 'member_group' => $member['member_group_id'], 'login_type' => $privacy));
             $this->registry->output->silentRedirect($this->settings['base_url'] . '&app=core&module=global&section=login&do=autologin&fromreg=1');
         }
     } else {
         /* This is a COPPA user, so lets tell them they registered OK and redirect to the form. */
         $this->DB->insert('validating', array('vid' => $validate_key, 'member_id' => $member['member_id'], 'real_group' => $this->settings['member_group'], 'temp_group' => $this->settings['auth_group'], 'entry_date' => $time, 'coppa_user' => $coppa, 'new_reg' => 1, 'ip_address' => $member['ip_address']));
         $this->registry->output->redirectScreen($this->lang->words['cp_success'], $this->settings['base_url'] . 'app=core&amp;module=global&amp;section=register&amp;do=12');
     }
 }
 /**
  * Completes the connection
  *
  * @access	public
  * @return	redirect
  */
 public function finishLogin()
 {
     /* From reg flag */
     if ($_REQUEST['code']) {
         /* Load oAuth */
         require_once IPS_KERNEL_PATH . 'facebook/facebookoauth.php';
         /*noLibHook*/
         $this->_oauth = new FacebookOAuth(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, FACEBOOK_CALLBACK, $this->extendedPerms);
         /* Load API */
         require_once IPS_KERNEL_PATH . 'facebook/facebook.php';
         /*noLibHook*/
         $this->_api = new Facebook(array('appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_APP_SECRET, 'cookie' => true));
         /* Ensure URL is correct */
         $_urlExtra = '';
         if ($_REQUEST['key']) {
             $_urlExtra .= '&key=' . $_REQUEST['key'];
         }
         if ($_REQUEST['_reg']) {
             $_urlExtra .= '&_reg=1';
         }
         /* Update callback url */
         $this->_oauth->setCallBackUrl(FACEBOOK_CALLBACK . $_urlExtra);
         /* Generate oAuth token */
         $rToken = $this->_oauth->getAccessToken($_REQUEST['code']);
         if (is_string($rToken)) {
             try {
                 $_userData = $this->_api->api('me', array('access_token' => $rToken));
             } catch (Exception $e) {
                 /* Try re-authorising */
                 if (stristr($e->getMessage(), 'invalid')) {
                     $this->redirectToConnectPage();
                 }
             }
             /* A little gymnastics */
             $this->_userData = $_userData;
             $_userData = $this->fetchUserData($rToken);
             /* Got a member linked already? */
             $_member = IPSMember::load($_userData['id'], 'all', 'fb_uid');
             /* Not connected, check email address */
             if (!$_member['member_id'] and $_userData['email']) {
                 $_member = IPSMember::load($_userData['email'], 'all', 'email');
                 /* We do have an existing account, so trash email forcing user to sign up with new */
                 if ($_member['member_id']) {
                     /* Update row */
                     IPSMember::save($_member['member_id'], array('core' => array('fb_uid' => $_userData['id'], 'fb_token' => $rToken)));
                 }
             }
             if ($_member['member_id']) {
                 $memberData = $_member;
                 /* Ensure user's row is up to date */
                 IPSMember::save($memberData['member_id'], array('core' => array('fb_token' => $rToken)));
                 /* Here, so log us in!! */
                 /* changed by denchu 26/12/12 */
                 $r = $this->_login()->loginWithoutCheckingCredentials($memberData['member_id'], TRUE);
                 if (is_array($r)) {
                     if (isset($r[1])) {
                         $this->registry->getClass('output')->redirectScreen($r[0], $r[1]);
                         $this->registry->getClass('output')->silentRedirect($r[1]);
                     } else {
                         $this->registry->getClass('output')->silentRedirect($r[0]);
                     }
                 } elseif (!$r) {
                     throw new Exception('LINKED_MEMBER_LOGIN_FAIL');
                 } else {
                     $this->registry->getClass('output')->silentRedirect($this->settings['base_url']);
                 }
             } else {
                 /* No? Create a new member */
                 foreach (array('fbc_s_pic', 'fbc_s_status', 'fbc_s_aboutme') as $field) {
                     $toSave[$field] = 1;
                 }
                 $fb_bwoptions = IPSBWOptions::freeze($toSave, 'facebook');
                 $safeFBName = IPS_DOC_CHAR_SET != 'UTF-8' ? IPSText::utf8ToEntities($_userData['name']) : $_userData['name'];
                 /* Make sure usernames are safe */
                 if ($this->settings['username_characters']) {
                     $check_against = preg_quote($this->settings['username_characters'], "/");
                     $check_against = str_replace('\\-', '-', $check_against);
                     $safeFBName = preg_replace('/[^' . $check_against . ']+/i', '', $safeFBName);
                 }
                 /* Check ban filters? */
                 if (IPSMember::isBanned('email', $_userData['email']) or IPSMember::isBanned('name', $safeFBName)) {
                     $this->registry->output->showError('you_are_banned', 1090003);
                 }
                 $displayName = $this->settings['fb_realname'] == 'enforced' ? $safeFBName : '';
                 /* From reg, so create new account properly */
                 $toSave = array('core' => array('name' => IPSText::parseCleanValue($safeFBName), 'members_display_name' => IPSText::parseCleanValue($displayName), 'members_created_remote' => 1, 'member_group_id' => $this->settings['fbc_mgid'] ? $this->settings['fbc_mgid'] : $this->settings['member_group'], 'email' => $_userData['email'], 'fb_uid' => $_userData['id'], 'time_offset' => $_userData['timezone'], 'members_auto_dst' => 1, 'fb_token' => $rToken), 'extendedProfile' => array('pp_about_me' => IPSText::getTextClass('bbcode')->stripBadWords(IPSText::convertCharsets($_userData['about'], 'utf-8', IPS_DOC_CHAR_SET)), 'fb_bwoptions' => $fb_bwoptions));
                 $memberData = IPSMember::create($toSave, FALSE, FALSE, TRUE);
                 if (!$memberData['member_id']) {
                     throw new Exception('CREATION_FAIL');
                 }
                 /* Sync up photo */
                 $this->syncMember($memberData['member_id']);
                 $pmember = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'members_partial', 'where' => "partial_member_id=" . $memberData['member_id']));
                 if ($pmember['partial_member_id']) {
                     $this->registry->getClass('output')->silentRedirect($this->settings['base_url'] . 'app=core&module=global&section=register&do=complete_login&mid=' . $memberData['member_id'] . '&key=' . $pmember['partial_date']);
                 } else {
                     /* Already got a display name */
                     if ($displayName) {
                         /* Here, so log us in!! */
                         $r = $this->_login()->loginWithoutCheckingCredentials($memberData['member_id'], TRUE);
                         IPSLib::runMemberSync('onCompleteAccount', $memberData);
                         if ($this->settings['new_reg_notify']) {
                             $this->registry->class_localization->loadLanguageFile(array('public_register'), 'core');
                             IPSText::getTextClass('email')->setPlainTextTemplate(IPSText::getTextClass('email')->getTemplate("admin_newuser"));
                             IPSText::getTextClass('email')->buildMessage(array('DATE' => $this->registry->getClass('class_localization')->getDate(time(), 'LONG', 1), 'LOG_IN_NAME' => $safeFBName, 'EMAIL' => $_userData['email'], 'IP' => $this->member->ip_address, 'DISPLAY_NAME' => $displayName));
                             IPSText::getTextClass('email')->subject = sprintf($this->lang->words['new_registration_email'], $this->settings['board_name']);
                             IPSText::getTextClass('email')->to = $this->settings['email_in'];
                             IPSText::getTextClass('email')->sendMail();
                         }
                         if (is_array($r)) {
                             if (isset($r[1])) {
                                 $this->registry->getClass('output')->redirectScreen($r[0], $r[1]);
                                 $this->registry->getClass('output')->silentRedirect($r[1]);
                             } else {
                                 $this->registry->getClass('output')->silentRedirect($r[0]);
                             }
                         } elseif (!$r) {
                             throw new Exception('LINKED_MEMBER_LOGIN_FAIL');
                         } else {
                             $this->registry->getClass('output')->silentRedirect($this->settings['base_url']);
                         }
                     } else {
                         throw new Exception('CREATION_FAIL');
                     }
                 }
             }
         } else {
             throw new Exception('CREATION_FAIL');
         }
     } else {
         /* Need to re-auth */
     }
 }
Exemple #3
0
 /**
  * Show the login form
  *
  * @param	string		Message to show on login form
  * @return	string		Login form HTML
  */
 public function loginForm($message = "", $replacement = '')
 {
     //-----------------------------------------
     // INIT
     //-----------------------------------------
     $extra_form = "";
     $show_form = 1;
     $template = '';
     $serviceClick = trim($this->request['serviceClick']);
     //-----------------------------------------
     // Are they banned?
     //-----------------------------------------
     if (IPSMember::isBanned('ip', $this->member->ip_address)) {
         $this->registry->getClass('output')->showError('you_are_banned', 2011, null, null, 403);
     }
     if ($message != "") {
         if ($replacement) {
             $message = sprintf($this->lang->words[$message], $replacement);
         } else {
             $message = $this->lang->words[$message];
         }
         $name = $this->request['UserName'] ? $this->request['UserName'] : $this->request['address'];
         $message = str_replace("<#NAME#>", "<b>" . $name . "</b>", $message);
         $template .= $this->registry->getClass('output')->getTemplate('login')->errors($message);
     }
     //-----------------------------------------
     // Using an alternate log in form?
     //-----------------------------------------
     $this->han_login->checkLoginUrlRedirect();
     /* Did we click a service? */
     if ($serviceClick) {
         switch ($serviceClick) {
             case 'facebook':
                 $this->registry->getClass('output')->silentRedirect($this->settings['_original_base_url'] . "/interface/facebook/index.php?_reg=1");
                 break;
             case 'twitter':
                 $this->registry->getClass('output')->silentRedirect($this->settings['_original_base_url'] . "/interface/twitter/index.php?_reg=1");
                 break;
         }
     }
     //-----------------------------------------
     // Extra  HTML?
     //-----------------------------------------
     $additionalForm = $this->han_login->additionalFormHTML();
     if (count($additionalForm[1])) {
         if ($additionalForm[0] == 'add') {
             $extra_form = $additionalForm[1];
             $show_form = 1;
         } else {
             if (is_array($additionalForm[1])) {
                 foreach ($additionalForm[1] as $_form) {
                     $template .= $_form;
                 }
             } else {
                 $template .= $additionalForm[1];
             }
             $show_form = 0;
         }
     }
     //-----------------------------------------
     // Continue...
     //-----------------------------------------
     if ($show_form) {
         if ($this->request['referer']) {
             $http_referrer = $this->request['referer'];
         } else {
             /* @link	http://community.invisionpower.com/tracker/issue-32302-login-redirect-when-activating */
             $_urlPieces = @parse_url($this->settings['board_url']);
             if (strpos(my_getenv('HTTP_REFERER'), $_urlPieces['host'] ? $_urlPieces['host'] : $this->settings['board_url']) !== false) {
                 $http_referrer = my_getenv('HTTP_REFERER');
             } else {
                 $http_referrer = '';
             }
         }
         $login_methods = false;
         $uses_name = false;
         $uses_email = false;
         foreach ($this->cache->getCache('login_methods') as $method) {
             $login_methods[$method['login_folder_name']] = $method['login_folder_name'];
             if ($method['login_user_id'] == 'username' or $method['login_user_id'] == 'either') {
                 $uses_name = true;
             }
             if ($method['login_user_id'] == 'email' or $method['login_user_id'] == 'either') {
                 $uses_email = true;
             }
         }
         if ($uses_name and $uses_email) {
             $this->lang->words['enter_name'] = $this->lang->words['enter_name_and_email'];
         } else {
             if ($uses_email) {
                 $this->lang->words['enter_name'] = $this->lang->words['enter_useremail'];
             } else {
                 $this->lang->words['enter_name'] = $this->lang->words['enter_username'];
             }
         }
         $template .= $this->registry->getClass('output')->getTemplate('login')->showLogInForm($this->lang->words['please_log_in'], htmlentities(urldecode($http_referrer)), $extra_form, $login_methods);
     }
     $this->registry->getClass('output')->addNavigation($this->lang->words['log_in'], '');
     $this->registry->getClass('output')->setTitle($this->lang->words['log_in'] . ' - ' . ipsRegistry::$settings['board_name']);
     $this->registry->getClass('output')->addContent($template);
     $this->registry->getClass('output')->sendOutput();
 }
 /**
  * Processes the registration form
  *
  * @return	@e void
  */
 public function registerProcessForm()
 {
     $this->_resetMember();
     $form_errors = array();
     $coppa = $this->request['coppa_user'] == 1 ? 1 : 0;
     $in_password = trim($this->request['PassWord']);
     $in_email = strtolower(trim($this->request['EmailAddress']));
     /* Did we agree to the t&c? */
     if (!$this->request['agree_tos']) {
         $form_errors['tos'] = array($this->lang->words['must_agree_to_terms']);
     }
     /* Custom profile field stuff */
     $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/customfields/profileFields.php', 'customProfileFields');
     $custom_fields = new $classToLoad();
     $custom_fields->initData('edit');
     $custom_fields->parseToSave($_POST, 'register');
     /* Check */
     if ($custom_fields->error_messages) {
         $form_errors['general'] = $custom_fields->error_messages;
     }
     /* Check the email address */
     if (!$in_email or strlen($in_email) < 6 or !IPSText::checkEmailAddress($in_email)) {
         $form_errors['email'][$this->lang->words['err_invalid_email']] = $this->lang->words['err_invalid_email'];
     }
     if (trim($this->request['PassWord_Check']) != $in_password or !$in_password) {
         $form_errors['password'][$this->lang->words['passwords_not_match']] = $this->lang->words['passwords_not_match'];
     }
     /*
     There's no reason for this - http://community.invisionpower.com/resources/bugs.html/_/ip-board/registrations-limit-passwords-to-32-characters-for-no-apparent-reason-r37770
     elseif ( strlen( $in_password ) < 3 )
     {
     	$form_errors['password'][$this->lang->words['pass_too_short']] = $this->lang->words['pass_too_short'];
     }
     elseif ( strlen( $in_password ) > 32 )
     {
     	$form_errors['password'][$this->lang->words['pass_too_long']] = $this->lang->words['pass_too_long'];
     }
     */
     /* Check the username */
     $user_check = IPSMember::getFunction()->cleanAndCheckName($this->request['members_display_name'], array(), 'name');
     $disp_check = IPSMember::getFunction()->cleanAndCheckName($this->request['members_display_name'], array(), 'members_display_name');
     if (is_array($user_check['errors']) && count($user_check['errors'])) {
         foreach ($user_check['errors'] as $key => $error) {
             $form_errors['dname'][$error] = isset($this->lang->words[$error]) ? $this->lang->words[$error] : $error;
         }
     }
     /* this duplicates username error above */
     /*if( is_array( $disp_check['errors'] ) && count( $disp_check['errors'] ) )
     		{
     			foreach( $disp_check['errors'] as $key => $error )
     			{
     				$form_errors['dname'][ $error ]	= isset($this->lang->words[ $error ]) ? $this->lang->words[ $error ] : $error;
     			}
     		}*/
     /* Is this email addy taken? */
     if (IPSMember::checkByEmail($in_email) == TRUE) {
         $form_errors['email'][$this->lang->words['reg_error_email_taken']] = $this->lang->words['reg_error_email_taken'];
     }
     /* Load handler... */
     $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/handlers/han_login.php', 'han_login');
     $this->han_login = new $classToLoad($this->registry);
     $this->han_login->init();
     $this->han_login->emailExistsCheck($in_email);
     if ($this->han_login->return_code and $this->han_login->return_code != 'METHOD_NOT_DEFINED' and $this->han_login->return_code != 'EMAIL_NOT_IN_USE') {
         $form_errors['email'][$this->lang->words['reg_error_email_taken']] = $this->lang->words['reg_error_email_taken'];
     }
     /* Are they banned [EMAIL]? */
     if (IPSMember::isBanned('email', $in_email) === TRUE) {
         $form_errors['email'][$this->lang->words['reg_error_email_ban']] = $this->lang->words['reg_error_email_ban'];
     }
     /* Check the CAPTCHA */
     if ($this->settings['bot_antispam_type'] != 'none') {
         if ($this->registry->getClass('class_captcha')->validate() !== TRUE) {
             $form_errors['general'][$this->lang->words['err_reg_code']] = $this->lang->words['err_reg_code'];
         }
     }
     /* Check the Q and A */
     $qanda = intval($this->request['qanda_id']);
     $pass = true;
     if ($qanda) {
         $pass = false;
         $data = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'question_and_answer', 'where' => 'qa_id=' . $qanda));
         if ($data['qa_id']) {
             $answers = explode("\n", str_replace("\r", "", $data['qa_answers']));
             if (count($answers)) {
                 foreach ($answers as $answer) {
                     $answer = trim($answer);
                     if (IPSText::mbstrlen($answer) and mb_strtolower($answer) == mb_strtolower($this->request['qa_answer'])) {
                         $pass = true;
                         break;
                     }
                 }
             }
         }
     } else {
         //-----------------------------------------
         // Do we have any questions?
         //-----------------------------------------
         $data = $this->DB->buildAndFetch(array('select' => 'COUNT(*) as questions', 'from' => 'question_and_answer'));
         if ($data['questions']) {
             $pass = false;
         }
     }
     if (!$pass) {
         $form_errors['general'][$this->lang->words['err_q_and_a']] = $this->lang->words['err_q_and_a'];
     }
     /* CHECK 2: Any errors ? */
     if (count($form_errors)) {
         $this->registerForm($form_errors);
         return;
     }
     /* Build up the hashes */
     $mem_group = $this->settings['member_group'];
     /* Are we asking the member or admin to preview? */
     if ($this->settings['reg_auth_type']) {
         $mem_group = $this->settings['auth_group'];
     } else {
         if ($coppa == 1) {
             $mem_group = $this->settings['auth_group'];
         }
     }
     /* Create member */
     $member = array('name' => $this->request['members_display_name'], 'password' => $in_password, 'members_display_name' => $this->request['members_display_name'], 'email' => $in_email, 'member_group_id' => $mem_group, 'joined' => time(), 'ip_address' => $this->member->ip_address, 'time_offset' => $this->request['time_offset'], 'coppa_user' => $coppa, 'members_auto_dst' => intval($this->settings['time_dst_auto_correction']), 'allow_admin_mails' => intval($this->request['allow_admin_mail']), 'language' => $this->member->language_id);
     /* Spam Service */
     $spamCode = 0;
     $_spamFlag = 0;
     if ($this->settings['spam_service_enabled']) {
         /* Query the service */
         $spamCode = IPSMember::querySpamService($in_email);
         /* Action to perform */
         $action = $this->settings['spam_service_action_' . $spamCode];
         /* Perform Action */
         switch ($action) {
             /* Proceed with registration */
             case 1:
                 break;
                 /* Flag for admin approval */
             /* Flag for admin approval */
             case 2:
                 $member['member_group_id'] = $this->settings['auth_group'];
                 $this->settings['reg_auth_type'] = 'admin';
                 $_spamFlag = 1;
                 break;
                 /* Approve the account, but ban it */
             /* Approve the account, but ban it */
             case 3:
                 $member['member_banned'] = 1;
                 $member['bw_is_spammer'] = 1;
                 $this->settings['reg_auth_type'] = '';
                 break;
                 /* Deny registration */
             /* Deny registration */
             case 4:
                 $this->registry->output->showError('spam_denied_account', '100x001', FALSE, '', 200);
                 break;
         }
     }
     //-----------------------------------------
     // Create the account
     //-----------------------------------------
     $member = IPSMember::create(array('members' => $member, 'pfields_content' => $custom_fields->out_fields), FALSE, FALSE, FALSE);
     //-----------------------------------------
     // Login handler create account callback
     //-----------------------------------------
     $this->han_login->createAccount(array('member_id' => $member['member_id'], 'email' => $member['email'], 'joined' => $member['joined'], 'password' => $in_password, 'ip_address' => $this->member->ip_address, 'username' => $member['members_display_name'], 'name' => $member['name'], 'members_display_name' => $member['members_display_name']));
     //-----------------------------------------
     // We'll just ignore if this fails - it shouldn't hold up IPB anyways
     //-----------------------------------------
     /*if ( $han_login->return_code AND ( $han_login->return_code != 'METHOD_NOT_DEFINED' AND $han_login->return_code != 'SUCCESS' ) )
     		{
     			$this->registry->output->showError( 'han_login_create_failed', 2017, true );
     		}*/
     //-----------------------------------------
     // Validation
     //-----------------------------------------
     $validate_key = md5(IPSMember::makePassword() . time());
     $time = time();
     if ($coppa != 1) {
         if ($this->settings['reg_auth_type'] == 'user' or $this->settings['reg_auth_type'] == 'admin' or $this->settings['reg_auth_type'] == 'admin_user') {
             //-----------------------------------------
             // We want to validate all reg's via email,
             // after email verificiation has taken place,
             // we restore their previous group and remove the validate_key
             //-----------------------------------------
             $this->DB->insert('validating', array('vid' => $validate_key, 'member_id' => $member['member_id'], 'real_group' => $this->settings['member_group'], 'temp_group' => $this->settings['auth_group'], 'entry_date' => $time, 'coppa_user' => $coppa, 'new_reg' => 1, 'ip_address' => $member['ip_address'], 'spam_flag' => $_spamFlag));
             if ($this->settings['reg_auth_type'] == 'user' or $this->settings['reg_auth_type'] == 'admin_user') {
                 /* Send out the email. */
                 $message = array('THE_LINK' => $this->registry->getClass('output')->buildSEOUrl("app=core&module=global&section=register&do=auto_validate&uid=" . urlencode($member['member_id']) . "&aid=" . urlencode($validate_key), 'publicNoSession', 'false'), 'NAME' => $member['members_display_name'], 'MAN_LINK' => $this->registry->getClass('output')->buildSEOUrl("app=core&module=global&section=register&do=05", 'publicNoSession', 'false'), 'EMAIL' => $member['email'], 'ID' => $member['member_id'], 'CODE' => $validate_key);
                 IPSText::getTextClass('email')->setPlainTextTemplate(IPSText::getTextClass('email')->getTemplate("reg_validate", $this->member->language_id));
                 IPSText::getTextClass('email')->buildPlainTextContent($message);
                 IPSText::getTextClass('email')->buildHtmlContent($message);
                 IPSText::getTextClass('email')->subject = sprintf($this->lang->words['new_registration_email'], $this->settings['board_name']);
                 IPSText::getTextClass('email')->to = $member['email'];
                 IPSText::getTextClass('email')->sendMail();
                 $this->output = $this->registry->output->getTemplate('register')->showAuthorize($member);
             } else {
                 if ($this->settings['reg_auth_type'] == 'admin') {
                     $this->output = $this->registry->output->getTemplate('register')->showPreview($member);
                 }
             }
             /* Only send new registration email if the member wasn't banned */
             if ($this->settings['new_reg_notify'] and !$member['member_banned']) {
                 $date = $this->registry->class_localization->getDate(time(), 'LONG', 1);
                 IPSText::getTextClass('email')->getTemplate('admin_newuser');
                 IPSText::getTextClass('email')->buildMessage(array('DATE' => $date, 'LOG_IN_NAME' => $member['name'], 'EMAIL' => $member['email'], 'IP' => $member['ip_address'], 'DISPLAY_NAME' => $member['members_display_name']));
                 IPSText::getTextClass('email')->subject = sprintf($this->lang->words['new_registration_email1'], $this->settings['board_name']);
                 IPSText::getTextClass('email')->to = $this->settings['email_in'];
                 IPSText::getTextClass('email')->sendMail();
             }
             $this->registry->output->setTitle($this->lang->words['reg_success'] . ' - ' . ipsRegistry::$settings['board_name']);
             $this->registry->output->addNavigation($this->lang->words['nav_reg'], '');
         } else {
             /* We don't want to preview, or get them to validate via email. */
             $stat_cache = $this->cache->getCache('stats');
             if ($member['members_display_name'] and $member['member_id'] and !$this->caches['group_cache'][$member['member_group_id']]['g_hide_online_list']) {
                 $stat_cache['last_mem_name'] = $member['members_display_name'];
                 $stat_cache['last_mem_name_seo'] = IPSText::makeSeoTitle($member['members_display_name']);
                 $stat_cache['last_mem_id'] = $member['member_id'];
             }
             $stat_cache['mem_count'] += 1;
             $this->cache->setCache('stats', $stat_cache, array('array' => 1));
             /* Only send new registration email if the member wasn't banned */
             if ($this->settings['new_reg_notify'] and !$member['member_banned']) {
                 $date = $this->registry->class_localization->getDate(time(), 'LONG', 1);
                 IPSText::getTextClass('email')->getTemplate('admin_newuser');
                 IPSText::getTextClass('email')->buildMessage(array('DATE' => $date, 'LOG_IN_NAME' => $member['name'], 'EMAIL' => $member['email'], 'IP' => $member['ip_address'], 'DISPLAY_NAME' => $member['members_display_name']));
                 IPSText::getTextClass('email')->subject = sprintf($this->lang->words['new_registration_email1'], $this->settings['board_name']);
                 IPSText::getTextClass('email')->to = $this->settings['email_in'];
                 IPSText::getTextClass('email')->sendMail();
             }
             IPSCookie::set('pass_hash', $member['member_login_key'], 1);
             IPSCookie::set('member_id', $member['member_id'], 1);
             //-----------------------------------------
             // Fix up session
             //-----------------------------------------
             $privacy = $member['g_hide_online_list'] || empty($this->settings['disable_anonymous']) && !empty($this->request['Privacy']) ? 1 : 0;
             # Update value for onCompleteAccount call
             $member['login_anonymous'] = $privacy . '&1';
             $this->member->sessionClass()->convertGuestToMember(array('member_name' => $member['members_display_name'], 'member_id' => $member['member_id'], 'member_group' => $member['member_group_id'], 'login_type' => $privacy));
             IPSLib::runMemberSync('onCompleteAccount', $member);
             $this->registry->output->silentRedirect($this->settings['base_url'] . '&app=core&module=global&section=login&do=autologin&fromreg=1');
         }
     } else {
         /* This is a COPPA user, so lets tell them they registered OK and redirect to the form. */
         $this->DB->insert('validating', array('vid' => $validate_key, 'member_id' => $member['member_id'], 'real_group' => $this->settings['member_group'], 'temp_group' => $this->settings['auth_group'], 'entry_date' => $time, 'coppa_user' => $coppa, 'new_reg' => 1, 'ip_address' => $member['ip_address']));
         $this->registry->output->redirectScreen($this->lang->words['cp_success'], $this->settings['base_url'] . 'app=core&amp;module=global&amp;section=register&amp;do=12');
     }
 }
 /**
  * Initiate the registry
  *
  * @return	mixed	false or void
  */
 public static function init()
 {
     $INFO = array();
     $_ipsPowerSettings = array();
     if (self::$initiated === TRUE) {
         return FALSE;
     }
     self::$initiated = TRUE;
     /* Load static classes */
     require IPS_ROOT_PATH . "sources/base/core.php";
     /*noLibHook*/
     require IPS_ROOT_PATH . "sources/base/ipsMember.php";
     /*noLibHook*/
     /* Debugging notices? */
     if (defined('IPS_ERROR_CAPTURE') and IPS_ERROR_CAPTURE !== FALSE) {
         @error_reporting(E_ALL | E_NOTICE);
         @set_error_handler("IPSDebug::errorHandler");
     }
     /* Load core variables */
     self::_loadCoreVariables();
     /* Load config file */
     if (is_file(DOC_IPS_ROOT_PATH . 'conf_global.php')) {
         require DOC_IPS_ROOT_PATH . 'conf_global.php';
         /*noLibHook*/
         if (is_array($INFO)) {
             foreach ($INFO as $key => $val) {
                 ipsRegistry::$settings[$key] = str_replace('&#092;', '\\', $val);
             }
         }
     }
     /* Load secret sauce */
     if (is_array($_ipsPowerSettings)) {
         ipsRegistry::$settings = array_merge($_ipsPowerSettings, ipsRegistry::$settings);
     }
     /* Make sure we're installed */
     if (empty($INFO['sql_database'])) {
         /* Quick PHP version check */
         if (!version_compare(MIN_PHP_VERS, PHP_VERSION, '<=')) {
             print "You must be using PHP " . MIN_PHP_VERS . " or better. You are currently using: " . PHP_VERSION;
             exit;
         }
         $host = $_SERVER['HTTP_HOST'] ? $_SERVER['HTTP_HOST'] : @getenv('HTTP_HOST');
         $self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : @getenv('PHP_SELF');
         if (IPS_AREA == 'admin') {
             @header("Location: http://" . $host . rtrim(dirname($self), '/\\') . "/install/index.php");
         } else {
             if (!defined('CP_DIRECTORY')) {
                 define('CP_DIRECTORY', 'admin');
             }
             @header("Location: http://" . $host . rtrim(dirname($self), '/\\') . "/" . CP_DIRECTORY . "/install/index.php");
         }
     }
     /* Switch off dev mode you idjit */
     if (!defined('IN_DEV')) {
         define('IN_DEV', 0);
     }
     /* Shell defined? */
     if (!defined('IPS_IS_SHELL')) {
         define('IPS_IS_SHELL', FALSE);
     }
     /* If this wasn't defined in the gateway file... */
     if (!defined('ALLOW_FURLS')) {
         define('ALLOW_FURLS', ipsRegistry::$settings['use_friendly_urls'] ? TRUE : FALSE);
     }
     if (!defined('IPS_IS_MOBILE_APP')) {
         define('IPS_IS_MOBILE_APP', false);
     }
     /**
      * File and folder permissions
      */
     if (!defined('IPS_FILE_PERMISSION')) {
         define('IPS_FILE_PERMISSION', 0777);
     }
     if (!defined('IPS_FOLDER_PERMISSION')) {
         define('IPS_FOLDER_PERMISSION', 0777);
     }
     /* Set it again incase a gateway turned it off */
     ipsRegistry::$settings['use_friendly_urls'] = ALLOW_FURLS;
     /* Start timer */
     IPSDebug::startTimer();
     /* Cookies... */
     IPSCookie::$sensitive_cookies = array('session_id', 'admin_session_id', 'member_id', 'pass_hash');
     /* INIT DB */
     self::$handles['db'] = ips_DBRegistry::instance();
     /* Set DB */
     self::$handles['db']->setDB(ipsRegistry::$settings['sql_driver']);
     /* Input set up... */
     if (is_array($_POST) and count($_POST)) {
         foreach ($_POST as $key => $value) {
             # Skip post arrays
             if (!is_array($value)) {
                 $_POST[$key] = IPSText::stripslashes($value);
             }
         }
     }
     //-----------------------------------------
     // Clean globals, first.
     //-----------------------------------------
     IPSLib::cleanGlobals($_GET);
     IPSLib::cleanGlobals($_POST);
     IPSLib::cleanGlobals($_COOKIE);
     IPSLib::cleanGlobals($_REQUEST);
     # GET first
     $input = IPSLib::parseIncomingRecursively($_GET, array());
     # Then overwrite with POST
     self::$request = IPSLib::parseIncomingRecursively($_POST, $input);
     # Fix some notices
     if (!isset(self::$request['module'])) {
         self::$request['module'] = '';
     }
     if (!isset(self::$request['section'])) {
         self::$request['section'] = '';
     }
     # Assign request method
     self::$request['request_method'] = strtolower(my_getenv('REQUEST_METHOD'));
     /* Define some constants */
     define('IPS_IS_TASK', (isset(self::$request['module']) and self::$request['module'] == 'task' and self::$request['app'] == 'core') ? TRUE : FALSE);
     define('IPS_IS_AJAX', (isset(self::$request['module']) and self::$request['module'] == 'ajax') ? TRUE : FALSE);
     /* First pass of app set up. Needs to be BEFORE caches and member are set up */
     self::_fUrlInit();
     self::_manageIncomingURLs();
     /* _manageIncomingURLs MUST be called first!!! */
     self::_setUpAppData();
     /* Load app / coreVariables.. must be called after app Data */
     self::_loadAppCoreVariables(IPS_APP_COMPONENT);
     /* Must be called after _manageIncomingURLs */
     self::$handles['db']->getDB()->setDebugMode(IPS_SQL_DEBUG_MODE ? isset($_GET['debug']) ? intval($_GET['debug']) : 0 : 0);
     /* Get caches */
     self::$handles['caches'] = ips_CacheRegistry::instance();
     /* Make sure all is well before we proceed */
     try {
         self::instance()->setUpSettings();
     } catch (Exception $e) {
         print file_get_contents(IPS_CACHE_PATH . 'cache/skin_cache/settingsEmpty.html');
         exit;
     }
     /* Reset database log file paths to cache path */
     self::$handles['db']->resetLogPaths();
     /* Just in case they copy a space in the license... */
     ipsRegistry::$settings['ipb_reg_number'] = trim(ipsRegistry::$settings['ipb_reg_number']);
     /* Bah, now let's go over any input cleaning routines that have settings *sighs* */
     self::$request = IPSLib::postParseIncomingRecursively(self::$request);
     /* Set up dummy member class to prevent errors if cache rebuild required */
     self::$handles['member'] = ips_MemberRegistryDummy::instance();
     /* Build module and application caches */
     self::instance()->checkCaches();
     /* Set up app specific redirects. Must be called before member/sessions setup */
     self::_parseAppResets();
     /* Re-assign member */
     unset(self::$handles['member']);
     self::$handles['member'] = ips_MemberRegistry::instance();
     /* Load other classes */
     $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/class_localization.php', 'class_localization');
     self::instance()->setClass('class_localization', new $classToLoad(self::instance()));
     $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/class_public_permissions.php', 'classPublicPermissions');
     self::instance()->setClass('permissions', new $classToLoad(self::instance()));
     /* Must be called before output initiated */
     self::getAppClass(IPS_APP_COMPONENT);
     if (IPS_AREA == 'admin') {
         require_once IPS_ROOT_PATH . 'sources/classes/output/publicOutput.php';
         /*noLibHook*/
         $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/output/adminOutput.php', 'adminOutput');
         self::instance()->setClass('output', new $classToLoad(self::instance()));
         $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . "sources/classes/class_admin_functions.php", 'adminFunctions');
         self::instance()->setClass('adminFunctions', new $classToLoad(self::instance()));
         $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/class_permissions.php', 'class_permissions');
         self::instance()->setClass('class_permissions', new $classToLoad(self::instance()));
         /* Do stuff that needs both adminFunctions and output initiated */
         self::instance()->getClass('adminFunctions')->postOutputInit();
     } else {
         $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/output/publicOutput.php', 'output');
         self::instance()->setClass('output', new $classToLoad(self::instance(), TRUE));
         register_shutdown_function(array('ipsRegistry', '__myDestruct'));
     }
     /* Post member processing */
     self::$handles['member']->postOutput();
     /* Add SEO templates to the output system */
     self::instance()->getClass('output')->seoTemplates = self::$_seoTemplates;
     //-----------------------------------------
     // Sort out report center early, so counts
     // and cache is right
     //-----------------------------------------
     $memberData =& self::$handles['member']->fetchMemberData();
     $memberData['showReportCenter'] = false;
     $member_group_ids = array($memberData['member_group_id']);
     $member_group_ids = array_diff(array_merge($member_group_ids, explode(',', $memberData['mgroup_others'])), array(''));
     $report_center = array_diff(explode(',', ipsRegistry::$settings['report_mod_group_access']), array(''));
     foreach ($report_center as $groupId) {
         if (in_array($groupId, $member_group_ids)) {
             $memberData['showReportCenter'] = true;
             break;
         }
     }
     if ($memberData['showReportCenter']) {
         $memberData['access_report_center'] = true;
         $memberCache = $memberData['_cache'];
         $reportsCache = self::$handles['caches']->getCache('report_cache');
         if (!$memberCache['report_last_updated'] || $memberCache['report_last_updated'] < $reportsCache['last_updated']) {
             $classToLoad = IPSLib::loadLibrary(IPSLib::getAppDir('core') . '/sources/classes/reportLibrary.php', 'reportLibrary');
             $reports = new $classToLoad(ipsRegistry::instance());
             $totalReports = $reports->rebuildMemberCacheArray();
             $memberCache['report_num'] = $totalReports;
             $memberData['_cache'] = $memberCache;
         }
     }
     /* More set up */
     self::_finalizeAppData();
     /* Finish fURL stuffs */
     self::_fUrlComplete();
     self::instance()->getClass('class_localization')->loadLanguageFile(array('public_global'), 'core');
     if (IPS_AREA == 'admin') {
         $validationStatus = self::member()->sessionClass()->getStatus();
         $validationMessage = self::member()->sessionClass()->getMessage();
         if (ipsRegistry::$request['module'] != 'login' and !$validationStatus) {
             //-----------------------------------------
             // Force log in
             //-----------------------------------------
             if (ipsRegistry::$request['module'] == 'ajax') {
                 @header("Content-type: application/json;charset=" . IPS_DOC_CHAR_SET);
                 print json_encode(array('error' => self::instance()->getClass('class_localization')->words['acp_sessiontimeout'], '__session__expired__log__out__' => 1));
                 exit;
             } elseif (ipsRegistry::$settings['logins_over_https'] && (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] != 'on')) {
                 /* Bug 38301 */
                 ipsRegistry::getClass('output')->silentRedirect(str_replace('http://', 'https://', ipsRegistry::$settings['this_url']));
                 return;
             } else {
                 ipsRegistry::$request['module'] = 'login';
                 ipsRegistry::$request['core'] = 'login';
                 $classToLoad = IPSLib::loadActionOverloader(IPSLib::getAppDir('core') . "/modules_admin/login/manualResolver.php", 'admin_core_login_manualResolver');
                 $runme = new $classToLoad(self::instance());
                 $runme->doExecute(self::instance());
                 exit;
             }
         }
     } else {
         if (IPS_AREA == 'public') {
             /* Set up member */
             self::$handles['member']->finalizePublicMember();
             /* Proper no cache key <update:1> */
             ipsRegistry::$settings['noCacheKey'] = md5('$Rev: 12261 $');
             /* Are we banned: Via IP Address? */
             if (IPSMember::isBanned('ipAddress', self::$handles['member']->ip_address) === TRUE) {
                 self::instance()->getClass('output')->showError('you_are_banned', 2000, true, null, 403);
             }
             /* Are we banned: By DB */
             if (self::$handles['member']->getProperty('member_banned') == 1 or self::$handles['member']->getProperty('temp_ban')) {
                 /* Don't show this message if we're viewing the warn log */
                 if (ipsRegistry::$request['module'] != 'ajax' or ipsRegistry::$request['section'] != 'warnings') {
                     self::getClass('class_localization')->loadLanguageFile('public_error', 'core');
                     $message = '';
                     if (self::$handles['member']->getProperty('member_banned')) {
                         $message = self::getClass('class_localization')->words['no_view_board_b'];
                     } else {
                         $ban_arr = IPSMember::processBanEntry(self::$handles['member']->getProperty('temp_ban'));
                         /* No longer banned */
                         if (time() >= $ban_arr['date_end']) {
                             self::DB()->update('members', array('temp_ban' => ''), 'member_id=' . self::$handles['member']->getProperty('member_id'));
                         } else {
                             $message = sprintf(self::getClass('class_localization')->words['account_susp'], self::getClass('class_localization')->getDate($ban_arr['date_end'], 'LONG', 1));
                         }
                     }
                     /* Get anything? */
                     if ($message) {
                         $warn = ipsRegistry::DB()->buildAndFetch(array('select' => '*', 'from' => 'members_warn_logs', 'where' => 'wl_member=' . self::$handles['member']->getProperty('member_id') . ' AND wl_suspend<>0 AND wl_suspend<>-2', 'order' => 'wl_date DESC', 'limit' => 1));
                         if ($warn['wl_id'] and ipsRegistry::$settings['warn_show_own']) {
                             $moredetails = "<a href='javascript:void(0);' onclick='warningPopup( this, {$warn['wl_id']} );'>" . self::getClass('class_localization')->words['warnings_moreinfo'] . "</a>";
                         }
                         self::instance()->getClass('output')->showError("{$message} {$moredetails}", 1001, true, null, 403);
                     }
                 }
             }
             /* Check server load */
             if (ipsRegistry::$settings['load_limit'] > 0) {
                 $server_load = IPSDebug::getServerLoad();
                 if ($server_load) {
                     $loadinfo = explode("-", $server_load);
                     if (count($loadinfo)) {
                         self::$server_load = $loadinfo[0];
                         if (self::$server_load > ipsRegistry::$settings['load_limit']) {
                             self::instance()->getClass('output')->showError('server_too_busy', 2001);
                         }
                     }
                 }
             }
             /* Specific Ajax Check */
             if (IPS_IS_AJAX and ipsRegistry::$request['section'] != 'warnings') {
                 if (self::$handles['member']->getProperty('g_view_board') != 1 || ipsRegistry::$settings['board_offline'] && !self::$handles['member']->getProperty('g_access_offline')) {
                     @header("Content-type: application/json;charset=" . IPS_DOC_CHAR_SET);
                     print json_encode(array('error' => 'no_permission', '__board_offline__' => 1));
                     exit;
                 }
             }
             /* Other public check */
             if (IPB_THIS_SCRIPT == 'public' and IPS_ENFORCE_ACCESS === FALSE and (ipsRegistry::$request['section'] != 'login' and ipsRegistry::$request['section'] != 'lostpass' and IPS_IS_AJAX === FALSE and ipsRegistry::$request['section'] != 'rss' and ipsRegistry::$request['section'] != 'attach' and ipsRegistry::$request['module'] != 'task' and ipsRegistry::$request['section'] != 'captcha')) {
                 //-----------------------------------------
                 // Permission to see the board?
                 //-----------------------------------------
                 if (self::$handles['member']->getProperty('g_view_board') != 1) {
                     self::getClass('output')->showError('no_view_board', 1000, null, null, 403);
                 }
                 //--------------------------------
                 //  Is the board offline?
                 //--------------------------------
                 if (ipsRegistry::$settings['board_offline'] == 1 and !IPS_IS_SHELL) {
                     if (self::$handles['member']->getProperty('g_access_offline') != 1) {
                         ipsRegistry::$settings['no_reg'] = 1;
                         self::getClass('output')->showBoardOffline();
                     }
                 }
                 //-----------------------------------------
                 // Do we have a display name?
                 //-----------------------------------------
                 if (!(ipsRegistry::$request['section'] == 'register' and (ipsRegistry::$request['do'] == 'complete_login' or ipsRegistry::$request['do'] == 'complete_login_do'))) {
                     if (!self::$handles['member']->getProperty('members_display_name')) {
                         $pmember = self::DB()->buildAndFetch(array('select' => '*', 'from' => 'members_partial', 'where' => "partial_member_id=" . self::$handles['member']->getProperty('member_id')));
                         if (!$pmember['partial_member_id']) {
                             $pmember = array('partial_member_id' => self::$handles['member']->getProperty('member_id'), 'partial_date' => time(), 'partial_email_ok' => self::$handles['member']->getProperty('email') == self::$handles['member']->getProperty('name') . '@' . self::$handles['member']->getProperty('joined') ? 0 : 1);
                             self::DB()->insert('members_partial', $pmember);
                             $pmember['partial_id'] = self::DB()->getInsertId();
                         }
                         self::instance()->getClass('output')->silentRedirect(ipsRegistry::$settings['base_url'] . 'app=core&module=global&section=register&do=complete_login&mid=' . self::$handles['member']->getProperty('member_id') . '&key=' . $pmember['partial_date']);
                     }
                 }
                 //--------------------------------
                 //  Is log in enforced?
                 //--------------------------------
                 if (!(defined('IPS_IS_SHELL') && IPS_IS_SHELL === TRUE) && (!IPS_IS_MOBILE_APP && self::$handles['member']->getProperty('member_group_id') == ipsRegistry::$settings['guest_group'] and ipsRegistry::$settings['force_login'] == 1 && !in_array(ipsRegistry::$request['section'], array('register', 'privacy', 'unsubscribe')))) {
                     if (ipsRegistry::$settings['logins_over_https'] and (!$_SERVER['HTTPS'] or $_SERVER['HTTPS'] != 'on')) {
                         //-----------------------------------------
                         // Set referrer
                         //-----------------------------------------
                         if (!my_getenv('HTTP_REFERER') or stripos(my_getenv('HTTP_REFERER'), ipsRegistry::$settings['board_url']) === false) {
                             $http_referrer = (strtolower($_SERVER['HTTPS']) == 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                         } else {
                             $http_referrer = my_getenv('HTTP_REFERER');
                         }
                         self::instance()->getClass('output')->silentRedirect(str_replace('http://', 'https://', ipsRegistry::$settings['base_url']) . 'app=core&module=global&section=login&referer=' . urlencode($http_referrer));
                     }
                     ipsRegistry::$request['app'] = 'core';
                     ipsRegistry::$request['module'] = 'login';
                     ipsRegistry::$request['core'] = 'login';
                     ipsRegistry::$request['referer'] = ipsRegistry::$request['referer'] ? ipsRegistry::$request['referer'] : (strtolower($_SERVER['HTTPS']) == 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                     if (is_file(DOC_IPS_ROOT_PATH . '/' . PUBLIC_DIRECTORY . '/style_css/' . ipsRegistry::getClass('output')->skin['_csscacheid'] . '/ipb_login_register.css')) {
                         ipsRegistry::getClass('output')->addToDocumentHead('importcss', ipsRegistry::$settings['css_base_url'] . 'style_css/' . ipsRegistry::getClass('output')->skin['_csscacheid'] . '/ipb_login_register.css');
                     }
                     $classToLoad = IPSLib::loadActionOverloader(IPSLib::getAppDir('core') . "/modules_public/global/login.php", 'public_core_global_login');
                     $runme = new $classToLoad(self::instance());
                     $runme->doExecute(self::instance());
                     exit;
                 }
             }
             /* Have we entered an incorrect FURL that has no match? */
             if (ipsRegistry::$settings['use_friendly_urls'] and self::$_noFurlMatch === true) {
                 self::getClass('output')->showError('incorrect_furl', 404, null, null, 404);
             } else {
                 if (isset(ipsRegistry::$request['act']) and ipsRegistry::$request['act'] == 'rssout') {
                     self::getClass('output')->showError('incorrect_furl', 404, null, null, 404);
                 }
             }
             /* Track search engine visits */
             if (!IPS_IS_TASK and $_SERVER['HTTP_REFERER']) {
                 seoTracker::track($_SERVER['HTTP_REFERER'], self::$settings['query_string_real'], self::$handles['member']->getProperty('member_id'));
             }
         }
     }
     IPSDebug::setMemoryDebugFlag("Registry initialized");
 }
 /**
  * Show the login form
  *
  * @access	public
  * @param	string		Message to show on login form
  * @return	string		Login form HTML
  */
 public function loginForm($message = "", $replacement = '')
 {
     //-----------------------------------------
     // INIT
     //-----------------------------------------
     $extra_form = "";
     $show_form = 1;
     $template = '';
     //-----------------------------------------
     // Are they banned?
     //-----------------------------------------
     if (IPSMember::isBanned('ip', $this->member->ip_address)) {
         $this->registry->getClass('output')->showError('you_are_banned', 2011);
     }
     if ($message != "") {
         if ($replacement) {
             $message = sprintf($this->lang->words[$message], $replacement);
         } else {
             $message = $this->lang->words[$message];
         }
         $name = $this->request['UserName'] ? $this->request['UserName'] : $this->request['address'];
         $message = str_replace("<#NAME#>", "<b>" . $name . "</b>", $message);
         $template .= $this->registry->getClass('output')->getTemplate('login')->errors($message);
     }
     //-----------------------------------------
     // Using an alternate log in form?
     //-----------------------------------------
     $this->han_login->checkLoginUrlRedirect();
     //-----------------------------------------
     // Extra  HTML?
     //-----------------------------------------
     $additionalForm = $this->han_login->additionalFormHTML();
     if (count($additionalForm[1])) {
         if ($additionalForm[0] == 'add') {
             $extra_form = $additionalForm[1];
             $show_form = 1;
         } else {
             $template .= $additionalForm[1];
             $show_form = 0;
         }
     }
     //-----------------------------------------
     // Continue...
     //-----------------------------------------
     if ($show_form) {
         if ($this->request['referer']) {
             $http_referrer = $this->request['referer'];
         } else {
             if (!my_getenv('HTTP_REFERER') or stripos(my_getenv('HTTP_REFERER'), $this->settings['board_url']) === false) {
                 // HTTP_REFERER isn't set when force_login is enabled
                 // This method will piece together the base url, and the querystring arguments
                 // This is not anymore secure/insecure than IPB, as IPB will have to process
                 // those arguments whether force_login is enabled or not.
                 $argv = is_array(my_getenv('argv')) && count(my_getenv('argv')) > 0 ? my_getenv('argv') : array();
                 $http_referrer = $this->settings['base_url'] . @implode("&amp;", $argv);
             } else {
                 $http_referrer = my_getenv('HTTP_REFERER');
             }
         }
         $facebookOpts = array();
         $login_methods = false;
         $uses_name = false;
         $uses_email = false;
         foreach ($this->cache->getCache('login_methods') as $method) {
             $login_methods[$method['login_folder_name']] = $method['login_folder_name'];
             if ($method['login_user_id'] == 'username') {
                 $uses_name = true;
             }
             if ($method['login_user_id'] == 'email') {
                 $uses_email = true;
             }
         }
         if ($uses_name and $uses_email) {
             $this->lang->words['enter_name'] = $this->lang->words['enter_name_and_email'];
         } else {
             if ($uses_email) {
                 $this->lang->words['enter_name'] = $this->lang->words['enter_useremail'];
             } else {
                 $this->lang->words['enter_name'] = $this->lang->words['enter_username'];
             }
         }
         $template .= $this->registry->getClass('output')->getTemplate('login')->showLogInForm($this->lang->words['please_log_in'], htmlentities(urldecode($http_referrer)), $extra_form, $login_methods, $facebookOpts);
     }
     /* Work around for bug http://bugs.developers.facebook.com/show_bug.cgi?id=3237 */
     if (IPSLib::fbc_enabled()) {
         $this->_facebook->testConnectSession();
     }
     $this->registry->getClass('output')->addNavigation($this->lang->words['log_in'], '');
     $this->registry->getClass('output')->setTitle($this->lang->words['log_in']);
     $this->registry->getClass('output')->addContent($template);
     $this->registry->getClass('output')->sendOutput();
 }
 /**
  * Completes the connection
  *
  * @access	public
  * @return	redirect
  * 
  */
 public function finishLogin()
 {
     /* From reg flag */
     if ($_REQUEST['code']) {
         /* Reset api to ensure user is not logged in */
         $this->resetApi();
         /* Ensure URL is correct */
         $_urlExtra = '';
         if ($_REQUEST['key']) {
             $_urlExtra .= '&key=' . $_REQUEST['key'];
         }
         if ($_REQUEST['reg']) {
             $_urlExtra .= '&reg=1';
         }
         /* Update callback url */
         $this->_api->setVariable('authorize_callback_uri', VKONTAKTE_CALLBACK . $_urlExtra);
         /* Generate oAuth token */
         $rToken = $this->_api->getAccessToken();
         if (is_string($rToken)) {
             try {
                 $oAuthSession = $this->_api->getSession();
                 $r = $this->_api->api('getProfiles', 'GET', array('uids' => $oAuthSession['user_id'], 'fields' => 'uid,first_name,last_name,nickname,photo,photo_medium,photo_big,timezone,sex,nickname,activity'));
                 $_userData = array_pop($r['response']);
             } catch (Exception $e) {
             }
             /* A little gymnastics */
             $this->_userData = $_userData;
             $this->_userData['photo'] = $_userData['photo_big'];
             /* Got a member linked already? */
             $_member = IPSMember::load($_userData['uid'], 'all', 'vk_uid');
             if ($_member['member_id']) {
                 $memberData = $_member;
                 /* Ensure user's row is up to date */
                 IPSMember::save($memberData['member_id'], array('core' => array('vk_token' => $rToken)));
                 /* Here, so log us in!! */
                 /* changed by denchu 26/12/12 */
                 $r = $this->_login()->loginWithoutCheckingCredentials($memberData['member_id'], TRUE);
                 if (is_array($r)) {
                     if (isset($r[1])) {
                         $this->registry->getClass('output')->redirectScreen($r[0], $r[1]);
                         $this->registry->getClass('output')->silentRedirect($r[1]);
                     } else {
                         $this->registry->getClass('output')->silentRedirect($r[0]);
                     }
                 } elseif (!$r) {
                     throw new Exception('LINKED_MEMBER_LOGIN_FAIL');
                 } else {
                     $this->registry->getClass('output')->silentRedirect($this->settings['base_url']);
                 }
             } else {
                 /* No? Create a new member */
                 foreach (array('vc_s_pic', 'vc_s_status') as $field) {
                     $toSave[$field] = 1;
                 }
                 $vk_bwoptions = IPSBWOptions::freeze($toSave, 'vkontakte');
                 $safeName = IPSText::convertCharsets($_userData['first_name'] . ' ' . $_userData['last_name'], 'utf-8', IPS_DOC_CHAR_SET);
                 $displayName = $this->settings['fb_realname'] == 'enforced' ? $safeName : '';
                 //$displayName  = ( ! $this->settings['auth_allow_dnames'] ) ? $safeName : FALSE;
                 /* Make sure usernames are safe */
                 if ($this->settings['username_characters']) {
                     $check_against = preg_quote($this->settings['username_characters'], "/");
                     $check_against = str_replace('\\-', '-', $check_against);
                     $safeName = preg_replace('/[^' . $check_against . ']+/i', '', $safeName);
                 }
                 if (IPSText::mbstrlen($safeName) > $this->settings['max_user_name_length']) {
                     $safeName = mb_substr(IPSText::convertCharsets($_userData['last_name'], 'utf-8', IPS_DOC_CHAR_SET), 0, $this->settings['max_user_name_length'], 'UTF-8');
                 }
                 /* Check ban filters? */
                 if (IPSMember::isBanned('name', $safeName)) {
                     $this->registry->output->showError('you_are_banned', 1090003);
                 }
                 /* From reg, so create new account properly */
                 $toSave = array('core' => array('name' => $safeName, 'members_display_name' => $displayName, 'members_created_remote' => 1, 'member_group_id' => $this->settings['vk_mgid'] ? $this->settings['vk_mgid'] : $this->settings['member_group'], 'email' => '', 'vk_uid' => $_userData['uid'], 'time_offset' => $_userData['timezone'], 'vk_token' => $rToken), 'extendedProfile' => array('vk_bwoptions' => $vk_bwoptions));
                 $memberData = IPSMember::create($toSave, TRUE, FALSE, TRUE);
                 if (!$memberData['member_id']) {
                     throw new Exception('CREATION_FAIL');
                 }
                 /* Sync up photo */
                 $this->syncMember($memberData['member_id']);
                 $pmember = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'members_partial', 'where' => "partial_member_id=" . $memberData['member_id']));
                 if ($pmember['partial_member_id']) {
                     $this->registry->getClass('output')->silentRedirect($this->settings['base_url'] . 'app=core&module=global&section=register&do=complete_login&mid=' . $memberData['member_id'] . '&key=' . $pmember['partial_date']);
                 } else {
                     /* Already got a display name */
                     if ($displayName) {
                         /* Here, so log us in!! */
                         /* changed by denchu 26/12/12*/
                         $r = $this->_login()->loginWithoutCheckingCredentials($memberData['member_id'], TRUE);
                         IPSLib::runMemberSync('onCompleteAccount', $memberData);
                         if ($this->settings['new_reg_notify']) {
                             $this->registry->class_localization->loadLanguageFile(array('public_register'), 'core');
                             IPSText::getTextClass('email')->setPlainTextTemplate(IPSText::getTextClass('email')->getTemplate("admin_newuser"));
                             IPSText::getTextClass('email')->buildMessage(array('DATE' => $this->registry->getClass('class_localization')->getDate(time(), 'LONG', 1), 'LOG_IN_NAME' => $safeFBName, 'EMAIL' => $_userData['email'], 'IP' => $this->member->ip_address, 'DISPLAY_NAME' => $displayName));
                             IPSText::getTextClass('email')->subject = sprintf($this->lang->words['new_registration_email'], $this->settings['board_name']);
                             IPSText::getTextClass('email')->to = $this->settings['email_in'];
                             IPSText::getTextClass('email')->sendMail();
                         }
                         if (is_array($r)) {
                             if (isset($r[1])) {
                                 $this->registry->getClass('output')->redirectScreen($r[0], $r[1]);
                                 $this->registry->getClass('output')->silentRedirect($r[1]);
                             } else {
                                 $this->registry->getClass('output')->silentRedirect($r[0]);
                             }
                         } elseif (!$r) {
                             throw new Exception('LINKED_MEMBER_LOGIN_FAIL');
                         } else {
                             $this->registry->getClass('output')->silentRedirect($this->settings['base_url']);
                         }
                     } else {
                         throw new Exception('CREATION_FAIL');
                     }
                 }
             }
         } else {
             throw new Exception('CREATION_FAIL');
         }
     }
 }