Пример #1
0
 /**
  * Run some validation tests, rules vs valid and invalid data
  */
 public function testValidation()
 {
     // These should all fail
     $validation = new Data_Validator();
     $validation->validation_rules($this->rules);
     $validation->sanitation_rules(array('min_len_csv' => 'trim'));
     $validation->input_processing(array('min_len_csv' => 'csv', 'min_len_array' => 'array'));
     $validation->validate($this->invalid_data);
     foreach ($this->invalid_data as $key => $value) {
         $test = $validation->validation_errors($key);
         $value = is_array($value) ? implode(' | ', $value) : $value;
         $this->assertNotNull($validation->validation_errors($key), 'Test: ' . $test[0] . ' passed data: ' . $value . ' but it should have failed');
     }
     // These should all pass
     $validation = new Data_Validator();
     $validation->validation_rules($this->rules);
     $validation->input_processing(array('min_len_csv' => 'csv', 'min_len_array' => 'array'));
     $validation->validate($this->valid_data);
     foreach ($this->valid_data as $key => $value) {
         $test = $validation->validation_errors($key);
         $value = is_array($value) ? implode(' | ', $value) : $value;
         $this->assertNull($validation->validation_errors($key), 'Test: ' . $test[0] . ' failed data: ' . $value . ' but it should have passed');
     }
 }
Пример #2
0
 /**
  * Shows the contact form for the user to fill out
  * Needs to be enabled to be used
  */
 public function action_contact()
 {
     global $context, $txt, $user_info, $modSettings;
     // Already inside, no need to use this, just send a PM
     // Disabled, you cannot enter.
     if (!$user_info['is_guest'] || empty($modSettings['enable_contactform']) || $modSettings['enable_contactform'] == 'disabled') {
         redirectexit();
     }
     loadLanguage('Login');
     loadTemplate('Register');
     if (isset($_REQUEST['send'])) {
         checkSession('post');
         validateToken('contact');
         spamProtection('contact');
         // No errors, yet.
         $context['errors'] = array();
         loadLanguage('Errors');
         // Could they get the right send topic verification code?
         require_once SUBSDIR . '/VerificationControls.class.php';
         require_once SUBSDIR . '/Members.subs.php';
         // form validation
         require_once SUBSDIR . '/DataValidator.class.php';
         $validator = new Data_Validator();
         $validator->sanitation_rules(array('emailaddress' => 'trim', 'contactmessage' => 'trim|Util::htmlspecialchars'));
         $validator->validation_rules(array('emailaddress' => 'required|valid_email', 'contactmessage' => 'required'));
         $validator->text_replacements(array('emailaddress' => $txt['error_email'], 'contactmessage' => $txt['error_message']));
         // Any form errors
         if (!$validator->validate($_POST)) {
             $context['errors'] = $validator->validation_errors();
         }
         // How about any verification errors
         $verificationOptions = array('id' => 'contactform');
         $context['require_verification'] = create_control_verification($verificationOptions, true);
         if (is_array($context['require_verification'])) {
             foreach ($context['require_verification'] as $error) {
                 $context['errors'][] = $txt['error_' . $error];
             }
         }
         // No errors, then send the PM to the admins
         if (empty($context['errors'])) {
             $admins = admins();
             if (!empty($admins)) {
                 require_once SUBSDIR . '/PersonalMessage.subs.php';
                 sendpm(array('to' => array_keys($admins), 'bcc' => array()), $txt['contact_subject'], $_REQUEST['contactmessage'], false, array('id' => 0, 'name' => $validator->emailaddress, 'username' => $validator->emailaddress));
             }
             // Send the PM
             redirectexit('action=contact;sa=done');
         } else {
             $context['emailaddress'] = $validator->emailaddress;
             $context['contactmessage'] = $validator->contactmessage;
         }
     }
     if (isset($_GET['sa']) && $_GET['sa'] == 'done') {
         $context['sub_template'] = 'contact_form_done';
     } else {
         $context['sub_template'] = 'contact_form';
         $context['page_title'] = $txt['admin_contact_form'];
         require_once SUBSDIR . '/VerificationControls.class.php';
         $verificationOptions = array('id' => 'contactform');
         $context['require_verification'] = create_control_verification($verificationOptions);
         $context['visual_verification_id'] = $verificationOptions['id'];
     }
     createToken('contact');
 }
Пример #3
0
 /**
  * Used when a field contains csv or array of data
  *
  * -Will convert field to individual elements and run a separate validation on that group
  * using the rules defined to the parent node
  *
  * @param mixed[] $input
  * @param string $field
  * @param string $rules
  */
 private function _validate_recursive($input, $field, $rules)
 {
     if (!isset($input[$field])) {
         return;
     }
     // Start a new instance of the validtor to work on this sub data (csv/array)
     $sub_validator = new Data_Validator();
     $fields = array();
     $validation_rules = array();
     if ($this->_datatype[$field] === 'array') {
         // Convert the array to individual values, they all use the same rules
         foreach ($input[$field] as $key => $value) {
             $validation_rules[$key] = $rules;
             $fields[$key] = $value;
         }
     } elseif ($this->_datatype[$field] === 'csv') {
         // Blow it up!
         $temp = explode(',', $input[$field]);
         foreach ($temp as $key => $value) {
             $validation_rules[$key] = $rules;
             $fields[$key] = $value;
         }
     }
     // Validate each "new" field
     $sub_validator->validation_rules($validation_rules);
     $result = $sub_validator->validate($fields);
     // If its not valid, then just take the first error and use it for the original field
     if (!$result) {
         $errors = $sub_validator->validation_errors(true);
         $this->_validation_errors[] = array('field' => $field, 'input' => $errors[0]['input'], 'function' => $errors[0]['function'], 'param' => $errors[0]['param']);
     }
     return $result;
 }
Пример #4
0
    /**
     * Set any setting related to paid subscriptions,
     *
     * - i.e. modify which payment methods are to be used.
     * - It requires the moderate_forum permission
     * - Accessed from ?action=admin;area=paidsubscribe;sa=settings.
     */
    public function action_paidSettings_display()
    {
        global $context, $txt, $scripturl;
        require_once SUBSDIR . '/PaidSubscriptions.subs.php';
        // Initialize the form
        $this->_init_paidSettingsForm();
        $config_vars = $this->_paidSettings->settings();
        // Now load all the other gateway settings.
        $gateways = loadPaymentGateways();
        foreach ($gateways as $gateway) {
            $gatewayClass = new $gateway['display_class']();
            $setting_data = $gatewayClass->getGatewaySettings();
            if (!empty($setting_data)) {
                $config_vars[] = array('title', $gatewayClass->title, 'text_label' => isset($txt['paidsubs_gateway_title_' . $gatewayClass->title]) ? $txt['paidsubs_gateway_title_' . $gatewayClass->title] : $gatewayClass->title);
                $config_vars = array_merge($config_vars, $setting_data);
            }
        }
        // Some important context stuff
        $context['page_title'] = $txt['settings'];
        $context['sub_template'] = 'show_settings';
        $context['settings_message'] = replaceBasicActionUrl($txt['paid_note']);
        $context[$context['admin_menu_name']]['current_subsection'] = 'settings';
        // Get the final touches in place.
        $context['post_url'] = $scripturl . '?action=admin;area=paidsubscribe;save;sa=settings';
        $context['settings_title'] = $txt['settings'];
        // We want javascript for our currency options.
        addInlineJavascript('
		toggleCurrencyOther();', true);
        // Saving the settings?
        if (isset($_GET['save'])) {
            checkSession();
            call_integration_hook('integrate_save_subscription_settings');
            // Check that the entered email addresses are valid
            if (!empty($_POST['paid_email_to'])) {
                require_once SUBSDIR . '/DataValidator.class.php';
                $validator = new Data_Validator();
                // Some cleaning and some rules
                $validator->sanitation_rules(array('paid_email_to' => 'trim'));
                $validator->validation_rules(array('paid_email_to' => 'valid_email'));
                $validator->input_processing(array('paid_email_to' => 'csv'));
                $validator->text_replacements(array('paid_email_to' => $txt['paid_email_to']));
                if ($validator->validate($_POST)) {
                    $_POST['paid_email_to'] = $validator->paid_email_to;
                } else {
                    // Thats not an email, lets set it back in the form to be fixed and let them know its wrong
                    $config_vars[1]['value'] = $_POST['paid_email_to'];
                    $context['error_type'] = 'minor';
                    $context['settings_message'] = array();
                    foreach ($validator->validation_errors() as $id => $error) {
                        $context['settings_message'][] = $error;
                    }
                }
            }
            // No errors, then save away
            if (empty($context['error_type'])) {
                // Sort out the currency stuff.
                if ($_POST['paid_currency'] != 'other') {
                    $_POST['paid_currency_code'] = $_POST['paid_currency'];
                    $_POST['paid_currency_symbol'] = $txt[$_POST['paid_currency'] . '_symbol'];
                }
                $_POST['paid_currency_code'] = trim($_POST['paid_currency_code']);
                unset($config_vars['dummy_currency']);
                Settings_Form::save_db($config_vars);
                redirectexit('action=admin;area=paidsubscribe;sa=settings');
            }
        }
        // Prepare the settings...
        Settings_Form::prepare_db($config_vars);
    }
Пример #5
0
 /**
  * This function handles submission of a template file.
  * It checks the file for syntax errors, and if it passes, it saves it.
  *
  * This function is forwarded to, from
  * ?action=admin;area=theme;sa=edit
  */
 private function _action_edit_submit()
 {
     global $context, $settings;
     $selectedTheme = isset($_GET['th']) ? (int) $_GET['th'] : (isset($_GET['id']) ? (int) $_GET['id'] : 0);
     if (empty($selectedTheme)) {
         // This should never be happening. Never I say. But... in case it does :P
         fatal_lang_error('theme_edit_missing');
     }
     $theme_dir = themeDirectory($context['theme_id']);
     $file = isset($_POST['entire_file']) ? $_POST['entire_file'] : '';
     // You did submit *something*, didn't you?
     if (empty($file)) {
         // @todo a better error message
         fatal_lang_error('theme_edit_missing');
     }
     // Checking PHP syntax on css files is not a most constructive use of processing power :P
     // We need to know what kind of file we have
     $is_php = substr($_REQUEST['filename'], -4) == '.php';
     $is_template = substr($_REQUEST['filename'], -13) == '.template.php';
     $is_css = substr($_REQUEST['filename'], -4) == '.css';
     // Check you up
     if (checkSession('post', '', false) == '' && validateToken('admin-te-' . md5($selectedTheme . '-' . $_REQUEST['filename']), 'post', false) == true) {
         // Consolidate the format in which we received the file contents
         if (is_array($file)) {
             $entire_file = implode("\n", $file);
         } else {
             $entire_file = $file;
         }
         // Convert our tabs back to tabs!
         $entire_file = rtrim(strtr($entire_file, array("\r" => '', '   ' => "\t")));
         // Errors? No errors!
         $errors = array();
         // For PHP files, we check the syntax.
         if ($is_php) {
             require_once SUBSDIR . '/DataValidator.class.php';
             $validator = new Data_Validator();
             $validator->validation_rules(array('entire_file' => 'php_syntax'));
             $validator->validate(array('entire_file' => $entire_file));
             // Retrieve the errors
             $errors = $validator->validation_errors();
         }
         // If successful so far, we'll take the plunge and save this piece of art.
         if (empty($errors)) {
             // Try to save the new file contents
             $fp = fopen($theme_dir . '/' . $_REQUEST['filename'], 'w');
             fwrite($fp, $entire_file);
             fclose($fp);
             // We're done here.
             redirectexit('action=admin;area=theme;th=' . $selectedTheme . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=browse;directory=' . dirname($_REQUEST['filename']));
         } else {
             // Pick the right sub-template for the next try
             if ($is_template) {
                 $context['sub_template'] = 'edit_template';
             } else {
                 $context['sub_template'] = 'edit_file';
             }
             // Fill contextual data for the template, the errors to show
             foreach ($errors as $error) {
                 $context['parse_error'][] = $error;
             }
             // The format of the data depends on template/non-template file.
             if (!is_array($file)) {
                 $file = array($file);
             }
             // Send back the file contents
             $context['entire_file'] = htmlspecialchars(strtr(implode('', $file), array("\t" => '   ')), ENT_COMPAT, 'UTF-8');
             foreach ($file as $i => $file_part) {
                 $context['file_parts'][$i]['lines'] = strlen($file_part);
                 $context['file_parts'][$i]['data'] = $file_part;
             }
             // Re-create token for another try
             createToken('admin-te-' . md5($selectedTheme . '-' . $_REQUEST['filename']));
             return;
         }
     } else {
         loadLanguage('Errors');
         // Notify the template of trouble
         $context['session_error'] = true;
         // Recycle the submitted data.
         if (is_array($file)) {
             $context['entire_file'] = htmlspecialchars(implode("\n", $file), ENT_COMPAT, 'UTF-8');
         } else {
             $context['entire_file'] = htmlspecialchars($file, ENT_COMPAT, 'UTF-8');
         }
         $context['edit_filename'] = htmlspecialchars($_POST['filename'], ENT_COMPAT, 'UTF-8');
         // Choose sub-template
         if ($is_template) {
             $context['sub_template'] = 'edit_template';
         } elseif ($is_css) {
             addJavascriptVar(array('previewData' => '\'\'', 'previewTimeout' => '\'\'', 'refreshPreviewCache' => '\'\'', 'editFilename' => JavaScriptEscape($context['edit_filename']), 'theme_id' => $settings['theme_id']));
             $context['sub_template'] = 'edit_style';
         } else {
             $context['sub_template'] = 'edit_file';
         }
         // Re-create the token so that it can be used
         createToken('admin-te-' . md5($selectedTheme . '-' . $_REQUEST['filename']));
         return;
     }
 }
Пример #6
0
 /**
  * Allow a user to send an email.
  *
  * - Send an email to the user - allow the sender to write the message.
  * - Can either be passed a user ID as uid or a message id as msg.
  * - Does not check permissions for a message ID as there is no information disclosed.
  * - accessed by ?action=emailuser;sa=email
  */
 public function action_email()
 {
     global $context, $user_info, $txt, $scripturl;
     // Can the user even see this information?
     if ($user_info['is_guest']) {
         fatal_lang_error('no_access', false);
     }
     isAllowedTo('send_email_to_members');
     // Are we sending to a user?
     $context['form_hidden_vars'] = array();
     if (isset($_REQUEST['uid'])) {
         require_once SUBSDIR . '/Members.subs.php';
         // Get the latest activated member's display name.
         $row = getBasicMemberData((int) $_REQUEST['uid']);
         $context['form_hidden_vars']['uid'] = (int) $_REQUEST['uid'];
     } elseif (isset($_REQUEST['msg'])) {
         require_once SUBSDIR . '/Messages.subs.php';
         $row = mailFromMessage((int) $_REQUEST['msg']);
         $context['form_hidden_vars']['msg'] = (int) $_REQUEST['msg'];
     }
     // Are you sure you got the address or any data?
     if (empty($row['email_address']) || empty($row)) {
         fatal_lang_error('cant_find_user_email');
     }
     // Can they actually do this?
     $context['show_email_address'] = showEmailAddress(!empty($row['hide_email']), $row['id_member']);
     if ($context['show_email_address'] === 'no') {
         fatal_lang_error('no_access', false);
     }
     // Does the user want to be contacted at all by you?
     require_once SUBSDIR . '/Members.subs.php';
     if (!canContact($row['id_member'])) {
         fatal_lang_error('no_access', false);
     }
     // Setup the context!
     $context['recipient'] = array('id' => $row['id_member'], 'name' => $row['real_name'], 'email' => $row['email_address'], 'email_link' => ($context['show_email_address'] == 'yes_permission_override' ? '<em>' : '') . '<a href="mailto:' . $row['email_address'] . '">' . $row['email_address'] . '</a>' . ($context['show_email_address'] == 'yes_permission_override' ? '</em>' : ''), 'link' => $row['id_member'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>' : $row['real_name']);
     // Can we see this person's email address?
     $context['can_view_recipient_email'] = $context['show_email_address'] == 'yes' || $context['show_email_address'] == 'yes_permission_override';
     // Template
     $context['sub_template'] = 'custom_email';
     $context['page_title'] = $txt['send_email'];
     // Are we actually sending it?
     if (isset($_POST['send']) && isset($_POST['email_body'])) {
         checkSession();
         // Don't let them send too many!
         spamProtection('sendmail');
         require_once SUBSDIR . '/Mail.subs.php';
         require_once SUBSDIR . '/DataValidator.class.php';
         // We will need to do some data checking
         $validator = new Data_Validator();
         $validator->sanitation_rules(array('y_name' => 'trim', 'email_body' => 'trim', 'email_subject' => 'trim'));
         $validator->validation_rules(array('y_name' => 'required|notequal[_]', 'y_email' => 'required|valid_email', 'email_body' => 'required', 'email_subject' => 'required'));
         $validator->text_replacements(array('y_name' => $txt['sendtopic_sender_name'], 'y_email' => $txt['sendtopic_sender_email'], 'email_body' => $txt['message'], 'email_subject' => $txt['send_email_subject']));
         $validator->validate($_POST);
         // If it's a guest sort out their names.
         if ($user_info['is_guest']) {
             $errors = $validator->validation_errors(array('y_name', 'y_email'));
             if ($errors) {
                 $context['sendemail_error'] = array('errors' => $errors, 'type' => 'minor', 'title' => $txt['validation_failure']);
                 return;
             }
             $from_name = $validator->y_name;
             $from_email = $validator->y_email;
         } else {
             $from_name = $user_info['name'];
             $from_email = $user_info['email'];
         }
         // Check we have a body (etc).
         $errors = $validator->validation_errors(array('email_body', 'email_subject'));
         if (!empty($errors)) {
             $context['sendemail_error'] = array('errors' => $errors, 'type' => 'minor', 'title' => $txt['validation_failure']);
             return;
         }
         // We use a template in case they want to customise!
         $replacements = array('EMAILSUBJECT' => $validator->email_subject, 'EMAILBODY' => $validator->email_body, 'SENDERNAME' => $from_name, 'RECPNAME' => $context['recipient']['name']);
         // Get the template and get out!
         $emaildata = loadEmailTemplate('send_email', $replacements);
         sendmail($context['recipient']['email'], $emaildata['subject'], $emaildata['body'], $from_email, null, false, 1, null, true);
         // Now work out where to go!
         if (isset($_REQUEST['uid'])) {
             redirectexit('action=profile;u=' . (int) $_REQUEST['uid']);
         } elseif (isset($_REQUEST['msg'])) {
             redirectexit('msg=' . (int) $_REQUEST['msg']);
         } else {
             redirectexit();
         }
     }
 }
 /**
  * Does the actual saving of the article data
  *
  * - validates the data is safe to save
  * - updates existing articles or creates new ones
  */
 private function _sportal_admin_article_edit_save()
 {
     global $context, $txt, $modSettings;
     // No errors, yet.
     $article_errors = Error_Context::context('article', 0);
     // Use our standard validation functions in a few spots
     require_once SUBSDIR . '/DataValidator.class.php';
     $validator = new Data_Validator();
     // If its not new, lets load the current data
     if (!$this->_is_new) {
         $_REQUEST['article_id'] = (int) $_REQUEST['article_id'];
         $context['article'] = sportal_get_articles($_REQUEST['article_id']);
     }
     // Clean and Review the post data for compliance
     $validator->sanitation_rules(array('title' => 'trim|Util::htmlspecialchars', 'namespace' => 'trim|Util::htmlspecialchars', 'article_id' => 'intval', 'category_id' => 'intval', 'permissions' => 'intval', 'type' => 'trim', 'content' => 'trim'));
     $validator->validation_rules(array('title' => 'required', 'namespace' => 'alpha_numeric|required', 'type' => 'required', 'content' => 'required'));
     $validator->text_replacements(array('title' => $txt['sp_admin_articles_col_title'], 'namespace' => $txt['sp_admin_articles_col_namespace'], 'content' => $txt['sp_admin_articles_col_body']));
     // If you messed this up, back you go
     if (!$validator->validate($_POST)) {
         foreach ($validator->validation_errors() as $id => $error) {
             $article_errors->addError($error);
         }
         $this->action_sportal_admin_article_edit();
     }
     // Lets make sure this namespace (article id) is unique
     $has_duplicate = sp_duplicate_articles($validator->article_id, $validator->namespace);
     if (!empty($has_duplicate)) {
         $article_errors->addError('sp_error_article_namespace_duplicate');
     }
     // And we can't have just a numeric namespace (article id)
     if (preg_replace('~[0-9]+~', '', $validator->namespace) === '') {
         $article_errors->addError('sp_error_article_namespace_numeric');
     }
     // Posting some PHP code, and allowed? Then we need to validate it will run
     if ($_POST['type'] === 'php' && !empty($_POST['content']) && empty($modSettings['sp_disable_php_validation'])) {
         $validator_php = new Data_Validator();
         $validator_php->validation_rules(array('content' => 'php_syntax'));
         // Bad PHP code
         if (!$validator_php->validate(array('content' => $_POST['content']))) {
             $article_errors->addError($validator_php->validation_errors());
         }
     }
     // None shall pass ... with errors
     if ($article_errors->hasErrors()) {
         $this->action_sportal_admin_article_edit();
     }
     // No errors then, prepare the data for saving
     $article_info = array('id' => $validator->article_id, 'id_category' => $validator->category_id, 'namespace' => $validator->namespace, 'title' => $validator->title, 'body' => Util::htmlspecialchars($_POST['content'], ENT_QUOTES), 'type' => in_array($validator->type, array('bbc', 'html', 'php')) ? $_POST['type'] : 'bbc', 'permissions' => $validator->permissions, 'status' => !empty($_POST['status']) ? 1 : 0);
     if ($article_info['type'] === 'bbc') {
         preparsecode($article_info['body']);
     }
     // Save away
     checkSession();
     sp_save_article($article_info, $this->_is_new);
     redirectexit('action=admin;area=portalarticles');
     return true;
 }
 /**
  * Does the actual saving of the page data
  *
  * - validates the data is safe to save
  * - updates existing pages or creates new ones
  */
 private function _sportal_admin_page_edit_save()
 {
     global $txt, $context, $modSettings;
     // No errors, yet.
     $pages_errors = Error_Context::context('pages', 0);
     // Use our standard validation functions in a few spots
     require_once SUBSDIR . '/DataValidator.class.php';
     $validator = new Data_Validator();
     // Clean and Review the post data for compliance
     $validator->sanitation_rules(array('title' => 'trim|Util::htmlspecialchars', 'namespace' => 'trim|Util::htmlspecialchars', 'permissions' => 'intval', 'type' => 'trim', 'content' => 'trim'));
     $validator->validation_rules(array('title' => 'required', 'namespace' => 'alpha_numeric|required', 'type' => 'required', 'content' => 'required'));
     $validator->text_replacements(array('title' => $txt['sp_error_page_name_empty'], 'namespace' => $txt['sp_error_page_namespace_empty'], 'content' => $txt['sp_admin_pages_col_body']));
     // If you messed this up, back you go
     if (!$validator->validate($_POST)) {
         foreach ($validator->validation_errors() as $id => $error) {
             $pages_errors->addError($error);
         }
         $this->action_sportal_admin_page_edit();
     }
     // Can't have the same name in the same space twice
     $has_duplicate = sp_check_duplicate_pages($_POST['namespace'], $_POST['page_id']);
     if (!empty($has_duplicate)) {
         $pages_errors->addError('sp_error_page_namespace_duplicate');
     }
     // Can't have a simple numeric namespace
     if (preg_replace('~[0-9]+~', '', $_POST['namespace']) === '') {
         $pages_errors->addError('sp_error_page_namespace_numeric');
     }
     if ($_POST['type'] === 'php' && !allowedTo('admin_forum')) {
         fatal_lang_error('cannot_admin_forum', false);
     }
     // Running some php code, then we need to validate its legit code
     if ($_POST['type'] === 'php' && !empty($_POST['content']) && empty($modSettings['sp_disable_php_validation'])) {
         $validator_php = new Data_Validator();
         $validator_php->validation_rules(array('content' => 'php_syntax'));
         // Bad PHP code
         if (!$validator_php->validate(array('content' => $_POST['content']))) {
             $pages_errors->addError($validator_php->validation_errors());
         }
     }
     // None shall pass ... with errors
     if ($pages_errors->hasErrors()) {
         $this->action_sportal_admin_page_edit();
     }
     // If you made it this far, we are going to save the work
     if (!empty($_POST['blocks']) && is_array($_POST['blocks'])) {
         foreach ($_POST['blocks'] as $id => $block) {
             $_POST['blocks'][$id] = (int) $block;
         }
     } else {
         $_POST['blocks'] = array();
     }
     // The data for the fields
     $page_info = array('id' => (int) $_POST['page_id'], 'namespace' => Util::htmlspecialchars($_POST['namespace'], ENT_QUOTES), 'title' => Util::htmlspecialchars($_POST['title'], ENT_QUOTES), 'body' => Util::htmlspecialchars($_POST['content'], ENT_QUOTES), 'type' => in_array($_POST['type'], array('bbc', 'html', 'php')) ? $_POST['type'] : 'bbc', 'permissions' => (int) $_POST['permissions'], 'style' => sportal_parse_style('implode'), 'status' => !empty($_POST['status']) ? 1 : 0);
     if ($page_info['type'] === 'bbc') {
         preparsecode($page_info['body']);
     }
     // Save away
     sp_save_page($page_info, $context['SPortal']['is_new']);
     $to_show = array();
     $not_to_show = array();
     $changes = array();
     foreach ($context['page_blocks'] as $page_blocks) {
         foreach ($page_blocks as $block) {
             if ($block['shown'] && !in_array($block['id'], $_POST['blocks'])) {
                 $not_to_show[] = $block['id'];
             } elseif (!$block['shown'] && in_array($block['id'], $_POST['blocks'])) {
                 $to_show[] = $block['id'];
             }
         }
     }
     foreach ($to_show as $id) {
         if (empty($this->blocks[$id]['display']) && empty($this->blocks[$id]['display_custom']) || $this->blocks[$id]['display'] == 'sportal') {
             $changes[$id] = array('display' => 'portal,p' . $page_info['id'], 'display_custom' => '');
         } elseif (in_array($this->blocks[$id]['display'], array('allaction', 'allboard'))) {
             $changes[$id] = array('display' => '', 'display_custom' => $this->blocks[$id]['display'] . ',p' . $page_info['id']);
         } elseif (in_array('-p' . $page_info['id'], explode(',', $this->blocks[$id]['display_custom']))) {
             $changes[$id] = array('display' => $this->blocks[$id]['display'], 'display_custom' => implode(',', array_diff(explode(',', $this->blocks[$id]['display_custom']), array('-p' . $page_info['id']))));
         } elseif (empty($this->blocks[$id]['display_custom'])) {
             $changes[$id] = array('display' => implode(',', array_merge(explode(',', $this->blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => '');
         } else {
             $changes[$id] = array('display' => $this->blocks[$id]['display'], 'display_custom' => implode(',', array_merge(explode(',', $this->blocks[$id]['display_custom']), array('p' . $page_info['id']))));
         }
     }
     foreach ($not_to_show as $id) {
         if (count(array_intersect(array($this->blocks[$id]['display'], $this->blocks[$id]['display_custom']), array('sforum', 'allpages', 'all'))) > 0) {
             $changes[$id] = array('display' => '', 'display_custom' => $this->blocks[$id]['display'] . $this->blocks[$id]['display_custom'] . ',-p' . $page_info['id']);
         } elseif (empty($this->blocks[$id]['display_custom'])) {
             $changes[$id] = array('display' => implode(',', array_diff(explode(',', $this->blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => '');
         } else {
             $changes[$id] = array('display' => implode(',', array_diff(explode(',', $this->blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => implode(',', array_diff(explode(',', $this->blocks[$id]['display_custom']), array('p' . $page_info['id']))));
         }
     }
     // Update the blocks as needed
     foreach ($changes as $id => $data) {
         sp_update_block_visibility($id, $data);
     }
     redirectexit('action=admin;area=portalpages');
     return true;
 }
 /**
  * Editing a membergroup.
  *
  * What it does:
  * - Screen to edit a specific membergroup.
  * - Called by ?action=admin;area=membergroups;sa=edit;group=x.
  * - It requires the manage_membergroups permission.
  * - Also handles the delete button of the edit form.
  * - Redirects to ?action=admin;area=membergroups.
  *
  * @uses the edit_group sub template of ManageMembergroups.
  */
 public function action_edit()
 {
     global $context, $txt, $modSettings;
     $current_group_id = isset($_REQUEST['group']) ? (int) $_REQUEST['group'] : 0;
     if (!empty($modSettings['deny_boards_access'])) {
         loadLanguage('ManagePermissions');
     }
     require_once SUBSDIR . '/Membergroups.subs.php';
     // Make sure this group is editable.
     if (!empty($current_group_id)) {
         $current_group = membergroupById($current_group_id);
     }
     // Now, do we have a valid id?
     if (!allowedTo('admin_forum') && !empty($current_group_id) && $current_group['group_type'] == 1) {
         fatal_lang_error('membergroup_does_not_exist', false);
     }
     // The delete this membergroup button was pressed.
     if (isset($_POST['delete'])) {
         checkSession();
         validateToken('admin-mmg');
         if (empty($current_group_id)) {
             fatal_lang_error('membergroup_does_not_exist', false);
         }
         // Let's delete the group
         deleteMembergroups($current_group['id_group']);
         redirectexit('action=admin;area=membergroups;');
     } elseif (isset($_POST['save'])) {
         // Validate the session.
         checkSession();
         validateToken('admin-mmg');
         if (empty($current_group_id)) {
             fatal_lang_error('membergroup_does_not_exist', false);
         }
         require_once SUBSDIR . '/DataValidator.class.php';
         $validator = new Data_Validator();
         // Cleanup the inputs! :D
         $validator->sanitation_rules(array('max_messages' => 'intval', 'min_posts' => 'intval|abs', 'group_type' => 'intval', 'group_desc' => 'trim|Util::htmlspecialchars', 'group_name' => 'trim|Util::htmlspecialchars', 'group_hidden' => 'intval', 'group_inherit' => 'intval', 'icon_count' => 'intval', 'icon_image' => 'trim|Util::htmlspecialchars', 'online_color' => 'trim|valid_color'));
         $validator->input_processing(array('boardaccess' => 'array'));
         $validator->validation_rules(array('boardaccess' => 'contains[allow,ignore,deny]'));
         $validator->validate($_POST);
         // Can they really inherit from this group?
         if ($validator->group_inherit != -2 && !allowedTo('admin_forum')) {
             $inherit_type = membergroupById($validator->group_inherit);
         }
         $min_posts = $validator->group_type == -1 && $validator->min_posts >= 0 && $current_group['id_group'] > 3 ? $validator->min_posts : ($current_group['id_group'] == 4 ? 0 : -1);
         $group_inherit = $current_group['id_group'] > 1 && $current_group['id_group'] != 3 && (empty($inherit_type['group_type']) || $inherit_type['group_type'] != 1) ? $validator->group_inherit : -2;
         //@todo Don't set online_color for the Moderators group?
         // Do the update of the membergroup settings.
         $properties = array('max_messages' => $validator->max_messages, 'min_posts' => $min_posts, 'group_type' => $validator->group_type < 0 || $validator->group_type > 3 || $validator->group_type == 1 && !allowedTo('admin_forum') ? 0 : $validator->group_type, 'hidden' => !$validator->group_hidden || $min_posts != -1 || $current_group['id_group'] == 3 ? 0 : $validator->group_hidden, 'id_parent' => $group_inherit, 'current_group' => $current_group['id_group'], 'group_name' => $validator->group_name, 'online_color' => $validator->online_color, 'icons' => $validator->icon_count <= 0 ? '' : min($validator->icon_count, 10) . '#' . $validator->icon_image, 'description' => $current_group['id_group'] == 1 || $validator->group_type != -1 ? $validator->group_desc : '');
         updateMembergroupProperties($properties);
         call_integration_hook('integrate_save_membergroup', array($current_group['id_group']));
         // Time to update the boards this membergroup has access to.
         if ($current_group['id_group'] == 2 || $current_group['id_group'] > 3) {
             $changed_boards = array();
             $changed_boards['allow'] = array();
             $changed_boards['deny'] = array();
             $changed_boards['ignore'] = array();
             if ($validator->boardaccess) {
                 foreach ($validator->boardaccess as $group_id => $action) {
                     $changed_boards[$action][] = (int) $group_id;
                 }
             }
             foreach (array('allow', 'deny') as $board_action) {
                 // Find all board this group is in, but shouldn't be in.
                 detachGroupFromBoards($current_group['id_group'], $changed_boards, $board_action);
                 // Add the membergroup to all boards that hadn't been set yet.
                 if (!empty($changed_boards[$board_action])) {
                     assignGroupToBoards($current_group['id_group'], $changed_boards, $board_action);
                 }
             }
         }
         // Remove everyone from this group!
         if ($min_posts != -1) {
             detachDeletedGroupFromMembers($current_group['id_group']);
         } elseif ($current_group['id_group'] != 3) {
             // Making it a hidden group? If so remove everyone with it as primary group (Actually, just make them additional).
             if ($validator->group_hidden == 2) {
                 setGroupToHidden($current_group['id_group']);
             }
             // Either way, let's check our "show group membership" setting is correct.
             validateShowGroupMembership();
         }
         // Do we need to set inherited permissions?
         if ($group_inherit != -2 && $group_inherit != $_POST['old_inherit']) {
             require_once SUBSDIR . '/Permission.subs.php';
             updateChildPermissions($group_inherit);
         }
         // Finally, moderators!
         $moderator_string = isset($_POST['group_moderators']) ? trim($_POST['group_moderators']) : '';
         detachGroupModerators($current_group['id_group']);
         if ((!empty($moderator_string) || !empty($_POST['moderator_list'])) && $min_posts == -1 && $current_group['id_group'] != 3) {
             // Get all the usernames from the string
             if (!empty($moderator_string)) {
                 $moderator_string = strtr(preg_replace('~&amp;#(\\d{4,5}|[2-9]\\d{2,4}|1[2-9]\\d);~', '&#$1;', htmlspecialchars($moderator_string, ENT_QUOTES, 'UTF-8')), array('&quot;' => '"'));
                 preg_match_all('~"([^"]+)"~', $moderator_string, $matches);
                 $moderators = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $moderator_string)));
                 for ($k = 0, $n = count($moderators); $k < $n; $k++) {
                     $moderators[$k] = trim($moderators[$k]);
                     if (strlen($moderators[$k]) == 0) {
                         unset($moderators[$k]);
                     }
                 }
                 // Find all the id_member's for the member_name's in the list.
                 if (!empty($moderators)) {
                     $group_moderators = getIDMemberFromGroupModerators($moderators);
                 }
             } else {
                 $moderators = array();
                 foreach ($_POST['moderator_list'] as $moderator) {
                     $moderators[] = (int) $moderator;
                 }
                 $group_moderators = array();
                 if (!empty($moderators)) {
                     require_once SUBSDIR . '/Members.subs.php';
                     $members = getBasicMemberData($moderators);
                     foreach ($members as $member) {
                         $group_moderators[] = $member['id_member'];
                     }
                 }
             }
             // Found some?
             if (!empty($group_moderators)) {
                 assignGroupModerators($current_group['id_group'], $group_moderators);
             }
         }
         // There might have been some post group changes.
         updateStats('postgroups');
         // We've definitely changed some group stuff.
         updateSettings(array('settings_updated' => time()));
         // Log the edit.
         logAction('edited_group', array('group' => $validator->group_name), 'admin');
         redirectexit('action=admin;area=membergroups');
     }
     // Fetch the current group information.
     $row = membergroupById($current_group['id_group'], true);
     if (empty($row) || !allowedTo('admin_forum') && $row['group_type'] == 1) {
         fatal_lang_error('membergroup_does_not_exist', false);
     }
     $row['icons'] = explode('#', $row['icons']);
     $context['group'] = array('id' => $row['id_group'], 'name' => $row['group_name'], 'description' => htmlspecialchars($row['description'], ENT_COMPAT, 'UTF-8'), 'editable_name' => $row['group_name'], 'color' => $row['online_color'], 'min_posts' => $row['min_posts'], 'max_messages' => $row['max_messages'], 'icon_count' => (int) $row['icons'][0], 'icon_image' => isset($row['icons'][1]) ? $row['icons'][1] : '', 'is_post_group' => $row['min_posts'] != -1, 'type' => $row['min_posts'] != -1 ? 0 : $row['group_type'], 'hidden' => $row['min_posts'] == -1 ? $row['hidden'] : 0, 'inherited_from' => $row['id_parent'], 'allow_post_group' => $row['id_group'] == 2 || $row['id_group'] > 4, 'allow_delete' => $row['id_group'] == 2 || $row['id_group'] > 4, 'allow_protected' => allowedTo('admin_forum'));
     // Get any moderators for this group
     $context['group']['moderators'] = getGroupModerators($row['id_group']);
     $context['group']['moderator_list'] = empty($context['group']['moderators']) ? '' : '&quot;' . implode('&quot;, &quot;', $context['group']['moderators']) . '&quot;';
     if (!empty($context['group']['moderators'])) {
         list($context['group']['last_moderator_id']) = array_slice(array_keys($context['group']['moderators']), -1);
     }
     // Get a list of boards this membergroup is allowed to see.
     $context['boards'] = array();
     if ($row['id_group'] == 2 || $row['id_group'] > 3) {
         require_once SUBSDIR . '/Boards.subs.php';
         $context += getBoardList(array('override_permissions' => true, 'access' => $row['id_group'], 'not_redirection' => true));
         // Include a list of boards per category for easy toggling.
         foreach ($context['categories'] as $category) {
             $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
         }
     }
     // Finally, get all the groups this could be inherited off.
     $context['inheritable_groups'] = getInheritableGroups($row['id_group']);
     call_integration_hook('integrate_view_membergroup');
     $context['sub_template'] = 'edit_group';
     $context['page_title'] = $txt['membergroups_edit_group'];
     // Use the autosuggest script when needed
     if ($context['group']['id'] != 3 && $context['group']['id'] != 4) {
         loadJavascriptFile('suggest.js', array('defer' => true));
     }
     createToken('admin-mmg');
 }
Пример #10
0
 /**
  * Removing old and inactive members.
  */
 public function action_purgeinactive_display()
 {
     global $context, $txt;
     checkSession();
     validateToken('admin-maint');
     require_once SUBSDIR . '/DataValidator.class.php';
     // Start with checking and cleaning what was sent
     $validator = new Data_Validator();
     $validator->sanitation_rules(array('maxdays' => 'intval'));
     $validator->validation_rules(array('maxdays' => 'required', 'groups' => 'isarray', 'del_type' => 'required'));
     // Validator says, you can pass or not
     if ($validator->validate($_POST)) {
         require_once SUBSDIR . '/Maintenance.subs.php';
         require_once SUBSDIR . '/Members.subs.php';
         $groups = array();
         foreach ($validator->groups as $id => $dummy) {
             $groups[] = (int) $id;
         }
         $time_limit = time() - $validator->maxdays * 24 * 3600;
         $members = purgeMembers($validator->type, $groups, $time_limit);
         deleteMembers($members);
         $context['maintenance_finished'] = array('errors' => array(sprintf($txt['maintain_done'], $txt['maintain_members'])));
     } else {
         $context['maintenance_finished'] = array('errors' => $validator->validation_errors(), 'type' => 'minor');
     }
 }
 /**
  * Adding or editing a block.
  */
 public function action_sportal_admin_block_edit()
 {
     global $txt, $context, $modSettings, $boards;
     // Just in case, the admin could be doing something silly like editing a SP block while SP is disabled. ;)
     require_once SUBSDIR . '/PortalBlocks.subs.php';
     $context['SPortal']['is_new'] = empty($_REQUEST['block_id']);
     // BBC Fix move the parameter to the correct position.
     if (!empty($_POST['bbc_name'])) {
         $_POST['parameters'][$_POST['bbc_name']] = !empty($_POST[$_POST['bbc_parameter']]) ? $_POST[$_POST['bbc_parameter']] : '';
         // If we came from WYSIWYG then turn it back into BBC regardless.
         if (!empty($_REQUEST['bbc_' . $_POST['bbc_name'] . '_mode']) && isset($_POST['parameters'][$_POST['bbc_name']])) {
             require_once SUBSDIR . 'Html2BBC.class.php';
             $bbc_converter = new Convert_BBC($_POST['parameters'][$_POST['bbc_name']]);
             $_POST['parameters'][$_POST['bbc_name']] = $bbc_converter->get_bbc();
             // We need to unhtml it now as it gets done shortly.
             $_POST['parameters'][$_POST['bbc_name']] = un_htmlspecialchars($_POST['parameters'][$_POST['bbc_name']]);
         }
     }
     // Passing the selected type via $_GET instead of $_POST?
     $start_parameters = array();
     if (!empty($_GET['selected_type']) && empty($_POST['selected_type'])) {
         $_POST['selected_type'] = array($_GET['selected_type']);
         if (!empty($_GET['parameters'])) {
             foreach ($_GET['parameters'] as $param) {
                 if (isset($_GET[$param])) {
                     $start_parameters[$param] = $_GET[$param];
                 }
             }
         }
     }
     // Want use a block on the portal?
     if ($context['SPortal']['is_new'] && empty($_POST['selected_type']) && empty($_POST['add_block'])) {
         // Gather the blocks we have available
         $context['SPortal']['block_types'] = getFunctionInfo();
         // Create a list of the blocks in use
         $in_use = getBlockInfo();
         foreach ($in_use as $block) {
             $context['SPortal']['block_inuse'][$block['type']] = array('state' => $block['state'], 'column' => $block['column']);
         }
         $context['location'] = array(1 => $txt['sp-positionLeft'], $txt['sp-positionTop'], $txt['sp-positionBottom'], $txt['sp-positionRight'], $txt['sp-positionHeader'], $txt['sp-positionFooter']);
         if (!empty($_REQUEST['col'])) {
             $context['SPortal']['block']['column'] = $_REQUEST['col'];
         }
         $context['sub_template'] = 'block_select_type';
         $context['page_title'] = $txt['sp-blocksAdd'];
     } elseif ($context['SPortal']['is_new'] && !empty($_POST['selected_type'])) {
         $context['SPortal']['block'] = array('id' => 0, 'label' => $txt['sp-blocksDefaultLabel'], 'type' => $_POST['selected_type'][0], 'type_text' => !empty($txt['sp_function_' . $_POST['selected_type'][0] . '_label']) ? $txt['sp_function_' . $_POST['selected_type'][0] . '_label'] : $txt['sp_function_unknown_label'], 'column' => !empty($_POST['block_column']) ? $_POST['block_column'] : 0, 'row' => 0, 'permissions' => 3, 'state' => 1, 'force_view' => 0, 'mobile_view' => 0, 'display' => '', 'display_custom' => '', 'style' => '', 'parameters' => !empty($start_parameters) ? $start_parameters : array(), 'options' => $_POST['selected_type'][0](array(), false, true), 'list_blocks' => !empty($_POST['block_column']) ? getBlockInfo($_POST['block_column']) : array());
     } elseif (!$context['SPortal']['is_new'] && empty($_POST['add_block'])) {
         $_REQUEST['block_id'] = (int) $_REQUEST['block_id'];
         $context['SPortal']['block'] = current(getBlockInfo(null, $_REQUEST['block_id']));
         $context['SPortal']['block'] += array('options' => $context['SPortal']['block']['type'](array(), false, true), 'list_blocks' => getBlockInfo($context['SPortal']['block']['column']));
     }
     // Want to take a look at how this block will appear, well we try our best
     if (!empty($_POST['preview_block']) || isset($_SESSION['sp_error'])) {
         // An error was generated on save, lets set things up like a preview and return to the preview
         if (isset($_SESSION['sp_error'])) {
             $context['SPortal']['error'] = $_SESSION['sp_error'];
             $_POST = $_SESSION['sp_error_post'];
             $_POST['preview_block'] = true;
             // Clean up
             unset($_SESSION['sp_error'], $_SESSION['sp_error_post'], $_POST['add_block']);
         }
         // Just in case, the admin could be doing something silly like editing a SP block while SP is disabled. ;)
         require_once BOARDDIR . '/SSI.php';
         sportal_init_headers();
         loadTemplate('Portal');
         $type_parameters = $_POST['block_type'](array(), 0, true);
         if (!empty($_POST['parameters']) && is_array($_POST['parameters']) && !empty($type_parameters)) {
             foreach ($type_parameters as $name => $type) {
                 if (isset($_POST['parameters'][$name])) {
                     $this->_prepare_parameters($type, $name);
                 }
             }
         } else {
             $_POST['parameters'] = array();
         }
         // Simple is clean
         if (empty($_POST['display_advanced'])) {
             if (!empty($_POST['display_simple']) && in_array($_POST['display_simple'], array('all', 'sportal', 'sforum', 'allaction', 'allboard', 'allpages'))) {
                 $display = $_POST['display_simple'];
             } else {
                 $display = '';
             }
             $custom = '';
         } else {
             $display = array();
             $custom = array();
             if (!empty($_POST['display_actions'])) {
                 foreach ($_POST['display_actions'] as $action) {
                     $display[] = Util::htmlspecialchars($action, ENT_QUOTES);
                 }
             }
             if (!empty($_POST['display_boards'])) {
                 foreach ($_POST['display_boards'] as $board) {
                     $display[] = 'b' . (int) substr($board, 1);
                 }
             }
             if (!empty($_POST['display_pages'])) {
                 foreach ($_POST['display_pages'] as $page) {
                     $display[] = 'p' . (int) substr($page, 1);
                 }
             }
             if (!empty($_POST['display_custom'])) {
                 $temp = explode(',', $_POST['display_custom']);
                 foreach ($temp as $action) {
                     $custom[] = Util::htmlspecialchars(Util::htmltrim($action), ENT_QUOTES);
                 }
             }
             $display = empty($display) ? '' : implode(',', $display);
             $custom = empty($custom) ? '' : implode(',', $custom);
         }
         // Create all the information we know about this block
         $context['SPortal']['block'] = array('id' => $_POST['block_id'], 'label' => Util::htmlspecialchars($_POST['block_name'], ENT_QUOTES), 'type' => $_POST['block_type'], 'type_text' => !empty($txt['sp_function_' . $_POST['block_type'] . '_label']) ? $txt['sp_function_' . $_POST['block_type'] . '_label'] : $txt['sp_function_unknown_label'], 'column' => $_POST['block_column'], 'row' => !empty($_POST['block_row']) ? $_POST['block_row'] : 0, 'placement' => !empty($_POST['placement']) && in_array($_POST['placement'], array('before', 'after')) ? $_POST['placement'] : '', 'permissions' => $_POST['permissions'], 'state' => !empty($_POST['block_active']), 'force_view' => !empty($_POST['block_force']), 'mobile_view' => !empty($_POST['block_mobile']), 'display' => $display, 'display_custom' => $custom, 'style' => sportal_parse_style('implode'), 'parameters' => !empty($_POST['parameters']) ? $_POST['parameters'] : array(), 'options' => $_POST['block_type'](array(), false, true), 'list_blocks' => getBlockInfo($_POST['block_column']), 'collapsed' => false);
         if (strpos($modSettings['leftwidth'], '%') !== false || strpos($modSettings['leftwidth'], 'px') !== false) {
             $context['widths'][1] = $modSettings['leftwidth'];
         } else {
             $context['widths'][1] = $modSettings['leftwidth'] . 'px';
         }
         if (strpos($modSettings['rightwidth'], '%') !== false || strpos($modSettings['rightwidth'], 'px') !== false) {
             $context['widths'][4] = $modSettings['rightwidth'];
         } else {
             $context['widths'][4] = $modSettings['rightwidth'] . 'px';
         }
         if (strpos($context['widths'][1], '%') !== false) {
             $context['widths'][2] = $context['widths'][3] = 100 - ($context['widths'][1] + $context['widths'][4]) . '%';
             $context['widths'][5] = $context['widths'][6] = '100%';
         } elseif (strpos($context['widths'][1], 'px') !== false) {
             $context['widths'][2] = $context['widths'][3] = 960 - ($context['widths'][1] + $context['widths'][4]) . 'px';
             $context['widths'][5] = $context['widths'][6] = '960px';
         }
         $context['SPortal']['preview'] = true;
     }
     if (!empty($_POST['selected_type']) || !empty($_POST['preview_block']) || !$context['SPortal']['is_new'] && empty($_POST['add_block'])) {
         // Only the admin can use PHP blocks
         if ($context['SPortal']['block']['type'] == 'sp_php' && !allowedTo('admin_forum')) {
             fatal_lang_error('cannot_admin_forum', false);
         }
         loadLanguage('SPortalHelp', sp_languageSelect('SPortalHelp'));
         // Load up the permissions
         $context['SPortal']['block']['permission_profiles'] = sportal_get_profiles(null, 1, 'name');
         if (empty($context['SPortal']['block']['permission_profiles'])) {
             fatal_lang_error('error_sp_no_permission_profiles', false);
         }
         $context['simple_actions'] = array('sportal' => $txt['sp-portal'], 'sforum' => $txt['sp-forum'], 'allaction' => $txt['sp-blocksOptionAllActions'], 'allboard' => $txt['sp-blocksOptionAllBoards'], 'allpages' => $txt['sp-blocksOptionAllPages'], 'all' => $txt['sp-blocksOptionEverywhere']);
         $context['display_actions'] = array('portal' => $txt['sp-portal'], 'forum' => $txt['sp-forum'], 'recent' => $txt['recent_posts'], 'unread' => $txt['unread_topics_visit'], 'unreadreplies' => $txt['unread_replies'], 'profile' => $txt['profile'], 'pm' => $txt['pm_short'], 'calendar' => $txt['calendar'], 'admin' => $txt['admin'], 'login' => $txt['login'], 'register' => $txt['register'], 'post' => $txt['post'], 'stats' => $txt['forum_stats'], 'search' => $txt['search'], 'mlist' => $txt['members_list'], 'moderate' => $txt['moderate'], 'help' => $txt['help'], 'who' => $txt['who_title']);
         // Load up boards and pages for selection in the template
         sp_block_template_helpers();
         if (empty($context['SPortal']['block']['display'])) {
             $context['SPortal']['block']['display'] = array('0');
         } else {
             $context['SPortal']['block']['display'] = explode(',', $context['SPortal']['block']['display']);
         }
         if (in_array($context['SPortal']['block']['display'][0], array('all', 'sportal', 'sforum', 'allaction', 'allboard', 'allpages')) || $context['SPortal']['is_new'] || empty($context['SPortal']['block']['display'][0]) && empty($context['SPortal']['block']['display_custom'])) {
             $context['SPortal']['block']['display_type'] = 0;
         } else {
             $context['SPortal']['block']['display_type'] = 1;
         }
         $context['SPortal']['block']['style'] = sportal_parse_style('explode', $context['SPortal']['block']['style'], !empty($context['SPortal']['preview']));
         // Prepare the Textcontent for BBC, only the first bbc will be detected correctly!
         $firstBBCFound = false;
         foreach ($context['SPortal']['block']['options'] as $name => $type) {
             // Selectable Boards :D
             if ($type == 'board_select' || $type == 'boards') {
                 if (empty($boards)) {
                     require_once SUBSDIR . '/Boards.subs.php';
                     getBoardTree();
                 }
                 // Merge the array ;)
                 if (!isset($context['SPortal']['block']['parameters'][$name])) {
                     $context['SPortal']['block']['parameters'][$name] = array();
                 } elseif (!empty($context['SPortal']['block']['parameters'][$name]) && is_array($context['SPortal']['block']['parameters'][$name])) {
                     $context['SPortal']['block']['parameters'][$name] = implode('|', $context['SPortal']['block']['parameters'][$name]);
                 }
                 $context['SPortal']['block']['board_options'][$name] = array();
                 $config_variable = !empty($context['SPortal']['block']['parameters'][$name]) ? $context['SPortal']['block']['parameters'][$name] : array();
                 $config_variable = !is_array($config_variable) ? explode('|', $config_variable) : $config_variable;
                 $context['SPortal']['block']['board_options'][$name] = array();
                 // Create the list for this Item
                 foreach ($boards as $board) {
                     // Ignore the redirected boards :)
                     if (!empty($board['redirect'])) {
                         continue;
                     }
                     $context['SPortal']['block']['board_options'][$name][$board['id']] = array('value' => $board['id'], 'text' => $board['name'], 'selected' => in_array($board['id'], $config_variable));
                 }
             } elseif ($type === 'bbc') {
                 // ELK support only one bbc correct, multiple bbc do not work at the moment
                 if (!$firstBBCFound) {
                     $firstBBCFound = true;
                     // Start Elk BBC System :)
                     require_once SUBSDIR . '/Editor.subs.php';
                     // Prepare the output :D
                     $form_message = !empty($context['SPortal']['block']['parameters'][$name]) ? $context['SPortal']['block']['parameters'][$name] : '';
                     // But if it's in HTML world, turn them into htmlspecialchar's so they can be edited!
                     if (strpos($form_message, '[html]') !== false) {
                         $parts = preg_split('~(\\[/code\\]|\\[code(?:=[^\\]]+)?\\])~i', $form_message, -1, PREG_SPLIT_DELIM_CAPTURE);
                         for ($i = 0, $n = count($parts); $i < $n; $i++) {
                             // It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
                             if ($i % 4 == 0) {
                                 $parts[$i] = preg_replace_callback('~\\[html\\](.+?)\\[/html\\]~is', create_function('$m', 'return "[html]" . preg_replace(\'~<br\\s?/?>~i\', \'&lt;br /&gt;<br />\', "$m[1]") . "[/html]";'), $parts[$i]);
                             }
                         }
                         $form_message = implode('', $parts);
                     }
                     $form_message = preg_replace('~<br(?: /)?' . '>~i', "\n", $form_message);
                     // Prepare the data before i want them inside the textarea
                     $form_message = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $form_message);
                     $context['SPortal']['bbc'] = 'bbc_' . $name;
                     $message_data = array('id' => $context['SPortal']['bbc'], 'width' => '95%', 'height' => '200px', 'value' => $form_message, 'form' => 'sp_block');
                     // Run the ELK bbc editor routine
                     create_control_richedit($message_data);
                     // Store the updated data on the parameters
                     $context['SPortal']['block']['parameters'][$name] = $form_message;
                 } else {
                     $context['SPortal']['block']['options'][$name] = 'textarea';
                 }
             }
         }
         loadJavascriptFile('portal.js?sp24');
         $context['sub_template'] = 'block_edit';
         $context['page_title'] = $context['SPortal']['is_new'] ? $txt['sp-blocksAdd'] : $txt['sp-blocksEdit'];
     }
     // Want to add / edit a block oo the portal
     if (!empty($_POST['add_block'])) {
         checkSession();
         // Only the admin can do php here
         if ($_POST['block_type'] == 'sp_php' && !allowedTo('admin_forum')) {
             fatal_lang_error('cannot_admin_forum', false);
         }
         // Make sure the block name is something safe
         if (!isset($_POST['block_name']) || Util::htmltrim(Util::htmlspecialchars($_POST['block_name']), ENT_QUOTES) === '') {
             fatal_lang_error('error_sp_name_empty', false);
         }
         if ($_POST['block_type'] == 'sp_php' && !empty($_POST['parameters']['content']) && empty($modSettings['sp_disable_php_validation'])) {
             require_once SUBSDIR . '/DataValidator.class.php';
             $validator = new Data_Validator();
             $validator->validation_rules(array('content' => 'php_syntax'));
             $validator->validate(array('content' => $_POST['parameters']['content']));
             $error = $validator->validation_errors();
             if ($error) {
                 $_SESSION['sp_error'] = $error[0];
                 $_SESSION['sp_error_post'] = $_POST;
                 redirectexit('action=admin;area=portalblocks;sa=' . $_REQUEST['sa'] . (!empty($_REQUEST['block_id']) ? ';block_id=' . $_REQUEST['block_id'] : ''));
             }
         }
         // If we have a block ID passed, we must be editing, so the the blocks current data
         if (!empty($_REQUEST['block_id'])) {
             $current_data = current(getBlockInfo(null, $_REQUEST['block_id']));
         }
         // Where are we going to place this new block, before, after, no change
         if (!empty($_POST['placement']) && ($_POST['placement'] === 'before' || $_POST['placement'] === 'after')) {
             if (!empty($current_data)) {
                 $current_row = $current_data['row'];
             } else {
                 $current_row = null;
             }
             // Before or after the chosen block
             if ($_POST['placement'] === 'before') {
                 $row = (int) $_POST['block_row'];
             } else {
                 $row = (int) $_POST['block_row'] + 1;
             }
             if (!empty($current_row) && $row > $current_row) {
                 sp_update_block_row($current_row, $row - 1, $_POST['block_column'], true);
             } else {
                 sp_update_block_row($current_row, $row, $_POST['block_column'], false);
             }
         } elseif (!empty($_POST['placement']) && $_POST['placement'] == 'nochange') {
             $row = 0;
         } else {
             $block_id = !empty($_REQUEST['block_id']) ? (int) $_REQUEST['block_id'] : 0;
             $row = sp_block_nextrow($_POST['block_column'], $block_id);
         }
         $type_parameters = $_POST['block_type'](array(), 0, true);
         if (!empty($_POST['parameters']) && is_array($_POST['parameters']) && !empty($type_parameters)) {
             foreach ($type_parameters as $name => $type) {
                 // Prepare BBC Content for ELK
                 if (isset($_POST['parameters'][$name])) {
                     $this->_prepare_parameters($type, $name);
                 }
             }
         } else {
             $_POST['parameters'] = array();
         }
         // Standard options
         if (empty($_POST['display_advanced'])) {
             if (!empty($_POST['display_simple']) && in_array($_POST['display_simple'], array('all', 'sportal', 'sforum', 'allaction', 'allboard', 'allpages'))) {
                 $display = $_POST['display_simple'];
             } else {
                 $display = '';
             }
             $custom = '';
         } else {
             $display = array();
             if (!empty($_POST['display_actions'])) {
                 foreach ($_POST['display_actions'] as $action) {
                     $display[] = Util::htmlspecialchars($action, ENT_QUOTES);
                 }
             }
             if (!empty($_POST['display_boards'])) {
                 foreach ($_POST['display_boards'] as $board) {
                     $display[] = 'b' . (int) substr($board, 1);
                 }
             }
             if (!empty($_POST['display_pages'])) {
                 foreach ($_POST['display_pages'] as $page) {
                     $display[] = 'p' . (int) substr($page, 1);
                 }
             }
             if (!empty($_POST['display_custom'])) {
                 $custom = array();
                 $temp = explode(',', $_POST['display_custom']);
                 foreach ($temp as $action) {
                     $custom[] = Util::htmlspecialchars(Util::htmltrim($action), ENT_QUOTES);
                 }
             }
             $display = empty($display) ? '' : implode(',', $display);
             if (!allowedTo('admin_forum') && isset($current_data['display_custom']) && substr($current_data['display_custom'], 0, 4) === '$php') {
                 $custom = $current_data['display_custom'];
             } elseif (!empty($_POST['display_custom'])) {
                 if (allowedTo('admin_forum') && substr($_POST['display_custom'], 0, 4) === '$php') {
                     $custom = Util::htmlspecialchars($_POST['display_custom'], ENT_QUOTES);
                 } else {
                     $custom = array();
                     $temp = explode(',', $_POST['display_custom']);
                     foreach ($temp as $action) {
                         $custom[] = Util::htmlspecialchars($action, ENT_QUOTES);
                     }
                     $custom = empty($custom) ? '' : implode(',', $custom);
                 }
             } else {
                 $custom = '';
             }
         }
         $blockInfo = array('id' => (int) $_POST['block_id'], 'label' => Util::htmlspecialchars($_POST['block_name'], ENT_QUOTES), 'type' => $_POST['block_type'], 'col' => $_POST['block_column'], 'row' => $row, 'permissions' => (int) $_POST['permissions'], 'state' => !empty($_POST['block_active']) ? 1 : 0, 'force_view' => !empty($_POST['block_force']) ? 1 : 0, 'mobile_view' => !empty($_POST['block_mobile']) ? 1 : 0, 'display' => $display, 'display_custom' => $custom, 'style' => sportal_parse_style('implode'));
         // Insert a new block in to the portal
         if ($context['SPortal']['is_new']) {
             unset($blockInfo['id']);
             $blockInfo['id'] = sp_block_insert($blockInfo);
         } else {
             sp_block_update($blockInfo);
         }
         // Save any parameters for the block
         if (!empty($_POST['parameters'])) {
             sp_block_insert_parameters($_POST['parameters'], $blockInfo['id']);
         }
         redirectexit('action=admin;area=portalblocks');
     }
 }