/**
  * Save the data to complete the partial member record login/registration
  *
  * @access	private
  * @return	void		[Outputs to screen/redirects]
  */
 private function _completeRegistrationSave()
 {
     //-----------------------------------------
     // INIT
     //-----------------------------------------
     $mid = intval($this->request['mid']);
     $key = intval($this->request['key']);
     $in_email = strtolower(trim($this->request['EmailAddress']));
     $banfilters = array();
     $form_errors = array('dname' => array(), 'email' => array(), 'general' => array());
     $members_display_name = trim($this->request['members_display_name']);
     $poss_session_id = "";
     //-----------------------------------------
     // Get DB row
     //-----------------------------------------
     $reg = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'members_partial', 'where' => "partial_member_id={$mid} AND partial_date={$key}"));
     $tmp_member = IPSMember::load($mid);
     //-----------------------------------------
     // Got it?
     //-----------------------------------------
     if (!$reg['partial_id'] or !$tmp_member['member_id']) {
         $this->registry->output->showError('partial_reg_noid', 10117);
     }
     //-----------------------------------------
     // Load ban filters
     //-----------------------------------------
     $this->DB->build(array('select' => '*', 'from' => 'banfilters'));
     $this->DB->execute();
     while ($r = $this->DB->fetch()) {
         $banfilters[$r['ban_type']][] = $r['ban_content'];
     }
     //-----------------------------------------
     // 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;
     }
     //-----------------------------------------
     // Remove 'sneaky' spaces
     //-----------------------------------------
     if ($this->settings['strip_space_chr']) {
         $members_display_name = IPSText::removeControlCharacters($members_display_name);
     }
     //-----------------------------------------
     // Testing email addresses?
     //-----------------------------------------
     if (!$reg['partial_email_ok']) {
         //-----------------------------------------
         // Check the email address
         //-----------------------------------------
         if (!IPSText::checkEmailAddress($in_email)) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_nm'];
         }
         //-----------------------------------------
         // Test email address
         //-----------------------------------------
         $this->request['EmailAddress_two'] = strtolower(trim($this->request['EmailAddress_two']));
         if ($this->request['EmailAddress_two'] != $in_email) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_nm'];
         }
         //-----------------------------------------
         // Are they banned [EMAIL]?
         //-----------------------------------------
         if (is_array($banfilters['email']) and count($banfilters['email'])) {
             foreach ($banfilters['email'] as $email) {
                 $email = str_replace('\\*', '.*', preg_quote($email, "/"));
                 if (preg_match("/^{$email}\$/i", $in_email)) {
                     $form_errors['email'][] = $this->lang->words['reg_error_email_taken'];
                     break;
                 }
             }
         }
         /* Is this email addy taken? */
         if (IPSMember::checkByEmail($in_email) == TRUE) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_taken'];
         }
         //-----------------------------------------
         // Load handler...
         //-----------------------------------------
         require_once IPS_ROOT_PATH . 'sources/handlers/han_login.php';
         $han_login = new han_login($this->registry);
         $han_login->init();
         if ($han_login->emailExistsCheck(trim(strtolower($member['email'])), trim(strtolower($in_email)))) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_taken'];
         }
     }
     if ($this->settings['auth_allow_dnames']) {
         /* Check the username */
         $user_check = IPSMember::getFunction()->cleanAndCheckName($members_display_name, $tmp_member, 'members_display_name');
         if (is_array($user_check['errors']) && count($user_check['errors'])) {
             $form_errors['dname'] = array_merge($form_errors['dname'], $user_check['errors']);
         }
     }
     //-----------------------------------------
     // CHECK 1: Any errors (duplicate names, etc)?
     //-----------------------------------------
     if (count($form_errors)) {
         $errorMessages = array();
         foreach ($form_errors as $errorCat => $errorMessage) {
             foreach ($errorMessage as $error) {
                 $errorMessages['general'][] = $error;
             }
         }
         if (count($errorMessages)) {
             $this->_completeRegistration($errorMessages);
             return;
         }
     }
     //-----------------------------------------
     // Update: Members
     //-----------------------------------------
     $members_display_name = $this->settings['auth_allow_dnames'] ? $members_display_name : $tmp_member['name'];
     if (!$reg['partial_email_ok']) {
         IPSMember::save($mid, array('members' => array('email' => $in_email, 'members_display_name' => $members_display_name, 'name' => $tmp_member['name'] ? $tmp_member['name'] : $members_display_name, 'members_l_username' => $tmp_member['members_l_username'] ? $tmp_member['members_l_username'] : $members_display_name, 'members_l_display_name' => strtolower($members_display_name))));
     } else {
         IPSMember::save($mid, array('members' => array('members_display_name' => $members_display_name, 'name' => $tmp_member['name'] ? $tmp_member['name'] : $members_display_name, 'members_l_username' => $tmp_member['members_l_username'] ? $tmp_member['members_l_username'] : $members_display_name, 'members_l_display_name' => strtolower($members_display_name))));
     }
     //-----------------------------------------
     // Delete: Partials row
     //-----------------------------------------
     $this->DB->delete('members_partial', 'partial_member_id=' . $mid);
     //-----------------------------------------
     //  Update: Profile fields
     //-----------------------------------------
     $this->DB->force_data_type = array();
     foreach ($custom_fields->out_fields as $_field => $_data) {
         $this->DB->force_data_type[$_field] = 'string';
     }
     if (is_array($custom_fields->out_fields) and count($custom_fields->out_fields)) {
         $this->DB->update('pfields_content', $custom_fields->out_fields, 'member_id=' . $mid);
     }
     //-----------------------------------------
     // Send out admin email
     //-----------------------------------------
     if ($this->settings['new_reg_notify']) {
         $date = $this->registry->getClass('class_localization')->getDate(time(), 'LONG', 1);
         IPSText::getTextClass('email')->getTemplate("admin_newuser");
         IPSText::getTextClass('email')->buildMessage(array('DATE' => $date, 'MEMBER_NAME' => $members_display_name));
         IPSText::getTextClass('email')->subject = $this->lang->words['new_registration_email'] . $this->settings['board_name'];
         IPSText::getTextClass('email')->to = $this->settings['email_in'];
         IPSText::getTextClass('email')->sendMail();
     }
     //-----------------------------------------
     // Set cookies
     //-----------------------------------------
     IPSCookie::set("member_id", $mid, 1);
     IPSCookie::set("pass_hash", $tmp_member['member_login_key'], 1);
     //-----------------------------------------
     // Fix up session
     //-----------------------------------------
     $privacy = $this->request['Privacy'] ? 1 : 0;
     if ($this->caches['group_cache'][$tmp_member['member_group_id']]['g_hide_online_list']) {
         $privacy = 1;
     }
     $this->member->sessionClass()->convertGuestToMember(array('member_name' => $members_display_name, 'member_id' => $mid, 'member_group' => $tmp_member['member_group_id'], 'login_type' => $privacy));
     //-----------------------------------------
     // Update Stats
     //-----------------------------------------
     $cache = $this->cache->getCache('stats');
     if ($members_display_name and $mid) {
         $cache['last_mem_name'] = $members_display_name;
         $cache['last_mem_id'] = $mid;
     }
     $cache['mem_count'] += 1;
     $this->cache->setCache('stats', $cache, array('array' => 1, 'deletefirst' => 0));
     /* Complete account */
     IPSLib::runMemberSync('onCompleteAccount', IPSMember::load($mid));
     //-----------------------------------------
     // Go to the board index
     //-----------------------------------------
     $this->registry->output->redirectScreen($this->lang->words['clogin_done'], $this->settings['base_url']);
 }
 /**
  * Save the data to complete the partial member record login/registration
  *
  * @return	@e void		[Outputs to screen/redirects]
  */
 public function _completeRegistrationSave()
 {
     //-----------------------------------------
     // INIT
     //-----------------------------------------
     $mid = intval($this->request['mid']);
     $key = intval($this->request['key']);
     $form_errors = array('dname' => array(), 'email' => array(), 'general' => array());
     $members_display_name = trim($this->request['members_display_name']);
     $poss_session_id = "";
     $login_user = trim($this->request['login_user']);
     $login_pass = trim($this->request['login_pass']);
     $connectService = trim(strtolower($this->request['connectService']));
     //-----------------------------------------
     // Get DB row
     //-----------------------------------------
     $reg = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'members_partial', 'where' => "partial_member_id={$mid} AND partial_date={$key}"));
     $tmp_member = IPSMember::load($mid);
     //-----------------------------------------
     // Got it?
     //-----------------------------------------
     if (!$reg['partial_id'] or !$tmp_member['member_id']) {
         $this->registry->output->showError('partial_reg_noid', 10117);
     }
     //-----------------------------------------
     // Set up email
     //-----------------------------------------
     $in_email = $this->request['EmailAddress'] ? strtolower(trim($this->request['EmailAddress'])) : $tmp_member['email'];
     //-----------------------------------------
     // Load log in handler...
     //-----------------------------------------
     $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/handlers/han_login.php', 'han_login');
     $han_login = new $classToLoad($this->registry);
     $han_login->init();
     //-----------------------------------------
     // 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($this->request, 'register');
     /* Check */
     if ($custom_fields->error_messages) {
         $form_errors['general'] = $custom_fields->error_messages;
     }
     /* Check the website url field */
     $website_field = $custom_fields->getFieldIDByKey('website');
     if ($website_field && $custom_fields->out_fields['field_' . $website_field]) {
         if (stristr($custom_fields->out_fields['field_' . $website_field], 'http://') === FALSE && stristr($custom_fields->out_fields['field_' . $website_field], 'https://') === FALSE) {
             $custom_fields->out_fields['field_' . $website_field] = 'http://' . $custom_fields->out_fields['field_' . $website_field];
         }
     }
     /* Are we trying to connect to an existing account */
     if ($connectService and $login_user and $login_pass and ($this->settings['fb_realname'] == 'enforced' or !$members_display_name)) {
         /* Load Full Member */
         $member = IPSMember::load($mid, 'all');
         /* Force email check */
         $han_login->setForceEmailCheck(TRUE);
         /* Now attempt to authorize member */
         $return = $han_login->loginPasswordCheck($login_user, $login_user, $login_pass);
         if ($return !== TRUE) {
             /* Wrong email/password */
             $form_errors['serviceLogIn'][] = $this->lang->words['connect_incorrect_details'];
         } else {
             /* Fetch data returned based on email address */
             $logInMember = $han_login->member_data;
             /* We're A-OK so allow service module to clean up member accounts, then log us the heck in! */
             if ($connectService == 'facebook' and $member['fb_uid']) {
                 /* Already FBd? */
                 if ($logInMember['fb_uid'] and $member['fb_uid'] != $logInMember['fb_uid']) {
                     /* User already has facebook link */
                     $form_errors['serviceLogIn'][] = sprintf($this->lang->words['connect_already_linked'], $login_user, ucfirst($connectService));
                 }
                 $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/facebook/connect.php', 'facebook_connect');
                 $facebook = new $classToLoad($this->registry, $member['fb_token'], $member['fb_uid']);
                 if ($facebook->finishNewConnection($logInMember['member_id'], $member['member_id']) !== true) {
                     /* Unknown error */
                     $form_errors['serviceLogIn'][] = $this->lang->words['connect_unknown'];
                 }
             } else {
                 if ($connectService == 'twitter' and $member['twitter_id']) {
                     /* Already Twitterd? */
                     if ($logInMember['twitter_id'] and $member['twitter_id'] != $logInMember['twitter_id']) {
                         /* User already has facebook link */
                         $form_errors['serviceLogIn'][] = sprintf($this->lang->words['connect_already_linked'], $login_user, ucfirst($connectService));
                     }
                     $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/twitter/connect.php', 'twitter_connect');
                     $twitter = new $classToLoad($this->registry, $member['twitter_token'], $member['twitter_secret']);
                     if ($twitter->finishNewConnection($logInMember['member_id'], $member['member_id']) !== true) {
                         /* Unknown error */
                         $form_errors['serviceLogIn'][] = $this->lang->words['connect_unknown'];
                     }
                 } else {
                     if ($connectService == 'vkontakte' and $member['vk_uid']) {
                         /* Already VKd? */
                         if ($logInMember['vk_uid'] and $member['vk_uid'] != $logInMember['vk_uid']) {
                             /* User already has vkontakte link */
                             $form_errors['serviceLogIn'][] = sprintf($this->lang->words['connect_already_linked'], $login_user, ucfirst($connectService));
                         }
                         $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/vkontakte/connect.php', 'vkontakte_connect');
                         $vk = new $classToLoad($this->registry, $key);
                         if ($vk->finishNewConnection($logInMember['member_id'], $member['member_id']) !== true) {
                             /* Unknown error */
                             $form_errors['serviceLogIn'][] = $this->lang->words['connect_unknown'];
                         }
                     }
                 }
             }
             /* Ok to proceed? */
             if (!count($form_errors['serviceLogIn'])) {
                 IPSMember::remove($member['member_id']);
                 /* Here, so log us in!! */
                 $r = $han_login->loginWithoutCheckingCredentials($logInMember['member_id'], TRUE);
                 /* Boing */
                 if (is_array($r)) {
                     $this->registry->getClass('output')->silentRedirect($this->settings['base_url'] . 'app=core&module=usercp&section=register&tab=core&area=' . $connectService);
                 }
             }
         }
     }
     //-----------------------------------------
     // Remove 'sneaky' spaces
     //-----------------------------------------
     if ($this->settings['strip_space_chr']) {
         $members_display_name = IPSText::removeControlCharacters($members_display_name);
     }
     //-----------------------------------------
     // Testing email addresses?
     //-----------------------------------------
     if (!$reg['partial_email_ok'] and $in_email) {
         //-----------------------------------------
         // Check the email address
         //-----------------------------------------
         if (!IPSText::checkEmailAddress($in_email)) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_nm'];
         }
         //-----------------------------------------
         // Test email address
         //-----------------------------------------
         $this->request['EmailAddress_two'] = strtolower(trim($this->request['EmailAddress_two']));
         if ($in_email and $this->request['EmailAddress_two'] != $in_email) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_nm'];
         }
         /* Is this email banned or does it exist already? */
         if (IPSMember::isBanned('email', $in_email) || IPSMember::checkByEmail($in_email) || $han_login->emailExistsCheck(trim(strtolower($in_email)))) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_taken'];
         }
     } else {
         if (!$reg['partial_email_ok'] and !$in_email and !$login_user) {
             $form_errors['email'][] = $this->lang->words['reg_error_email_nm'];
         }
     }
     if ($this->settings['auth_allow_dnames']) {
         /* Check the username */
         $user_check = IPSMember::getFunction()->cleanAndCheckName($members_display_name, $tmp_member, 'members_display_name');
         if (is_array($user_check['errors']) && count($user_check['errors'])) {
             $form_errors['dname'][] = isset($this->lang->words[$user_check['errors']['dname']]) ? $this->lang->words[$user_check['errors']['dname']] : $user_check['errors']['dname'];
         }
     }
     //-----------------------------------------
     // CHECK 1: Any errors (duplicate names, etc)?
     //-----------------------------------------
     if (count($form_errors)) {
         $errorMessages = array();
         foreach ($form_errors as $errorCat => $errorMessage) {
             foreach ($errorMessage as $error) {
                 $errorMessages['general'][] = $error;
             }
         }
         if (count($errorMessages)) {
             $this->_completeRegistration($errorMessages);
             return;
         }
     }
     //-----------------------------------------
     // Update: Members
     //-----------------------------------------
     $members_display_name = $this->settings['auth_allow_dnames'] ? $members_display_name : $tmp_member['name'];
     $member_group_id = ($tmp_member['twitter_token'] and $tmp_member['member_group_id'] == $this->settings['auth_group']) ? $this->settings['member_group'] : $tmp_member['member_group_id'];
     if (!$reg['partial_email_ok']) {
         IPSMember::save($mid, array('members' => array('email' => $in_email, 'members_display_name' => $members_display_name, 'members_seo_name' => IPSText::makeSeoTitle($members_display_name), 'name' => $tmp_member['name'] ? $tmp_member['name'] : $members_display_name, 'members_l_username' => $tmp_member['members_l_username'] ? $tmp_member['members_l_username'] : $members_display_name, 'member_group_id' => $member_group_id, 'members_l_display_name' => strtolower($members_display_name))));
     } else {
         IPSMember::save($mid, array('members' => array('members_display_name' => $members_display_name, 'members_seo_name' => IPSText::makeSeoTitle($members_display_name), 'name' => $tmp_member['name'] ? $tmp_member['name'] : $members_display_name, 'members_l_username' => $tmp_member['members_l_username'] ? $tmp_member['members_l_username'] : $members_display_name, 'member_group_id' => $member_group_id, 'members_l_display_name' => mb_strtolower($members_display_name))));
     }
     //-----------------------------------------
     // Delete: Partials row
     //-----------------------------------------
     $this->DB->delete('members_partial', 'partial_member_id=' . $mid);
     //-----------------------------------------
     //  Update: Profile fields
     //-----------------------------------------
     $this->DB->resetDataTypes();
     $this->DB->setDataType(array_keys($custom_fields->out_fields), 'string');
     if (is_array($custom_fields->out_fields) and count($custom_fields->out_fields)) {
         $this->DB->update('pfields_content', $custom_fields->out_fields, 'member_id=' . $mid);
     }
     //-----------------------------------------
     // Pass twitter/facebook via spam service
     //-----------------------------------------
     if ($connectService and !$login_user and $this->settings['spam_service_enabled']) {
         /* Load all member data */
         $member = IPSMember::load($mid, 'all');
         /* Spam Service */
         $spamCode = 0;
         $_spamFlag = 0;
         /* Query the service */
         $spamCode = IPSMember::querySpamService($member['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;
         }
         /* Update member */
         IPSMember::save($member['member_id'], array('core' => array('member_group_id' => $member['member_group_id'], 'member_banned' => intval($member['member_banned']), 'bw_is_spammer' => intval($member['bw_is_spammer']))));
         /* Did we put them in validating? */
         if ($_spamFlag) {
             $validate_key = md5(IPSMember::makePassword() . time());
             $time = time();
             $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' => 0, 'new_reg' => 1, 'ip_address' => $member['ip_address'], 'spam_flag' => $_spamFlag));
             $this->output = $this->registry->output->getTemplate('register')->showPreview($member);
             return;
             #Goes back to doExecute which sends $this->output to output class
         }
     }
     /* Send out notification */
     if ($this->settings['new_reg_notify']) {
         $date = $this->registry->getClass('class_localization')->getDate(time(), 'LONG', 1);
         IPSText::getTextClass('email')->getTemplate("admin_newuser");
         IPSText::getTextClass('email')->buildMessage(array('DATE' => $date, 'LOG_IN_NAME' => $tmp_member['name'] ? $tmp_member['name'] : $members_display_name, 'EMAIL' => $in_email, 'IP' => $tmp_member['ip_address'], 'DISPLAY_NAME' => $members_display_name));
         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();
     }
     //-----------------------------------------
     // Update Stats
     //-----------------------------------------
     $cache = $this->cache->getCache('stats');
     if ($members_display_name and $mid) {
         $cache['last_mem_name'] = $members_display_name;
         $cache['last_mem_name_seo'] = IPSText::makeSeoTitle($members_display_name);
         $cache['last_mem_id'] = $mid;
     }
     $cache['mem_count'] += 1;
     $this->cache->setCache('stats', $cache, array('array' => 1));
     /* Complete account */
     $memberData = IPSMember::load($mid);
     IPSLib::runMemberSync('onCompleteAccount', $memberData);
     /* Got admin validation enabled? */
     if ($connectService && !$login_user && in_array($this->settings['reg_auth_type'], array('admin', 'admin_user'))) {
         /* Make them validating */
         IPSMember::save($member['member_id'], array('core' => array('member_group_id' => $this->settings['auth_group'])));
         //-----------------------------------------
         // 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' => 0, 'new_reg' => 1, 'ip_address' => $member['ip_address'], 'spam_flag' => $_spamFlag));
         $this->output = $this->registry->output->getTemplate('register')->showPreview(IPSMember::load($member['member_id']));
         return;
     }
     //-----------------------------------------
     // Set cookies
     //-----------------------------------------
     IPSCookie::set("member_id", $mid, 1);
     IPSCookie::set("pass_hash", $tmp_member['member_login_key'], 1);
     //-----------------------------------------
     // Fix up session
     //-----------------------------------------
     $privacy = $this->caches['group_cache'][$tmp_member['member_group_id']]['g_hide_online_list'] || empty($this->settings['disable_anonymous']) && !empty($this->request['Privacy']) ? 1 : 0;
     $this->member->sessionClass()->convertGuestToMember(array('member_name' => $members_display_name, 'member_id' => $mid, 'member_group' => $tmp_member['member_group_id'], 'login_type' => $privacy));
     IPSLib::runMemberSync('onLogin', $memberData);
     //-----------------------------------------
     // Go to the board index
     //-----------------------------------------
     $this->registry->output->redirectScreen($this->lang->words['clogin_done'], $this->settings['base_url']);
 }
 /**
  * Clean a username or display name
  *
  * @access	protected
  * @param	string		Name
  * @param	string		Field (name or members_display_name)
  * @return	array		array( 'name' => $cleaned_name, 'errors' => array() )
  */
 protected function _cleanName($name, $field = 'members_display_name')
 {
     $original = $name;
     $name = trim($name);
     if ($field == 'name') {
         // Commented out for bug report #15354
         //$name	= str_replace( '|', '|' , $name );
         /* Remove multiple spaces */
         $name = preg_replace("/\\s{2,}/", " ", $name);
     }
     //-----------------------------------------
     // Remove line breaks
     //-----------------------------------------
     if (ipsRegistry::$settings['usernames_nobr']) {
         $name = IPSText::br2nl($name);
         $name = str_replace("\n", "", $name);
         $name = str_replace("\r", "", $name);
     }
     //-----------------------------------------
     // Remove sneaky spaces
     //-----------------------------------------
     if (ipsRegistry::$settings['strip_space_chr']) {
         /* use hexdec to convert between '0xAD' and chr */
         $name = IPSText::removeControlCharacters($name);
     }
     //-----------------------------------------
     // Trim after above ops
     //-----------------------------------------
     $name = trim($name);
     //-----------------------------------------
     // Test unicode name
     //-----------------------------------------
     $unicode_name = $this->_getUnicodeName($name);
     //-----------------------------------------
     // Do we have a name?
     //-----------------------------------------
     if ($field == 'name' or $field == 'members_display_name' and ipsRegistry::$settings['auth_allow_dnames']) {
         if (!$name or IPSText::mbstrlen($name) < 3 or IPSText::mbstrlen($name) > ipsRegistry::$settings['max_user_name_length']) {
             ipsRegistry::getClass('class_localization')->loadLanguageFile(array('public_register'), 'core');
             $key = $field == 'members_display_name' ? 'reg_error_no_name' : 'reg_error_username_none';
             $text = sprintf(ipsRegistry::getClass('class_localization')->words[$key], ipsRegistry::$settings['max_user_name_length']);
             //-----------------------------------------
             // Only show note about special chars when relevant
             //-----------------------------------------
             if (strpos($name, '&') !== false) {
                 $text .= ipsRegistry::getClass('class_localization')->words['reg_error_no_name_spec'];
             }
             return array('name' => $original, 'errors' => array($text));
         }
     }
     //-----------------------------------------
     // Blocking certain chars in username?
     //-----------------------------------------
     if (ipsRegistry::$settings['username_characters']) {
         $check_against = preg_quote(ipsRegistry::$settings['username_characters'], "/");
         if (!preg_match("/^[" . $check_against . "]+\$/i", $name)) {
             return array('name' => $original, 'errors' => array(str_replace('{chars}', ipsRegistry::$settings['username_characters'], ipsRegistry::$settings['username_errormsg'])));
         }
     }
     //-----------------------------------------
     // Manually check against bad chars
     //-----------------------------------------
     if (strpos($unicode_name, '&#92;') !== false or strpos($unicode_name, '&#quot;') !== false or strpos($unicode_name, '&#036;') !== false or strpos($unicode_name, '&#lt;') !== false or strpos($unicode_name, '$') !== false or strpos($unicode_name, ']') !== false or strpos($unicode_name, '[') !== false or strpos($unicode_name, ',') !== false or strpos($unicode_name, '|') !== false or strpos($unicode_name, '&#gt;') !== false) {
         ipsRegistry::getClass('class_localization')->loadLanguageFile(array('public_register'), 'core');
         return array('name' => $original, 'errors' => array(ipsRegistry::getClass('class_localization')->words['reg_error_chars']));
     }
     return array('name' => $name, 'errors' => array());
 }
 /**
  * Clean _GET _POST value after settings loaded
  *
  * @access	public
  * @param	string		Input
  * @return	string		Cleaned Input
  * @since	2.1
  */
 public static function postParseCleanValue($val)
 {
     if ($val == "") {
         return "";
     }
     /* This looks wrong but it's correct. During FURL set up in registry this function is called before settings are loaded
      * and we want to strip hidden chars in this instance, so.. */
     if (!isset(ipsRegistry::$settings['strip_space_chr']) or ipsRegistry::$settings['strip_space_chr']) {
         $val = IPSText::removeControlCharacters($val);
     }
     return $val;
 }
 /**
  * Edit a post
  *
  * Usage:
  * $post->setForumID(1);
  * $post->setTopicID(5);
  * $post->setPostID(100);
  * $post->setAuthor( $member );
  * 
  * $post->setPostContent( "Hello [b]there![/b]" );
  * # Optional: No bbcode, etc parsing will take place
  * # $post->setPostContentPreFormatted( "Hello <b>there!</b>" );
  * $post->editPost();
  *
  * Exception Error Codes:
  * NO_POSTING_PPD       : No post ID set
  * NO_CONTENT        : No post content set
  * CONTENT_TOO_LONG  : Post is too long
  *
  * @return	mixed
  */
 public function editPost()
 {
     //-----------------------------------------
     // Global checks and functions
     //-----------------------------------------
     try {
         $this->globalSetUp();
     } catch (Exception $error) {
         $e = $error->getMessage();
         if ($e != 'NO_POSTING_PPD') {
             $this->_postErrors = $error->getMessage();
         }
     }
     if ($this->_bypassPermChecks !== TRUE && IPSMember::isOnModQueue($this->getAuthor()) === NULL) {
         $this->_postErrors = 'warnings_restrict_post_perm';
     }
     if (!$this->getPostContent() and !$this->getPostContentPreFormatted()) {
         $this->_postErrors = 'NO_CONTENT';
     }
     //-----------------------------------------
     // Get topic
     //-----------------------------------------
     try {
         $topic = $this->editSetUp();
     } catch (Exception $error) {
         $this->_postErrors = $error->getMessage();
     }
     //-----------------------------------------
     // Parse the post, and check for any errors.
     //-----------------------------------------
     $post = $this->compilePostData();
     //-----------------------------------------
     // Do we have a valid post?
     //-----------------------------------------
     if (strlen(trim(IPSText::removeControlCharacters(IPSText::br2nl($post['post'])))) < 1) {
         $this->_postErrors = 'NO_CONTENT';
     }
     if (IPSText::mbstrlen($post['post']) > $this->settings['max_post_length'] * 1024) {
         $this->_postErrors = 'CONTENT_TOO_LONG';
     }
     if ($this->_postErrors != "") {
         //-----------------------------------------
         // Show the form again
         //-----------------------------------------
         return FALSE;
     }
     //-----------------------------------------
     // Ajax specifics
     //-----------------------------------------
     if ($this->getIsAjax() === TRUE) {
         # Prevent polls from being edited
         $this->can_add_poll = 0;
         # Prevent titles from being edited
         $this->edit_title = 0;
         # Prevent open time from being edited
         $this->can_set_open_time = 0;
         # Prevent close time from being edited
         $this->can_set_close_time = 0;
         # Set Settings
         $this->setSettings(array('enableSignature' => $this->_originalPost['use_sig'] ? 1 : 0, 'enableEmoticons' => $this->_originalPost['use_emo'] ? 1 : 0, 'post_htmlstatus' => $this->getSettings('post_htmlstatus')));
         if (!$this->getAuthor('g_append_edit')) {
             $this->request['add_edit'] = ($this->_originalPost['append_edit'] or !$this->getAuthor('g_append_edit') ? 1 : 0);
         }
     }
     //-----------------------------------------
     // Compile the poll
     //-----------------------------------------
     if ($this->can_add_poll) {
         //-----------------------------------------
         // Load the poll from the DB
         //-----------------------------------------
         $this->poll_data = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'polls', 'where' => "tid=" . intval($topic['tid'])));
         $this->poll_answers = !empty($this->poll_data['choices']) && IPSLib::isSerialized($this->poll_data['choices']) ? IPSLib::safeUnserialize(stripslashes($this->poll_data['choices'])) : array();
     }
     //-----------------------------------------
     // Compile the poll
     //-----------------------------------------
     $this->poll_questions = $this->compilePollData();
     if ($this->_postErrors != "" or $this->getIsPreview() === TRUE) {
         //-----------------------------------------
         // Show the form again
         //-----------------------------------------
         return FALSE;
     }
     /* Got a topics table to update? */
     $updateTopicTable = array();
     //-----------------------------------------
     // Reset some data
     //-----------------------------------------
     $post['ip_address'] = $this->_originalPost['ip_address'];
     $post['topic_id'] = $this->_originalPost['topic_id'];
     $post['author_id'] = $this->_originalPost['author_id'];
     $post['post_date'] = $this->_originalPost['post_date'];
     $post['author_name'] = $this->_originalPost['author_name'];
     $post['queued'] = $this->_originalPost['queued'];
     $post['edit_time'] = $this->getDate() ? $this->getDate() : IPS_UNIX_TIME_NOW;
     $post['edit_name'] = $this->getAuthor('members_display_name');
     if ($this->_originalPost['new_topic'] == 1) {
         /* Tagging */
         if (isset($_POST['ipsTags'])) {
             $this->registry->tags->replace($_POST['ipsTags'], array('meta_id' => $topic['tid'], 'meta_parent_id' => $topic['forum_id'], 'member_id' => $this->memberData['member_id'], 'meta_visible' => $topic['approved']));
         }
         /* Like if not ajax edit */
         if (!IPS_IS_AJAX) {
             $this->addTopicToTracker($topic['tid']);
         }
         //-----------------------------------------
         // Update open and close times
         //-----------------------------------------
         if ($this->can_set_open_time and $this->times['open']) {
             $updateTopicTable['topic_open_time'] = intval($this->times['open']);
             if ($topic['topic_open_time'] and $this->times['open']) {
                 $updateTopicTable['state'] = 'closed';
                 if (IPS_UNIX_TIME_NOW > $topic['topic_open_time']) {
                     if (IPS_UNIX_TIME_NOW < $topic['topic_close_time']) {
                         $updateTopicTable['state'] = 'open';
                     }
                 }
             }
             if (!$this->times['open'] and $topic['topic_open_time']) {
                 if ($topic['state'] == 'closed') {
                     $updateTopicTable['state'] = 'open';
                 }
             }
         } else {
             if ($this->can_set_open_time and $topic['topic_open_time']) {
                 $updateTopicTable['topic_open_time'] = 0;
             }
         }
         if ($this->can_set_close_time and $this->times['close']) {
             $updateTopicTable['topic_close_time'] = intval($this->times['close']);
             //-----------------------------------------
             // Was a close time, but not now?
             //-----------------------------------------
             if (!$this->times['close'] and $topic['topic_close_time']) {
                 if ($topic['state'] == 'closed') {
                     $updateTopicTable['state'] = 'open';
                 }
             }
         } else {
             if ($this->can_set_close_time and $topic['topic_close_time']) {
                 $updateTopicTable['topic_close_time'] = 0;
             }
         }
         if ($this->edit_title) {
             if ($this->getForumID() != $topic['forum_id']) {
                 $updateTopicTable['forum_id'] = $this->getForumID();
             }
         }
     }
     //-----------------------------------------
     // Update poll
     //-----------------------------------------
     if ($this->can_add_poll) {
         if (is_array($this->poll_questions) and count($this->poll_questions)) {
             $poll_only = 0;
             if ($this->settings['ipb_poll_only'] and $this->request['poll_only'] == 1) {
                 $poll_only = 1;
             }
             $poll_view_voters = !$this->poll_data['votes'] ? $this->request['poll_view_voters'] : $this->poll_data['poll_view_voters'];
             if ($topic['poll_state']) {
                 $_pollData = array('votes' => intval($this->poll_total_votes), 'choices' => addslashes(serialize($this->poll_questions)), 'poll_question' => IPSText::stripAttachTag($this->request['poll_question']), 'poll_only' => $poll_only, 'poll_view_voters' => intval($poll_view_voters));
                 /* Data Hook Location */
                 IPSLib::doDataHooks($_pollData, 'editPostUpdatePoll');
                 $this->DB->update('polls', $_pollData, 'tid=' . $topic['tid']);
                 if ($this->poll_data['choices'] != serialize($this->poll_questions) or $this->poll_data['votes'] != intval($this->poll_total_votes)) {
                     $this->DB->insert('moderator_logs', array('forum_id' => $this->getForumData('id'), 'topic_id' => $topic['tid'], 'post_id' => $this->_originalPost['pid'], 'member_id' => $this->getAuthor('member_id'), 'member_name' => $this->getAuthor('members_display_name'), 'ip_address' => $this->ip_address, 'http_referer' => htmlspecialchars(my_getenv('HTTP_REFERER')), 'ctime' => IPS_UNIX_TIME_NOW, 'topic_title' => $topic['title'], 'action' => $this->lang->words['edited_poll'], 'query_string' => htmlspecialchars(my_getenv('QUERY_STRING'))));
                 }
             } else {
                 $_pollData = array('tid' => $topic['tid'], 'forum_id' => $this->getForumData('id'), 'start_date' => IPS_UNIX_TIME_NOW, 'choices' => addslashes(serialize($this->poll_questions)), 'starter_id' => $this->getAuthor('member_id'), 'votes' => 0, 'poll_question' => IPSText::stripAttachTag($this->request['poll_question']), 'poll_only' => $poll_only, 'poll_view_voters' => intval($poll_view_voters));
                 /* Data Hook Location */
                 IPSLib::doDataHooks($_pollData, 'editPostAddPoll');
                 $this->DB->insert('polls', $_pollData);
                 $this->DB->insert('moderator_logs', array('forum_id' => $this->getForumData('id'), 'topic_id' => $topic['tid'], 'post_id' => $this->_originalPost['pid'], 'member_id' => $this->getAuthor('member_id'), 'member_name' => $this->getAuthor('members_display_name'), 'ip_address' => $this->ip_address, 'http_referer' => htmlspecialchars(my_getenv('HTTP_REFERER')), 'ctime' => IPS_UNIX_TIME_NOW, 'topic_title' => $topic['title'], 'action' => sprintf($this->lang->words['added_poll'], $this->request['poll_question']), 'query_string' => htmlspecialchars(my_getenv('QUERY_STRING'))));
                 /* Update topics table later */
                 $updateTopicTable['poll_state'] = 1;
                 $updateTopicTable['last_vote'] = 0;
             }
         } else {
             /* Remove the poll */
             $this->DB->delete('polls', 'tid=' . $topic['tid']);
             $this->DB->delete('voters', 'tid=' . $topic['tid']);
             /* Update topics table later */
             $updateTopicTable['poll_state'] = 0;
             $updateTopicTable['last_vote'] = 0;
         }
     }
     //-----------------------------------------
     // Update topic title?
     //-----------------------------------------
     if ($this->edit_title == 1) {
         //-----------------------------------------
         // Update topic title
         //-----------------------------------------
         if ($this->_topicTitle != "") {
             if ($this->_topicTitle != $topic['title'] or !$topic['title_seo']) {
                 $updateTopicTable['title'] = $this->_topicTitle;
                 $updateTopicTable['title_seo'] = IPSText::makeSeoTitle($this->_topicTitle);
                 $_forumUpdate = array();
                 if ($topic['tid'] == $this->getForumData('last_id')) {
                     $_forumUpdate['last_title'] = $updateTopicTable['title'];
                     $_forumUpdate['seo_last_title'] = $updateTopicTable['title_seo'];
                 }
                 if ($topic['tid'] == $this->getForumData('newest_id')) {
                     $_forumUpdate['newest_title'] = $updateTopicTable['title'];
                 }
                 if (count($_forumUpdate)) {
                     $this->DB->update('forums', $_forumUpdate, 'id=' . $this->getForumData('id'));
                 }
                 if ($this->moderator['edit_topic'] == 1 or $this->getAuthor('g_is_supmod') == 1) {
                     $this->DB->insert('moderator_logs', array('forum_id' => $this->getForumData('id'), 'topic_id' => $topic['tid'], 'post_id' => $this->_originalPost['pid'], 'member_id' => $this->getAuthor('member_id'), 'member_name' => $this->getAuthor('members_display_name'), 'ip_address' => $this->ip_address, 'http_referer' => htmlspecialchars(my_getenv('HTTP_REFERER')), 'ctime' => IPS_UNIX_TIME_NOW, 'topic_title' => $topic['title'], 'action' => sprintf($this->lang->words['edited_topic_title'], $topic['title'], $this->_topicTitle), 'query_string' => htmlspecialchars(my_getenv('QUERY_STRING'))));
                 }
             }
         }
     }
     //-----------------------------------------
     // Reason for edit?
     //-----------------------------------------
     if ($this->_bypassPermChecks or isset($this->moderator['edit_post']) && $this->moderator['edit_post'] or $this->getAuthor('g_is_supmod')) {
         $post['post_edit_reason'] = trim($this->request['post_edit_reason']);
     }
     //-----------------------------------------
     // Update the database (ib_forum_post)
     //-----------------------------------------
     $post['append_edit'] = 1;
     if ($this->_bypassPermChecks or $this->getAuthor('g_append_edit')) {
         if ($this->request['add_edit'] != 1) {
             $post['append_edit'] = 0;
         }
     }
     /* HTML Status */
     $post['post_htmlstate'] = $this->getSettings('post_htmlstatus');
     /* Typecast */
     $this->DB->setDataType('post_edit_reason', 'string');
     /* Data Hook Location */
     IPSLib::doDataHooks($post, 'editPostData');
     $this->DB->update('posts', $post, 'pid=' . $this->_originalPost['pid']);
     /* Got a topic to update? */
     $updateTopicTable['post_data'] = $post;
     $updateTopicTable['forum_data'] = $this->getForumData();
     IPSLib::doDataHooks($updateTopicTable, 'editPostTopicData');
     unset($updateTopicTable['post_data'], $updateTopicTable['forum_data']);
     // Remove added data
     if (count($updateTopicTable)) {
         $this->DB->update('topics', $updateTopicTable, 'tid=' . $topic['tid']);
     }
     /* remove saved content */
     if ($this->memberData['member_id']) {
         $this->editor->removeAutoSavedContent(array('member_id' => $this->memberData['member_id'], 'autoSaveKey' => 'edit-' . intval($this->_originalPost['pid'])));
     }
     /* Add to cache */
     IPSContentCache::update($this->_originalPost['pid'], 'post', $this->formatPostForCache($post['post']));
     /* Upload Attachments */
     $this->uploadAttachments($this->post_key, $this->_originalPost['pid']);
     //-----------------------------------------
     // Make attachments "permanent"
     //-----------------------------------------
     $this->makeAttachmentsPermanent($this->post_key, $this->_originalPost['pid'], 'post', array('topic_id' => $topic['tid']));
     //-----------------------------------------
     // Make sure paperclip symbol is OK
     //-----------------------------------------
     $this->recountTopicAttachments($topic['tid']);
     //-----------------------------------------
     // Leave data for other apps
     //-----------------------------------------
     $this->setTopicData($topic);
     $this->setPostData(array_merge($this->_originalPost, $post));
     return TRUE;
 }
 /**
  * Update a user's login or display name
  *
  * @param	string		Field to update
  * @return	@e void		[Outputs to screen]
  */
 protected function save_member_name($field = 'members_display_name')
 {
     $member_id = intval($this->request['member_id']);
     $member = IPSMember::load($member_id);
     //-----------------------------------------
     // Allowed to edit administrators?
     //-----------------------------------------
     if ($member['g_access_cp'] and !$this->registry->getClass('class_permissions')->checkPermission('member_edit_admin', 'members', 'members')) {
         $this->registry->output->showError($this->lang->words['m_editadmin']);
     }
     if ($field == 'members_display_name') {
         $display_name = $this->request['display_name'];
         $display_name = str_replace("&#43;", "+", $display_name);
     } else {
         $display_name = $this->request['name'];
         $display_name = str_replace("&#43;", "+", $display_name);
         $display_name = str_replace('|', '&#124;', $display_name);
         $display_name = trim(preg_replace("/\\s{2,}/", " ", $display_name));
     }
     if ($this->settings['strip_space_chr']) {
         // use hexdec to convert between '0xAD' and chr
         $display_name = IPSText::removeControlCharacters($display_name);
     }
     if ($field == 'members_display_name' and preg_match("#[\\[\\];,\\|]#", IPSText::UNhtmlspecialchars($display_name))) {
         $this->registry->output->showError($this->lang->words['m_displaynames']);
     }
     try {
         if (IPSMember::getFunction()->updateName($member_id, $display_name, $field, TRUE) === TRUE) {
             if ($field == 'members_display_name') {
                 ipsRegistry::getClass('adminFunctions')->saveAdminLog(sprintf($this->lang->words['m_dnamelog'], $member['members_display_name'], $display_name));
             } else {
                 ipsRegistry::getClass('adminFunctions')->saveAdminLog(sprintf($this->lang->words['m_namelog'], $member['name'], $display_name));
                 //-----------------------------------------
                 // If updating a name, and display names
                 //	disabled, update display name too
                 //-----------------------------------------
                 if (!ipsRegistry::$settings['auth_allow_dnames']) {
                     IPSMember::getFunction()->updateName($member_id, $display_name, 'members_display_name', TRUE);
                 }
                 //-----------------------------------------
                 // I say, did we choose to email 'dis member?
                 //-----------------------------------------
                 if ($this->request['send_email'] == 1) {
                     //-----------------------------------------
                     // By golly, we did!
                     //-----------------------------------------
                     $msg = trim(IPSText::stripslashes(nl2br($_POST['email_contents'])));
                     $msg = str_replace("{old_name}", $member['name'], $msg);
                     $msg = str_replace("{new_name}", $display_name, $msg);
                     $msg = str_replace("<#BOARD_NAME#>", $this->settings['board_name'], $msg);
                     $msg = str_replace("<#BOARD_ADDRESS#>", $this->settings['board_url'] . '/index.' . $this->settings['php_ext'], $msg);
                     IPSText::getTextClass('email')->message = stripslashes(IPSText::getTextClass('email')->cleanMessage($msg));
                     IPSText::getTextClass('email')->subject = $this->lang->words['m_changesubj'];
                     IPSText::getTextClass('email')->to = $member['email'];
                     IPSText::getTextClass('email')->sendMail();
                 }
             }
             $this->cache->rebuildCache('stats', 'global');
         } else {
             # We should absolutely never get here. So this is a fail-safe, really to
             # prevent a "false" positive outcome for the end-user
             $this->registry->output->showError($this->lang->words['m_namealready']);
         }
     } catch (Exception $error) {
         //	$this->returnJsonError( $error->getMessage() );
         switch ($error->getMessage()) {
             case 'NO_USER':
                 $this->registry->output->showError($this->lang->words['m_noid']);
                 break;
             case 'NO_PERMISSION':
             case 'NO_NAME':
                 $this->registry->output->showError(sprintf($this->lang->words['m_morethan3'], $this->settings['max_user_name_length']));
                 break;
             case 'ILLEGAL_CHARS':
                 $this->registry->output->showError($this->lang->words['m_illegal']);
                 break;
             case 'USER_NAME_EXISTS':
                 $this->registry->output->showError($this->lang->words['m_namealready']);
                 break;
             default:
                 $this->registry->output->showError($error->getMessage());
                 break;
         }
     }
     $this->registry->output->global_message = $this->lang->words[$field . '_updated_success'];
     $this->registry->output->silentRedirectWithMessage($this->settings['base_url'] . 'module=members&do=viewmember&member_id=' . $member_id);
 }
 /**
  * Post a reply
  * Very simply posts a reply. Simple.
  *
  * Usage:
  * $post->setFopicID(1);
  * $post->setTopicID(5);
  * $post->setPostID(100);
  * $post->setAuthor( $member );
  * 
  * $post->setPostContent( "Hello [b]there![/b]" );
  * # Optional: No bbcode, etc parsing will take place
  * # $post->setPostContentPreFormatted( "Hello <b>there!</b>" );
  * $post->editPost();
  *
  * Exception Error Codes:
  * NO_TOPIC_ID       : No topic ID set
  * NO_FORUM_ID		: No forum ID set
  * NO_AUTHOR_SET	    : No Author set
  * NO_CONTENT        : No post content set
  * CONTENT_TOO_LONG  : Post is too long
  * NO_SUCH_TOPIC     : No such topic
  * NO_SUCH_FORUM		: No such forum
  * NO_REPLY_PERM     : Author cannot reply to this topic
  * TOPIC_LOCKED		: The topic is locked
  * NO_REPLY_POLL     : Cannot reply to this poll only topic
  * TOPIC_LOCKED		: The topic is locked
  * NO_REPLY_POLL		: This is a poll only topic
  * NO_POST_FORUM		: Unable to post in that forum
  * FORUM_LOCKED		: Forum read only
  *
  * @access	public
  * @return	mixed
  */
 public function editPost()
 {
     //-----------------------------------------
     // Set up
     //-----------------------------------------
     $topic_id = intval($this->getTopicID());
     $forum_id = intval($this->getForumID());
     //-----------------------------------------
     // Global checks and functions
     //-----------------------------------------
     try {
         $this->globalSetUp();
     } catch (Exception $error) {
         $this->_postErrors = $error->getMessage();
     }
     if (!$this->getPostContent() and !$this->getPostContentPreFormatted()) {
         $this->_postErrors = 'NO_CONTENT';
     }
     //-----------------------------------------
     // Get topic
     //-----------------------------------------
     try {
         $topic = $this->editSetUp();
     } catch (Exception $error) {
         $this->_postErrors = $error->getMessage();
     }
     //-----------------------------------------
     // Parse the post, and check for any errors.
     //-----------------------------------------
     $post = $this->compilePostData();
     //-----------------------------------------
     // Do we have a valid post?
     //-----------------------------------------
     if (strlen(trim(IPSText::removeControlCharacters(IPSText::br2nl($post['post'])))) < 1) {
         $this->_postErrors = 'NO_CONTENT';
     }
     if (IPSText::mbstrlen($postContent) > $this->settings['max_post_length'] * 1024) {
         $this->_postErrors = 'CONTENT_TOO_LONG';
     }
     //-----------------------------------------
     // Ajax specifics
     //-----------------------------------------
     if ($this->getIsAjax() === TRUE) {
         # Prevent polls from being edited
         $this->can_add_poll = 0;
         # Prevent titles from being edited
         $this->edit_title = 0;
         # Set Settings
         $this->setSettings(array('enableSignature' => $this->_originalPost['use_sig'] ? 1 : 0, 'enableEmoticons' => $this->_originalPost['use_emo'] ? 1 : 0, 'post_htmlstatus' => intval($this->_originalPost['post_htmlstate'])));
         $this->request['iconid'] = $this->_originalPost['icon_id'];
         if (!$this->getAuthor('g_append_edit')) {
             $this->request['add_edit'] = ($this->_originalPost['append_edit'] or !$this->getAuthor('g_append_edit') ? 1 : 0);
         }
     }
     //-----------------------------------------
     // Compile the poll
     //-----------------------------------------
     if ($this->can_add_poll) {
         //-----------------------------------------
         // Load the poll from the DB
         //-----------------------------------------
         $this->poll_data = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'polls', 'where' => "tid=" . $topic['tid']));
         $this->DB->execute();
         $this->poll_answers = $this->poll_data['choices'] ? unserialize(stripslashes($this->poll_data['choices'])) : array();
     }
     //-----------------------------------------
     // Compile the poll
     //-----------------------------------------
     $this->poll_questions = $this->compilePollData();
     if ($this->_postErrors != "" or $this->getIsPreview() === TRUE) {
         //-----------------------------------------
         // Show the form again
         //-----------------------------------------
         return FALSE;
     }
     //-----------------------------------------
     // Grab the edit time
     //-----------------------------------------
     $time = ipsRegistry::getClass('class_localization')->getDate(time(), 'LONG');
     //-----------------------------------------
     // Reset some data
     //-----------------------------------------
     $post['ip_address'] = $this->_originalPost['ip_address'];
     $post['topic_id'] = $this->_originalPost['topic_id'];
     $post['author_id'] = $this->_originalPost['author_id'];
     $post['post_date'] = $this->_originalPost['post_date'];
     $post['author_name'] = $this->_originalPost['author_name'];
     $post['queued'] = $this->_originalPost['queued'];
     $post['edit_time'] = time();
     $post['edit_name'] = $this->getAuthor('members_display_name');
     //-----------------------------------------
     // If the post icon has changed, update the topic post icon
     //-----------------------------------------
     if ($this->_originalPost['new_topic'] == 1) {
         if ($post['icon_id'] != $this->_originalPost['icon_id']) {
             $this->DB->update('topics', array('icon_id' => $post['icon_id']), 'tid=' . $topic['tid']);
         }
     }
     //-----------------------------------------
     // Update open and close times
     //-----------------------------------------
     if ($this->_originalPost['new_topic'] == 1) {
         $times = array();
         if ($this->can_set_open_time and $this->times['open']) {
             $times['topic_open_time'] = intval($this->times['open']);
             if ($topic['topic_open_time'] and $this->times['open']) {
                 $times['state'] = "closed";
                 if (time() > $topic['topic_open_time']) {
                     if (time() < $topic['topic_close_time']) {
                         $times['state'] = "open";
                     }
                 }
             }
             if (!$this->times['open'] and $topic['topic_open_time']) {
                 if ($topic['state'] == 'closed') {
                     $times['state'] = 'open';
                 }
             }
         }
         if ($this->can_set_close_time and $this->times['close']) {
             $times['topic_close_time'] = intval($this->times['close']);
             //-----------------------------------------
             // Was a close time, but not now?
             //-----------------------------------------
             if (!$this->times['close'] and $topic['topic_close_time']) {
                 if ($topic['state'] == 'closed') {
                     $times['state'] = 'open';
                 }
             }
         }
         if (count($times)) {
             $this->DB->update('topics', $times, "tid=" . $topic['tid']);
         }
     }
     //-----------------------------------------
     // Update poll
     //-----------------------------------------
     if ($this->can_add_poll) {
         if (is_array($this->poll_questions) and count($this->poll_questions)) {
             $poll_only = 0;
             if ($this->settings['ipb_poll_only'] and $this->request['poll_only'] == 1) {
                 $poll_only = 1;
             }
             $poll_view_voters = !$this->poll_data['votes'] ? $this->request['poll_view_voters'] : $this->poll_data['poll_view_voters'];
             if ($topic['poll_state']) {
                 $this->DB->update('polls', array('votes' => intval($this->poll_total_votes), 'choices' => addslashes(serialize($this->poll_questions)), 'poll_question' => IPSText::stripAttachTag($this->request['poll_question']), 'poll_only' => $poll_only, 'poll_view_voters' => intval($poll_view_voters)), 'tid=' . $topic['tid']);
                 if ($this->poll_data['choices'] != serialize($this->poll_questions) or $this->poll_data['votes'] != intval($this->poll_total_votes)) {
                     $this->DB->insert('moderator_logs', array('forum_id' => $this->getForumData('id'), 'topic_id' => $topic['tid'], 'post_id' => $this->_originalPost['pid'], 'member_id' => $this->getAuthor('member_id'), 'member_name' => $this->getAuthor('members_display_name'), 'ip_address' => $this->ip_address, 'http_referer' => my_getenv('HTTP_REFERER'), 'ctime' => time(), 'topic_title' => $topic['title'], 'action' => "Edited poll", 'query_string' => my_getenv('QUERY_STRING')));
                 }
             } else {
                 $this->DB->insert('polls', array('tid' => $topic['tid'], 'forum_id' => $this->getForumData('id'), 'start_date' => time(), 'choices' => addslashes(serialize($this->poll_questions)), 'starter_id' => $this->getAuthor('member_id'), 'votes' => 0, 'poll_question' => IPSText::stripAttachTag($this->request['poll_question']), 'poll_only' => $poll_only, 'poll_view_voters' => intval($poll_view_voters)));
                 $this->DB->insert('moderator_logs', array('forum_id' => $this->getForumData('id'), 'topic_id' => $topic['tid'], 'post_id' => $this->_originalPost['pid'], 'member_id' => $this->getAuthor('member_id'), 'member_name' => $this->getAuthor('members_display_name'), 'ip_address' => $this->ip_address, 'http_referer' => my_getenv('HTTP_REFERER'), 'ctime' => time(), 'topic_title' => $topic['title'], 'action' => "Added a poll to the topic titled '" . $this->request['poll_question'] . "'", 'query_string' => my_getenv('QUERY_STRING')));
                 $this->DB->update('topics', array('poll_state' => 1, 'last_vote' => 0, 'total_votes' => 0), 'tid=' . $topic['tid']);
             }
         } else {
             //-----------------------------------------
             // Remove the poll
             //-----------------------------------------
             $this->DB->buildAndFetch(array('delete' => 'polls', 'where' => "tid=" . $topic['tid']));
             $this->DB->buildAndFetch(array('delete' => 'voters', 'where' => "tid=" . $topic['tid']));
             $this->DB->update('topics', array('poll_state' => 0, 'last_vote' => 0, 'total_votes' => 0), 'tid=' . $topic['tid']);
         }
     }
     //-----------------------------------------
     // Update topic title?
     //-----------------------------------------
     if ($this->edit_title == 1) {
         //-----------------------------------------
         // Update topic title
         //-----------------------------------------
         if ($this->_topicTitle != "") {
             if ($this->_topicTitle != $topic['title'] or $this->_topicDescription != $topic['description'] or !$topic['title_seo']) {
                 $this->DB->update('topics', array('title' => $this->_topicTitle, 'title_seo' => IPSText::makeSeoTitle($this->_topicTitle), 'description' => $this->_topicDescription), "tid=" . $topic['tid']);
                 if ($topic['tid'] == $this->getForumData('last_id')) {
                     $this->DB->update('forums', array('last_title' => $this->_topicTitle), 'id=' . $this->getForumData('id'));
                     //ipsRegistry::getClass('class_forums')->updateForumCache();
                 }
                 if ($this->moderator['edit_topic'] == 1 or $this->getAuthor('g_is_supmod') == 1) {
                     $this->DB->insert('moderator_logs', array('forum_id' => $this->getForumData('id'), 'topic_id' => $topic['tid'], 'post_id' => $this->_originalPost['pid'], 'member_id' => $this->getAuthor('member_id'), 'member_name' => $this->getAuthor('members_display_name'), 'ip_address' => $this->ip_address, 'http_referer' => my_getenv('HTTP_REFERER'), 'ctime' => time(), 'topic_title' => $topic['title'], 'action' => "Edited topic title or description '{$topic['title']}' to '" . $this->_topicTitle . "' via post form", 'query_string' => my_getenv('QUERY_STRING')));
                 }
             }
         }
     }
     //-----------------------------------------
     // Reason for edit?
     //-----------------------------------------
     if ($this->moderator['edit_post'] or $this->getAuthor('g_is_supmod')) {
         $post['post_edit_reason'] = trim($this->request['post_edit_reason']);
     }
     //-----------------------------------------
     // Update the database (ib_forum_post)
     //-----------------------------------------
     $post['append_edit'] = 1;
     if ($this->getAuthor('g_append_edit')) {
         if ($this->request['add_edit'] != 1) {
             $post['append_edit'] = 0;
         }
     }
     $this->DB->force_data_type = array('post_edit_reason' => 'string');
     $this->DB->update('posts', $post, 'pid=' . $this->_originalPost['pid']);
     if ($this->_originalPost['topic_firstpost']) {
         $pid = 0;
         $title = $r['title'];
     } else {
         $pid = serialize(array('pid' => $r['pid'], 'title' => $r['title']));
         $title = '';
     }
     /* Remove from the search index */
     $this->registry->class_forums->removePostFromSearchIndex($post['topic_id'], $this->_originalPost['pid'], $topic['posts'] ? 0 : 1);
     /* Update the search index */
     $topic_title = $this->_topicTitle ? $this->_topicTitle : $topic['title'];
     /* Add to cache */
     IPSContentCache::update($this->_originalPost['pid'], 'post', $this->formatPostForCache($post['post']));
     /* Upload Attachments */
     $this->uploadAttachments($this->post_key, $this->_originalPost['pid']);
     //-----------------------------------------
     // Make attachments "permanent"
     //-----------------------------------------
     $this->makeAttachmentsPermanent($this->post_key, $this->_originalPost['pid'], 'post', array('topic_id' => $topic['tid']));
     //-----------------------------------------
     // Make sure paperclip symbol is OK
     //-----------------------------------------
     $this->recountTopicAttachments($topic['tid']);
     //-----------------------------------------
     // Leave data for other apps
     //-----------------------------------------
     $this->setTopicData($topic);
     $this->setPostData(array_merge($this->_originalPost, $post));
     return TRUE;
 }
 /**
  * Saves the add/edit calendar event form
  *
  * @access	public
  * @param	string	$type	Either add or edit
  * @return	void
  */
 public function calendarEventSave($type = 'add')
 {
     /* INIT */
     $read_perms = '*';
     $end_day = "";
     $end_month = "";
     $end_year = "";
     $end_date = "";
     $event_ranged = 0;
     $event_repeat = 0;
     $can_edit = 0;
     $form_type = $this->request['formtype'];
     $event_id = intval($this->request['event_id']);
     $calendar_id = intval($this->request['calendar_id']);
     $allow_emoticons = $this->request['enableemo'] == 'yes' ? 1 : 0;
     $private_event = $this->request['e_type'] == 'private' ? 1 : 0;
     $event_title = trim($this->request['event_title']);
     $day = intval($this->request['e_day']);
     $month = intval($this->request['e_month']);
     $year = intval($this->request['e_year']);
     $end_day = intval($this->request['end_day']);
     $end_month = intval($this->request['end_month']);
     $end_year = intval($this->request['end_year']);
     $recur_unit = intval($this->request['recur_unit']);
     $event_tz = intval($this->request['event_tz']);
     $offset = 0;
     $event_all_day = 0;
     $event_calendar_id = intval($this->request['event_calendar_id']);
     $set_time = intval($this->request['set_times']);
     $hour_min = array();
     if ($set_time) {
         $hour_min = strstr($this->request['event_timestart'], ":") ? explode(":", $this->request['event_timestart']) : 0;
         if (intval($hour_min[0]) < 0 || intval($hour_min[0]) > 23) {
             $hour_min[0] = 0;
         }
         if (intval($hour_min[1]) < 0 || intval($hour_min[1]) > 59) {
             $hour_min[1] = 0;
         }
         if ($hour_min[0] || $hour_min[1]) {
             $offset = $event_tz * 3600;
         } else {
             $hour_min = array();
             $offset = 0;
         }
     } else {
         $event_all_day = 1;
     }
     $this->settings['max_post_length'] = $this->settings['max_post_length'] ? $this->settings['max_post_length'] : 2140000;
     /* Check Permissions */
     if (!$this->memberData['member_id']) {
         $this->registry->output->showError('calendar_no_guests', 10412);
     }
     $this->calendarBuildPermissions($event_calendar_id);
     if (!$this->can_post) {
         $this->registry->output->showError('calendar_no_post_perm', 10413);
     }
     /* WHATDOWEDO? */
     if ($type == 'add') {
     } else {
         /* Check ID */
         if (!$event_id) {
             $this->registry->output->showError('calendar_event_not_found', 10414);
         }
         /* Get the event */
         $this->DB->build(array('select' => '*', 'from' => 'cal_events', 'where' => "event_id={$event_id}"));
         $this->DB->execute();
         if (!($event = $this->DB->fetch())) {
             $this->registry->output->showError('calendar_event_not_found', 10415);
         }
         /* Do we have permission to edit this event */
         if ($this->memberData['member_id'] == $event['event_member_id']) {
             $can_edit = 1;
         } else {
             if ($this->memberData['g_is_supmod'] == 1) {
                 $can_edit = 1;
             }
         }
         if ($can_edit != 1) {
             $this->registry->output->showError('calendar_no_edit_perm', 10416);
         }
     }
     /* Do we have a valid post? */
     if (strlen(trim(IPSText::removeControlCharacters(IPSText::br2nl($_POST['Post'])))) < 1) {
         $this->registry->output->showError('calendar_post_too_short', 10417);
     }
     /* Check the post length */
     if (IPSText::mbstrlen($_POST['Post']) > $this->settings['max_post_length'] * 1024) {
         $this->registry->output->showError('calendar_post_too_long', 10418);
     }
     /* Fix up the event title */
     if (IPSText::mbstrlen($event_title) < 2 or !$event_title) {
         $this->registry->output->showError('calendar_no_title', 10419);
     }
     if (IPSText::mbstrlen($event_title) > 64) {
         $this->registry->output->showError('calendar_title_too_long', 10420);
     }
     /* Are we an admin, and have we set w/groups can see */
     if ($this->memberData['g_access_cp']) {
         if (is_array($_POST['e_groups'])) {
             foreach ($this->cache->getCache('group_cache') as $gid => $groupCache) {
                 if ($groupCache['g_access_cp']) {
                     $_POST['e_groups'][] = $gid;
                 }
             }
             $read_perms = implode(",", $_POST['e_groups']);
         }
         if ($read_perms == "") {
             $read_perms = '*';
         }
     }
     /* Check dates: Range */
     if ($form_type == 'range') {
         if ($end_year < $year) {
             $this->registry->output->showError('calendar_range_wrong', 10421);
         }
         if ($end_year == $year) {
             if ($end_month < $month) {
                 $this->registry->output->showError('calendar_range_wrong', 10422);
             }
             if ($end_month == $month and $end_day <= $day) {
                 $this->registry->output->showError('calendar_range_wrong', 10423);
             }
         }
         $_final_unix_from = gmmktime(0, 0, 0, $month, $day, $year) + $offset;
         // # Midday
         $_final_unix_to = gmmktime(23, 59, 59, $end_month, $end_day, $end_year) + $offset;
         // # End of the day
         $event_ranged = 1;
         $set_time = 0;
         $hour_min = array();
     } elseif ($form_type == 'recur') {
         if ($this->request['recur_unit']) {
             $event_repeat = 1;
         }
         if ($end_year < $year) {
             $this->registry->output->showError('calendar_range_wrong', 10424);
         }
         if ($end_year == $year) {
             if ($end_month < $month) {
                 $this->registry->output->showError('calendar_range_wrong', 10425);
             }
             if ($end_month == $month and $end_day <= $day) {
                 $this->registry->output->showError('calendar_range_wrong', 10426);
             }
         }
         $hour = 0;
         $min = 0;
         if ($set_time) {
             if (is_array($hour_min)) {
                 $hour = $hour_min[0];
                 $min = $hour_min[1];
             }
         }
         $_final_unix_from = gmmktime($hour, $min, 0, $month, $day, $year) + $offset;
         $_final_unix_to = gmmktime($hour, $min, 0, $end_month, $end_day, $end_year) + $offset;
         # End of the day
         $event_recur = 1;
     } else {
         $hour = 0;
         $min = 0;
         if ($set_time) {
             if (is_array($hour_min)) {
                 $hour = $hour_min[0];
                 $min = $hour_min[1];
             }
         }
         $_final_unix_from = gmmktime($hour, $min, 0, $month, $day, $year) - $offset;
         $_final_unix_to = 0;
     }
     /* Do we have a sensible date? */
     if (!checkdate($month, $day, $year)) {
         $this->registry->output->showError('calendar_invalid_date', 10427);
     }
     /* Post process the editor, now we have safe HTML and bbcode */
     IPSText::getTextClass('bbcode')->parse_html = 0;
     IPSText::getTextClass('bbcode')->parse_smilies = intval($allow_emoticons);
     IPSText::getTextClass('bbcode')->parse_bbcode = 1;
     IPSText::getTextClass('bbcode')->parsing_section = 'calendar';
     $this->request['Post'] = IPSText::getTextClass('editor')->processRawPost('Post');
     $this->request['Post'] = IPSText::getTextClass('bbcode')->preDbParse($this->request['Post']);
     /* Event approved? */
     $event_approved = $this->can_avoid_queue ? 1 : ($this->calendar_cache[$event_calendar_id]['cal_moderate'] ? 0 : 1);
     if ($private_event == 1) {
         $event_approved = 1;
     }
     /* Create new event */
     if ($type == 'add') {
         /* Add it to the DB */
         $this->DB->insert('cal_events', array('event_calendar_id' => $event_calendar_id, 'event_member_id' => $this->memberData['member_id'], 'event_content' => $this->request['Post'], 'event_title' => $event_title, 'event_smilies' => $allow_emoticons, 'event_perms' => $read_perms, 'event_private' => $private_event, 'event_approved' => $event_approved, 'event_unixstamp' => time(), 'event_recurring' => $recur_unit, 'event_tz' => $event_tz, 'event_timeset' => count($hour_min) > 0 ? intval($hour_min[0]) . ":" . intval($hour_min[1]) : 0, 'event_unix_from' => $_final_unix_from, 'event_unix_to' => $_final_unix_to, 'event_all_day' => $event_all_day));
         /* Recache */
         $this->calendarCallRecache();
         /* Bounce */
         if ($event_approved) {
             $this->registry->output->redirectScreen($this->lang->words['new_event_redirect'], $this->settings['base_url'] . "app=calendar&amp;module=calendar&amp;cal_id={$event_calendar_id}");
         } else {
             $this->registry->output->redirectScreen($this->lang->words['new_event_mod'], $this->settings['base_url'] . "app=calendar&amp;module=calendar&amp;cal_id{$event_calendar_id}");
         }
     } else {
         /* Update the database recored */
         $this->DB->update('cal_events', array('event_calendar_id' => $event_calendar_id, 'event_content' => $this->request['Post'], 'event_title' => $event_title, 'event_smilies' => $allow_emoticons, 'event_perms' => $read_perms, 'event_private' => $private_event, 'event_approved' => $event_approved, 'event_unixstamp' => time(), 'event_recurring' => $recur_unit, 'event_tz' => $event_tz, 'event_timeset' => count($hour_min) > 0 ? intval($hour_min[0]) . ":" . intval($hour_min[1]) : 0, 'event_unix_from' => $_final_unix_from, 'event_unix_to' => $_final_unix_to, 'event_all_day' => $event_all_day), 'event_id=' . $event_id);
         /* Recache */
         $this->calendarCallRecache();
         /* Bounce */
         if ($event_approved) {
             $this->registry->output->redirectScreen($this->lang->words['edit_event_redirect'], $this->settings['base_url'] . "app=calendar&amp;module=calendar&amp;cal_id={$event_calendar_id}&amp;do=showevent&amp;event_id={$event_id}");
         } else {
             $this->registry->output->redirectScreen($this->lang->words['new_event_mod'], $this->settings['base_url'] . "app=calendar&amp;module=calendar&amp;cal_id={$event_calendar_id}");
         }
     }
 }
    /**
     * Update a user's login or display name
     *
     * @access	protected
     * @param	string		Field to update
     * @return	void		[Outputs to screen]
     */
    protected function save_member_name($field = 'members_display_name')
    {
        $member_id = intval($this->request['member_id']);
        $member = IPSMember::load($member_id);
        //-----------------------------------------
        // Allowed to edit administrators?
        //-----------------------------------------
        if ($member['g_access_cp'] and !$this->registry->getClass('class_permissions')->checkPermission('member_edit_admin', 'members', 'members')) {
            $this->returnJsonError($this->lang->words['m_editadmin']);
            exit;
        }
        if ($field == 'members_display_name') {
            $display_name = $this->convertAndMakeSafe($_POST['display_name'], 1);
            $display_name = str_replace("&#43;", "+", $display_name);
        } else {
            $display_name = $this->convertAndMakeSafe($_POST['name'], 1);
            $display_name = str_replace("&#43;", "+", $display_name);
            $display_name = str_replace('|', '&#124;', $display_name);
            $display_name = trim(preg_replace("/\\s{2,}/", " ", $display_name));
        }
        if ($this->settings['strip_space_chr']) {
            // use hexdec to convert between '0xAD' and chr
            $display_name = IPSText::removeControlCharacters($display_name);
        }
        if ($field == 'members_display_name' and preg_match("#[\\[\\];,\\|]#", str_replace('&#39;', "'", str_replace('&amp;', '&', $members_display_name)))) {
            $this->returnJsonError($this->lang->words['m_displaynames']);
        }
        try {
            if (IPSMember::getFunction()->updateName($member_id, $display_name, $field) === TRUE) {
                if ($field == 'members_display_name') {
                    ipsRegistry::getClass('adminFunctions')->saveAdminLog(sprintf($this->lang->words['m_dnamelog'], $member['members_display_name'], $display_name));
                } else {
                    ipsRegistry::getClass('adminFunctions')->saveAdminLog(sprintf($this->lang->words['m_namelog'], $member['name'], $display_name));
                    //-----------------------------------------
                    // If updating a name, and display names
                    //	disabled, update display name too
                    //-----------------------------------------
                    if (!ipsRegistry::$settings['auth_allow_dnames']) {
                        IPSMember::getFunction()->updateName($member_id, $display_name, 'members_display_name');
                    }
                    //-----------------------------------------
                    // I say, did we choose to email 'dis member?
                    //-----------------------------------------
                    if ($this->request['send_email'] == 1) {
                        //-----------------------------------------
                        // By golly, we did!
                        //-----------------------------------------
                        $msg = trim(IPSText::stripslashes(nl2br($_POST['email_contents'])));
                        $msg = str_replace("{old_name}", $member['name'], $msg);
                        $msg = str_replace("{new_name}", $display_name, $msg);
                        $msg = str_replace("<#BOARD_NAME#>", $this->settings['board_name'], $msg);
                        $msg = str_replace("<#BOARD_ADDRESS#>", $this->settings['board_url'] . '/index.' . $this->settings['php_ext'], $msg);
                        IPSText::getTextClass('email')->message = stripslashes(IPSText::getTextClass('email')->cleanMessage($msg));
                        IPSText::getTextClass('email')->subject = $this->lang->words['m_changesubj'];
                        IPSText::getTextClass('email')->to = $member['email'];
                        IPSText::getTextClass('email')->sendMail();
                    }
                }
                $this->cache->rebuildCache('stats', 'global');
            } else {
                # We should absolutely never get here. So this is a fail-safe, really to
                # prevent a "false" positive outcome for the end-user
                $this->returnJsonError($this->lang->words['m_namealready']);
            }
        } catch (Exception $error) {
            $this->returnJsonError($error->getMessage());
            switch ($error->getMessage()) {
                case 'NO_USER':
                    $this->returnJsonError($this->lang->words['m_noid']);
                    break;
                case 'NO_PERMISSION':
                case 'NO_NAME':
                    $this->returnJsonError(sprintf($this->lang->words['m_morethan3'], $this->settings['max_user_name_length']));
                    break;
                case 'ILLEGAL_CHARS':
                    $this->returnJsonError($this->lang->words['m_illegal']);
                    break;
                case 'USER_NAME_EXISTS':
                    $this->returnJsonError($this->lang->words['m_namealready']);
                    break;
                default:
                    $this->returnJsonError($error->getMessage());
                    break;
            }
        }
        //-----------------------------------------
        // Load handler...
        //-----------------------------------------
        if ($field == 'name') {
            require_once IPS_ROOT_PATH . 'sources/handlers/han_login.php';
            $han_login = new han_login($this->registry);
            $han_login->init();
            $han_login->changeName($member['name'], $display_name, $member['email']);
        } else {
            IPSLib::runMemberSync('onNameChange', $member_id, $display_name);
        }
        $__display_name = addslashes($display_name);
        $_string = <<<EOF
\t\t{
\t\t\t'success'      : true,
\t\t\t'display_name' : "{$__display_name}"
\t\t}
\t\t
EOF;
        $this->returnString($_string);
    }
Exemple #10
0
 /**
  * Saves the add/edit calendar event form
  *
  * @param	string	$type	Either add or edit
  * @return	@e void
  */
 public function calendarEventSave($type = 'add')
 {
     //-----------------------------------------
     // Check permissions
     //-----------------------------------------
     if ($this->request['auth_key'] != $this->member->form_hash) {
         $this->registry->output->showError('no_permission', 10410, null, null, 403);
     }
     if ($this->request['preview']) {
         return $this->calendarEventForm($type);
     }
     //-----------------------------------------
     // Init
     //-----------------------------------------
     $event_id = intval($this->request['event_id']);
     $calendar_id = intval($this->request['event_calendar_id']);
     $_calendar = $this->functions->getCalendar($calendar_id);
     $event_title = IPSText::getTextClass('bbcode')->stripBadWords(trim($this->request['event_title']));
     $start_date = '';
     $end_date = '';
     $recurring = 0;
     //-----------------------------------------
     // Verify start date/time
     //-----------------------------------------
     switch ($this->settings['cal_date_format']) {
         case 'american':
         default:
             $_startBits = explode('/', $this->request['start_date']);
             if ($this->request['set_enddate']) {
                 $_endBits = $this->request['end_date'] ? explode('/', $this->request['end_date']) : array();
             }
             break;
         case 'danish':
             $_inputStart = explode('/', $this->request['start_date']);
             $_startBits = array(0 => $_inputStart[1], 1 => $_inputStart[2], 2 => $_inputStart[0]);
             if ($this->request['set_enddate']) {
                 $_inputEnd = $this->request['end_date'] ? explode('/', $this->request['end_date']) : array();
                 $_endBits = array(0 => $_inputEnd[1], 1 => $_inputEnd[2], 2 => $_inputEnd[0]);
             }
             break;
         case 'italian':
             $_inputStart = explode('/', $this->request['start_date']);
             $_startBits = array(0 => $_inputStart[1], 1 => $_inputStart[0], 2 => $_inputStart[2]);
             if ($this->request['set_enddate']) {
                 $_inputEnd = $this->request['end_date'] ? explode('/', $this->request['end_date']) : array();
                 $_endBits = array(0 => $_inputEnd[1], 1 => $_inputEnd[0], 2 => $_inputEnd[2]);
             }
             break;
         case 'db':
             $_inputStart = explode('-', $this->request['start_date']);
             $_startBits = array(0 => $_inputStart[1], 1 => $_inputStart[2], 2 => $_inputStart[0]);
             if ($this->request['set_enddate']) {
                 $_inputEnd = $this->request['end_date'] ? explode('-', $this->request['end_date']) : array();
                 $_endBits = array(0 => $_inputEnd[1], 1 => $_inputEnd[2], 2 => $_inputEnd[0]);
             }
             break;
     }
     if (!$this->request['start_date'] or count($_startBits) != 3) {
         $this->registry->output->showError('calendar_invalid_date', 10427.0);
     } else {
         if (!@checkdate($_startBits[0], $_startBits[1], $_startBits[2])) {
             $this->registry->output->showError('calendar_invalid_date', 10427.1);
         }
     }
     if ($this->request['all_day']) {
         $start_date = gmmktime(0, 0, 0, $_startBits[0], $_startBits[1], $_startBits[2]);
     } else {
         $_time = explode(':', $this->request['start_time']);
         if ($this->settings['cal_time_format'] == 'standard') {
             if (count($_time) != 2 or $_time[0] > 12 or $_time[1] > 59) {
                 $this->registry->output->showError('calendar_invalid_time', 10427.2);
             }
             if ($this->request['start_time_ampm'] == 'PM' and $_time[0] < 12) {
                 $_time[0] += 12;
             } else {
                 if ($this->request['start_time_ampm'] == 'AM' and $_time[0] == 12) {
                     $_time[0] = 0;
                 }
             }
         } else {
             if (count($_time) != 2 or $_time[0] > 23 or $_time[1] > 59) {
                 $this->registry->output->showError('calendar_invalid_time', 10427.2);
             }
         }
         $start_date = gmmktime($_time[0], $_time[1], 0, $_startBits[0], $_startBits[1], $_startBits[2]);
     }
     //-----------------------------------------
     // Verify end date/time
     //-----------------------------------------
     if ($this->request['set_enddate']) {
         if (count($_endBits) != 3) {
             $this->registry->output->showError('calendar_invalid_date', 10427.3);
         } else {
             if (!@checkdate($_endBits[0], $_endBits[1], $_endBits[2])) {
                 $this->registry->output->showError('calendar_invalid_date', 10427.4);
             }
         }
         if ($this->request['all_day']) {
             $end_date = gmmktime(0, 0, 0, $_endBits[0], $_endBits[1], $_endBits[2]);
         } else {
             $_time = explode(':', $this->request['end_time']);
             if ($this->settings['cal_time_format'] == 'standard') {
                 if (count($_time) != 2 or $_time[0] > 12 or $_time[1] > 59) {
                     $this->registry->output->showError('calendar_invalid_date', 10427.5);
                 }
                 if ($this->request['end_time_ampm'] == 'PM') {
                     $_time[0] += 12;
                 }
             } else {
                 if (count($_time) != 2 or $_time[0] > 23 or $_time[1] > 59) {
                     $this->registry->output->showError('calendar_invalid_date', 10427.5);
                 }
             }
             $end_date = gmmktime($_time[0], $_time[1], 0, $_endBits[0], $_endBits[1], $_endBits[2]);
         }
     }
     if ($end_date and $end_date < $start_date) {
         $this->registry->output->showError('calendar_range_wrong', 10421);
     } else {
         if ($this->request['end_date'] and $this->request['set_enddate'] and !$end_date) {
             $this->registry->output->showError('calendar_range_wrong', 10421.1);
         }
     }
     //-----------------------------------------
     // Set recurring flag
     //-----------------------------------------
     if ($this->request['set_recurfields']) {
         if (!$end_date) {
             $this->registry->output->showError('recurring_requires_enddate', 10427.6);
         }
         $recurring = intval($this->request['recur_unit']);
     }
     //-----------------------------------------
     // Adjust to GMT
     //-----------------------------------------
     if ($this->request['event_timezone'] and !$this->request['all_day']) {
         $start_date = $start_date - $this->request['event_timezone'] * 3600;
         if ($end_date) {
             $end_date = $end_date - $this->request['event_timezone'] * 3600;
         }
     }
     $start_date = gmstrftime("%Y-%m-%d %H:%M:00", $start_date);
     $end_date = $end_date ? gmstrftime("%Y-%m-%d %H:%M:00", $end_date) : 0;
     //-----------------------------------------
     // Check posted content for errors
     //-----------------------------------------
     if (strlen(trim(IPSText::removeControlCharacters(IPSText::br2nl($_POST['Post'])))) < 1) {
         $this->registry->output->showError('calendar_post_too_short', 10417, null, null, 403);
     }
     $this->settings['max_post_length'] = $this->settings['max_post_length'] ? $this->settings['max_post_length'] : 2140000;
     if (IPSText::mbstrlen($_POST['Post']) > $this->settings['max_post_length'] * 1024) {
         $this->registry->output->showError('calendar_post_too_long', 10418, null, null, 403);
     }
     if (!$event_title or IPSText::mbstrlen($event_title) < 2) {
         $this->registry->output->showError('calendar_no_title', 10419, null, null, 403);
     }
     if (IPSText::mbstrlen($event_title) > 200) {
         $this->registry->output->showError('calendar_title_too_long', 10420, null, null, 403);
     }
     //-----------------------------------------
     // Adding or editing?
     //-----------------------------------------
     if ($type == 'edit') {
         //-----------------------------------------
         // Get event
         //-----------------------------------------
         if (!$event_id) {
             $this->registry->output->showError('calendar_event_not_found', 10414, null, null, 404);
         }
         $event = $this->DB->buildAndFetch(array('select' => '*', 'from' => 'cal_events', 'where' => 'event_id=' . $event_id));
         if (!$event['event_id']) {
             $this->registry->output->showError('calendar_event_not_found', 10415, null, null, 404);
         }
         //-----------------------------------------
         // Do we have permission to edit?
         //-----------------------------------------
         if (!$this->memberData['g_is_supmod'] and $this->memberData['member_id'] != $event['event_member_id']) {
             $this->registry->output->showError('calendar_no_edit_perm', 10416, null, null, 403);
         }
     }
     //-----------------------------------------
     // Set event view permissions
     //-----------------------------------------
     if ($this->memberData['g_access_cp']) {
         if (is_array($this->request['e_groups'])) {
             foreach ($this->cache->getCache('group_cache') as $group) {
                 if ($group['g_access_cp']) {
                     $this->request['e_groups'][] = $group['g_id'];
                 }
             }
             $read_perms = implode(",", $this->request['e_groups']);
         }
     }
     $read_perms = $read_perms ? $read_perms : '*';
     //-----------------------------------------
     // Get editor and format post
     //-----------------------------------------
     $classToLoad = IPSLib::loadLibrary(IPS_ROOT_PATH . 'sources/classes/editor/composite.php', 'classes_editor_composite');
     $editor = new $classToLoad();
     $event_content = $editor->process($_POST['Post']);
     IPSText::getTextClass('bbcode')->parse_html = 0;
     IPSText::getTextClass('bbcode')->parse_smilies = intval($this->request['enableemo']);
     IPSText::getTextClass('bbcode')->parse_bbcode = 1;
     IPSText::getTextClass('bbcode')->parsing_section = 'calendar';
     $event_content = IPSText::getTextClass('bbcode')->preDbParse($event_content);
     //-----------------------------------------
     // Event approved?
     //-----------------------------------------
     if ($this->request['e_type'] == 'private') {
         $event_approved = 1;
     } else {
         $event_approved = $this->registry->permissions->check('nomod', $_calendar) ? 1 : ($_calendar['cal_moderate'] ? 0 : 1);
     }
     //-----------------------------------------
     // Store the event
     //-----------------------------------------
     if ($type == 'add') {
         //-----------------------------------------
         // Format array for storage
         //-----------------------------------------
         $_eventData = array('event_calendar_id' => $calendar_id, 'event_member_id' => $this->memberData['member_id'], 'event_content' => $event_content, 'event_title' => $event_title, 'event_title_seo' => IPSText::makeSeoTitle($event_title), 'event_smilies' => intval($this->request['enableemo']), 'event_comments' => 0, 'event_perms' => $read_perms, 'event_private' => $this->request['e_type'] == 'private' ? 1 : 0, 'event_approved' => $event_approved, 'event_saved' => time(), 'event_lastupdated' => time(), 'event_recurring' => $recurring, 'event_start_date' => $start_date, 'event_end_date' => $end_date, 'event_post_key' => $this->request['post_key'], 'event_rsvp' => $this->registry->permissions->check('askrsvp', $_calendar) ? intval($this->request['event_rsvp']) : 0, 'event_sequence' => 0, 'event_all_day' => intval($this->request['all_day']));
         //-----------------------------------------
         // Data hooks
         //-----------------------------------------
         IPSLib::doDataHooks($_eventData, 'calendarAddEvent');
         //-----------------------------------------
         // Insert
         //-----------------------------------------
         $this->DB->insert('cal_events', $_eventData);
         $event_id = $this->DB->getInsertId();
         //-----------------------------------------
         // Set language strings
         //-----------------------------------------
         $_langString = $event_approved ? $this->lang->words['new_event_redirect'] : $this->lang->words['new_event_mod'];
     } else {
         //-----------------------------------------
         // Format array for storage
         //-----------------------------------------
         $_eventData = array('event_calendar_id' => $calendar_id, 'event_content' => $event_content, 'event_title' => $event_title, 'event_title_seo' => IPSText::makeSeoTitle($event_title), 'event_smilies' => intval($this->request['enableemo']), 'event_perms' => $read_perms, 'event_private' => $this->request['e_type'] == 'private' ? 1 : 0, 'event_approved' => $event_approved, 'event_lastupdated' => time(), 'event_recurring' => $recurring, 'event_start_date' => $start_date, 'event_end_date' => $end_date, 'event_post_key' => $this->request['post_key'], 'event_rsvp' => $this->registry->permissions->check('askrsvp', $_calendar) ? intval($this->request['event_rsvp']) : $event['event_rsvp'], 'event_sequence' => intval($event['event_rsvp']) + 1, 'event_all_day' => intval($this->request['all_day']));
         //-----------------------------------------
         // Data hooks
         //-----------------------------------------
         IPSLib::doDataHooks($_eventData, 'calendarEditEvent');
         //-----------------------------------------
         // Update database
         //-----------------------------------------
         $this->DB->update('cal_events', $_eventData, 'event_id=' . $event_id);
         //-----------------------------------------
         // Set language strings
         //-----------------------------------------
         $_langString = $event_approved ? $this->lang->words['edit_event_redirect'] : $this->lang->words['new_event_mod'];
     }
     //-----------------------------------------
     // Upload attachments
     //-----------------------------------------
     if ($this->memberData['g_attach_max'] != -1) {
         $classToLoad = IPSLib::loadLibrary(IPSLib::getAppDir('core') . '/sources/classes/attach/class_attach.php', 'class_attach');
         $class_attach = new $classToLoad($this->registry);
         $class_attach->type = 'event';
         $class_attach->attach_post_key = $_eventData['event_post_key'];
         $class_attach->attach_rel_id = $event_id;
         $class_attach->init();
         $class_attach->processMultipleUploads();
         $class_attach->postProcessUpload(array());
     }
     //-----------------------------------------
     // Send notifications
     //-----------------------------------------
     if ($event_approved) {
         require_once IPS_ROOT_PATH . 'sources/classes/like/composite.php';
         /*noLibHook*/
         $_like = classes_like::bootstrap('calendar', $type == 'edit' ? 'events' : 'calendars');
         $_url = $this->registry->output->buildSEOUrl('app=calendar&amp;module=calendar&amp;section=view&amp;do=showevent&amp;event_id=' . $event_id, 'public', $_eventData['event_title_seo'], 'cal_event');
         $_like->sendNotifications($type == 'edit' ? $event_id : $_eventData['event_calendar_id'], array('immediate', 'offline'), array('notification_key' => $type == 'edit' ? 'updated_event' : 'new_event', 'notification_url' => $_url, 'email_template' => $type . '_event_follow', 'email_subject' => sprintf($this->lang->words[$type . '_event_follow_subject'], $_url, $_eventData['event_title']), 'build_message_array' => array('NAME' => '-member:members_display_name-', 'AUTHOR' => $this->memberData['members_display_name'], 'TITLE' => $_eventData['event_title'], 'URL' => $_url)));
     }
     //-----------------------------------------
     // Rebuild cache
     //-----------------------------------------
     $this->cache->rebuildCache('calendar_events', 'calendar');
     //-----------------------------------------
     // Redirect
     //-----------------------------------------
     if ($event_approved) {
         $this->registry->output->redirectScreen($_langString, $this->settings['base_url'] . "app=calendar&amp;module=calendar&amp;section=view&amp;do=showevent&amp;event_id=" . $event_id, $_eventData['event_title_seo'], 'cal_event');
     } else {
         $this->registry->output->redirectScreen($_langString, $this->settings['base_url'] . "app=calendar&amp;module=calendar&amp;section=view&amp;cal_id=" . $calendar_id, $this->caches['calendars'][$calendar_id]['cal_title_seo'], 'cal_calendar');
     }
 }