function main_page($enabled)
{
    $form = new Form('index.php?module=cloudflare-ipv46&action=change', 'post');
    $form_container = new FormContainer("IPv6 Support");
    $form_container->output_row('IPv6 Support', 'Enable IPv6 support and gateway', $form->generate_yes_no_radio('enable_ipv6', $enabled ? "1" : "0"));
    $form_container->end();
    $buttons[] = $form->generate_submit_button('Submit');
    $form->output_submit_wrapper($buttons);
    $form->end();
}
function main_page($current_cache_level, $modified_on)
{
    $form = new Form('index.php?module=cloudflare-cache_lvl&action=change', 'post');
    $form_container = new FormContainer('Modify Cache Level');
    $form_container->output_row('Cache Level', "Cache Level functions based off the setting level. The basic setting will cache most static resources (i.e., css, images, and JavaScript). The simplified setting will ignore the query string when delivering a cached resource. The aggressive setting will cache all static resources, including ones with a query string. ", $form->generate_select_box('cache_level', array('basic' => 'Basic', 'simplified' => 'Simplified', 'aggressive' => 'Aggressive'), $current_cache_level));
    $form_container->end();
    $buttons[] = $form->generate_submit_button('Submit');
    $form->output_submit_wrapper($buttons);
    $form->end();
}
function main_page()
{
    $form = new Form("index.php?module=cloudflare-whitelist&action=run", "post");
    $form_container = new FormContainer("Whitelist an IP");
    $form_container->output_row("IP Address", "The IP address you would like to whitelist", $form->generate_text_box('ip_address'));
    $form_container->output_row("Notes", "Any notes you would like to add", $form->generate_text_box('notes'));
    $form_container->end();
    $buttons[] = $form->generate_submit_button("Submit");
    $form->output_submit_wrapper($buttons);
    $form->end();
}
function main_page()
{
    $form = new Form("index.php?module=cloudflare-blacklist&action=run", "post");
    $form_container = new FormContainer("Blacklist an IP");
    $form_container->output_row("IP Address", "The IP address you would like to blacklist<br /><b>Only a single IP is currently supported!</b>", $form->generate_text_box('ip_address'));
    $form_container->output_row("Notes", "Any notes you would like to add", $form->generate_text_box('notes'));
    $form_container->end();
    $buttons[] = $form->generate_submit_button("Submit");
    $form->output_submit_wrapper($buttons);
    $form->end();
}
function main_page()
{
    $form = new Form('index.php?module=cloudflare-purge_cache&amp;action=purge', 'post');
    $form_container = new FormContainer('Purge Cache');
    $form_container->output_row('Purge Entire Cache', 'Remove ALL files from CloudFlare\'s cache. This will include javascript, stylesheets and images. CloudFlare can take up to 3 hours to recache resources again<br /><b>Note: </b>This may have dramatic affects on your origin server load after performing this action.', $form->generate_yes_no_radio('purge_input', 0));
    $form_container->output_row('Purge by URL', 'Granularly remove one or more files from CloudFlare\'s cache either by specifying the URL<br /><b>Note: </b><u>One</u> URL per line (max: 30)', $form->generate_text_area('urls'));
    $form_container->end();
    $buttons[] = $form->generate_submit_button('Submit');
    $form->output_submit_wrapper($buttons);
    $form->end();
}
function main_page()
{
    $form = new Form("index.php?module=cloudflare-challenge&amp;action=add_ip", "post");
    $form_container = new FormContainer("Challenge an IP");
    $form_container->output_row("IP Address", "The IP address won't be able to access your site until they have completed the captcha successfully or you have removed them from the challenge list.", $form->generate_text_box('ip_address'));
    $form_container->output_row("Notes", "Any notes you would like to add", $form->generate_text_box('notes'));
    $form_container->end();
    $buttons[] = $form->generate_submit_button("Submit");
    $form->output_submit_wrapper($buttons);
    $form->end();
}
Example #7
0
function myalerts_acp_manage_alert_types()
{
    global $mybb, $lang, $page, $db, $cache;
    $alertTypeManager = MybbStuff_MyAlerts_AlertTypeManager::getInstance();
    $alertTypes = $alertTypeManager->getAlertTypes();
    if (strtolower($mybb->request_method) == 'post') {
        if (!verify_post_check($mybb->get_input('my_post_key'))) {
            flash_message($lang->invalid_post_verify_key2, 'error');
            admin_redirect("index.php?module=config-myalerts_alert_types");
        }
        $enabledAlertTypes = $mybb->get_input('alert_types_enabled', MyBB::INPUT_ARRAY);
        $canBeUserDisabled = $mybb->get_input('alert_types_can_be_user_disabled', MyBB::INPUT_ARRAY);
        $enabledAlertTypes = array_map('intval', array_keys($enabledAlertTypes));
        $canBeUserDisabled = array_map('intval', array_keys($canBeUserDisabled));
        $updateArray = array();
        foreach ($alertTypes as $alertType) {
            $type = MybbStuff_MyAlerts_Entity_AlertType::unserialize($alertType);
            $type->setEnabled(in_array($type->getId(), $enabledAlertTypes));
            $type->setCanBeUserDisabled(in_array($type->getId(), $canBeUserDisabled));
            $updateArray[] = $type;
        }
        $alertTypeManager->updateAlertTypes($updateArray);
        flash_message($lang->myalerts_alert_types_updated, 'success');
        admin_redirect("index.php?module=config-myalerts_alert_types");
    } else {
        $page->output_header($lang->myalerts_alert_types);
        $form = new Form('index.php?module=config-myalerts_alert_types', 'post');
        $table = new Table();
        $table->construct_header($lang->myalerts_alert_type_code);
        $table->construct_header($lang->myalerts_alert_type_enabled, array('width' => '5%', 'class' => 'align_center'));
        $table->construct_header($lang->myalerts_alert_type_can_be_user_disabled, array('width' => '10%', 'class' => 'align_center'));
        $noResults = false;
        if (!empty($alertTypes)) {
            foreach ($alertTypes as $type) {
                $alertCode = htmlspecialchars_uni($type['code']);
                $table->construct_cell($alertCode);
                $table->construct_cell($form->generate_check_box('alert_types_enabled[' . $type['id'] . ']', '', '', array('checked' => $type['enabled'])));
                $table->construct_cell($form->generate_check_box('alert_types_can_be_user_disabled[' . $type['id'] . ']', '', '', array('checked' => $type['can_be_user_disabled'])));
                $table->construct_row();
            }
        } else {
            $table->construct_cell($lang->myalerts_no_alert_types, array('colspan' => 2));
            $table->construct_row();
            $noResults = true;
        }
        $table->output($lang->myalerts_alert_types);
        if (!$noResults) {
            $buttons[] = $form->generate_submit_button($lang->myalerts_update_alert_types);
            $form->output_submit_wrapper($buttons);
        }
        $form->end();
        $page->output_footer();
    }
}
function main_page($in_dev_mode, $time_remaining = 0)
{
    global $page;
    if ($in_dev_mode) {
        $page->output_alert("CloudFlare is currently in development mode. This will expire in " . gmdate("H:i:s", $time_remaining));
    }
    $form = new Form('index.php?module=cloudflare-dev_mode&amp;action=change', 'post');
    $form_container = new FormContainer('Change development mode');
    $form_container->output_row('Development Mode', "This will bypass CloudFlare's accelerated cache and slow down your site, but is useful if you are making changes to cacheable content (like images, css, or JavaScript) and would like to see those changes right away.", $form->generate_on_off_radio('dev_mode', $in_dev_mode ? 1 : 0));
    $form_container->end();
    $buttons[] = $form->generate_submit_button('Submit');
    $form->output_submit_wrapper($buttons);
    $form->end();
}
function main_page($current_setting)
{
    global $security_levels;
    $form = new Form('index.php?module=cloudflare-security_lvl&amp;action=change_security_level', 'post');
    $form_container = new FormContainer('Modify Security Level');
    $form_container->output_row('Security Level', 'The Security Level you choose will determine which visitors will be presented with a challenge page<br />
		<ul>
			<li><b>Essentially Off:</b> Challenges only the most grievous offenders</li>
			<li><b>Low:</b> Challenges only the most threatening visitors</li>
			<li><b>Medium:</b> Challenges both moderate threat visitors and the most threatening visitors</li>
			<li><b>High:</b> Challenges all visitors that have exhibited threatening behavior within the last 14 days</li>
			<li><b>I\'m Under Attack!:</b> Should only be used if your website is under a DDoS attack</li>
				<ul><li>Visitors will receive an interstitial page while we analyze their traffic and behavior to make sure they are a legitimate human visitor trying to access your website</li></ul>
			</li>
		</ul>', $form->generate_select_box('sec_level', $security_levels, $current_setting));
    $form_container->end();
    $buttons[] = $form->generate_submit_button('Submit');
    $form->output_submit_wrapper($buttons);
    $form->end();
}
Example #10
0
        }
        $table->output();
        $table = new Table();
        $table->construct_header('Rank');
        $table->construct_header('Tier');
        $table->construct_header('Order');
        $table->construct_header('Always Visible?');
        $table->construct_header('Split Duplicates?');
        $table->construct_header('Duplicate Amount (if split)');
        $table->construct_header('Activity Check Exempt?');
        $table->construct_header('Delete?');
        foreach ($ranktable->get_ranks() as $rank) {
            $table->construct_cell('<input type="text" class="text_input" name="rank' . $rank['id'] . 'label" value="' . $rank['label'] . '">');
            $table->construct_cell('<select name="rank' . $rank['id'] . 'tier">' . $ranktable->generate_tieroptions($rank['tid']) . '</select>');
            $table->construct_cell('<input type="text" class="text_input" name="rank' . $rank['id'] . 'seq" value="' . $rank['seq'] . '">');
            $checked = $rank['visible'] ? 'checked' : '';
            $table->construct_cell('<input type="checkbox" name="rank' . $rank['id'] . 'visible" value="1" ' . $checked . '>');
            $checked = $rank['split_dups'] ? 'checked' : '';
            $table->construct_cell('<input type="checkbox" name="rank' . $rank['id'] . 'split_dups" value="1" ' . $checked . '>');
            $table->construct_cell('<input type="text" class="text_input" name="rank' . $rank['id'] . 'dups" value="' . $rank['dups'] . '">');
            $checked = $rank['ignoreactivitycheck'] ? 'checked' : '';
            $table->construct_cell('<input type="checkbox" name="rank' . $rank['id'] . 'ignoreactivitycheck" value="1" ' . $checked . '>');
            $table->construct_cell('<input type="checkbox" name="deleteranks[]" value="' . $rank['id'] . '">');
            $table->construct_row();
        }
        $table->output();
        $editbuttons[] = $editform->generate_submit_button("Submit Modifications");
        $editform->output_submit_wrapper($editbuttons);
    }
}
$page->output_footer();
function akismet_admin()
{
    global $mybb, $db, $page, $lang;
    if ($page->active_action != "akismet") {
        return;
    }
    $page->add_breadcrumb_item($lang->akismet);
    if ($mybb->input['delete_all'] && $mybb->request_method == "post") {
        // User clicked no
        if ($mybb->input['no']) {
            admin_redirect("index.php?module=forum-akismet");
        }
        if ($mybb->request_method == "post") {
            // Delete the template
            $db->delete_query("posts", "visible = '-4'");
            // Log admin action
            log_admin_action();
            flash_message($lang->success_deleted_spam, 'success');
            admin_redirect("index.php?module=forum-akismet");
        } else {
            $page->output_confirm_action("index.php?module=forum-akismet&amp;delete_all=1", $lang->confirm_spam_deletion);
        }
    }
    if ($mybb->input['unmark'] && $mybb->request_method == "post") {
        $unmark = $mybb->input['akismet'];
        if (empty($unmark)) {
            flash_message($lang->error_unmark, 'error');
            admin_redirect("index.php?module=forum-akismet");
        }
        $posts_in = '';
        $comma = '';
        foreach ($unmark as $key => $val) {
            $posts_in .= $comma . intval($key);
            $comma = ',';
        }
        $query = $db->simple_select("posts", "pid, tid", "pid IN ({$posts_in}) AND replyto = '0'");
        while ($post = $db->fetch_array($query)) {
            $threadp[] = $post['tid'];
        }
        if (!is_array($threadp)) {
            $threadp = array();
        }
        $thread_list = implode(',', $threadp);
        $query = $db->query("\r\n\t\t\tSELECT p.tid, f.usepostcounts, p.uid, p.fid, p.dateline, p.replyto, t.lastpost, t.lastposter, t.lastposteruid, t.subject\r\n\t\t\tFROM " . TABLE_PREFIX . "posts p\r\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "threads t ON (t.tid=p.tid)\r\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "forums f ON (f.fid=p.fid)\r\n\t\t\tWHERE p.pid IN ({$posts_in}) AND p.visible = '-4'\r\n\t\t");
        while ($post = $db->fetch_array($query)) {
            // Fetch the last post for this forum
            $query2 = $db->query("\r\n\t\t\t\tSELECT tid, lastpost, lastposter, lastposteruid, subject\r\n\t\t\t\tFROM " . TABLE_PREFIX . "threads\r\n\t\t\t\tWHERE fid='{$post['fid']}' AND visible='1' AND closed NOT LIKE 'moved|%'\r\n\t\t\t\tORDER BY lastpost DESC\r\n\t\t\t\tLIMIT 0, 1\r\n\t\t\t");
            $lastpost = $db->fetch_array($query2);
            if ($post['lastpost'] > $lastpost['lastpost']) {
                $lastpost['lastpost'] = $post['lastpost'];
                $lastpost['lastposter'] = $post['lastposter'];
                $lastpost['lastposteruid'] = $post['lastposteruid'];
                $lastpost['subject'] = $post['subject'];
                $lastpost['tid'] = $post['tid'];
            }
            $update_count = array("lastpost" => intval($lastpost['lastpost']), "lastposter" => $db->escape_string($lastpost['lastposter']), "lastposteruid" => intval($lastpost['lastposteruid']), "lastposttid" => intval($lastpost['tid']), "lastpostsubject" => $db->escape_string($lastpost['subject']));
            $db->update_query("forums", $update_count, "fid='{$post['fid']}'");
            $query2 = $db->query("\r\n\t\t\t\tSELECT u.uid, u.username, p.username AS postusername, p.dateline\r\n\t\t\t\tFROM " . TABLE_PREFIX . "posts p\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "users u ON (u.uid=p.uid)\r\n\t\t\t\tWHERE p.tid='{$post['tid']}' AND p.visible='1' OR p.pid = '{$post['pid']}'\r\n\t\t\t\tORDER BY p.dateline DESC\r\n\t\t\t\tLIMIT 1");
            $lastpost = $db->fetch_array($query2);
            $query2 = $db->query("\r\n\t\t\t\tSELECT u.uid, u.username, p.username AS postusername, p.dateline\r\n\t\t\t\tFROM " . TABLE_PREFIX . "posts p\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "users u ON (u.uid=p.uid)\r\n\t\t\t\tWHERE p.tid='{$post['tid']}'\r\n\t\t\t\tORDER BY p.dateline ASC\r\n\t\t\t\tLIMIT 0,1\r\n\t\t\t");
            $firstpost = $db->fetch_array($query2);
            if (!$firstpost['username']) {
                $firstpost['username'] = $firstpost['postusername'];
            }
            if (!$lastpost['username']) {
                $lastpost['username'] = $lastpost['postusername'];
            }
            if (!$lastpost['dateline']) {
                $lastpost['username'] = $firstpost['username'];
                $lastpost['uid'] = $firstpost['uid'];
                $lastpost['dateline'] = $firstpost['dateline'];
            }
            $lastpost['username'] = $db->escape_string($lastpost['username']);
            $firstpost['username'] = $db->escape_string($firstpost['username']);
            $query2 = $db->simple_select("users", "akismetstopped", "uid='{$post['uid']}'");
            $akismetstopped = $db->fetch_field($query2, "akismetstopped") - 1;
            if ($akismetstopped < 0) {
                $akismetstopped = 0;
            }
            $db->update_query("users", array('akismetstopped' => $akismetstopped), "uid='{$post['uid']}'");
            $update_array = array('username' => $firstpost['username'], 'uid' => intval($firstpost['uid']), 'lastpost' => intval($lastpost['dateline']), 'lastposter' => $lastpost['username'], 'lastposteruid' => intval($lastpost['uid']));
            $db->update_query("threads", $update_array, "tid='{$post['tid']}'");
            if ($post['usepostcounts'] != 0) {
                $db->write_query("UPDATE " . TABLE_PREFIX . "users SET postnum=postnum+1 WHERE uid = '{$post['uid']}'");
            }
            $newthreads = $newreplies = 0;
            if ($post['replyto'] == 0) {
                ++$newthreads;
            } else {
                ++$newreplies;
            }
            update_thread_counters($post['tid'], array('replies' => '+' . $newreplies));
            update_forum_counters($post['fid'], array('threads' => '+' . $newthreads, 'posts' => '+1'));
        }
        $approve = array("visible" => 1);
        if ($thread_list) {
            $db->update_query("threads", $approve, "tid IN ({$thread_list})");
        }
        $db->update_query("posts", $approve, "pid IN ({$posts_in})");
        // Log admin action
        log_admin_action();
        flash_message($lang->success_unmarked, 'success');
        admin_redirect("index.php?module=forum-akismet");
    }
    if ($mybb->input['delete'] && $mybb->request_method == "post") {
        $deletepost = $mybb->input['akismet'];
        if (empty($deletepost)) {
            flash_message($lang->error_deletepost, 'error');
            admin_redirect("index.php?module=forum-akismet");
        }
        $posts_in = '';
        $comma = '';
        foreach ($deletepost as $key => $val) {
            $posts_in .= $comma . intval($key);
            $comma = ',';
        }
        $query = $db->simple_select("posts", "pid, tid", "pid IN ({$posts_in}) AND replyto = '0'");
        while ($post = $db->fetch_array($query)) {
            $threadp[$post['pid']] = $post['tid'];
        }
        if (!is_array($threadp)) {
            $threadp = array();
        }
        require_once MYBB_ROOT . "inc/functions_upload.php";
        foreach ($deletepost as $pid => $val) {
            if (array_key_exists($pid, $threadp)) {
                $db->delete_query("posts", "pid IN ({$posts_in})");
                $db->delete_query("attachments", "pid IN ({$posts_in})");
                // Get thread info
                $query = $db->simple_select("threads", "poll", "tid='" . $threadp[$pid] . "'");
                $poll = $db->fetch_field($query, 'poll');
                // Delete threads, redirects, favorites, polls, and poll votes
                $db->delete_query("threads", "tid='" . $threadp[$pid] . "'");
                $db->delete_query("threads", "closed='moved|" . $threadp[$pid] . "'");
                $db->delete_query("threadsubscriptions", "tid='" . $threadp[$pid] . "'");
                $db->delete_query("polls", "tid='" . $threadp[$pid] . "'");
                $db->delete_query("pollvotes", "pid='{$poll}'");
            }
            // Remove attachments
            remove_attachments($pid);
            // Delete the post
            $db->delete_query("posts", "pid='{$pid}'");
        }
        // Log admin action
        log_admin_action();
        flash_message($lang->success_spam_deleted, 'success');
        admin_redirect("index.php?module=forum-akismet");
    }
    if (!$mybb->input['action']) {
        require MYBB_ROOT . "inc/class_parser.php";
        $parser = new postParser();
        $page->output_header($lang->akismet);
        $form = new Form("index.php?module=forum-akismet", "post");
        $table = new Table();
        $table->construct_header($form->generate_check_box("checkall", 1, '', array('class' => 'checkall')), array('width' => '5%'));
        $table->construct_header("Title / Username / Post", array('class' => 'align_center'));
        $mybb->input['page'] = intval($mybb->input['page']);
        if ($mybb->input['page'] > 0) {
            $start = $mybb->input['page'] * 20;
        } else {
            $start = 0;
        }
        $query = $db->simple_select("posts", "COUNT(pid) as spam", "visible = '-4'");
        $total_rows = $db->fetch_field($query, 'spam');
        if ($start > $total_rows) {
            $start = $total_rows - 20;
        }
        if ($start < 0) {
            $start = 0;
        }
        $query = $db->simple_select("posts", "*", "visible = '-4'", array('limit_start' => $start, 'limit' => '20', 'order_by' => 'dateline', 'order_dir' => 'desc'));
        while ($post = $db->fetch_array($query)) {
            if ($post['uid'] != 0) {
                $username = "******"../" . str_replace("{uid}", $post['uid'], PROFILE_URL) . "\" target=\"_blank\">" . format_name($post['username'], $post['usergroup'], $post['displaygroup']) . "</a>";
            } else {
                $username = $post['username'];
            }
            $table->construct_cell($form->generate_check_box("akismet[{$post['pid']}]", 1, ''));
            $table->construct_cell("<span style=\"float: right;\">{$lang->username} {$username}</span> <span style=\"float: left;\">{$lang->title}: " . htmlspecialchars_uni($post['subject']) . " <strong>(" . my_date($mybb->settings['dateformat'], $post['dateline']) . ", " . my_date($mybb->settings['timeformat'], $post['dateline']) . ")</strong></span>");
            $table->construct_row();
            $parser_options = array("allow_html" => 0, "allow_mycode" => 0, "allow_smilies" => 0, "allow_imgcode" => 0, "me_username" => $post['username'], "filter_badwords" => 1);
            $post['message'] = $parser->parse_message($post['message'], $parser_options);
            $table->construct_cell($post['message'], array("colspan" => 2));
            $table->construct_row();
        }
        $num_rows = $table->num_rows();
        if ($num_rows == 0) {
            $table->construct_cell($lang->no_spam_found, array("class" => "align_center", "colspan" => 2));
            $table->construct_row();
        }
        $table->output($lang->detected_spam_messages);
        echo "<br />" . draw_admin_pagination($mybb->input['page'], 20, $total_rows, "index.php?module=forum-akismet&amp;page={page}");
        $buttons[] = $form->generate_submit_button($lang->unmark_selected, array('name' => 'unmark'));
        $buttons[] = $form->generate_submit_button($lang->deleted_selected, array('name' => 'delete'));
        if ($num_rows > 0) {
            $buttons[] = $form->generate_submit_button($lang->delete_all, array('name' => 'delete_all', 'onclick' => "return confirm('{$lang->confirm_spam_deletion}');"));
        }
        $form->output_submit_wrapper($buttons);
        $form->end();
        $page->output_footer();
    }
    exit;
}
Example #12
0
function newpoints_shop_admin()
{
    global $db, $lang, $mybb, $page, $run_module, $action_file, $mybbadmin, $plugins;
    newpoints_lang_load('newpoints_shop');
    if ($run_module == 'newpoints' && $action_file == 'newpoints_shop') {
        if ($mybb->request_method == "post") {
            switch ($mybb->input['action']) {
                case 'do_addcat':
                    if ($mybb->input['name'] == '') {
                        newpoints_shop_messageredirect($lang->newpoints_shop_missing_field, 1);
                    }
                    $name = $db->escape_string($mybb->input['name']);
                    $description = $db->escape_string($mybb->input['description']);
                    // get visible to user groups options
                    if (is_array($mybb->input['usergroups'])) {
                        foreach ($mybb->input['usergroups'] as $gid) {
                            if ($gid == $mybb->input['usergroups']) {
                                unset($mybb->input['usergroups'][$gid]);
                            }
                        }
                        $usergroups = implode(",", $mybb->input['usergroups']);
                    } else {
                        $usergroups = '';
                    }
                    $usergroups = $db->escape_string($usergroups);
                    $visible = intval($mybb->input['visible']);
                    $icon = $db->escape_string($mybb->input['icon']);
                    $disporder = intval($mybb->input['disporder']);
                    $expanded = intval($mybb->input['expanded']);
                    $insert_query = array('name' => $name, 'description' => $description, 'usergroups' => $usergroups, 'visible' => $visible, 'disporder' => $disporder, 'icon' => $icon, 'expanded' => $expanded);
                    $db->insert_query('newpoints_shop_categories', $insert_query);
                    newpoints_shop_messageredirect($lang->newpoints_shop_cat_added);
                    break;
                case 'do_editcat':
                    $cid = intval($mybb->input['cid']);
                    if ($cid <= 0 || !($cat = $db->fetch_array($db->simple_select('newpoints_shop_categories', '*', "cid = {$cid}")))) {
                        newpoints_shop_messageredirect($lang->newpoints_shop_invalid_cat, 1);
                    }
                    if ($mybb->input['name'] == '') {
                        newpoints_shop_messageredirect($lang->newpoints_shop_missing_field, 1);
                    }
                    $name = $db->escape_string($mybb->input['name']);
                    $description = $db->escape_string($mybb->input['description']);
                    // get visible to user groups options
                    if (is_array($mybb->input['usergroups'])) {
                        foreach ($mybb->input['usergroups'] as $gid) {
                            if ($gid == $mybb->input['usergroups']) {
                                unset($mybb->input['usergroups'][$gid]);
                            }
                        }
                        $usergroups = implode(",", $mybb->input['usergroups']);
                    } else {
                        $usergroups = '';
                    }
                    $usergroups = $db->escape_string($usergroups);
                    $visible = intval($mybb->input['visible']);
                    $icon = $db->escape_string($mybb->input['icon']);
                    $disporder = intval($mybb->input['disporder']);
                    $expanded = intval($mybb->input['expanded']);
                    $update_query = array('name' => $name, 'description' => $description, 'usergroups' => $usergroups, 'visible' => $visible, 'disporder' => $disporder, 'icon' => $icon, 'expanded' => $expanded);
                    $db->update_query('newpoints_shop_categories', $update_query, 'cid=\'' . $cid . '\'');
                    newpoints_shop_messageredirect($lang->newpoints_shop_cat_edited);
                    break;
                case 'do_additem':
                    if ($mybb->input['name'] == '' || $mybb->input['cid'] == '') {
                        newpoints_shop_messageredirect($lang->newpoints_shop_missing_field, 1);
                    }
                    $name = $db->escape_string($mybb->input['name']);
                    $description = $db->escape_string($mybb->input['description']);
                    $icon = $db->escape_string($mybb->input['icon']);
                    $pm = $db->escape_string($mybb->input['pm']);
                    $price = floatval($mybb->input['price']);
                    $infinite = intval($mybb->input['infinite']);
                    if ($infinite == 1) {
                        $stock = 0;
                    } else {
                        $stock = intval($mybb->input['stock']);
                    }
                    $limit = intval($mybb->input['limit']);
                    $visible = intval($mybb->input['visible']);
                    $disporder = intval($mybb->input['disporder']);
                    $sendable = intval($mybb->input['sendable']);
                    $sellable = intval($mybb->input['sellable']);
                    $cid = intval($mybb->input['cid']);
                    if ($cid <= 0 || !($cat = $db->fetch_array($db->simple_select('newpoints_shop_categories', '*', "cid = {$cid}")))) {
                        newpoints_shop_messageredirect($lang->newpoints_shop_invalid_cat, 1);
                    }
                    $insert_array = array('name' => $name, 'description' => $description, 'icon' => $icon, 'visible' => $visible, 'disporder' => $disporder, 'price' => $price, 'infinite' => $infinite, 'stock' => $stock, 'limit' => $limit, 'sendable' => $sendable, 'sellable' => $sellable, 'cid' => $cid, 'pm' => $pm);
                    $plugins->run_hooks("newpoints_shop_commit", $insert_array);
                    $db->insert_query('newpoints_shop_items', $insert_array);
                    $db->write_query('UPDATE ' . TABLE_PREFIX . 'newpoints_shop_categories SET items = items+1 WHERE cid=\'' . $cid . '\'');
                    newpoints_shop_messageredirect($lang->newpoints_shop_item_added, 0, "items&amp;cid=" . $cid);
                    break;
                case 'do_edititem':
                    $iid = intval($mybb->input['iid']);
                    if ($iid <= 0 || !($item = $db->fetch_array($db->simple_select('newpoints_shop_items', '*', "iid = {$iid}")))) {
                        newpoints_shop_messageredirect($lang->newpoints_shop_invalid_item, 1, 'items');
                    }
                    if ($mybb->input['name'] == '' || $mybb->input['cid'] == '') {
                        newpoints_shop_messageredirect($lang->newpoints_shop_missing_field, 1);
                    }
                    $name = $db->escape_string($mybb->input['name']);
                    $description = $db->escape_string($mybb->input['description']);
                    $icon = $db->escape_string($mybb->input['icon']);
                    $price = floatval($mybb->input['price']);
                    $pm = $db->escape_string($mybb->input['pm']);
                    $infinite = intval($mybb->input['infinite']);
                    if ($infinite == 1) {
                        $stock = 0;
                    } else {
                        $stock = intval($mybb->input['stock']);
                    }
                    $limit = intval($mybb->input['limit']);
                    $visible = intval($mybb->input['visible']);
                    $disporder = intval($mybb->input['disporder']);
                    $sendable = intval($mybb->input['sendable']);
                    $sellable = intval($mybb->input['sellable']);
                    $cid = intval($mybb->input['cid']);
                    if ($cid <= 0 || !($cat = $db->fetch_array($db->simple_select('newpoints_shop_categories', '*', "cid = {$cid}")))) {
                        newpoints_shop_messageredirect($lang->newpoints_shop_invalid_cat, 1);
                    }
                    $update_array = array('name' => $name, 'description' => $description, 'icon' => $icon, 'visible' => $visible, 'disporder' => $disporder, 'price' => $price, 'infinite' => $infinite, 'stock' => $stock, 'limit' => $limit, 'sendable' => $sendable, 'sellable' => $sellable, 'cid' => $cid, 'pm' => $pm);
                    $plugins->run_hooks("newpoints_shop_commit", $update_array);
                    $db->update_query('newpoints_shop_items', $update_array, 'iid=\'' . $iid . '\'');
                    if ($cid != $item['cid']) {
                        $db->write_query('UPDATE ' . TABLE_PREFIX . 'newpoints_shop_categories SET items = items-1 WHERE cid=\'' . $item['cid'] . '\'');
                        $db->write_query('UPDATE ' . TABLE_PREFIX . 'newpoints_shop_categories SET items = items+1 WHERE cid=\'' . $cid . '\'');
                    }
                    newpoints_shop_messageredirect($lang->newpoints_shop_item_edited, 0, "items&amp;cid=" . $cid);
                    break;
            }
        }
        if ($mybb->input['action'] == 'do_deletecat') {
            $page->add_breadcrumb_item($lang->newpoints_shop, 'index.php?module=newpoints-shop');
            $page->output_header($lang->newpoints_shop);
            $cid = intval($mybb->input['cid']);
            if ($mybb->input['no']) {
                admin_redirect("index.php?module=newpoints-shop");
            }
            if ($mybb->request_method == "post") {
                if ($cid <= 0 || !($cat = $db->fetch_array($db->simple_select('newpoints_shop_categories', 'cid', "cid = {$cid}")))) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_invalid_cat, 1);
                }
                $db->delete_query('newpoints_shop_categories', "cid = {$cid}");
                // unassign items from this category
                $db->update_query('newpoints_shop_items', array('cid' => 0), "cid = {$cid}");
                newpoints_shop_messageredirect($lang->newpoints_shop_cat_deleted);
            } else {
                $mybb->input['cid'] = intval($mybb->input['cid']);
                $form = new Form("index.php?module=newpoints-shop&amp;action=do_deletecat&amp;cid={$mybb->input['cid']}&amp;my_post_key={$mybb->post_code}", 'post');
                echo "<div class=\"confirm_action\">\n";
                echo "<p>{$lang->newpoints_shop_confirm_deletecat}</p>\n";
                echo "<br />\n";
                echo "<p class=\"buttons\">\n";
                echo $form->generate_submit_button($lang->yes, array('class' => 'button_yes'));
                echo $form->generate_submit_button($lang->no, array("name" => "no", 'class' => 'button_no'));
                echo "</p>\n";
                echo "</div>\n";
                $form->end();
            }
        } elseif ($mybb->input['action'] == 'do_deleteitem') {
            $page->add_breadcrumb_item($lang->newpoints_shop, 'index.php?module=newpoints-shop');
            $page->output_header($lang->newpoints_shop);
            $iid = intval($mybb->input['iid']);
            if ($mybb->input['no']) {
                admin_redirect("index.php?module=newpoints-shop", 0, "items&amp;cid=" . $cid);
            }
            if ($mybb->request_method == "post") {
                if ($iid <= 0 || !($item = $db->fetch_array($db->simple_select('newpoints_shop_items', 'cid', "iid = {$iid}")))) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_invalid_item, 1, "items&amp;cid=" . $cid);
                }
                $db->delete_query('newpoints_shop_items', "iid = {$iid}");
                // remove one from the items count
                $db->write_query('UPDATE ' . TABLE_PREFIX . 'newpoints_shop_categories SET items = items-1 WHERE cid=\'' . $item['cid'] . '\'');
                newpoints_shop_messageredirect($lang->newpoints_shop_item_deleted, 0, "items&amp;cid=" . $cid);
            } else {
                $mybb->input['iid'] = intval($mybb->input['iid']);
                $form = new Form("index.php?module=newpoints-shop&amp;action=do_deleteitem&amp;iid={$mybb->input['iid']}&amp;my_post_key={$mybb->post_code}", 'post');
                echo "<div class=\"confirm_action\">\n";
                echo "<p>{$lang->newpoints_shop_confirm_deleteitem}</p>\n";
                echo "<br />\n";
                echo "<p class=\"buttons\">\n";
                echo $form->generate_submit_button($lang->yes, array('class' => 'button_yes'));
                echo $form->generate_submit_button($lang->no, array("name" => "no", 'class' => 'button_no'));
                echo "</p>\n";
                echo "</div>\n";
                $form->end();
            }
        } elseif ($mybb->input['action'] == 'remove') {
            $page->add_breadcrumb_item($lang->newpoints_shop, 'index.php?module=newpoints-shop');
            $page->output_header($lang->newpoints_shop);
            $iid = intval($mybb->input['iid']);
            $mybb->input['uid'] = intval($mybb->input['uid']);
            if ($mybb->input['no']) {
                admin_redirect("index.php?module=newpoints-shop", 0, "items&amp;cid=" . $cid);
            }
            if ($mybb->request_method == "post") {
                if ($iid <= 0 || !($item = $db->fetch_array($db->simple_select('newpoints_shop_items', '*', "iid = {$iid}")))) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_invalid_item, 1, "items&amp;cid=" . $cid);
                }
                $uid = (int) $mybb->input['uid'];
                if ($uid <= 0) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_invalid_user, 1);
                }
                $user = get_user($uid);
                // we're viewing someone else's inventory
                if (empty($user)) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_invalid_user, 1);
                }
                $inventory = @unserialize($user['newpoints_items']);
                if (!$inventory) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_inventory_empty, 1);
                }
                // make sure we own the item
                $key = array_search($item['iid'], $inventory);
                if ($key === false) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_selected_item_not_owned, 1);
                }
                // remove item from our inventory
                unset($inventory[$key]);
                sort($inventory);
                $db->update_query('users', array('newpoints_items' => serialize($inventory)), 'uid=\'' . $uid . '\'');
                // update stock
                if ($item['infinite'] != 1) {
                    $db->update_query('newpoints_shop_items', array('stock' => $item['stock'] + 1), 'iid=\'' . $item['iid'] . '\'');
                }
                newpoints_addpoints($uid, floatval($item['price']) * $mybb->settings['newpoints_shop_percent']);
                newpoints_shop_messageredirect($lang->newpoints_shop_item_removed, 0, "inventory&amp;uid=" . $uid);
            } else {
                $form = new Form("index.php?module=newpoints-shop&amp;action=remove&amp;iid={$mybb->input['iid']}&amp;uid={$mybb->input['uid']}&amp;my_post_key={$mybb->post_code}", 'post');
                echo "<div class=\"confirm_action\">\n";
                echo "<p>{$lang->newpoints_shop_confirm_removeitem}</p>\n";
                echo "<br />\n";
                echo "<p class=\"buttons\">\n";
                echo $form->generate_submit_button($lang->yes, array('class' => 'button_yes'));
                echo $form->generate_submit_button($lang->no, array("name" => "no", 'class' => 'button_no'));
                echo "</p>\n";
                echo "</div>\n";
                $form->end();
            }
        }
        if (!$mybb->input['action'] || $mybb->input['action'] == 'categories' || $mybb->input['action'] == 'inventory' || $mybb->input['action'] == 'addcat' || $mybb->input['action'] == 'editcat') {
            $page->add_breadcrumb_item($lang->newpoints_shop, 'index.php?module=newpoints-shop');
            $page->output_header($lang->newpoints_shop);
            $sub_tabs['newpoints_shop_categories'] = array('title' => $lang->newpoints_shop_categories, 'link' => 'index.php?module=newpoints-shop', 'description' => $lang->newpoints_shop_categories_desc);
            if (!$mybb->input['action'] || $mybb->input['action'] == 'categories' || $mybb->input['action'] == 'addcat' || $mybb->input['action'] == 'editcat') {
                $sub_tabs['newpoints_shop_categories_add'] = array('title' => $lang->newpoints_shop_addcat, 'link' => 'index.php?module=newpoints-shop&amp;action=addcat', 'description' => $lang->newpoints_shop_addcat_desc);
                $sub_tabs['newpoints_shop_categories_edit'] = array('title' => $lang->newpoints_shop_editcat, 'link' => 'index.php?module=newpoints-shop&amp;action=editcat', 'description' => $lang->newpoints_shop_editcat_desc);
                $sub_tabs['newpoints_shop_categories_delete'] = array('title' => $lang->newpoints_shop_deletecat, 'link' => 'index.php?module=newpoints-shop&amp;action=do_deletecat', 'description' => $lang->newpoints_shop_deletecat_desc);
            }
        }
        if ($mybb->input['action'] == 'inventory') {
            $sub_tabs['newpoints_shop_inventory'] = array('title' => $lang->newpoints_shop_inventory, 'link' => 'index.php?module=newpoints-shop&amp;action=inventory&amp;uid=' . intval($mybb->input['uid']), 'description' => $lang->newpoints_shop_inventory_desc);
        }
        if ($mybb->input['action'] == 'items' || $mybb->input['action'] == 'additem' || $mybb->input['action'] == 'edititem') {
            $page->add_breadcrumb_item($lang->newpoints_shop, 'index.php?module=newpoints-shop');
            $page->output_header($lang->newpoints_shop);
            $sub_tabs['newpoints_shop_categories'] = array('title' => $lang->newpoints_shop_categories, 'link' => 'index.php?module=newpoints-shop', 'description' => $lang->newpoints_shop_categories_desc);
            $sub_tabs['newpoints_shop_items'] = array('title' => $lang->newpoints_shop_items, 'link' => 'index.php?module=newpoints-shop&amp;action=items&amp;cid=' . intval($mybb->input['cid']), 'description' => $lang->newpoints_shop_items_desc);
            if ($mybb->input['action'] == 'items' || $mybb->input['action'] == 'additem' || $mybb->input['action'] == 'edititem') {
                $sub_tabs['newpoints_shop_items_add'] = array('title' => $lang->newpoints_shop_additem, 'link' => 'index.php?module=newpoints-shop&amp;action=additem&amp;cid=' . intval($mybb->input['cid']), 'description' => $lang->newpoints_shop_additem_desc);
                $sub_tabs['newpoints_shop_items_edit'] = array('title' => $lang->newpoints_shop_edititem, 'link' => 'index.php?module=newpoints-shop&amp;action=edititem', 'description' => $lang->newpoints_shop_edititem_desc);
                $sub_tabs['newpoints_shop_items_delete'] = array('title' => $lang->newpoints_shop_deleteitem, 'link' => 'index.php?module=newpoints-shop&amp;action=do_deleteitem', 'description' => $lang->newpoints_shop_deleteitem_desc);
            }
        }
        if (!$mybb->input['action'] || $mybb->input['action'] == 'categories') {
            $page->output_nav_tabs($sub_tabs, 'newpoints_shop_categories');
            // table
            $table = new Table();
            $table->construct_header($lang->newpoints_shop_cat_name, array('width' => '30%'));
            $table->construct_header($lang->newpoints_shop_cat_description, array('width' => '35%'));
            $table->construct_header($lang->newpoints_shop_cat_items, array('width' => '10%', 'class' => 'align_center'));
            $table->construct_header($lang->newpoints_shop_cat_disporder, array('width' => '10%', 'class' => 'align_center'));
            $table->construct_header($lang->newpoints_shop_cat_action, array('width' => '25%', 'class' => 'align_center'));
            $query = $db->simple_select('newpoints_shop_categories', '*', '', array('order_by' => 'disporder', 'order_dir' => 'ASC'));
            while ($cat = $db->fetch_array($query)) {
                $table->construct_cell("<a href=\"index.php?module=newpoints-shop&amp;action=items&amp;cid={$cat['cid']}\">" . htmlspecialchars_uni($cat['name']) . "</a>");
                $table->construct_cell(htmlspecialchars_uni($cat['description']));
                $table->construct_cell(intval($cat['items']), array('class' => 'align_center'));
                $table->construct_cell(intval($cat['disporder']), array('class' => 'align_center'));
                // actions column
                $table->construct_cell("<a href=\"index.php?module=newpoints-shop&amp;action=editcat&amp;cid=" . intval($cat['cid']) . "\">" . $lang->newpoints_shop_edit . "</a> - <a href=\"index.php?module=newpoints-shop&amp;action=do_deletecat&amp;cid=" . intval($cat['cid']) . "\">" . $lang->newpoints_shop_delete . "</a>", array('class' => 'align_center'));
                $table->construct_row();
            }
            if ($table->num_rows() == 0) {
                $table->construct_cell($lang->newpoints_shop_no_cats, array('colspan' => 5));
                $table->construct_row();
            }
            $table->output($lang->newpoints_shop_categories);
        } elseif ($mybb->input['action'] == 'addcat') {
            $page->output_nav_tabs($sub_tabs, 'newpoints_shop_categories_add');
            $query = $db->simple_select("usergroups", "gid, title", "gid != '1'", array('order_by' => 'title'));
            while ($usergroup = $db->fetch_array($query)) {
                $options[$usergroup['gid']] = $usergroup['title'];
            }
            $form = new Form("index.php?module=newpoints-shop&amp;action=do_addcat", "post", "newpoints_shop");
            $form_container = new FormContainer($lang->newpoints_shop_addcat);
            $form_container->output_row($lang->newpoints_shop_addedit_cat_name . "<em>*</em>", $lang->newpoints_shop_addedit_cat_name_desc, $form->generate_text_box('name', '', array('id' => 'name')), 'name');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_description, $lang->newpoints_shop_addedit_cat_description_desc, $form->generate_text_box('description', '', array('id' => 'description')), 'description');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_visible, $lang->newpoints_shop_addedit_cat_visible_desc, $form->generate_yes_no_radio('visible', 1), 'visible');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_icon, $lang->newpoints_shop_addedit_cat_icon_desc, $form->generate_text_box('icon', '', array('id' => 'icon')), 'icon');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_usergroups, $lang->newpoints_shop_addedit_cat_usergroups_desc, $form->generate_select_box('usergroups[]', $options, '', array('id' => 'usergroups', 'multiple' => true, 'size' => 5)), 'groups');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_disporder, $lang->newpoints_shop_addedit_cat_disporder_desc, $form->generate_text_box('disporder', '0', array('id' => 'disporder')), 'disporder');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_expanded, $lang->newpoints_shop_addedit_cat_expanded_desc, $form->generate_yes_no_radio('expanded', 1), 'expanded');
            $form_container->end();
            $buttons = "";
            $buttons[] = $form->generate_submit_button($lang->newpoints_shop_submit);
            $buttons[] = $form->generate_reset_button($lang->newpoints_shop_reset);
            $form->output_submit_wrapper($buttons);
            $form->end();
        } elseif ($mybb->input['action'] == 'editcat') {
            $page->output_nav_tabs($sub_tabs, 'newpoints_shop_categories_edit');
            $cid = intval($mybb->input['cid']);
            if ($cid <= 0 || !($cat = $db->fetch_array($db->simple_select('newpoints_shop_categories', '*', "cid = {$cid}")))) {
                newpoints_shop_messageredirect($lang->newpoints_shop_invalid_cat, 1);
            }
            $query = $db->simple_select("usergroups", "gid, title", "gid != '1'", array('order_by' => 'title'));
            while ($usergroup = $db->fetch_array($query)) {
                $options[$usergroup['gid']] = $usergroup['title'];
            }
            $form = new Form("index.php?module=newpoints-shop&amp;action=do_editcat", "post", "newpoints_shop");
            echo $form->generate_hidden_field('cid', $cat['cid']);
            $form_container = new FormContainer($lang->newpoints_shop_addcat);
            $form_container->output_row($lang->newpoints_shop_addedit_cat_name . "<em>*</em>", $lang->newpoints_shop_addedit_cat_name_desc, $form->generate_text_box('name', htmlspecialchars_uni($cat['name']), array('id' => 'name')), 'name');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_description, $lang->newpoints_shop_addedit_cat_description_desc, $form->generate_text_box('description', htmlspecialchars_uni($cat['description']), array('id' => 'description')), 'description');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_visible, $lang->newpoints_shop_addedit_cat_visible_desc, $form->generate_yes_no_radio('visible', intval($cat['visible'])), 'visible');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_icon, $lang->newpoints_shop_addedit_cat_icon_desc, $form->generate_text_box('icon', htmlspecialchars_uni($cat['icon']), array('id' => 'icon')), 'icon');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_usergroups, $lang->newpoints_shop_addedit_cat_usergroups_desc, $form->generate_select_box('usergroups[]', $options, explode(',', $cat['usergroups']), array('id' => 'usergroups', 'multiple' => true, 'size' => 5)), 'groups');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_disporder, $lang->newpoints_shop_addedit_cat_disporder_desc, $form->generate_text_box('disporder', intval($cat['disporder']), array('id' => 'disporder')), 'disporder');
            $form_container->output_row($lang->newpoints_shop_addedit_cat_expanded, $lang->newpoints_shop_addedit_cat_expanded_desc, $form->generate_yes_no_radio('expanded', intval($cat['expanded'])), 'expanded');
            $form_container->end();
            $buttons = "";
            $buttons[] = $form->generate_submit_button($lang->newpoints_shop_submit);
            $buttons[] = $form->generate_reset_button($lang->newpoints_shop_reset);
            $form->output_submit_wrapper($buttons);
            $form->end();
        } else {
            if ($mybb->input['action'] == 'items') {
                $page->output_nav_tabs($sub_tabs, 'newpoints_shop_items');
                $cid = intval($mybb->input['cid']);
                if ($cid <= 0 || !($cat = $db->fetch_array($db->simple_select('newpoints_shop_categories', '*', "cid = {$cid}")))) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_invalid_cat, 1);
                }
                // table
                $table = new Table();
                $table->construct_header($lang->newpoints_shop_item_icon, array('width' => '10%', 'class' => 'align_center'));
                $table->construct_header($lang->newpoints_shop_item_name, array('width' => '30%'));
                $table->construct_header($lang->newpoints_shop_item_price, array('width' => '15%', 'class' => 'align_center'));
                $table->construct_header($lang->newpoints_shop_item_disporder, array('width' => '15%', 'class' => 'align_center'));
                $table->construct_header($lang->newpoints_shop_item_action, array('width' => '20%', 'class' => 'align_center'));
                $query = $db->simple_select('newpoints_shop_items', '*', 'cid=\'' . $cid . '\'', array('order_by' => 'disporder', 'order_dir' => 'ASC'));
                while ($item = $db->fetch_array($query)) {
                    if ($item['infinite'] == 1) {
                        $item['stock'] = $lang->newpoints_shop_infinite;
                    }
                    if ($item['visible'] == 0) {
                        $visible_info = ' (<span style="color: #FF0000;">hidden</span>)';
                    } else {
                        $visible_info = '';
                    }
                    $table->construct_cell(htmlspecialchars_uni($item['icon']) ? '<img src="' . $mybb->settings['bburl'] . '/' . $item['icon'] . '">' : '<img src="' . $mybb->settings['bburl'] . '/images/newpoints/default.png">', array('class' => 'align_center'));
                    $table->construct_cell(htmlspecialchars_uni($item['name']) . " (" . (intval($item['infinite']) ? $lang->newpoints_shop_infinite : intval($item['stock'])) . ")" . $visible_info . "<br /><small>" . htmlspecialchars_uni($item['description']) . "</small>");
                    $table->construct_cell(newpoints_format_points($item['price']), array('class' => 'align_center'));
                    $table->construct_cell(intval($item['disporder']), array('class' => 'align_center'));
                    // actions column
                    $table->construct_cell("<a href=\"index.php?module=newpoints-shop&amp;action=edititem&amp;iid=" . intval($item['iid']) . "\">" . $lang->newpoints_shop_edit . "</a> - <a href=\"index.php?module=newpoints-shop&amp;action=do_deleteitem&amp;iid=" . intval($item['iid']) . "\">" . $lang->newpoints_shop_delete . "</a>", array('class' => 'align_center'));
                    $table->construct_row();
                }
                if ($table->num_rows() == 0) {
                    $table->construct_cell($lang->newpoints_shop_no_items, array('colspan' => 6));
                    $table->construct_row();
                }
                $table->output($lang->newpoints_shop_items);
            } elseif ($mybb->input['action'] == 'additem') {
                $page->output_nav_tabs($sub_tabs, 'newpoints_shop_items_add');
                $cid = intval($mybb->input['cid']);
                if ($cid > 0) {
                    if ($cid <= 0 || !($cat = $db->fetch_array($db->simple_select('newpoints_shop_categories', '*', "cid = {$cid}")))) {
                        newpoints_shop_messageredirect($lang->newpoints_shop_invalid_cat, 1);
                    }
                } else {
                    $cid = 0;
                }
                $categories[0] = $lang->newpoints_shop_select_cat;
                $query = $db->simple_select('newpoints_shop_categories', '*');
                while ($cat = $db->fetch_array($query)) {
                    $categories[$cat['cid']] = $cat['name'];
                }
                $form = new Form("index.php?module=newpoints-shop&amp;action=do_additem", "post", "newpoints_shop");
                $form_container = new FormContainer($lang->newpoints_shop_additem);
                $form_container->output_row($lang->newpoints_shop_addedit_item_name . "<em>*</em>", $lang->newpoints_shop_addedit_item_name_desc, $form->generate_text_box('name', '', array('id' => 'name')), 'name');
                $form_container->output_row($lang->newpoints_shop_addedit_item_description, $lang->newpoints_shop_addedit_item_description_desc, $form->generate_text_box('description', '', array('id' => 'description')), 'description');
                $form_container->output_row($lang->newpoints_shop_addedit_item_price, $lang->newpoints_shop_addedit_item_price_desc, $form->generate_text_box('price', '0', array('id' => 'price')), 'price');
                $form_container->output_row($lang->newpoints_shop_addedit_item_icon, $lang->newpoints_shop_addedit_item_icon_desc, $form->generate_text_box('icon', '', array('id' => 'icon')), 'icon');
                $form_container->output_row($lang->newpoints_shop_addedit_item_disporder, $lang->newpoints_shop_addedit_item_disporder_desc, $form->generate_text_box('disporder', '0', array('id' => 'disporder')), 'disporder');
                $form_container->output_row($lang->newpoints_shop_addedit_item_stock, $lang->newpoints_shop_addedit_item_stock_desc, $form->generate_text_box('stock', '0', array('id' => 'stock')), 'stock');
                $form_container->output_row($lang->newpoints_shop_addedit_item_infinite, $lang->newpoints_shop_addedit_item_infinite_desc, $form->generate_yes_no_radio('infinite', 1), 'infinite');
                $form_container->output_row($lang->newpoints_shop_addedit_item_limit, $lang->newpoints_shop_addedit_item_limit_desc, $form->generate_text_box('limit', '0', array('id' => 'limit')), 'limit');
                $form_container->output_row($lang->newpoints_shop_addedit_item_visible, $lang->newpoints_shop_addedit_item_visible_desc, $form->generate_yes_no_radio('visible', 1), 'visible');
                $form_container->output_row($lang->newpoints_shop_addedit_item_sendable, $lang->newpoints_shop_addedit_item_sendable_desc, $form->generate_yes_no_radio('sendable', 1), 'sendable');
                $form_container->output_row($lang->newpoints_shop_addedit_item_sellable, $lang->newpoints_shop_addedit_item_sellable_desc, $form->generate_yes_no_radio('sellable', 1), 'sellable');
                $form_container->output_row($lang->newpoints_shop_addedit_item_pm, $lang->newpoints_shop_addedit_item_pm_desc, $form->generate_text_area('pm', '', array('id' => 'pm_text')), 'pm');
                $form_container->output_row($lang->newpoints_shop_addedit_item_category . "<em>*</em>", $lang->newpoints_shop_addedit_item_category_desc, $form->generate_select_box('cid', $categories, $cid, array('id' => 'cid')), 'cid');
                $args = array($form_container, $form, array());
                $plugins->run_hooks("newpoints_shop_row", $args);
                $form_container->end();
                $buttons = "";
                $buttons[] = $form->generate_submit_button($lang->newpoints_shop_submit);
                $buttons[] = $form->generate_reset_button($lang->newpoints_shop_reset);
                $form->output_submit_wrapper($buttons);
                $form->end();
            } elseif ($mybb->input['action'] == 'edititem') {
                $page->output_nav_tabs($sub_tabs, 'newpoints_shop_items_edit');
                $iid = intval($mybb->input['iid']);
                if ($iid <= 0 || !($item = $db->fetch_array($db->simple_select('newpoints_shop_items', '*', "iid = {$iid}")))) {
                    newpoints_shop_messageredirect($lang->newpoints_shop_invalid_item, 1, 'items');
                }
                $categories[0] = $lang->newpoints_shop_select_cat;
                $query = $db->simple_select('newpoints_shop_categories', '*');
                while ($cat = $db->fetch_array($query)) {
                    $categories[$cat['cid']] = $cat['name'];
                }
                $form = new Form("index.php?module=newpoints-shop&amp;action=do_edititem", "post", "newpoints_shop");
                echo $form->generate_hidden_field('iid', $iid);
                $form_container = new FormContainer($lang->newpoints_shop_additem);
                $form_container->output_row($lang->newpoints_shop_addedit_item_name . "<em>*</em>", $lang->newpoints_shop_addedit_item_name_desc, $form->generate_text_box('name', htmlspecialchars_uni($item['name']), array('id' => 'name')), 'name');
                $form_container->output_row($lang->newpoints_shop_addedit_item_description, $lang->newpoints_shop_addedit_item_description_desc, $form->generate_text_box('description', htmlspecialchars_uni($item['description']), array('id' => 'description')), 'description');
                $form_container->output_row($lang->newpoints_shop_addedit_item_price, $lang->newpoints_shop_addedit_item_price_desc, $form->generate_text_box('price', floatval($item['price']), array('id' => 'price')), 'price');
                $form_container->output_row($lang->newpoints_shop_addedit_item_icon, $lang->newpoints_shop_addedit_item_icon_desc, $form->generate_text_box('icon', htmlspecialchars_uni($item['icon']), array('id' => 'icon')), 'icon');
                $form_container->output_row($lang->newpoints_shop_addedit_item_disporder, $lang->newpoints_shop_addedit_item_disporder_desc, $form->generate_text_box('disporder', intval($item['disporder']), array('id' => 'disporder')), 'disporder');
                $form_container->output_row($lang->newpoints_shop_addedit_item_stock, $lang->newpoints_shop_addedit_item_stock_desc, $form->generate_text_box('stock', intval($item['stock']), array('id' => 'stock')), 'stock');
                $form_container->output_row($lang->newpoints_shop_addedit_item_infinite, $lang->newpoints_shop_addedit_item_infinite_desc, $form->generate_yes_no_radio('infinite', intval($item['infinite'])), 'infinite');
                $form_container->output_row($lang->newpoints_shop_addedit_item_limit, $lang->newpoints_shop_addedit_item_limit_desc, $form->generate_text_box('limit', intval($item['limit']), array('id' => 'limit')), 'limit');
                $form_container->output_row($lang->newpoints_shop_addedit_item_visible, $lang->newpoints_shop_addedit_item_visible_desc, $form->generate_yes_no_radio('visible', intval($item['visible'])), 'visible');
                $form_container->output_row($lang->newpoints_shop_addedit_item_sendable, $lang->newpoints_shop_addedit_item_sendable_desc, $form->generate_yes_no_radio('sendable', intval($item['sendable'])), 'sendable');
                $form_container->output_row($lang->newpoints_shop_addedit_item_sellable, $lang->newpoints_shop_addedit_item_sellable_desc, $form->generate_yes_no_radio('sellable', intval($item['sellable'])), 'sellable');
                $form_container->output_row($lang->newpoints_shop_addedit_item_pm, $lang->newpoints_shop_addedit_item_pm_desc, $form->generate_text_area('pm', htmlspecialchars_uni($item['pm']), array('id' => 'pm_text')), 'pm');
                $form_container->output_row($lang->newpoints_shop_addedit_item_category . "<em>*</em>", $lang->newpoints_shop_addedit_item_category_desc, $form->generate_select_box('cid', $categories, intval($item['cid']), array('id' => 'cid')), 'cid');
                $args = array($form_container, $form, $item);
                $plugins->run_hooks("newpoints_shop_row", $args);
                $form_container->end();
                $buttons = "";
                $buttons[] = $form->generate_submit_button($lang->newpoints_shop_submit);
                $buttons[] = $form->generate_reset_button($lang->newpoints_shop_reset);
                $form->output_submit_wrapper($buttons);
                $form->end();
            } else {
                if ($mybb->input['action'] == 'inventory') {
                    $page->output_nav_tabs($sub_tabs, 'newpoints_shop_inventory');
                    $uid = (int) $mybb->input['uid'];
                    if ($uid <= 0) {
                        newpoints_shop_messageredirect($lang->newpoints_shop_invalid_user, 1);
                    }
                    $user = get_user($uid);
                    // we're viewing someone else's inventory
                    if (empty($user)) {
                        newpoints_shop_messageredirect($lang->newpoints_shop_invalid_user, 1);
                    }
                    $inventory = @unserialize($user['newpoints_items']);
                    if (!$inventory) {
                        $inventory = array(0);
                    }
                    // Item id is 0 because it doesn't exist, this when we use it in the query we won't show anything
                    // table
                    $table = new Table();
                    $table->construct_header($lang->newpoints_shop_item_icon, array('width' => '10%', 'class' => 'align_center'));
                    $table->construct_header($lang->newpoints_shop_item_name, array('width' => '30%'));
                    $table->construct_header($lang->newpoints_shop_item_price, array('width' => '15%', 'class' => 'align_center'));
                    $table->construct_header($lang->newpoints_shop_item_disporder, array('width' => '15%', 'class' => 'align_center'));
                    $table->construct_header($lang->newpoints_shop_item_action, array('width' => '20%', 'class' => 'align_center'));
                    $query = $db->simple_select('newpoints_shop_items', '*', 'iid IN (' . implode(',', array_unique($inventory)) . ')', array('order_by' => 'disporder', 'order_dir' => 'ASC'));
                    while ($item = $db->fetch_array($query)) {
                        if ($item['infinite'] == 1) {
                            $item['stock'] = $lang->newpoints_shop_infinite;
                        }
                        if ($item['visible'] == 0) {
                            $visible_info = ' (<span style="color: #FF0000;">hidden</span>)';
                        } else {
                            $visible_info = '';
                        }
                        $table->construct_cell(htmlspecialchars_uni($item['icon']) ? '<img src="' . $mybb->settings['bburl'] . '/' . $item['icon'] . '">' : '<img src="' . $mybb->settings['bburl'] . '/images/newpoints/default.png">', array('class' => 'align_center'));
                        $table->construct_cell(htmlspecialchars_uni($item['name']) . " (" . count(array_keys($inventory, $item['iid'])) . ")" . $visible_info . "<br /><small>" . htmlspecialchars_uni($item['description']) . "</small>");
                        $table->construct_cell(newpoints_format_points($item['price']), array('class' => 'align_center'));
                        $table->construct_cell(intval($item['disporder']), array('class' => 'align_center'));
                        // actions column
                        $table->construct_cell("<a href=\"index.php?module=newpoints-shop&amp;action=remove&amp;iid=" . intval($item['iid']) . "&amp;uid=" . (int) $user['uid'] . "\">" . $lang->newpoints_shop_remove . "</a>", array('class' => 'align_center'));
                        $table->construct_row();
                    }
                    if ($table->num_rows() == 0) {
                        $table->construct_cell($lang->newpoints_shop_no_items, array('colspan' => 5));
                        $table->construct_row();
                    }
                    $table->output($lang->newpoints_shop_inventory_of . " " . htmlspecialchars_uni($user['username']));
                }
            }
        }
        $page->output_footer();
        exit;
    }
}
function restfulapi_admin_load()
{
    global $mybb, $db, $page, $lang, $cache;
    if ($page->active_action == RESTFULAPI_URL) {
        $page->add_breadcrumb_item($lang->restfulapi_title);
        $page->output_header($lang->restfulapi_title);
        $result = $db->simple_select("apisettings");
        $action = "config";
        if (isset($mybb->input["action"]) && in_array($mybb->input["action"], array("manage-keys", "add-key"))) {
            $action = $mybb->input["action"];
        }
        $navs = array("config" => array("link" => "index.php?module=config-" . RESTFULAPI_URL, "title" => $lang->restfulapi_config, "description" => $lang->restfulapi_config_description), "manage-keys" => array("link" => "index.php?module=config-" . RESTFULAPI_URL . "&amp;action=manage-keys", "title" => $lang->restfulapi_manage_api_keys, "description" => $lang->restfulapi_manage_api_keys_description), "add-key" => array("link" => "index.php?module=config-" . RESTFULAPI_URL . "&amp;action=add-key", "title" => $lang->restfulapi_add_api_key, "description" => $lang->restfulapi_add_api_key_description));
        $page->output_nav_tabs($navs, $action);
        switch ($action) {
            case "manage-keys":
                if (isset($mybb->input["do"]) && in_array($mybb->input["do"], array("regenerate", "edit", "delete"))) {
                    $do = $mybb->input["do"];
                    if ($do == "edit" && isset($mybb->input["key_id"]) && is_string($mybb->input["key_id"])) {
                        $key_id = (int) $db->escape_string($mybb->input["key_id"]);
                        $result = $db->simple_select("apikeys", "*", "id='{$key_id}'");
                        if ($result->num_rows != 1) {
                            flash_message($lang->restfulapi_key_not_found, "error");
                            admin_redirect("index.php?module=config-restfulapi&amp;action=manage-keys");
                            exit;
                        }
                        if ($mybb->request_method == "post" && isset($mybb->input["apicustomer"]) && is_string($mybb->input["apicustomer"]) && isset($mybb->input["apicomment"]) && is_string($mybb->input["apicomment"]) && isset($mybb->input["maxreq"]) && is_numeric($mybb->input["maxreq"]) && isset($mybb->input["maxreqrate"]) && in_array($mybb->input["maxreqrate"], array("m", "w", "d", "h"))) {
                            $update = array("apicustomer" => $db->escape_string(htmlspecialchars_uni($mybb->input["apicustomer"])), "apicomment" => $db->escape_string(htmlspecialchars_uni($mybb->input["apicomment"])), "maxreq" => (int) $mybb->input["maxreq"], "maxreqrate" => $db->escape_string(htmlspecialchars_uni($mybb->input["maxreqrate"])));
                            $db->update_query("apikeys", $update, "id='{$key_id}'");
                            $db->delete_query("apipermissions", "apikey='{$key_id}'");
                            if (isset($mybb->input["apinames"]) && is_array($mybb->input["apinames"])) {
                                $insert_allowed = array();
                                foreach ($mybb->input["apinames"] as $apiname) {
                                    $insert_allowed[] = array("apikey" => $key_id, "apiname" => $db->escape_string($apiname));
                                }
                                $db->insert_query_multiple("apipermissions", $insert_allowed);
                            }
                            restfulapi_cache_rebuild();
                            flash_message($lang->restfulapi_key_edited_successfully, "success");
                            admin_redirect("index.php?module=config-restfulapi&amp;action=manage-keys");
                        } else {
                            $keyset = $result->fetch_array();
                            $form = new Form("index.php?module=config-" . RESTFULAPI_URL . "&amp;action=manage-keys&amp;do=edit&amp;key_id={$key_id}", "post", "edit");
                            $form_container = new FormContainer($lang->restfulapi_edit_api_key);
                            $form_container->output_row($lang->restfulapi_customer_name . " <em>*</em>", $lang->restfulapi_customer_name_description, $form->generate_text_box('apicustomer', htmlspecialchars_uni($keyset["apicustomer"]), array('id' => 'apicustomer')), 'apicustomer');
                            $rate_types = array("h" => $lang->restfulapi_per_hour, "d" => $lang->restfulapi_per_day, "w" => $lang->restfulapi_per_week, "m" => $lang->restfulapi_per_month);
                            $form_container->output_row($lang->restfulapi_max_requests . " <em>*</em>", $lang->restfulapi_max_requests_description, $form->generate_text_box('maxreq', htmlspecialchars_uni($keyset["maxreq"]), array('id' => 'maxreq')) . " " . $form->generate_select_box('maxreqrate', $rate_types, htmlspecialchars_uni($keyset["maxreqrate"]), array('id' => 'maxreqrate')), 'maxreq');
                            $form_container->output_row($lang->restfulapi_comment, $lang->restfulapi_comment_description, $form->generate_text_area('apicomment', htmlspecialchars_uni($keyset["apicomment"]), array('id' => 'apicomment')), 'apicomment');
                            $apis = glob(RESTFULAPI_PATH . "api/*api.class.php");
                            $presentable_apis = array();
                            foreach ($apis as $key => $value) {
                                $value = htmlspecialchars_uni(str_replace(array(RESTFULAPI_PATH . "api/", "api.class.php"), "", $value));
                                $presentable_apis[$value] = $value;
                            }
                            $selected = array();
                            // reminder, $key_id has already been escaped!
                            $result = $db->simple_select("apipermissions", "*", "apikey='{$key_id}'");
                            while ($apipermission = $db->fetch_array($result)) {
                                $selected[] = $apipermission["apiname"];
                            }
                            $form_container->output_row($lang->restfulapi_select_allowed_apis, $lang->restfulapi_select_allowed_apis_description, $form->generate_select_box('apinames[]', $presentable_apis, $selected, array('id' => 'apinames', 'multiple' => true, 'size' => 10)), 'apinames');
                            $form_container->end();
                            $buttons[] = $form->generate_submit_button($lang->restfulapi_edit_api_key);
                            $form->output_submit_wrapper($buttons);
                            $form->end();
                        }
                    } elseif ($do == "delete" && isset($mybb->input["key_id"]) && isset($mybb->input["my_post_key"]) && verify_post_check($mybb->input["my_post_key"])) {
                        $key_id = $db->escape_string($mybb->input["key_id"]);
                        if ($db->simple_select("apikeys", "*", "id='{$key_id}'")->num_rows == 1) {
                            $db->delete_query("apipermissions", "apikey='{$key_id}'");
                            $db->delete_query("apikeys", "id='{$key_id}'");
                            restfulapi_cache_rebuild();
                            flash_message($lang->restfulapi_key_deleted_successfully, "success");
                        } else {
                            flash_message($lang->restfulapi_key_not_found, "error");
                        }
                        admin_redirect("index.php?module=config-restfulapi&amp;action=manage-keys");
                    } elseif ($do == "regenerate" && isset($mybb->input["key_id"]) && isset($mybb->input["my_post_key"]) && verify_post_check($mybb->input["my_post_key"])) {
                        $key_id = $db->escape_string($mybb->input["key_id"]);
                        if ($db->simple_select("apikeys", "*", "id='{$key_id}'")->num_rows == 1) {
                            $apikey = restfulapi_generate_key();
                            /* can't figure out a better way to generate a random yet never-generated-before API key than this one */
                            while ($db->simple_select("apikeys", "*", "apikey='{$apikey}'")->num_rows != 0) {
                                $apikey = restfulapi_generate_key();
                            }
                            $update = array("apikey" => $db->escape_string(htmlspecialchars_uni($apikey)));
                            $db->update_query("apikeys", $update, "id='{$key_id}'");
                            restfulapi_cache_rebuild();
                            flash_message($lang->restfulapi_key_regenerated_successfully, "success");
                        } else {
                            flash_message($lang->restfulapi_key_not_found, "error");
                        }
                        admin_redirect("index.php?module=config-restfulapi&amp;action=manage-keys");
                    }
                } else {
                    $restfulapi_cache = $cache->read("restfulapi");
                    $apikeysets = $restfulapi_cache["keys"];
                    $table = new Table();
                    $table->construct_header($lang->restfulapi_customer, array("width" => "15%"));
                    $table->construct_header($lang->restfulapi_api_key, array("class" => "align_center", "width" => "29%"));
                    $table->construct_header($lang->restfulapi_comment, array("class" => "align_center", "width" => "30%"));
                    $table->construct_header($lang->restfulapi_usage, array("class" => "align_center", "width" => "5%"));
                    $table->construct_header($lang->restfulapi_controls, array("class" => "align_center", "width" => "21%", "colspan" => 3));
                    if (count($apikeysets) == 0) {
                        $table->construct_cell($lang->sprintf($lang->restfulapi_no_api_key, '<a href="index.php?module=config-restfulapi&action=add-key">', '</a>'), array("class" => "first", "colspan" => 5));
                        $table->construct_row();
                    } else {
                        // TODO : pagination maybe ?
                        foreach ($apikeysets as $key => $keyset) {
                            $table->construct_cell("<b>" . htmlspecialchars_uni($keyset['apicustomer']) . "</b>");
                            $table->construct_cell(htmlspecialchars_uni($keyset['apikey']));
                            $table->construct_cell(htmlspecialchars_uni($keyset['apicomment']));
                            $table->construct_cell(htmlspecialchars_uni($keyset['access']), array("class" => "align_center"));
                            $table->construct_cell("<a href=\"index.php?module=config-restfulapi&amp;action=manage-keys&amp;do=regenerate&amp;key_id={$keyset['id']}&my_post_key={$mybb->post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->restfulapi_regenerate_api_key_confirmation}')\">{$lang->restfulapi_regenerate_api_key}</a>", array("class" => "align_center", "width" => "9%"));
                            $table->construct_cell("<a href=\"index.php?module=config-restfulapi&amp;action=manage-keys&amp;do=edit&amp;key_id={$keyset['id']}\">{$lang->restfulapi_edit}</a>", array("class" => "align_center", "width" => "6%"));
                            $table->construct_cell("<a href=\"index.php?module=config-restfulapi&amp;action=manage-keys&amp;do=delete&amp;key_id={$keyset['id']}&my_post_key={$mybb->post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$lang->restfulapi_delete_confirm}')\">{$lang->restfulapi_delete}</a>", array("class" => "align_center", "width" => "6%"));
                            $table->construct_row();
                        }
                    }
                    $table->output($lang->restfulapi_manage_api_keys);
                }
                break;
            case "add-key":
                if ($mybb->request_method == "post" && isset($mybb->input["apicustomer"]) && is_string($mybb->input["apicustomer"]) && isset($mybb->input["apicomment"]) && is_string($mybb->input["apicomment"]) && isset($mybb->input["maxreq"]) && is_numeric($mybb->input["maxreq"]) && isset($mybb->input["maxreqrate"]) && in_array($mybb->input["maxreqrate"], array("m", "w", "d", "h"))) {
                    $apikey = restfulapi_generate_key();
                    /* can't figure out a better way to generate a random yet never-generated-before API key than this one */
                    while ($db->simple_select("apikeys", "*", "apikey='{$db->escape_string($apikey)}'")->num_rows != 0) {
                        $apikey = restfulapi_generate_key();
                    }
                    $insert = array("apicustomer" => $db->escape_string(htmlspecialchars_uni($mybb->input["apicustomer"])), "apicomment" => $db->escape_string(htmlspecialchars_uni($mybb->input["apicomment"])), "access" => 0, "maxreq" => (int) $mybb->input["maxreq"], "maxreqrate" => $db->escape_string(htmlspecialchars_uni($mybb->input["maxreqrate"])), "apikey" => $db->escape_string(htmlspecialchars_uni($apikey)));
                    $apikeyid = $db->insert_query("apikeys", $insert);
                    if (isset($mybb->input["apinames"]) && is_array($mybb->input["apinames"])) {
                        $insert_allowed = array();
                        foreach ($mybb->input["apinames"] as $apiname) {
                            $insert_allowed[] = array("apikey" => $db->escape_string($apikeyid), "apiname" => $db->escape_string($apiname));
                        }
                        $db->insert_query_multiple("apipermissions", $insert_allowed);
                    }
                    restfulapi_cache_rebuild();
                    flash_message($lang->sprintf($lang->restfulapi_generated_successfully, $apikey, $mybb->input["apicustomer"]), 'success');
                    admin_redirect("index.php?module=config-restfulapi&amp;action=manage-keys");
                } else {
                    $form = new Form("index.php?module=config-" . RESTFULAPI_URL . "&amp;action=add-key", "post", "add");
                    $form_container = new FormContainer($lang->restfulapi_add_api_key);
                    $form_container->output_row($lang->restfulapi_customer_name . " <em>*</em>", $lang->restfulapi_customer_name_description, $form->generate_text_box('apicustomer', '', array('id' => 'apicustomer')), 'apicustomer');
                    $rate_types = array("h" => $lang->restfulapi_per_hour, "d" => $lang->restfulapi_per_day, "w" => $lang->restfulapi_per_week, "m" => $lang->restfulapi_per_month);
                    $form_container->output_row($lang->restfulapi_max_requests . " <em>*</em>", $lang->restfulapi_max_requests_description, $form->generate_text_box('maxreq', '0', array('id' => 'maxreq')) . " " . $form->generate_select_box('maxreqrate', $rate_types, "m", array('id' => 'maxreqrate')), 'maxreq');
                    $form_container->output_row($lang->restfulapi_comment, $lang->restfulapi_comment_description, $form->generate_text_area('apicomment', '', array('id' => 'apicomment')), 'apicomment');
                    $apis = glob(RESTFULAPI_PATH . "api/*api.class.php");
                    $presentable_apis = array();
                    foreach ($apis as $key => $value) {
                        $value = htmlspecialchars_uni(str_replace(array(RESTFULAPI_PATH . "api/", "api.class.php"), "", $value));
                        $presentable_apis[$value] = $value;
                    }
                    $form_container->output_row($lang->restfulapi_select_allowed_apis . " <em>*</em>", $lang->restfulapi_select_allowed_apis_description, $form->generate_select_box('apinames[]', $presentable_apis, array_keys($presentable_apis), array('id' => 'apinames', 'multiple' => true, 'size' => 10)), 'apinames');
                    $form_container->end();
                    $buttons[] = $form->generate_submit_button($lang->restfulapi_generate_api_key);
                    $form->output_submit_wrapper($buttons);
                    $form->end();
                }
                break;
            default:
                $apilist = $cache->read("restfulapilist");
                // routine to install newly detected APIs, and activate them if needed
                restfulapi_apilist_activate();
                if ($mybb->request_method == "post") {
                    // we delete all the previously-deactivated options
                    $db->delete_query("apisettings", "apiaction='deactivate'");
                    $inserts = array();
                    foreach ($mybb->input as $key => $input) {
                        if (substr($key, 0, 7) == "option_" && $input == "1") {
                            // replace first occurrence of 'option_' with '' in case the option name is 'option_', so that 'option_option_' won't be all replaced into an empty string
                            // yeah I know, probably would never happen but we never know
                            $option = preg_replace('/option\\_/', '', $key, 1);
                            restfulapi_api_activate($option);
                        } elseif (substr($key, 0, 7) == "option_" && $input == "0") {
                            $option = preg_replace('/option\\_/', '', $key, 1);
                            restfulapi_api_deactivate($option);
                        }
                    }
                    flash_message($lang->restfulapi_saved_config, "success");
                    admin_redirect("index.php?module=config-restfulapi");
                } else {
                    $result = $db->simple_select("apisettings", "*", "apiaction='deactivate'");
                    $deactivatedapis = array();
                    while ($apiarray = $db->fetch_array($result)) {
                        $deactivatedapis[] = $apiarray["apivalue"];
                    }
                    if (count($apilist) == 0) {
                        echo '<div class="notice">' . $lang->sprintf($lang->restfulapi_no_api, '<a href="index.php?module=config-restfulapi&action=add-key">', '</a>') . '</div>';
                    } else {
                        $form = new Form("index.php?module=config-" . RESTFULAPI_URL, "post", "config");
                        $form_container = new FormContainer($lang->restfulapi_config);
                        $table = new Table();
                        foreach ($apilist as $api => $info_array) {
                            require_once RESTFULAPI_PATH . "api/" . $api . "api.class.php";
                            $api = htmlspecialchars_uni($api);
                            $apiclass = $api . "api";
                            $api_instance = new $apiclass();
                            $info_array = $api_instance->info();
                            $name = isset($info_array["name"]) && is_string($info_array["name"]) ? htmlspecialchars_uni($info_array["name"]) . " : " . $api : $api;
                            $description = isset($info_array["description"]) && is_string($info_array["description"]) ? htmlspecialchars_uni($info_array["description"]) : $lang->restfulapi_config_on_off_description;
                            $setting_code = $form->generate_on_off_radio("option_" . $api, in_array($api, $deactivatedapis) ? 0 : 1, true, array('id' => $api . '_yes'), array('id' => $api . '_no'));
                            $form_container->output_row($name, $description, $setting_code, '', array(), array('id' => 'row_' . $api));
                        }
                        $form_container->end();
                        $buttons[] = $form->generate_submit_button($lang->restfulapi_save_config);
                        $form->output_submit_wrapper($buttons);
                        $form->end();
                    }
                }
                break;
        }
        $page->output_footer();
    }
}
                $actions .= '<img src="spamalyser_img/action_' . $action . '.gif" title="' . $lang->{$lang_title} . '" alt="' . $lang->{$lang_alt} . '" style="font-size: smaller;" />';
            }
            if ($actions) {
                $actions = '<br />' . $actions;
            }
            $table->construct_cell('<a href="' . SPAMALYSER_URL . '&amp;action=view&amp;lid=' . $logitem['lid'] . '">' . number_format($logitem['score'], 7) . '</a>' . $actions, array('class' => 'align_center'));
            $table->construct_row();
        }
    }
    if ($table->num_rows() == 0) {
        $table->construct_cell($lang->no_spamalyserlogs, array('colspan' => '4'));
        $table->construct_row();
    }
    $table->output($lang->spamalyser_logs);
    if ($pages > 1) {
        echo draw_admin_pagination($pagenum, $perpage, $entries, SPAMALYSER_URL . $urlargs) . '<br />';
    }
    // HTML display
    $sortbysel = array($sortby => ' selected="selected"');
    $ordersel = array($order => ' selected="selected"');
    $scorecmpsel = array($scorecmp => ' selected="selected"');
    $form = new Form('index.php', 'get');
    echo $form->generate_hidden_field('module', 'tools' . ($mybb->version_code >= 1500 ? '-' : '/') . 'spamalyserlog');
    $form_container = new FormContainer($lang->filter_spamalyser_logs);
    $form_container->output_row($lang->sort_by, '', $form->generate_select_box('sortby', array('dateline' => $lang->date, 'username' => $lang->username, 'score' => $lang->weighting), $sortby, array('id' => 'sortby')) . ' ' . $lang->in . ' ' . $form->generate_select_box('order', array('asc' => $lang->asc, 'desc' => $lang->desc), $order, array('id' => 'order')) . ' ' . $lang->order, 'order');
    $form_container->output_row($lang->results_per_page, '', $form->generate_text_box('perpage', $perpage, array('id' => 'perpage')), 'perpage');
    $form_container->end();
    $form->output_submit_wrapper(array($form->generate_submit_button($lang->filter_spamalyser_logs)));
    $form->end();
    $page->output_footer();
}
function PHP_files_cleaner_actions()
{
    global $lang, $mybb, $sub_tabs;
    $lang->load('PHP_files_cleaner_acp');
    $sub_tabs['PHP_files_cleaner'] = array('title' => $lang->PHP_files_cleaner, 'link' => 'index.php?module=tools-system_health&amp;action=clean_PHP_files', 'description' => $lang->PHP_files_cleaner_info);
    if ($mybb->input['action'] == 'do_clean_PHP_files' && $mybb->request_method == 'post') {
        $errors = array();
        $lead = $mybb->get_input('leading', MyBB::INPUT_ARRAY);
        $trail = $mybb->get_input('trailing', MyBB::INPUT_ARRAY);
        if (!$mybb->settings['PHP_files_cleaner_leading'] && !$mybb->settings['PHP_files_cleaner_trailing']) {
            $errors[] = $lang->PHP_files_cleaner_nothing_enabled;
        }
        if (empty($lead) && empty($trail)) {
            $errors[] = $lang->PHP_files_cleaner_nothing_chosen;
        }
        if (!$errors) {
            $leadandtrail = array_unique(array_merge($lead, $trail));
            $nonchangeable = array();
            foreach ($leadandtrail as $filename) {
                $fullfilename = MYBB_ROOT . $filename;
                if (is_readable($fullfilename) && is_writable($fullfilename)) {
                    $file = file_get_contents($fullfilename);
                    // Remove BOM and leading whitespace
                    if ($mybb->settings['PHP_files_cleaner_leading'] && in_array($filename, $lead)) {
                        $file = preg_replace('/^\\x{FEFF}?\\s*/u', '', $file);
                    }
                    // Remove ending tag and trailing whitespace
                    if ($mybb->settings['PHP_files_cleaner_trailing'] && in_array($filename, $trail)) {
                        $file = preg_replace('/(\\s*\\?>)?\\s*$/', '', $file);
                    }
                    file_put_contents($fullfilename, $file);
                } else {
                    $nonchangeable[] = htmlspecialchars_uni($filename);
                }
            }
            if ($nonchangeable) {
                flash_message($lang->sprintf($lang->PHP_files_cleaner_nonchangeable, implode($lang->comma, $nonchangeable)), 'error');
            } else {
                flash_message($lang->PHP_files_cleaner_success, 'success');
            }
            admin_redirect('index.php?module=tools-system_health&amp;action=clean_PHP_files');
        } else {
            $mybb->input['action'] = 'clean_PHP_files';
        }
    }
    if ($mybb->input['action'] == 'clean_PHP_files') {
        global $page;
        $page->add_breadcrumb_item($lang->PHP_files_cleaner);
        $page->output_header($lang->PHP_files_cleaner);
        $page->output_nav_tabs($sub_tabs, 'PHP_files_cleaner');
        if (!empty($errors)) {
            $page->output_inline_error($errors);
        }
        $table = new Table();
        if (!$mybb->settings['PHP_files_cleaner_leading'] && !$mybb->settings['PHP_files_cleaner_trailing']) {
            $table->construct_cell($lang->PHP_files_cleaner_nothing_enabled);
            $table->construct_row();
        } else {
            $leading = $trailing = array();
            $diriterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(MYBB_ROOT));
            $phpfiles = new RegexIterator($diriterator, '/\\.php$/i', RegexIterator::GET_MATCH);
            foreach ($phpfiles as $filename => $info) {
                if (is_readable($filename)) {
                    $contents = file_get_contents($filename);
                    if ($mybb->settings['PHP_files_cleaner_leading'] && preg_match('/^\\x{FEFF}?\\s*/u', $contents, $matches) && $matches[0]) {
                        $leading[] = $filename;
                    }
                    if ($mybb->settings['PHP_files_cleaner_trailing'] && preg_match('/(\\s*\\?>)?\\s*$/', $contents, $matches) && $matches[0]) {
                        $trailing[] = $filename;
                    }
                }
            }
            // Filenames sorted by the number of issues
            $cnt = array_count_values(array_merge($leading, $trailing));
            arsort($cnt);
            $allfiles = array_keys($cnt);
            if (empty($allfiles)) {
                $table->construct_cell($lang->PHP_files_cleaner_nothing_found);
                $table->construct_row();
            } else {
                $form = new Form('index.php?module=tools-system_health&amp;action=do_clean_PHP_files', 'post');
                $table->construct_header($lang->PHP_files_cleaner_filename);
                $table->construct_header($lang->PHP_files_cleaner_leading, array('class' => 'align_center'));
                $table->construct_header($lang->PHP_files_cleaner_trailing, array('class' => 'align_center'));
                $table->construct_header($form->generate_check_box('allbox', 1, '', array('class' => 'checkall', 'checked' => 1)), array('style' => 'text-align: right;'));
                foreach ($allfiles as $filename) {
                    $clean_filename = htmlspecialchars_uni(str_replace(MYBB_ROOT, '', $filename));
                    $leading_cbox = in_array($filename, $leading) ? $form->generate_check_box('leading[]', $clean_filename, '', array('checked' => 1)) : '';
                    $trailing_cbox = in_array($filename, $trailing) ? $form->generate_check_box('trailing[]', $clean_filename, '', array('checked' => 1)) : '';
                    $table->construct_cell($clean_filename);
                    $table->construct_cell($leading_cbox, array('class' => 'align_center'));
                    $table->construct_cell($trailing_cbox, array('class' => 'align_center'));
                    $table->construct_cell('');
                    $table->construct_row();
                }
            }
        }
        $table->output($lang->PHP_files_cleaner);
        if (!empty($allfiles)) {
            $buttons[] = $form->generate_submit_button($lang->PHP_files_cleaner_clean, array('name' => 'clean'));
            $form->output_submit_wrapper($buttons);
            $form->end();
        }
        $page->output_footer();
    }
}
Example #16
0
    $query = $db->simple_select('threadprefixes', 'pid, prefix');
    if ($db->num_rows($query) > 0) {
        $thread_prefixes = array('-1' => $lang->no_change, '0' => $lang->no_prefix);
        while ($prefix = $db->fetch_array($query)) {
            $thread_prefixes[$prefix['pid']] = $prefix['prefix'];
        }
        $form_container->output_row($lang->apply_thread_prefix . " <em>*</em>", '', $form->generate_select_box('threadprefix', $thread_prefixes, $mybb->input['threadprefix'], array('id' => 'threadprefix')), 'threadprefix');
    }
    $form_container->output_row($lang->new_subject . " <em>*</em>", $lang->new_subject_desc, $form->generate_text_box('newsubject', $mybb->input['newsubject']));
    $form_container->end();
    $form_container = new FormContainer($lang->add_new_reply);
    $form_container->output_row($lang->add_new_reply, $lang->add_new_reply_desc, $form->generate_text_area('newreply', $mybb->input['newreply'], array('id' => 'newreply')), 'newreply');
    $form_container->output_row($lang->reply_subject, $lang->reply_subject_desc, $form->generate_text_box('newreplysubject', $mybb->input['newreplysubject'], array('id' => 'newreplysubject')), 'newreplysubject');
    $form_container->end();
    $buttons[] = $form->generate_submit_button($lang->save_post_tool);
    $form->output_submit_wrapper($buttons);
    $form->end();
    $page->output_footer();
}
if (!$mybb->input['action']) {
    $plugins->run_hooks("admin_config_mod_tools_start");
    $page->output_header($lang->mod_tools . " - " . $lang->thread_tools);
    $sub_tabs['thread_tools'] = array('title' => $lang->thread_tools, 'link' => "index.php?module=config-mod_tools", 'description' => $lang->thread_tools_desc);
    $sub_tabs['add_thread_tool'] = array('title' => $lang->add_new_thread_tool, 'link' => "index.php?module=config-mod_tools&amp;action=add_thread_tool");
    $sub_tabs['post_tools'] = array('title' => $lang->post_tools, 'link' => "index.php?module=config-mod_tools&amp;action=post_tools");
    $sub_tabs['add_post_tool'] = array('title' => $lang->add_new_post_tool, 'link' => "index.php?module=config-mod_tools&amp;action=add_post_tool");
    $page->output_nav_tabs($sub_tabs, 'thread_tools');
    $table = new Table();
    $table->construct_header($lang->title);
    $table->construct_header($lang->controls, array('class' => "align_center", 'colspan' => 2));
    $query = $db->simple_select('modtools', 'tid, name, description, type', "type='t'", array('order_by' => 'name'));
Example #17
0
function threadfields_add_edit_handler(&$tf, $update)
{
    global $mybb, $page, $lang, $db, $plugins, $sub_tabs;
    global $form;
    if ($update) {
        $title = $lang->edit_threadfield;
    } else {
        $title = $lang->add_threadfield;
    }
    $props = xthreads_threadfields_props();
    if ($mybb->request_method == 'post') {
        foreach ($props as $field => &$prop) {
            if ($field == 'field') {
                $field = 'newfield';
            }
            // cause you can't "continue" in a switch statement, lol...
            if ($field == 'forums' || $field == 'editable_gids' || $field == 'viewable_gids' || $field == 'filemaxsize' || $field == 'multival') {
                continue;
            }
            if ($prop['datatype'] == 'string') {
                $mybb->input[$field] = trim($mybb->input[$field]);
            } else {
                $mybb->input[$field] = (int) $mybb->input[$field];
            }
        }
        $mybb->input['textmask'] = str_replace("", '', $mybb->input['textmask']);
        $mybb->input['filemaxsize'] = xthreads_size_to_bytes($mybb->input['filemaxsize']);
        $mybb->input['fileimage_mindim'] = strtolower(trim($mybb->input['fileimage_mindim']));
        $mybb->input['fileimage_maxdim'] = strtolower(trim($mybb->input['fileimage_maxdim']));
        if (!xthreads_empty($mybb->input['formatmap'])) {
            $fm = array();
            $fms = str_replace("{\n}", "\r", str_replace("\r", '', $mybb->input['formatmap']));
            foreach (explode("\n", $fms) as $map) {
                $map = str_replace("\r", "\n", $map);
                $p = strpos($map, '{|}');
                if (!$p) {
                    continue;
                }
                // can't be zero index either - blank display format used for that
                $fmkey = substr($map, 0, $p);
                if (isset($fm[$fmkey])) {
                    $errors[] = $lang->sprintf($lang->error_dup_formatmap, htmlspecialchars_uni($fmkey));
                    unset($fm);
                    break;
                }
                $fm[$fmkey] = substr($map, $p + 3);
            }
            if (isset($fm)) {
                $mybb->input['formatmap'] = serialize($fm);
            }
        }
        if (is_array($mybb->input['forums'])) {
            $mybb->input['forums'] = implode(',', array_unique(array_map('intval', array_map('trim', $mybb->input['forums']))));
            if (empty($mybb->input['forums'])) {
                $mybb->input['forums'] = '';
            }
        } else {
            $mybb->input['forums'] = trim($mybb->input['forums']);
            if ($mybb->input['forums']) {
                $mybb->input['forums'] = implode(',', array_unique(array_map('intval', array_map('trim', explode(',', $mybb->input['forums'])))));
            }
            if (!$mybb->input['forums']) {
                $mybb->input['forums'] = '';
            }
        }
        if ($mybb->input['editable'] == '99') {
            if (is_array($mybb->input['editable_gids'])) {
                $mybb->input['editable_gids'] = implode(',', array_unique(array_map('intval', array_map('trim', $mybb->input['editable_gids']))));
                if (empty($mybb->input['editable_gids'])) {
                    $mybb->input['editable_gids'] = '';
                }
            } else {
                $mybb->input['editable_gids'] = trim($mybb->input['editable_gids']);
                if ($mybb->input['editable_gids']) {
                    $mybb->input['editable_gids'] = implode(',', array_unique(array_map('intval', array_map('trim', explode(',', $mybb->input['editable_gids'])))));
                }
                if (!$mybb->input['editable_gids']) {
                    $mybb->input['editable_gids'] = '';
                }
            }
            if ($mybb->input['editable_gids']) {
                $mybb->input['editable'] = 0;
            } else {
                $mybb->input['editable'] = XTHREADS_EDITABLE_NONE;
            }
            // no group ids selected
        } else {
            $mybb->input['editable'] = min_max((int) $mybb->input['editable'], XTHREADS_EDITABLE_ALL, XTHREADS_EDITABLE_NONE);
            $mybb->input['editable_gids'] = '';
        }
        $mybb->input['hidefield'] = 0;
        foreach (array('input' => XTHREADS_HIDE_INPUT, 'thread' => XTHREADS_HIDE_THREAD) as $k => $v) {
            if ($mybb->input['hidefield_' . $k]) {
                $mybb->input['hidefield'] |= $v;
            }
        }
        if (!xthreads_empty($mybb->input['editable_values'])) {
            $ev = array();
            $evs = str_replace("{\n}", "\r", str_replace("\r", '', $mybb->input['editable_values']));
            foreach (explode("\n", $evs) as $editable_value) {
                $editable_value = str_replace("\r", "\n", $editable_value);
                $p = strpos($editable_value, '{|}');
                if ($p === false) {
                    continue;
                }
                $evkey = substr($editable_value, 0, $p);
                if (isset($ev[$evkey])) {
                    $errors[] = $lang->sprintf($lang->error_dup_editable_value, htmlspecialchars_uni($evkey));
                    unset($ev);
                    break;
                }
                $ev[$evkey] = array_unique(array_map('intval', explode(',', substr($editable_value, $p + 3))));
                // remove '0' element
                if (($zerorm = array_search(0, $ev[$evkey])) !== false) {
                    unset($ev[$evkey][$zerorm]);
                }
            }
            if (isset($ev)) {
                $mybb->input['editable_values'] = serialize($ev);
            }
        }
        if (is_array($mybb->input['viewable_gids'])) {
            $mybb->input['viewable_gids'] = implode(',', array_unique(array_map('intval', array_map('trim', $mybb->input['viewable_gids']))));
            if (empty($mybb->input['viewable_gids'])) {
                $mybb->input['viewable_gids'] = '';
            }
        } else {
            $mybb->input['viewable_gids'] = trim($mybb->input['viewable_gids']);
            if ($mybb->input['viewable_gids']) {
                $mybb->input['viewable_gids'] = implode(',', array_unique(array_map('intval', array_map('trim', explode(',', $mybb->input['viewable_gids'])))));
            }
            if (!$mybb->input['viewable_gids']) {
                $mybb->input['viewable_gids'] = '';
            }
        }
        $mybb->input['sanitize'] = min_max((int) $mybb->input['sanitize'], XTHREADS_SANITIZE_HTML, XTHREADS_SANITIZE_NONE);
        //if($mybb->input['sanitize'] == XTHREADS_SANITIZE_PARSER) {
        $parser_opts = array('parser_nl2br' => XTHREADS_SANITIZE_PARSER_NL2BR, 'parser_nobadw' => XTHREADS_SANITIZE_PARSER_NOBADW, 'parser_html' => XTHREADS_SANITIZE_PARSER_HTML, 'parser_mycode' => XTHREADS_SANITIZE_PARSER_MYCODE, 'parser_mycodeimg' => XTHREADS_SANITIZE_PARSER_MYCODEIMG, 'parser_mycodevid' => XTHREADS_SANITIZE_PARSER_VIDEOCODE, 'parser_smilies' => XTHREADS_SANITIZE_PARSER_SMILIES);
        foreach ($parser_opts as $opt => $n) {
            if ($mybb->input[$opt]) {
                $mybb->input['sanitize'] |= $n;
            }
        }
        //}
        $mybb->input['inputtype'] = min_max((int) $mybb->input['inputtype'], XTHREADS_INPUT_TEXT, XTHREADS_INPUT_FILE_URL);
        if (xthreads_empty($mybb->input['title'])) {
            $errors[] = $lang->error_missing_title;
        }
        if (xthreads_empty($mybb->input['newfield'])) {
            $errors[] = $lang->error_missing_field;
        }
        if (!xthreads_empty($mybb->input['textmask'])) {
            // test for bad regex
            xthreads_catch_errorhandler();
            @preg_match('~' . str_replace('~', '\\~', $mybb->input['textmask']) . '~si', 'testvalue');
            restore_error_handler();
            if (!empty($GLOBALS['_previous_error'])) {
                $errmsg =& $GLOBALS['_previous_error'][1];
                if (substr($errmsg, 0, 12) == 'preg_match()') {
                    $p = strpos($errmsg, ':', 12);
                    if ($p) {
                        $errmsg = trim(substr($errmsg, $p + 1));
                    } else {
                        $errmsg = trim(substr($errmsg, 12));
                    }
                    $errors[] = $lang->sprintf($lang->error_bad_textmask, $errmsg);
                }
            }
        }
        switch ($mybb->input['inputtype']) {
            case XTHREADS_INPUT_SELECT:
            case XTHREADS_INPUT_RADIO:
            case XTHREADS_INPUT_CHECKBOX:
                $mybb->input['sanitize'] = $mybb->input['inputtype'] == XTHREADS_INPUT_SELECT ? XTHREADS_SANITIZE_HTML : XTHREADS_SANITIZE_NONE;
                $mybb->input['textmask'] = '';
                // must have value defined
                if (xthreads_empty($mybb->input['vallist'])) {
                    $errors[] = $lang->error_require_valllist;
                }
                break;
            case XTHREADS_INPUT_TEXTAREA:
            case XTHREADS_INPUT_FILE:
            case XTHREADS_INPUT_FILE_URL:
                $mybb->input['allowfilter'] = 0;
                $mybb->input['vallist'] = '';
                break;
            case XTHREADS_INPUT_TEXT:
                $mybb->input['vallist'] = '';
        }
        if ($mybb->input['multival_enable'] || $mybb->input['inputtype'] == XTHREADS_INPUT_CHECKBOX) {
            if (xthreads_empty($mybb->input['multival'])) {
                $errors[] = $lang->error_require_multival_delimiter;
            }
            // force textual datatype
            if ($mybb->input['datatype'] !== XTHREADS_DATATYPE_TEXT) {
                $mybb->input['datatype'] = XTHREADS_DATATYPE_TEXT;
            }
        } else {
            $mybb->input['multival'] = '';
        }
        if ($mybb->input['use_formhtml']) {
            if (xthreads_empty($mybb->input['formhtml'])) {
                $errors[] = $lang->error_require_formhtml;
            }
        } else {
            $mybb->input['formhtml'] = '';
        }
        if ($mybb->input['datatype'] !== XTHREADS_DATATYPE_TEXT) {
            // verify value list if applicable
            /* if($mybb->input['inputtype'] == XTHREADS_INPUT_SELECT || $mybb->input['inputtype'] == XTHREADS_INPUT_RADIO) {
            				// maybe we won't do this...
            			} */
            $mybb->input['datatype'] = min_max($mybb->input['datatype'], XTHREADS_DATATYPE_TEXT, XTHREADS_DATATYPE_FLOAT);
        }
        $mybb->input['fileimage'] = '';
        if ($mybb->input['filereqimg']) {
            if ($mybb->input['fileimage_mindim'] && !preg_match('~^[0-9]+x[0-9]+$~', $mybb->input['fileimage_mindim'])) {
                $errors[] = $lang->error_invalid_min_dims;
            }
            if ($mybb->input['fileimage_maxdim'] && !preg_match('~^[0-9]+x[0-9]+$~', $mybb->input['fileimage_maxdim'])) {
                $errors[] = $lang->error_invalid_max_dims;
            }
            if ($mybb->input['fileimage_mindim']) {
                $mybb->input['fileimage'] = $mybb->input['fileimage_mindim'];
            } else {
                $mybb->input['fileimage'] = '0x0';
            }
            if ($mybb->input['fileimage_maxdim']) {
                $mybb->input['fileimage'] .= '|' . $mybb->input['fileimage_maxdim'];
            }
        }
        //if($mybb->input['fileimgthumbs']) {
        // TODO: verify format
        //if(!preg_match('~^[0-9]+x[0-9]+(\\|[0-9]+x[0-9]+)*$~', $mybb->input['fileimgthumbs']))
        //	$errors[] = $lang->error_invalid_thumb_dims;
        //}
        if ($update) {
            // check that sent field name is valid
            // and whilst we're here, check for bad conversions (eg file -> textbox)
            $oldfield = $db->fetch_array($db->simple_select('threadfields', '*', 'field="' . $db->escape_string($mybb->input['field']) . '"'));
            if (empty($oldfield)) {
                $errors[] = $lang->error_bad_old_field;
            } else {
                switch ($oldfield['inputtype']) {
                    case XTHREADS_INPUT_FILE:
                    case XTHREADS_INPUT_FILE_URL:
                        if ($oldfield['inputtype'] != $mybb->input['inputtype']) {
                            $errors['error_invalid_inputtype'] = $lang->error_invalid_inputtype;
                        }
                        break;
                    default:
                        if ($mybb->input['inputtype'] == XTHREADS_INPUT_FILE || $mybb->input['inputtype'] == XTHREADS_INPUT_FILE_URL) {
                            $errors['error_invalid_inputtype'] = $lang->error_invalid_inputtype;
                        }
                }
            }
        }
        if (!xthreads_empty($mybb->input['newfield'])) {
            if ($mybb->input['newfield'] == 'tid') {
                $errors[] = $lang->error_field_name_tid;
            } elseif (strlen($mybb->input['newfield']) > 50) {
                $errors[] = $lang->error_field_name_too_long;
            } elseif (!preg_match('~^[a-zA-Z0-9_]+$~', $mybb->input['newfield'])) {
                $errors[] = $lang->error_field_name_invalid;
            } elseif (isset($mybb->input['newfield'][2]) && $mybb->input['newfield'][0] == '_' && $mybb->input['newfield'][1] == '_') {
                // don't allow fields starting with "__" (reserved for special use)
                // in hindsight, special uses (eg filters) really should've used something like '~' so we don't need to do this, but it's too late now
                $errors[] = $lang->error_field_name_reserved;
            } elseif (!$update || $mybb->input['field'] != $mybb->input['newfield']) {
                $ftest = $db->fetch_field($db->simple_select('threadfields', 'field', 'field="' . $db->escape_string($mybb->input['newfield']) . '"'), 'field');
                if (!xthreads_empty($ftest)) {
                    $errors[] = $lang->error_field_name_in_use;
                }
            }
        }
        // check for syntax errors in conditionals
        // this is a bit tricky because we need the cache function to build the conditional for checking
        if ($update) {
            $test_tf = array_merge($oldfield, $mybb->input);
        } else {
            $test_tf = $mybb->input;
        }
        xthreads_buildtfcache_parseitem($test_tf);
        // test for bad conditional syntax
        foreach (array('defaultval', 'blankval', 'inputformat', 'inputvalidate', 'dispformat', 'dispitemformat', 'unviewableval', 'formhtml', 'formhtml_item') as $condcheck) {
            if ($test_tf[$condcheck] && !xthreads_check_evalstr($test_tf[$condcheck])) {
                if ($condcheck == 'formhtml_item') {
                    $condcheck = 'formhtml';
                }
                $tflangkey = 'threadfields_' . $condcheck;
                $errors[] = $lang->sprintf($lang->error_bad_conditional, $lang->{$tflangkey});
            }
        }
        if (!xthreads_empty($test_tf['formatmap'])) {
            foreach ($test_tf['formatmap'] as &$fm) {
                if ($fm && !xthreads_check_evalstr($fm)) {
                    $errors[] = $lang->sprintf($lang->error_bad_conditional, $lang->threadfields_formatmap);
                    break;
                }
            }
        }
        if (!xthreads_empty($test_tf['fileimgthumbs'])) {
            foreach ($test_tf['fileimgthumbs'] as $thumb => $chain) {
                if ($chain) {
                    if (!xthreads_check_evalstr('".$img->' . $chain . '."')) {
                        $errors[] = $lang->sprintf($lang->error_bad_conditional, $lang->threadfields_fileimgthumbs);
                        break;
                    }
                }
            }
        }
        if (!$errors) {
            $new_tf = array();
            foreach (array_keys($props) as $field) {
                if ($field == 'field') {
                    $new_tf[$field] = $db->escape_string($mybb->input['newfield']);
                } else {
                    $new_tf[$field] = $db->escape_string($mybb->input[$field]);
                }
            }
            if ($mybb->input['inputtype'] == XTHREADS_INPUT_FILE) {
                if (xthreads_empty($mybb->input['multival'])) {
                    $fieldtype = xthreads_db_fielddef('int', null, true) . ' not null default 0';
                } else {
                    $fieldtype = 'varchar(255) not null default ""';
                }
                // we'll stick a hard limit of 25 files
            } elseif ($mybb->input['inputtype'] == XTHREADS_INPUT_FILE_URL) {
                $fieldtype = 'varchar(255) not null default ""';
            } else {
                switch ($new_tf['datatype']) {
                    case XTHREADS_DATATYPE_INT:
                    case XTHREADS_DATATYPE_UINT:
                        $fieldtype = xthreads_db_fielddef('int', null, $new_tf['datatype'] == XTHREADS_DATATYPE_UINT) . ' default null';
                        break;
                    case XTHREADS_DATATYPE_BIGINT:
                    case XTHREADS_DATATYPE_BIGUINT:
                        $fieldtype = xthreads_db_fielddef('bigint', null, $new_tf['datatype'] == XTHREADS_DATATYPE_BIGUINT) . ' default null';
                        break;
                    case XTHREADS_DATATYPE_FLOAT:
                        $fieldtype = 'double default null';
                        break;
                    default:
                        switch ($mybb->input['inputtype']) {
                            case XTHREADS_INPUT_TEXTAREA:
                                $fieldtype = 'text not null';
                                break;
                            case XTHREADS_INPUT_SELECT:
                            case XTHREADS_INPUT_RADIO:
                                if ($new_tf['multival'] === '' || $mybb->input['inputtype'] == XTHREADS_INPUT_RADIO) {
                                    $fieldtype = 'varchar(255) not null default ""';
                                    $using_long_varchar = false;
                                    break;
                                }
                            default:
                                if ($new_tf['allowfilter']) {
                                    // initially, try 1024 chars
                                    $fieldtype = 'varchar(1024) not null default ""';
                                    $using_long_varchar = true;
                                } else {
                                    $fieldtype = 'text not null';
                                }
                        }
                }
            }
            if ($update) {
                $plugins->run_hooks('admin_config_threadfields_edit_commit');
                $db->update_query('threadfields', $new_tf, 'field="' . $db->escape_string($mybb->input['field']) . '"');
                $alterations = array();
                // TODO: perhaps only run this query if necessary
                //if($mybb->input['field'] != $mybb->input['newfield'])
                $alterfield_base = 'CHANGE `' . $db->escape_string($mybb->input['field']) . '` `' . $new_tf['field'] . '` ';
                $alterations['field'] = $alterfield_base . $fieldtype;
                if ((bool) $new_tf['allowfilter'] != (bool) $oldfield['allowfilter']) {
                    if ($new_tf['allowfilter']) {
                        $alterations['addkey'] = 'ADD KEY `' . $new_tf['field'] . '` (`' . $new_tf['field'] . '`)';
                    } else {
                        $alterations['dropkey'] = 'DROP KEY `' . $db->escape_string($mybb->input['field']) . '`';
                    }
                } elseif ($new_tf['allowfilter'] && $mybb->input['field'] != $mybb->input['newfield']) {
                    // change key name - only way to do this in MySQL appears to be recreating the key...
                    $alterations['dropkey'] = 'DROP KEY `' . $db->escape_string($mybb->input['field']) . '`';
                    $alterations['addkey'] = 'ADD KEY `' . $new_tf['field'] . '` (`' . $new_tf['field'] . '`)';
                }
                if (!empty($alterations)) {
                    $qry_base = 'ALTER TABLE `' . $db->table_prefix . 'threadfields_data` ';
                    if ($using_long_varchar) {
                        if (!$db->write_query($qry_base . implode(', ', $alterations), true)) {
                            $alterations['field'] = $alterfield_base . str_replace('varchar(1024)', 'varchar(255)', $fieldtype);
                            $db->write_query($qry_base . implode(', ', $alterations));
                        }
                    } else {
                        $db->write_query($qry_base . implode(', ', $alterations));
                    }
                    if ($mybb->input['field'] != $mybb->input['newfield'] && ($new_tf['inputtype'] == XTHREADS_INPUT_FILE || $new_tf['inputtype'] == XTHREADS_INPUT_FILE_URL)) {
                        // need to update xtattachments table too!
                        $db->update_query('xtattachments', array('field' => $new_tf['field']), 'field="' . $db->escape_string($mybb->input['field']) . '"');
                    }
                }
            } else {
                $plugins->run_hooks('admin_config_threadfields_add_commit');
                $db->insert_query('threadfields', $new_tf);
                $addkey = '';
                if ($new_tf['allowfilter']) {
                    $addkey .= ', ADD KEY (`' . $new_tf['field'] . '`)';
                }
                $qry_base = 'ALTER TABLE `' . $db->table_prefix . 'threadfields_data` ADD COLUMN `' . $new_tf['field'] . '` ';
                if ($using_long_varchar) {
                    if (!$db->write_query($qry_base . $fieldtype . $addkey, true)) {
                        $db->write_query($qry_base . str_replace('varchar(1024)', 'varchar(255)', $fieldtype) . $addkey);
                    }
                } else {
                    $db->write_query($qry_base . $fieldtype . $addkey);
                }
            }
            // Log admin action
            log_admin_action($new_tf['field'], htmlspecialchars_uni($mybb->input['title']));
            xthreads_buildtfcache();
            if ($update) {
                flash_message($lang->success_updated_threadfield, 'success');
            } else {
                flash_message($lang->success_added_threadfield, 'success');
            }
            admin_redirect(xthreads_admin_url('config', 'threadfields'));
        }
    }
    $page->add_breadcrumb_item($title);
    $page->output_header($lang->custom_threadfields . ' - ' . $title);
    echo '<noscript>';
    $page->output_alert($lang->threadfields_enable_js);
    echo '</noscript>';
    if (!$update) {
        $page->output_nav_tabs($sub_tabs, 'threadfields_add');
    }
    if ($update) {
        $form = new Form(xthreads_admin_url('config', 'threadfields') . '&amp;action=edit&amp;field=' . urlencode($tf['field']), 'post');
    } else {
        $form = new Form(xthreads_admin_url('config', 'threadfields&amp;action=add'), 'post');
    }
    if ($errors) {
        $page->output_inline_error($errors);
        $GLOBALS['data'] =& $mybb->input;
    } else {
        $GLOBALS['data'] =& $tf;
    }
    global $data;
    global $form_container;
    $form_container = new FormContainer($title);
    $form_container->output_row($lang->threadfields_title . ' <em>*</em>', $lang->threadfields_title_desc, $form->generate_text_box('title', $data['title'], array('id' => 'title')), 'title');
    if (isset($data['newfield'])) {
        $key =& $data['newfield'];
    } else {
        $key =& $data['field'];
    }
    $form_container->output_row($lang->threadfields_name . ' <em>*</em>', $lang->threadfields_name_desc, $form->generate_text_box('newfield', $key, array('id' => 'newfield')), 'newfield');
    if ($data['forums'] && !is_array($data['forums'])) {
        $data['forums'] = array_map('intval', array_map('trim', explode(',', $data['forums'])));
    }
    $form_container->output_row($lang->threadfields_forums, $lang->threadfields_forums_desc, $form->generate_forum_select('forums[]', $data['forums'], array('multiple' => true, 'size' => 5)), 'forums');
    $hidefield_boxes = '';
    foreach (array('input' => XTHREADS_HIDE_INPUT, 'thread' => XTHREADS_HIDE_THREAD) as $k => $v) {
        $l = 'threadfields_hidefield_' . $k;
        $ld = 'threadfields_hidefield_' . $k . '_desc';
        $hidefield_boxes .= $form->generate_check_box('hidefield_' . $k, '1', $lang->{$l}, array('checked' => (bool) ($data['hidefield'] & $v))) . '<div style="margin-left: 2.25em;" class="description">' . $lang->{$ld} . '</div>';
    }
    $form_container->output_row($lang->threadfields_hidefield, $lang->threadfields_hidefield_desc, $hidefield_boxes, 'hidefield');
    $inputtypes = array(XTHREADS_INPUT_TEXT => $lang->threadfields_inputtype_text, XTHREADS_INPUT_TEXTAREA => $lang->threadfields_inputtype_textarea, XTHREADS_INPUT_SELECT => $lang->threadfields_inputtype_select, XTHREADS_INPUT_RADIO => $lang->threadfields_inputtype_radio, XTHREADS_INPUT_CHECKBOX => $lang->threadfields_inputtype_checkbox, XTHREADS_INPUT_FILE => $lang->threadfields_inputtype_file);
    if ($update) {
        // disable some conversions as they are not possible
        if (isset($errors['error_invalid_inputtype'])) {
            // but if invalid type is supplied, don't lock the user in either
            $inputtype = $oldfield['inputtype'];
        } else {
            $inputtype = $data['inputtype'];
        }
        if ($inputtype == XTHREADS_INPUT_FILE || $inputtype == XTHREADS_INPUT_FILE_URL) {
            foreach ($inputtypes as $k => &$v) {
                if ($k != $inputtype) {
                    unset($inputtypes[$k]);
                }
            }
        } else {
            unset($inputtypes[XTHREADS_INPUT_FILE], $inputtypes[XTHREADS_INPUT_FILE_URL]);
        }
    }
    // TODO: weird issue where inputtype isn't being set...
    if (!ini_get('file_uploads')) {
        $lang->threadfields_file_name_info .= '<div style="color: red; font-style: italic;">' . $lang->threadfields_file_upload_disabled_warning . '</div>';
    }
    make_form_row('inputtype', 'select_box', $inputtypes, '<div id="inputtype_file_explain" style="font-size: 0.95em; margin-top: 1em;">' . $lang->threadfields_file_name_info . '</div>');
    make_form_row('disporder', 'text_box');
    $form_container->end();
    unset($GLOBALS['form_container']);
    global $form_container;
    $form_container = new FormContainer($lang->threadfields_cat_input);
    if ($data['editable_gids'] && !is_array($data['editable_gids'])) {
        $data['editable_gids'] = array_map('intval', array_map('trim', explode(',', $data['editable_gids'])));
    }
    if (!empty($data['editable_gids'])) {
        $data['editable'] = 99;
    }
    make_form_row('editable', 'select_box', array(XTHREADS_EDITABLE_ALL => $lang->threadfields_editable_everyone, XTHREADS_EDITABLE_REQ => $lang->threadfields_editable_requied, XTHREADS_EDITABLE_MOD => $lang->threadfields_editable_mod, XTHREADS_EDITABLE_ADMIN => $lang->threadfields_editable_admin, XTHREADS_EDITABLE_NONE => $lang->threadfields_editable_none, 99 => $lang->threadfields_editable_bygroup));
    $form_container->output_row($lang->threadfields_editable_gids, $lang->threadfields_editable_gids_desc, xt_generate_group_select('editable_gids[]', $data['editable_gids'], array('multiple' => true, 'size' => 5)), 'editable_gids', array(), array('id' => 'row_editable_gids'));
    make_form_row('maxlen', 'text_box');
    make_form_row('vallist', 'text_area');
    make_form_row('fileexts', 'text_box');
    if (!is_int(2147483648)) {
        // detect 32-bit PHP
        $lang->threadfields_filemaxsize_desc .= $lang->threadfields_filemaxsize_desc_2gbwarn;
    }
    // PHP upload limits
    $upload_max_filesize = @ini_get('upload_max_filesize');
    $post_max_size = @ini_get('post_max_size');
    // TODO: maybe also pull in [ file_uploads, max_file_uploads, max_input_time ] ?
    if ($upload_max_filesize || $post_max_size) {
        $lang->threadfields_filemaxsize_desc .= '<br /><br />' . $lang->threadfields_filemaxsize_desc_phplimit;
        if (!$lang->limit_upload_max_filesize) {
            $lang->load('config_attachment_types');
        }
        if ($upload_max_filesize) {
            $lang->threadfields_filemaxsize_desc .= '<br />' . $lang->sprintf($lang->limit_upload_max_filesize, $upload_max_filesize);
        }
        if ($post_max_size) {
            $lang->threadfields_filemaxsize_desc .= '<br />' . $lang->sprintf($lang->limit_post_max_size, $post_max_size);
        }
    }
    make_form_row('filemaxsize', 'text_box');
    make_form_row('filemagic', 'text_box');
    $data['filereqimg'] = $data['fileimage'] ? 1 : 0;
    if (!function_exists('imagecreate')) {
        $lang->threadfields_filereqimg_desc .= $lang->threadfields_filereqimg_desc_nogd;
    }
    make_form_row('filereqimg', 'yes_no_radio');
    unset($data['filereqimg']);
    $data['fileimage_mindim'] = $data['fileimage_maxdim'] = '';
    if ($data['fileimage']) {
        list($min, $max) = explode('|', $data['fileimage']);
        if ($min === '0x0') {
            $min = '';
        }
        $data['fileimage_mindim'] = $min;
        $data['fileimage_maxdim'] = $max;
    }
    make_form_row('fileimage_mindim', 'text_box');
    make_form_row('fileimage_maxdim', 'text_box');
    unset($data['fileimage_mindim'], $data['fileimage_maxdim']);
    make_form_row('fileimgthumbs', 'text_box');
    $data['multival_enable'] = $data['multival'] !== '' ? 1 : 0;
    make_form_row('multival_enable', 'yes_no_radio');
    unset($data['multival_enable']);
    make_form_row('multival_limit', 'text_box');
    make_form_row('textmask', 'text_box');
    make_form_row('inputformat', 'text_area', array('style' => 'font-family: monospace'));
    make_form_row('inputvalidate', 'text_area', array('style' => 'font-family: monospace'));
    if (!is_array($data['editable_values'])) {
        $ev = @unserialize($data['editable_values']);
        if (is_array($ev)) {
            $data['editable_values'] =& $ev;
        }
    }
    if (is_array($data['editable_values'])) {
        $evtxt = '';
        foreach ($data['editable_values'] as $k => &$v) {
            // don't need to htmlspecialchar - it'll be done for us
            $evtxt .= str_replace("\n", "{\n}", $k) . '{|}' . implode(',', $v) . "\n";
        }
        $data['editable_values'] =& $evtxt;
    }
    make_form_row('editable_values', 'text_area', array('style' => 'font-family: monospace'));
    $form_container->end();
    unset($GLOBALS['form_container']);
    global $form_container;
    $form_container = new FormContainer($lang->threadfields_cat_inputfield);
    make_form_row('desc', 'text_box');
    make_form_row('defaultval', 'text_area', array('style' => 'font-family: monospace'));
    make_form_row('fieldwidth', 'text_box');
    make_form_row('fieldheight', 'text_box');
    make_form_row('tabstop', 'yes_no_radio');
    $data['use_formhtml'] = $data['formhtml'] !== '' ? 1 : 0;
    make_form_row('use_formhtml', 'yes_no_radio');
    unset($data['use_formhtml']);
    $lang->threadfields_formhtml .= ' <em>*</em>';
    make_form_row('formhtml', 'text_area', array('style' => 'font-family: monospace'));
    $form_container->end();
    unset($GLOBALS['form_container']);
    global $form_container;
    $form_container = new FormContainer($lang->threadfields_cat_output);
    $sanitize = $data['sanitize'];
    $data['sanitize'] &= XTHREADS_SANITIZE_MASK;
    make_form_row('sanitize', 'select_box', array(XTHREADS_SANITIZE_HTML => $lang->threadfields_sanitize_plain, XTHREADS_SANITIZE_HTML_NL => $lang->threadfields_sanitize_plain_nl, XTHREADS_SANITIZE_PARSER => $lang->threadfields_sanitize_mycode, XTHREADS_SANITIZE_NONE => $lang->threadfields_sanitize_none));
    $parser_opts = array('parser_nl2br' => $sanitize & XTHREADS_SANITIZE_PARSER_NL2BR, 'parser_nobadw' => $sanitize & XTHREADS_SANITIZE_PARSER_NOBADW, 'parser_html' => $sanitize & XTHREADS_SANITIZE_PARSER_HTML, 'parser_mycode' => $sanitize & XTHREADS_SANITIZE_PARSER_MYCODE, 'parser_mycodeimg' => $sanitize & XTHREADS_SANITIZE_PARSER_MYCODEIMG, 'parser_mycodevid' => $sanitize & XTHREADS_SANITIZE_PARSER_VIDEOCODE, 'parser_smilies' => $sanitize & XTHREADS_SANITIZE_PARSER_SMILIES);
    if ($mybb->version_code < 1600) {
        unset($parser_opts['parser_mycodevid']);
    }
    $parser_opts_str = '';
    foreach ($parser_opts as $opt => $checked) {
        $langstr = 'threadfields_sanitize_' . $opt;
        $parser_opts_str .= '<div style="display: block;">' . $form->generate_check_box($opt, 1, $lang->{$langstr}, array('checked' => $checked ? 1 : 0)) . '</div>';
    }
    $form_container->output_row($lang->threadfields_sanitize_parser, $lang->threadfields_sanitize_parser_desc, $parser_opts_str, 'sanitize_parser', array(), array('id' => 'parser_opts'));
    make_form_row('blankval', 'text_area', array('style' => 'font-family: monospace'));
    make_form_row('dispformat', 'text_area', array('style' => 'font-family: monospace'));
    $lang->threadfields_multival .= ' <em>*</em>';
    make_form_row('multival', 'text_box');
    $lang->threadfields_multival = substr($lang->threadfields_multival, 0, -11);
    make_form_row('dispitemformat', 'text_area', array('style' => 'font-family: monospace'));
    if (!is_array($data['formatmap'])) {
        $fm = @unserialize($data['formatmap']);
        if (is_array($fm)) {
            $data['formatmap'] =& $fm;
        }
    }
    if (is_array($data['formatmap'])) {
        $fmtxt = '';
        foreach ($data['formatmap'] as $k => &$v) {
            // don't need to htmlspecialchar - it'll be done for us
            $fmtxt .= str_replace("\n", "{\n}", $k . '{|}' . $v) . "\n";
        }
        $data['formatmap'] =& $fmtxt;
    }
    make_form_row('formatmap', 'text_area', array('style' => 'font-family: monospace'));
    if ($data['viewable_gids'] && !is_array($data['viewable_gids'])) {
        $data['viewable_gids'] = array_map('intval', array_map('trim', explode(',', $data['viewable_gids'])));
    }
    $form_container->output_row($lang->threadfields_viewable_gids, $lang->threadfields_viewable_gids_desc, xt_generate_group_select('viewable_gids[]', $data['viewable_gids'], array('multiple' => true, 'size' => 5, 'id' => 'viewable_gids')), 'viewable_gids', array(), array('id' => 'row_viewable_gids'));
    make_form_row('unviewableval', 'text_area', array('style' => 'font-family: monospace'));
    $form_container->end();
    unset($GLOBALS['form_container']);
    // this will currently be empty if a file input is chosen...
    global $form_container;
    $form_container = new FormContainer($lang->threadfields_cat_misc);
    make_form_row('allowfilter', 'select_box', array(XTHREADS_FILTER_NONE => $lang->threadfields_filter_none, XTHREADS_FILTER_EXACT => $lang->threadfields_filter_exact, XTHREADS_FILTER_PREFIX => $lang->threadfields_filter_prefix, XTHREADS_FILTER_ANYWHERE => $lang->threadfields_filter_anywhere, XTHREADS_FILTER_WILDCARD => $lang->threadfields_filter_wildcard));
    make_form_row('datatype', 'select_box', array(XTHREADS_DATATYPE_TEXT => $lang->threadfields_datatype_text, XTHREADS_DATATYPE_INT => $lang->threadfields_datatype_int, XTHREADS_DATATYPE_UINT => $lang->threadfields_datatype_uint, XTHREADS_DATATYPE_BIGINT => $lang->threadfields_datatype_bigint, XTHREADS_DATATYPE_BIGUINT => $lang->threadfields_datatype_biguint, XTHREADS_DATATYPE_FLOAT => $lang->threadfields_datatype_float));
    $form_container->end();
    unset($GLOBALS['form_container']);
    if ($update) {
        $buttons[] = $form->generate_submit_button($lang->update_threadfield);
    } else {
        $buttons[] = $form->generate_submit_button($lang->add_threadfield);
    }
    $form->output_submit_wrapper($buttons);
    $form->end();
    ?>
<script type="text/javascript">
<!--
	var xt_inited = false;
	function xt_visi(o,v) {
		document.getElementById(o).style.display = (v ? '':'none');
	}
	document.getElementById('sanitize').onchange = function() {
		xt_visi('parser_opts', this.options[this.selectedIndex].value == "<?php 
    echo XTHREADS_SANITIZE_PARSER;
    ?>
" && document.getElementById('row_sanitize').style.display != 'none');
	};
	
	function xt_multival_enable() {
		var si = parseInt(document.getElementById('inputtype').options[document.getElementById('inputtype').selectedIndex].value);
		var checkboxIn = (si == <?php 
    echo XTHREADS_INPUT_CHECKBOX;
    ?>
);
		var pureFileIn = (si == <?php 
    echo XTHREADS_INPUT_FILE;
    ?>
);
		var fileIn = (pureFileIn || si == <?php 
    echo XTHREADS_INPUT_FILE_URL;
    ?>
);
		e = checkboxIn; // forced
		
		var datatypeText = (document.getElementById('datatype').options[document.getElementById('datatype').selectedIndex].value == "<?php 
    echo XTHREADS_DATATYPE_TEXT;
    ?>
");
		xt_visi('row_multival_enable', checkboxIn || ((
			si != <?php 
    echo XTHREADS_INPUT_RADIO;
    ?>
 && (datatypeText || pureFileIn)
		)));
		
		if(!e) e = (document.getElementById('multival_enable_yes').checked && document.getElementById('row_multival_enable').style.display != 'none');
		xt_visi('row_multival', e);
		xt_visi('row_multival_limit', e);
		xt_visi('row_dispitemformat', e);
		datatypeVisible = (!e && !checkboxIn && !fileIn);
		xt_visi('row_datatype', datatypeVisible);
		
		// hide some sanitise options (if browser supports it)
		var sanitizeOptShow = ((datatypeVisible && !datatypeText) ? 'none' : '');
		for(i in document.getElementById('sanitize').options) {
			var optItem = document.getElementById('sanitize').options[i];
			if(!optItem) continue; // fix IE6 bug
			if(optItem.value == "<?php 
    echo XTHREADS_SANITIZE_HTML_NL;
    ?>
" || optItem.value == "<?php 
    echo XTHREADS_SANITIZE_NONE;
    ?>
") {
				// our target
				if(sanitizeOptShow == 'none' && document.getElementById('sanitize').selectedIndex == i)
					document.getElementById('sanitize').selectedIndex = 0;
				optItem.style.display = sanitizeOptShow;
			}
		}
		
		dispfmt_obj = document.getElementById('dispformat');
		fileVal = "<a href=\"{URL}\">{FILENAME}</a>";
		nonFileVal = "{VALUE}";
		if(pureFileIn) {
			if(e) {
				if(document.getElementById('dispitemformat').value == nonFileVal) {
					if(dispfmt_obj.value == nonFileVal)
						document.getElementById('dispitemformat').value = fileVal;
					else {
						// swap dispformat <-> dispitemformat
						document.getElementById('dispitemformat').value = dispfmt_obj.value;
						dispfmt_obj.value = nonFileVal;
					}
				}
				if(dispfmt_obj.value == fileVal)
					dispfmt_obj.value = nonFileVal;
			} else {
				if(dispfmt_obj.value == nonFileVal) {
					dispfmt_obj.value = fileVal;
					if(document.getElementById('dispitemformat').value != nonFileVal) {
						// maybe swap?
						var DIFval = document.getElementById('dispitemformat').value.toUpperCase();
						if((function(s){
							for(i in s)
								if(DIFval.indexOf("{"+s[i]+"}") > -1)
									return true;
							return false;
						})(
							["DOWNLOADS","DOWNLOADS_FRIENDLY","FILENAME","UPLOADMIME","URL","FILESIZE","FILESIZE_FRIENDLY","MD5HASH","UPLOADTIME","UPLOAD_TIME","UPLOAD_DATE","UPDATETIME","UPDATE_TIME","UPDATE_DATE","THUMBS","DIMS","MODIFIED"]
						)) {
							dispfmt_obj.value = document.getElementById('dispitemformat').value;
							document.getElementById('dispitemformat').value = nonFileVal;
						}
					}
				}
				if(document.getElementById('dispitemformat').value == fileVal)
					document.getElementById('dispitemformat').value = nonFileVal;
			}
		} else {
			if(document.getElementById('dispitemformat').value == fileVal)
				document.getElementById('dispitemformat').value = nonFileVal;
			if(dispfmt_obj.value == fileVal)
				dispfmt_obj.value = nonFileVal;
		}
	}
	document.getElementById('multival_enable_yes').onclick = xt_multival_enable;
	document.getElementById('multival_enable_no').onclick = xt_multival_enable;
	
	(document.getElementById('use_formhtml_yes').onclick = document.getElementById('use_formhtml_no').onclick = xt_use_formhtml = function() {
		xt_visi('row_formhtml', document.getElementById('use_formhtml_yes').checked);
		xt_visi('formhtml_desc_js', true);
	})();
	
	function xt_filereqimg() {
		var e = (document.getElementById('filereqimg_yes').checked && document.getElementById('row_filereqimg').style.display != 'none');
		xt_visi('row_fileimage_mindim', e);
		xt_visi('row_fileimage_maxdim', e);
		xt_visi('row_fileimgthumbs', e);
	}
	document.getElementById('filereqimg_yes').onclick = xt_filereqimg;
	document.getElementById('filereqimg_no').onclick = xt_filereqimg;
	
	
	(document.getElementById('inputtype').onchange = function() {
		var si = parseInt(this.options[this.selectedIndex].value);
		
		var pureFileIn = (si == <?php 
    echo XTHREADS_INPUT_FILE;
    ?>
);
		var fileIn = (pureFileIn || si == <?php 
    echo XTHREADS_INPUT_FILE_URL;
    ?>
);
		var radioIn = (si == <?php 
    echo XTHREADS_INPUT_RADIO;
    ?>
);
		var checkboxIn = (si == <?php 
    echo XTHREADS_INPUT_CHECKBOX;
    ?>
);
		var selectBoxIn = (si == <?php 
    echo XTHREADS_INPUT_SELECT;
    ?>
);
		var selectIn = (selectBoxIn || radioIn || checkboxIn);
		var textAreaIn = (si == <?php 
    echo XTHREADS_INPUT_TEXTAREA;
    ?>
);
		var textIn = (textAreaIn || si == <?php 
    echo XTHREADS_INPUT_TEXT;
    ?>
);
		xt_visi('row_sanitize', !fileIn && !selectIn);
		document.getElementById('sanitize').onchange();
		
		xt_visi('inputtype_file_explain', pureFileIn);
		
		xt_visi('row_allowfilter', !fileIn && !textAreaIn);
		xt_visi('row_formatmap', !fileIn);
		xt_visi('row_editable_values', !fileIn);
		xt_visi('row_defaultval', !pureFileIn);
		
		xt_visi('row_textmask', textIn);
		xt_visi('row_inputformat', !fileIn);
		xt_visi('row_maxlen', textIn);
		xt_visi('row_fieldwidth', textIn || fileIn || selectBoxIn);
		xt_visi('row_fieldheight', textAreaIn || selectBoxIn);
		
		xt_visi('row_vallist', selectIn);
		
		//xt_visi('row_datatype', !checkboxIn && !fileIn);
		//xt_visi('row_multival_enable', !checkboxIn && !radioIn && !fileIn);
		xt_multival_enable();
		
		xt_visi('row_filemagic', pureFileIn);
		xt_visi('row_fileexts', pureFileIn);
		xt_visi('row_filemaxsize', pureFileIn);
		xt_visi('row_filereqimg', pureFileIn);
		xt_filereqimg();
		
		if(textAreaIn) {
			if(document.getElementById('sanitize').options[document.getElementById('sanitize').selectedIndex].value == "<?php 
    echo XTHREADS_SANITIZE_HTML;
    ?>
")
				document.getElementById('sanitize').selectedIndex++;
		} else if(textIn) {
			if(document.getElementById('sanitize').options[document.getElementById('sanitize').selectedIndex].value == "<?php 
    echo XTHREADS_SANITIZE_HTML_NL;
    ?>
")
				document.getElementById('sanitize').selectedIndex--;
		}
		
		var setFormhtml = true;
		if(document.getElementById('use_formhtml_yes').checked) {
			if(!xt_inited)
				setFormhtml = (document.getElementById("formhtml").value == "");
			else
				setFormhtml = confirm("<?php 
    echo xt_js_str_escape($lang->threadfields_formhtml_js_reset_warning);
    ?>
");
			if(setFormhtml) {
				document.getElementById('use_formhtml_no').checked = true;
			}
			xt_use_formhtml();
		}
		switch(si) {
			<?php 
    foreach (array(XTHREADS_INPUT_TEXTAREA, XTHREADS_INPUT_SELECT, XTHREADS_INPUT_CHECKBOX, XTHREADS_INPUT_RADIO, XTHREADS_INPUT_FILE, XTHREADS_INPUT_TEXT) as $inputtype) {
        $formhtml_info = xthreads_default_threadfields_formhtml($inputtype);
        $formhtml_desc = '';
        foreach ($formhtml_info[1] as $fhvar) {
            $langvar = 'threadfields_formhtml_desc_' . strtolower($fhvar);
            $formhtml_desc .= '<li><code>{' . $fhvar . '}</code>: ' . $lang->{$langvar} . '</li>';
        }
        echo '
				case ' . $inputtype . ':
					if(setFormhtml) document.getElementById("formhtml").value = "' . xt_js_str_escape($formhtml_info[0]) . '";
					document.getElementById("formhtml_desc_ul_js").innerHTML = "' . xt_js_str_escape($formhtml_desc) . '";
					break;';
    }
    ?>
		}
	}).apply(document.getElementById('inputtype'));
	
	(document.getElementById('datatype').onchange = function() {
		//var isText = this.options[this.selectedIndex].value == "<?php 
    echo XTHREADS_DATATYPE_TEXT;
    ?>
";
		//xt_visi('row_multival_enable', isText);
		xt_multival_enable();
	}).apply(document.getElementById('datatype'));
	
	(document.getElementById('editable').onchange = function() {
		xt_visi('row_editable_gids', this.options[this.selectedIndex].value == "99");
	}).apply(document.getElementById('editable'));
	
	(document.getElementById('viewable_gids').onchange = function() {
		var e=false;
		var o=document.getElementById('viewable_gids').options;
		for(i=0; i<o.length; i++)
			if(e = o[i].selected) // no, I do mean =, not ==
				break;
		xt_visi('row_unviewableval', e);
	}).apply(document.getElementById('viewable_gids'));
	
	<?php 
    $textmask_types = array('anything' => '^.*$', 'digit' => '^\\d+$', 'alphadigit' => '^[a-z0-9]+$', 'number' => '^(-?)([0-9]*)(?:\\.(\\d*))?(?:e([+-]?\\d*))?$', 'date' => '^(0?[1-9]|[12]\\d|3[01])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)$', 'date_us' => '^(0?[1-9]|1[012])/(0?[1-9]|[12]\\d|3[01])/((?:19|20)\\d\\d)$', 'uri' => '^([^:/?#]+)\\:((//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?)$', 'url' => '^([a-z0-9]+)\\://([^/?#]+)(/([^\\r\\n"<>#?]*)(\\?([^\\r\\n"<>#]*))?(#([^\\r\\n"<>]*))?)?$', 'httpurl' => '^(https?)\\://([^/?#]+)(/([^\\r\\n"<>#?]*)(\\?([^\\r\\n"<>#]*))?(#([^\\r\\n"<>]*))?)?$', 'email' => '^(.+)@([a-z0-9_.\\-]+)$', 'emailr' => '^([^ "(),:;<>@\\[\\\\\\]]+)@([a-z0-9_.\\-]+)$', 'css' => '^[a-z0-9_\\- ]+$', 'color' => '^[a-z\\-]+|#?[0-9a-f]{6}$');
    ?>
	document.getElementById('textmask').parentNode.innerHTML =
			'<select name="textmask_select" id="textmask_select">' +
<?php 
    foreach ($textmask_types as $type => &$mask) {
        $langvar = 'threadfields_textmask_' . $type;
        echo '			\'<option value="', $type, '">', $lang->{$langvar}, '</option>\' +
';
    }
    ?>
			'<option value="custom">'+<?php 
    echo "'", $lang->threadfields_textmask_custom, "'";
    ?>
+'</option>' +
			'</select> ' + document.getElementById('textmask').parentNode.innerHTML + '<div id="textmask_select_descriptions" style="font-size: smaller; padding-top: 0.5em;">' +
<?php 
    foreach ($textmask_types as $type => &$mask) {
        $langvar = 'threadfields_textmask_' . $type . '_desc';
        if (property_exists($lang, $langvar)) {
            echo '			\'<div id="textmask_selector_desc_', $type, '" style="display: none;">', xt_js_str_escape($lang->{$langvar}), '</div>\' +
';
        }
    }
    ?>
			'</div>';
	var textmaskMapping = {
<?php 
    $comma = '';
    foreach ($textmask_types as $type => &$mask) {
        echo $comma, '		', $type, ': "', xt_js_str_escape($mask), '"';
        if (!$comma) {
            $comma = ',
';
        }
    }
    ?>

	};
	// determine which option to be selected by default
	(function() {
		// we can only index by number, and as we're a little lazy, create a name -> index map
		var textmaskSelectOpts = document.getElementById('textmask_select').options;
		var textmaskSelectMap = {};
		for(i=0; i<textmaskSelectOpts.length; i++) {
			textmaskSelectMap[textmaskSelectOpts[i].value] = i;
		}
		
		var mask = document.getElementById('textmask').value;
		for(var maskName in textmaskMapping) {
			if(mask == textmaskMapping[maskName]) {
				document.getElementById('textmask_select').selectedIndex = textmaskSelectMap[maskName];
				textmaskSelectUpdated();
				return;
			}
		}
		document.getElementById('textmask_select').selectedIndex = textmaskSelectMap["custom"];
	})();
	document.getElementById('textmask_select').onchange = function() {
		var maskName = this.options[this.selectedIndex].value;
		if(textmaskMapping[maskName])
			document.getElementById('textmask').value = textmaskMapping[maskName];
		textmaskSelectUpdated();
	};
	document.getElementById('textmask_select').onkeypress = document.getElementById('textmask_select').onkeydown = document.getElementById('textmask_select').onkeyup = function(e) {
		document.getElementById('textmask_select').onchange();
		return true;
	};
	function textmaskSelectUpdated() {
		var maskName = document.getElementById('textmask_select').options[document.getElementById('textmask_select').selectedIndex].value;
		var d = (maskName != "custom");
		document.getElementById('textmask').readOnly = d;
		document.getElementById('textmask').tabIndex = (d?'-1':''); // note, this is non-standard
		document.getElementById('textmask').style.background = (d ? "#F0F0F0":"");
		document.getElementById('textmask').style.color = (d ? "#808080":"");
		
		var o = document.getElementById('textmask_select_descriptions').childNodes;
		for(i=0; i<o.length; i++) {
			if(o[i].id == "textmask_selector_desc_"+maskName)
				o[i].style.display = "";
			else
				o[i].style.display = "none";
		}
	}
	document.getElementById('textmask').onfocus = function() {
		if(this.readOnly)
			document.getElementById('textmask_select').focus();
	};
	xt_inited = true;
//-->
</script>
<script type="text/javascript" src="jscripts/xtofedit.js?xtver=<?php 
    echo XTHREADS_VERSION;
    ?>
"></script>
<script type="text/javascript">
<!--
xtOFEditorLang.confirmFormSubmit = "<?php 
    echo $lang->xthreads_js_confirm_form_submit;
    ?>
";
xtOFEditorLang.windowTitle = "<?php 
    echo $lang->xthreads_js_edit_value;
    ?>
";
xtOFEditorLang.saveButton = "<?php 
    echo $lang->xthreads_js_save_changes;
    ?>
";
xtOFEditorLang.closeSaveChanges = "<?php 
    echo $lang->xthreads_js_close_save_changes;
    ?>
";

var fmtMapEditor = new xtOFEditor();
fmtMapEditor.src = document.getElementById('formatmap');
fmtMapEditor.loadFunc = function(s) {
	var a = s.replace(/\r/g, "").replace(/\{\n\}/g, "\r").split("\n");
	var data = [];
	for(var i=0; i<a.length; i++) {
		a[i] = a[i].replace(/\r/g, "\n");
		var p = a[i].indexOf("{|}");
		if(p < 0) continue;
		data.push([ a[i].substring(0, p), a[i].substring(p+3) ]);
	}
	return data;
};
fmtMapEditor.saveFunc = function(a) {
	var ret = "";
	for(var i=0; i<a.length; i++) {
		ret += a[i].join("{|}").replace(/\n/g, "{\n}") + "\n";
	}
	return ret;
};
fmtMapEditor.fields = [
	{title: "<?php 
    echo $lang->xthreads_js_formatmap_from;
    ?>
", width: '45%', elemFunc: fmtMapEditor.textAreaFunc},
	{title: "<?php 
    echo $lang->xthreads_js_formatmap_to;
    ?>
", width: '55%', elemFunc: fmtMapEditor.textAreaFunc}
];

fmtMapEditor.copyStyles=true;
fmtMapEditor.init();

var editValEditor = new xtOFEditor();
editValEditor.src = document.getElementById('editable_values');
editValEditor.loadFunc = function(s) {
	var a = s.replace(/\r/g, "").replace(/\{\n\}/g, "\r").split("\n");
	var data = [];
	for(var i=0; i<a.length; i++) {
		a[i] = a[i].replace(/\r/g, "\n");
		var p = a[i].indexOf("{|}");
		if(p < 0) continue;
		data.push([ a[i].substring(0, p), a[i].substring(p+3).split(",") ]);
	}
	return data;
};
editValEditor.saveFunc = function(a) {
	var ret = "";
	for(var i=0; i<a.length; i++) {
		ret += a[i][0].replace(/\n/g, "{\n}") + "{|}" + a[i][1].join(",") + "\n";
	}
	return ret;
};
editValEditor.fields = [
	{title: "<?php 
    echo $lang->xthreads_js_formatmap_from;
    ?>
", width: '50%', elemFunc: editValEditor.textAreaFunc},
	{title: "<?php 
    echo $lang->xthreads_js_editable_values_groups;
    ?>
", width: '50%', elemFunc: function(c) {
		var o = appendNewChild(c, "select");
		o.multiple = true;
		o.size = 3;
		o.style.width = '100%';
		o.innerHTML = '<?php 
    foreach ($GLOBALS['cache']->read('usergroups') as $group) {
        echo '<option value="' . $group['gid'] . '">' . xt_js_str_escape(htmlspecialchars_uni(strip_tags($group['title']))) . '</option>';
    }
    ?>
';
		return o;
	}}
];

editValEditor.copyStyles=true;
editValEditor.init();

//-->
</script><?php 
    $page->output_footer();
}
Example #18
0
function asb_admin_manage_scripts()
{
    global $mybb, $db, $page, $lang, $html, $min;
    require_once MYBB_ROOT . 'inc/plugins/asb/classes/script_info.php';
    $page->add_breadcrumb_item($lang->asb, $html->url());
    if ($mybb->request_method == 'post') {
        if ($mybb->input['mode'] == 'edit') {
            $mybb->input['action'] = $mybb->input['script_action'];
            $script_info = new ScriptInfo($mybb->input);
            if (!$script_info->save()) {
                flash_message($lang->asb_script_save_fail, 'error');
                admin_redirect($html->url(array("action" => 'manage_scripts')));
            }
            flash_message($lang->asb_script_save_success, 'success');
            asb_cache_has_changed();
            admin_redirect($html->url(array("action" => 'manage_scripts')));
        } elseif ($mybb->input['mode'] == 'import') {
            if (!$_FILES['file'] || $_FILES['file']['error'] == 4) {
                flash_message($lang->asb_custom_import_no_file, 'error');
                admin_redirect($html->url(array("action" => 'manage_scripts')));
            }
            if ($_FILES['file']['error']) {
                flash_message($lang->sprintf($lang->asb_custom_import_file_error, $_FILES['file']['error']), 'error');
                admin_redirect($html->url(array("action" => 'manage_scripts')));
            }
            if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
                flash_message($lang->asb_custom_import_file_upload_error, 'error');
                admin_redirect($html->url(array("action" => 'manage_scripts')));
            }
            $contents = @file_get_contents($_FILES['file']['tmp_name']);
            @unlink($_FILES['file']['tmp_name']);
            if (strlen(trim($contents)) == 0) {
                flash_message($lang->asb_custom_import_file_empty, 'error');
                admin_redirect($html->url(array("action" => 'manage_scripts')));
            }
            $this_script = new ScriptInfo();
            if (!$this_script->import($contents)) {
                flash_message($lang->asb_script_import_fail, 'error');
                admin_redirect($html->url(array("action" => 'manage_scripts')));
            }
            if (!$this_script->save()) {
                flash_message($lang->asb_script_import_fail, 'error');
            }
            flash_message($lang->asb_script_import_success, 'success');
            asb_cache_has_changed();
            admin_redirect($html->url(array("action" => 'manage_scripts')));
        }
    }
    if ($mybb->input['mode'] == 'delete' && $mybb->input['id']) {
        $this_script = new ScriptInfo((int) $mybb->input['id']);
        if (!$this_script->remove()) {
            flash_message($lang->asb_script_delete_fail, 'error');
        } else {
            flash_message($lang->asb_script_delete_success, 'success');
            asb_cache_has_changed();
        }
    } elseif ($mybb->input['mode'] == 'export' && $mybb->input['id']) {
        $this_script = new ScriptInfo((int) $mybb->input['id']);
        if (!$this_script->export()) {
            flash_message($lang->asb_script_export_fail, 'error');
            admin_redirect($html->url(array("action" => 'manage_scripts')));
        }
        exit;
    } elseif (($mybb->input['mode'] == 'activate' || $mybb->input['mode'] == 'deactivate') && $mybb->input['id']) {
        $this_script = new ScriptInfo((int) $mybb->input['id']);
        $this_script->set('active', $mybb->input['mode'] == 'activate');
        if (!$this_script->save()) {
            $action = $mybb->input['mode'] == 'activate' ? $lang->asb_script_activate_fail : $lang->asb_script_deactivate_fail;
            flash_message($action, 'error');
        } else {
            $action = $mybb->input['mode'] == 'activate' ? $lang->asb_script_activate_success : $lang->asb_script_deactivate_success;
            flash_message($action, 'success');
            asb_cache_has_changed();
        }
        admin_redirect($html->url(array("action" => 'manage_scripts')));
    }
    $data = array("active" => 'false', "find_top" => '{$header}', "find_bottom" => '{$footer}', "replace_all" => 0, "eval" => 0, "width_left" => 160, "width_right" => 160);
    if ($mybb->input['mode'] == 'edit') {
        $this_script = new ScriptInfo((int) $mybb->input['id']);
        $detected_show = ' style="display: none;"';
        $button_text = $lang->asb_add;
        $filename = '';
        $action = $lang->asb_edit_script;
        if ($this_script->is_valid()) {
            $data = $this_script->get('data');
            $detected_info = asb_detect_script_info($data['filename']);
            $detected_show = '';
            $button_text = $lang->asb_update;
            $filename = $data['filename'];
            $action = "{$lang->asb_edit} {$data['title']}";
        }
        $lang->asb_edit_script = $action;
        $queryadmin = $db->simple_select('adminoptions', '*', "uid='{$mybb->user['uid']}'");
        $admin_options = $db->fetch_array($queryadmin);
        if ($admin_options['codepress'] != 0) {
            $page->extra_header .= <<<EOF
\t<link type="text/css" href="./jscripts/codepress/languages/codepress-mybb.css" rel="stylesheet" id="cp-lang-style"/>
\t<script type="text/javascript" src="./jscripts/codepress/codepress.js"></script>
\t<script type="text/javascript">
\t<!--
\t\tCodePress.language = 'mybb';
\t// -->
\t</script>'
EOF;
        }
        $page->extra_header .= <<<EOF
\t<script type="text/javascript" src="./jscripts/peeker.js"></script>
\t<script type="text/javascript" src="jscripts/asb/asb_scripts{$min}.js"></script>
\t<script type="text/javascript">
\t<!--
\t\tASB.scripts.setCurrent('{$filename}');
\t// -->
\t</script>
\t<link rel="stylesheet" type="text/css" href="styles/asb_acp.css" media="screen" />
\t<script src="jscripts/asb/asb{$min}.js" type="text/javascript"></script>

EOF;
        $page->add_breadcrumb_item($lang->asb_manage_scripts, $html->url(array("action" => 'manage_scripts')));
        $page->add_breadcrumb_item($lang->asb_edit_script);
        $page->output_header("{$lang->asb} - {$lang->asb_manage_scripts} - {$lang->asb_edit_script}");
        asb_output_tabs('asb_edit_script');
        $spinner = <<<EOF
<div class="ajax_spinners" style="display: none;">
\t<img src="../images/spinner.gif" alt="{$lang->asb_detecting} . . ."/><br /><br />
</div>
EOF;
        $form = new Form($html->url(array("action" => 'manage_scripts', "mode" => 'edit')), 'post', 'edit_script');
        $form_container = new FormContainer($lang->asb_edit_script);
        $form_container->output_row("{$lang->asb_title}:", $lang->asb_title_desc, $form->generate_text_box('title', $data['title']));
        $form_container->output_row("{$lang->asb_filename}:", $lang->asb_filename_desc, $form->generate_text_box('filename', $data['filename'], array("id" => 'filename')));
        $form_container->output_row("{$lang->asb_action}:", $lang->sprintf($lang->asb_scriptvar_generic_desc, strtolower($lang->asb_action)), "{$spinner}<div id=\"action_list\"{$detected_show}>{$detected_info['actions']}</div>" . $form->generate_text_box('script_action', $data['action'], array("id" => 'action')));
        $form_container->output_row($lang->asb_page, $lang->sprintf($lang->asb_scriptvar_generic_desc, strtolower($lang->asb_page)), $form->generate_text_box('page', $data['page']));
        $form_container->output_row($lang->asb_width_left, $lang->asb_width_left_desc, $form->generate_text_box('width_left', $data['width_left']));
        $form_container->output_row($lang->asb_width_right, $lang->asb_width_right_desc, $form->generate_text_box('width_right', $data['width_right']));
        $form_container->output_row("{$lang->asb_output_to_vars}?", $lang->sprintf($lang->asb_output_to_vars_desc, '<span style="font-family: courier; font-weight: bold; font-size: 1.2em;">$asb_left</span> and <span style="font-family: courier; font-weight: bold; font-size: 1.2em;";>$asb_right</span>'), $form->generate_yes_no_radio('eval', $data['eval'], true, array("id" => 'eval_yes', "class" => 'eval'), array("id" => 'eval_no', "class" => 'eval')), '', '', array("id" => 'var_output'));
        $form_container->output_row("{$lang->asb_template}:", $lang->asb_template_desc, "{$spinner}<div id=\"template_list\"{$detected_show}>{$detected_info['templates']}</div>" . $form->generate_text_box('template_name', $data['template_name'], array("id" => 'template_name')), '', '', array("id" => 'template_row'));
        $form_container->output_row("{$lang->asb_hook}:", $lang->asb_hook_desc, "{$spinner}<div id=\"hook_list\"{$detected_show}>{$detected_info['hooks']}</div>" . $form->generate_text_box('hook', $data['hook'], array("id" => 'hook')), '', '', array("id" => 'hook_row'));
        $form_container->output_row($lang->asb_header_search_text, $lang->asb_header_search_text_desc, $form->generate_text_area('find_top', $data['find_top'], array("id" => 'find_top', 'class' => 'codepress mybb', 'style' => 'width: 100%; height: 100px;')), '', '', array("id" => 'header_search'));
        $form_container->output_row($lang->asb_footer_search_text, $lang->asb_footer_search_text_desc, $form->generate_text_area('find_bottom', $data['find_bottom'], array("id" => 'find_bottom', 'class' => 'codepress mybb', 'style' => 'width: 100%; height: 100px;')) . $form->generate_hidden_field('id', $data['id']) . $form->generate_hidden_field('active', $data['active']) . $form->generate_hidden_field('action', 'manage_scripts') . $form->generate_hidden_field('mode', 'edit'), '', '', array("id" => 'footer_search'));
        $form_container->output_row($lang->asb_replace_template, $lang->asb_replace_template_desc, $form->generate_yes_no_radio('replace_all', $data['replace_all'], true, array("id" => 'replace_all_yes', "class" => 'replace_all'), array("id" => 'replace_all_no', "class" => 'replace_all')), '', '', array("id" => 'replace_all'));
        $form_container->output_row($lang->asb_replacement_content, $lang->asb_replacement_content_desc, $form->generate_text_area('replacement', $data['replacement'], array("id" => 'replacement', 'class' => 'codepress mybb', 'style' => 'width: 100%; height: 240px;')), '', '', array("id" => 'replace_content'));
        $form_container->end();
        $buttons = array($form->generate_submit_button($button_text, array('name' => 'add')));
        $form->output_submit_wrapper($buttons);
        $form->end();
        // output CodePress scripts if necessary
        if ($admin_options['codepress'] != 0) {
            echo <<<EOF
\t\t<script type="text/javascript">
\t\t<!--
\t\t\tEvent.observe('edit_script', 'submit', function() {
\t\t\t\tif (\$('find_top_cp')) {
\t\t\t\t\tvar area = \$('find_top_cp');
\t\t\t\t\tarea.id = 'find_top';
\t\t\t\t\tarea.value = find_top.getCode();
\t\t\t\t\tarea.disabled = false;
\t\t\t\t}

\t\t\t\tif (\$('find_bottom_cp')) {
\t\t\t\t\tvar area = \$('find_bottom_cp');
\t\t\t\t\tarea.id = 'find_bottom';
\t\t\t\t\tarea.value = find_bottom.getCode();
\t\t\t\t\tarea.disabled = false;
\t\t\t\t}

\t\t\t\tif (\$('replacement_cp')) {
\t\t\t\t\tvar area = \$('replacement_cp');
\t\t\t\t\tarea.id = 'replacement';
\t\t\t\t\tarea.value = replacement.getCode();
\t\t\t\t\tarea.disabled = false;
\t\t\t\t}
\t\t\t});
\t\t// -->
\t\t</script>
EOF;
        }
        // output the link menu and MyBB footer
        asb_output_footer('edit_scripts');
    } else {
        $page->extra_header .= <<<EOF
\t<link rel="stylesheet" type="text/css" href="styles/asb_acp.css" media="screen" />
\t<script src="jscripts/asb/asb{$min}.js" type="text/javascript"></script>

EOF;
        $page->add_breadcrumb_item($lang->asb_manage_scripts);
        $page->output_header("{$lang->asb} - {$lang->asb_manage_scripts}");
        asb_output_tabs('asb_scripts');
        $new_script_url = $html->url(array("action" => 'manage_scripts', "mode" => 'edit'));
        $new_script_link = $html->link($new_script_url, $lang->asb_add_new_script, array("style" => 'font-weight: bold;', "title" => $lang->asb_add_new_script, "icon" => "{$mybb->settings['bburl']}/inc/plugins/asb/images/add.png"), array("alt" => '+', "title" => $lang->asb_add_new_script, "style" => 'margin-bottom: -3px;'));
        echo $new_script_link . '<br /><br />';
        $table = new Table();
        $table->construct_header($lang->asb_title, array("width" => '16%'));
        $table->construct_header($lang->asb_filename, array("width" => '16%'));
        $table->construct_header($lang->asb_action, array("width" => '7%'));
        $table->construct_header($lang->asb_page, array("width" => '7%'));
        $table->construct_header($lang->asb_template, array("width" => '18%'));
        $table->construct_header($lang->asb_hook, array("width" => '20%'));
        $table->construct_header($lang->asb_status, array("width" => '7%'));
        $table->construct_header($lang->asb_controls, array("width" => '8%'));
        $query = $db->simple_select('asb_script_info', '*', '', array("order_by" => 'title', "order_dir" => 'ASC'));
        if ($db->num_rows($query) > 0) {
            while ($data = $db->fetch_array($query)) {
                $edit_url = $html->url(array("action" => 'manage_scripts', "mode" => 'edit', "id" => $data['id']));
                $activate_url = $html->url(array("action" => 'manage_scripts', "mode" => 'activate', "id" => $data['id']));
                $deactivate_url = $html->url(array("action" => 'manage_scripts', "mode" => 'deactivate', "id" => $data['id']));
                $activate_link = $html->link($activate_url, $lang->asb_inactive, array("style" => 'font-weight: bold; color: red;', "title" => $lang->asb_inactive_desc));
                $deactivate_link = $html->link($deactivate_url, $lang->asb_active, array("style" => 'font-weight: bold; color: green', "title" => $lang->asb_active_desc));
                $none = <<<EOF
<span style="color: gray;"><em>{$lang->asb_none}</em></span>
EOF;
                $table->construct_cell($html->link($edit_url, $data['title'], array("style" => 'font-weight: bold;')));
                $table->construct_cell($data['filename']);
                $table->construct_cell($data['action'] ? $data['action'] : $none);
                $table->construct_cell($data['page'] ? $data['page'] : $none);
                $table->construct_cell($data['template_name'] ? $data['template_name'] : $none);
                $table->construct_cell($data['hook'] ? $data['hook'] : $none);
                $table->construct_cell($data['active'] ? $deactivate_link : $activate_link);
                // options popup
                $popup = new PopupMenu("script_{$data['id']}", $lang->asb_options);
                // edit
                $popup->add_item($lang->asb_edit, $edit_url);
                // export
                $popup->add_item($lang->asb_custom_export, $html->url(array("action" => 'manage_scripts', "mode" => 'export', "id" => $data['id'])));
                // delete
                $popup->add_item($lang->asb_delete, $html->url(array("action" => 'manage_scripts', "mode" => 'delete', "id" => $data['id'])), "return confirm('{$lang->asb_script_del_warning}');");
                // popup cell
                $table->construct_cell($popup->fetch());
                $table->construct_row();
            }
        } else {
            $table->construct_cell("<span style=\"color: gray;\"><em>{$lang->asb_no_scripts}</em></span>", array("colspan" => 8));
            $table->construct_row();
        }
        $table->output($lang->asb_script_info);
        $form = new Form($html->url(array("action" => 'manage_scripts', "mode" => 'import')), 'post', '', 1);
        $form_container = new FormContainer($lang->asb_custom_import);
        $form_container->output_row($lang->asb_custom_import_select_file, '', $form->generate_file_upload_box('file'));
        $form_container->end();
        $import_buttons[] = $form->generate_submit_button($lang->asb_custom_import, array('name' => 'import'));
        $form->output_submit_wrapper($import_buttons);
        $form->end();
        // output the link menu and MyBB footer
        asb_output_footer('manage_scripts');
    }
}
Example #19
0
            }
            $awards->update_cache();
            $awards->admin_redirect();
        }
        $form = new Form($awards->build_url('action=updatedisporder'), 'post');
        $query2 = $db->simple_select('ougc_awards', 'COUNT(aid) AS awards');
        $awardscount = (int) $db->fetch_field($query2, 'awards');
        echo draw_admin_pagination($mybb->input['page'], $limit, $awardscount, 'index.php?module=user-ougc_awards');
        while ($award = $db->fetch_array($query)) {
            $edit_link = "index.php?module=user-ougc_awards&amp;action=edit&amp;aid={$award['aid']}";
            $award['visible'] or $award['name'] = '<i>' . $award['name'] . '</i>';
            $table->construct_cell('<img src="' . $awards->get_award_icon($award['aid']) . '" />', array('class' => 'align_center'));
            $table->construct_cell('<a href="' . $edit_link . '">' . $award['name'] . '</a>');
            $table->construct_cell($award['description']);
            $table->construct_cell($form->generate_text_box('disporder[' . $award['aid'] . ']', (int) $award['disporder'], array('style' => 'text-align: center; width: 30px;')), array('class' => 'align_center'));
            $table->construct_cell('<img src="styles/default/images/icons/bullet_o' . (!$award['visible'] ? 'ff' : 'n') . '.png" alt="" title="' . (!$award['visible'] ? $lang->ougc_awards_form_hidden : $lang->ougc_awards_form_visible) . '" />', array('class' => 'align_center'));
            $popup = new PopupMenu("award_{$award['aid']}", $lang->options);
            $popup->add_item($lang->ougc_awards_tab_give, "index.php?module=user-ougc_awards&amp;action=give&amp;aid={$award['aid']}");
            $popup->add_item($lang->ougc_awards_tab_revoke, "index.php?module=user-ougc_awards&amp;action=revoke&amp;aid={$award['aid']}");
            $popup->add_item($lang->ougc_awards_tab_users, "index.php?module=user-ougc_awards&amp;action=users&amp;aid={$award['aid']}");
            $popup->add_item($lang->ougc_awards_tab_edit, $edit_link);
            $popup->add_item($lang->ougc_awards_tab_delete, "index.php?module=user-ougc_awards&amp;action=delete&amp;aid={$award['aid']}");
            $table->construct_cell($popup->fetch(), array('class' => 'align_center'));
            $table->construct_row();
        }
        $table->output($lang->ougc_awards_tab_view_d);
        $form->output_submit_wrapper(array($form->generate_submit_button($lang->ougc_awards_button_order), $form->generate_reset_button($lang->reset)));
        $form->end();
    }
    $page->output_footer();
}
Example #20
0
    } else {
        if ($mybb->request_method == 'post' && $mybb->get_input('action') == 'updatedisporder') {
            foreach ($mybb->get_input('disporder', 2) as $cid => $disporder) {
                $ougc_pages->update_category(array('disporder' => $disporder), $cid);
            }
            $ougc_pages->update_cache();
            $ougc_pages->redirect();
        }
        echo $multipage;
        $query = $db->simple_select('ougc_pages_categories', '*', '', array('limit_start' => $ougc_pages->query_start, 'limit' => $ougc_pages->query_limit, 'order_by' => 'disporder'));
        $form = new Form($ougc_pages->build_url('action=updatedisporder'), 'post');
        while ($category = $db->fetch_array($query)) {
            $manage_link = $ougc_pages->build_url(array('manage' => 'pages', 'cid' => $category['cid']));
            $category['name'] = htmlspecialchars_uni($category['name']);
            $category['visible'] or $category['name'] = '<em>' . $category['name'] . '</em>';
            $table->construct_cell('<a href="' . $manage_link . '"><strong>' . $category['name'] . '</strong></a> <span style="font-size: 90%">(' . $ougc_pages->build_category_link($lang->ougc_pages_view_page, $category['cid']) . ')</span>');
            $table->construct_cell($form->generate_text_box('disporder[' . $category['cid'] . ']', (int) $category['disporder'], array('style' => 'text-align: center; width: 30px;')), array('class' => 'align_center'));
            $table->construct_cell('<a href="' . $ougc_pages->build_url(array('action' => 'update', 'cid' => $category['cid'], 'my_post_key' => $mybb->post_code)) . '"><img src="styles/default/images/icons/bullet_o' . (!$category['visible'] ? 'ff' : 'n') . '.png" alt="" title="' . (!$category['visible'] ? $lang->ougc_pages_form_disabled : $lang->ougc_pages_form_visible) . '" /></a>', array('class' => 'align_center'));
            $popup = new PopupMenu('category_' . $category['cid'], $lang->options);
            $popup->add_item($lang->ougc_pages_manage, $manage_link);
            $popup->add_item($lang->edit, $ougc_pages->build_url(array('action' => 'edit', 'cid' => $category['cid'])));
            $popup->add_item($lang->delete, $ougc_pages->build_url(array('action' => 'delete', 'cid' => $category['cid'])));
            $table->construct_cell($popup->fetch(), array('class' => 'align_center'));
            $table->construct_row();
        }
        $table->output($sub_tabs['ougc_pages_cat_view']['title']);
        $form->output_submit_wrapper(array($form->generate_submit_button($lang->ougc_pages_button_disponder), $form->generate_reset_button($lang->reset)));
        $form->end();
    }
    $page->output_footer();
}